text:
Q: postgresql / postgres grant permissions to everything in the current schema I know I can run this:
grant select on all tables in schema whatever to "my_dev_group";

but the way I've built our CI system - we use lots of different schemas, so the schema is only known at the time of running the tests - not when the script is written.   Ie we run the same script against lots of different test schemas and we set the schema name at the start...
so I am trying to achieve the equivalent of the above grant statement - but to operate on the current schema - without any success.
ie all of these were spectacularly unsuccessful
grant select on all tables in schema current to "my_dev_group";
grant select on all tables in schema current_schema() to "my_dev_group";
grant select on all tables to "my_dev_group";

is it possible to do without going into the world of executing dynamic sql, which I'd prefer not to

A: SQL doesn't have a notion of a "current schema".  Consequently, there is no syntax to change the permissions of all tables in the current schema.
You could loop through all schemas in the search_path or all schemas in the database and run a GRANT statement for each one. Make sure to skip system schemas like information_schema and pg_catalog.
Alternatively, you could use the current_schema() function to retrieve the first existing schema on your search_path and change permissions for that schema.


text:
Q: Removing Duplicate Row using SQL (Hive / Impala syntax) I would like to remove duplicate rows based on event_dates and case_ids.
I have a query that looks like this (the query is much longer, this is just to show the problem):
SELECT
    event_date,
    event_id,
    event_owner
FROM eventtable

This gives me results such as the following:
event_date          event_id event_owner
2018-02-06 00:00:00 123456   UNASSIGNED
2018-02-07 00:00:00 123456   UNASSIGNED
2018-02-07 00:00:00 123456   Mickey Mouse
2018-02-08 00:00:00 123456   Mickey Mouse
2018-02-09 00:00:00 123456   Minnie Mouse
2018-02-10 00:00:00 123456   Minnie Mouse
2018-02-11 00:00:00 123456   Mickey Mouse
.
.
.

Problem:
I have duplicate entries on 2018-02-07. I would like to have only the second one to remain.
So the result should be this:
event_date          event_id event_owner
2018-02-06 00:00:00 123456   UNASSIGNED
2018-02-07 00:00:00 123456   Mickey Mouse
2018-02-08 00:00:00 123456   Mickey Mouse
2018-02-09 00:00:00 123456   Minnie Mouse
2018-02-10 00:00:00 123456   Minnie Mouse
2018-02-11 00:00:00 123456   Mickey Mouse
.
.
.

I've tried to use SELECT DISTINCT ... , but that gives back all the results since it takes into consideration all 3 columns and in that sence all rows are uniqe. I only want to apply DISTINCT on 2 columns event_data and event_id.
Should I use nested sub-queries? Or where lies the truth? All help is much appreciated.

A: You can use the ROW_NUMBER analytic function for this purpose, but you should clarify the order when you say " I would like to have only the second one to remain". That order doesn't exists in the data, so you need to do something to generate it by yourself.
Try this query:
select event_date, event_id, event_owner
from (
  select
    row_number() over (partition by event_date order by case when event_owner='UNASSIGNED' then 0 else 1 end desc) as rn,
    *
  from eventtable
  ) t
where rn=1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find a permutation with the given square or cube Problem: find a permutation such that

*

*$x^2 = (1\;3\;4\;5\;7)$,  $x\in S_7$

*$x^3 = (1\;3\;4\;5\;7)$,  $x\in S_7$
Must find all possible solutions for $x$.
Progress
I have solved for the first part, $x=(57134)$ but I am not sure on how to prove that there is only one $x$ value.

A: Note that in cycle notation for permutations, $(1~3~4~5~7) = (5~7~1~3~4)$.
Part 1: The idea here would be to create a cycle that moved 1 to 3 after two moves, 3 to 4 after two moves, 4 to 5 after two moves, 5 to 7 after two moves, and 7 to one after two moves.
Then (arbitrarily and without loss of generality), 1 is first in our cycle notation, followed by something, then 3, then something, then 4. So we have $(1~a_1~3~a_2~4)$ as our cycle. Now we try to figure out what goes in place of $a_1$ and $a_2$. After 1 iteration of this permutation, 4 maps to 1. On the second iteration, it should map to five, so that $x^2(4) = 5$. Note that I'm viewing $x$ as a function with $x^2 = x \circ x$. We now have $x = (1~5~3~a_2~4)$. Next, we need $x^2(5) = 7$. The way to do that is to set $a_2 = 7$. Thus we see, and can confirm, that $(1~5~3~7~4)^2 = (1~3~4~5~7)$. There's a pair left over in $S_7$; we haven't moved 2 or 6. Since $(2~6)^2$ is the identity, we can set $x = (1~5~3~7~4)(2~6)$ as well.
Hopefully this helps; the teacher in me won't let me do the whole problem (or the actual proof) for you. :)


text:
Q: A red black tree with the same key multiple times: store collections in the nodes or store them as multiple nodes? Apparently you could do either, but the former is more common.
Why would you choose the latter and how does it work?
I read this: http://www.drdobbs.com/cpp/stls-red-black-trees/184410531; which made me think that they did it. It says:

insert_always is a status variable that tells rb_tree whether multiple instances of the same key value are allowed. This variable is set by the constructor and is used by the STL to distinguish between set and multiset and between map and multimap. set and map can only have one occurrence of a particular key, whereas multiset and multimap can have multiple occurrences.

Although now i think it doesnt necessarily mean that. They might still be using containers.
I'm thinking all the nodes with the same key would have to be in a row, because you either have to store all nodes with the same key on the right side or the left side. So if you store equal nodes to the right and insert 1000 1s and one 2, you'd basically have a linked list, which would ruin the properties of the red black tree.
Is the reason why i can't find much on it that it's just a bad idea?

A: down side of store as multiple nodes:

*

*expands tree size, which make search slower.

*if you want to retrieve all values for key K, you need M*log(N) time, where N is number of total nodes, M is number of values for key K, unless you introduce extra code (which complicates the data structure) to implement linked list for these values. (if storing collection, time complexity only take log(N), and it's simple to implement)

*more costly to delete. with multi-node method, you'll need to remove node on every delete, but with collection-storage, you only need to remove node K when the last value of key K is deleted.
Can't think of any good side of multi-node method.

A: Binary Search trees by definition cannot contain duplicates.  If you use them to produce a sorted list throwing out the duplicates would produce an incorrect result.
I am working on an implementation of Red Black trees in PHP when I ran into the duplicate issue.  We are going to use the tree for sorting and searching.
I am considering adding an occurrence value to the node data type. When a duplicate is encountered just increment occurrence.   When walking the tree to produce output just repeat the value by the number of occurrences.  I think I would still have a valid BST and avoid having a whole chain of duplicate values which preserve the optimal search time.


text:
Q: Error logging into SQL Azure using manage link on Azure portal I have logged into Azure and navigated to Database link. I created a new database using "create' on the azure portal. Now i try to test connectivity. It fails. So i try to debug by clicking on "manage". Here i enter the database name user id and password. It fails, stating "Login is disabled or credentials are invalid"
I am using windows azure in conjunction with Visual Studio express (trial edition). I have tried with checking the "allow other windows azure services.." box and also by providing the IP designated to the db server in firewall rules. In both cases i get the same error.
This effort is part of deploying the sample VS 2010 windows azure web application on azure. It works fine on the emulator, but fails when actually deployed, at the time for registering a user. I have changed the default connection string to point to SQL azure as described @ http://msdn.microsoft.com/library/hh369932.aspx#SQLAzure.
Any pointers would be appreciated
regards
Sameer

A: I too had similar problem earlier,
And now it is solved.
The UserId, is youruserid@servername
You can see your userid, under Show connection strings link
And password is the password which you entered, during your database creation.

A: If the test of connectivity is failing it is extremely likely that your IP address is not correctly configured in your firewall rules.  You will need to add or edit a rule to permit you to access the database. Note that your IP address may have changed since you first configured the firewall rule.
The firewall rule popup screen will tell you which ip address you are currently using.  I have observed that this may be wrong if I was already logged into the management portal before BT reset my ip address.  If you simply log out and log back into the management portal you can confirm the ip address you are currently using and ensure that it is permitted to access the database.
This should resolve your problem. Good luck.


text:
Q: pgAdmin III Why query results are shortened? I've recently installed pgAdmin III 1.18.1 and noticed a strange thing:
Long json query results are shortened to 256 symbols and then ' (...)' is added.
Could someone help me disable this shortening?

A: Thanks to user Erwin Brandstetter for his answer on Database Administrators.

There is a setting for that in the options: Max characters per column - useful when dealing with big columns. Obviously your setting is 256 characters.

Set it higher or set it to -1 to disable the feature.

A: in pgadmin (Version 5.4) select
file >> preferences >> Query Tool >> Results grid
and change Resize by data? to false. This will the column be sized to the widest of the datatype or column name.


text:
Q: inst is undefined on countdown I'm using this great plugins : http://keith-wood.name/countdown.html
I have 3 countdown timers which are loaded with a json array. When I want to recharge them they block and this error appears:
TypeError: inst.options is undefinedjquery.countdown.js:682:1
    jQuery 4
        _generateHTML
        _updateCountdown
        _updateElems
        timerCallBack
Here my code on first load after ajax load (in success state) (regen give x seconds) :
var timer = [];
$.each(json.element, function (index, value) {
    if($.isNumeric(json.regen[i])){
        var timer = json.regen[i];
        var stat = json.stat[i];
        //Creating the countdown for each element
        $("#under_"+value).html('+1 in ');
        //initialize countdown and loop it at the end.
        $('#countdown_'+json.element[i]).countdown({until: timer, compact: true, format: 'MS', onExpiry: function() {
            getattribute(stat);
            }
        });
    };
    i++;
});

When i click on button to refresh those countdown the error appear...
How can i fix it ?
Here the codepen : https://codepen.io/Logobi/pen/KKdmNby
Thx

A: It seem OK, i have to check countdown before reinitialize it. If countdown isn't over, i let it down and if its over, i reload getattribute.
let oCountdown = $('#countdown_'+[i]+'_'+element[i]);
  if(oCountdown.length>0){
    oCountdown.countdown('option', "until", timer);
  }else{
    $("#under_"+elemval).html('+1 in ');
    $('#countdown_'+[i]+'_'+element[i]).countdown(
      {
        until: timer,
        format: 'MS',
        compact: true,
        onExpiry:function() {
          getattribute();
        }
      }
    );// format ii:ss
  }

Here the solution in codepen :
https://codepen.io/Zonecss/pen/jObmdBM


text:
Q: Does the "subset" command in MuMIn's dredge function work with random effects? I have the following GLMM with a random slope that I'm conducting model averaging on using MuMIn "dredge" (I don't think my dataset is relevant so I'm just including the code here):
sett_global2 <- glmmTMB(sett_dens~ depth_scale + sst_six_scale + exposure_six_month_daily_log_scale + (1|kelp)+ (0 + sst_six_scale|kelp) + (1|site) + (1|Year), data = sett_model_data,  family=nbinom2)
When I originally tried to dredge the model, it worked but with the following warning messages:
dredge(sett_global2, beta = "none", rank = "AIC", trace = 2)

Warning messages:
  1: Random slopes not present as fixed effects. This artificially inflates the conditional random effect variances.
    Solution: Respecify fixed structure!
  2: Random slopes not present as fixed effects. This artificially inflates the conditional random effect variances.
    Solution: Respecify fixed structure!
  3: Random slopes not present as fixed effects. This artificially inflates the conditional random effect variances.
    Solution: Respecify fixed structure!

indicating that even when the fixed effect of "sst_six_scale" wasn't in the model being fitted in the complete model set, the model was still being fitted with the random slope "(0 + sst_six_scale|kelp)".
So I tried to dredge the model again using the "dc" argument in the "subset" command to only include the random slope if the corresponding fixed effect was in the model:
dredge(sett_global2, beta = "none", rank = "AIC", subset = dc("cond(sst_six_scale)" , "cond(0 + sst_six_scale | kelp)"), trace = 2)
But I still end up with the same warning messages as before, indicating to me that the subset command didn't work properly. I made sure to use "getAllTerms" to get the appropriate variable names to put in the subset command, and I get no errors when running the above code, so I can't really think of any reason why it isn't working. This leads me to wonder if the "subset" command works with random effects at all. Can anyone shed light on this for me?


text:
Q: How do i show HDD partitions in "Other locations" section? I have currently dualboot Windows and Ubuntu 17.10 . There are 4 hardisk partitions that appear like this shown in image.

Now i want to remove windows completely, repartition harddisk and use ubuntu, but want to show partitions like this only. How is it possible ?

A: Firstly, it's always a good idea to back-up before deleting or re-sizing partitions. You can use something like partimage, clonezilla or dd if your feeling brave!
1) Create a USB Gparted live image and boot to it. https://gparted.org/liveusb.php
2) Find your Windows partition in Gparted's menu, it should be NTFS.
3) Right-click on your Windows partition and choose "Delete". Select any other Windows related partitions, you may want to delete them as well.
4) Right-click on your Linux partition and choose "Resize/Move." Resize it so it takes up the rest of the now-free space on your drive.
5) Click the "Apply All Operations" button in the toolbar to perform the selected tasks.
6) Shutdown and remove the USB Gparted live image.
7) On startup your boot-loader will still have some Windows entries. To delete, open a terminal and type: sudo update-grub


text:
Q: Issue during running server written in go under the local Docker container (Windows, wsl-2) I have a server code written in golang that listen to http and connecting to mongodb at localhost:27017 at my development machine and on aws ec-2 instance also the same host. All is working well when I run it via go run main.go.
sudo docker build -t server /mnt/c/code/tttfm/backend/server returns
 => [internal] load build definition from Dockerfile                                                                                0.1s
 => => transferring dockerfile: 38B                                                                                0.0s
 => [internal] load .dockerignore                                                                                0.1s
 => => transferring context: 2B                                                                                0.0s
 => [internal] load metadata for docker.io/library/golang:1.16.3-buster                                                                        2.3s
 => [1/6] FROM docker.io/library/golang:1.16.3-buster@sha256:2ff1a0d92edf6c2d4a2dd0d6bfa43e512c8b2f3aac738ffbb6195caf7cb38164                  0.0s
 => [internal] load build context                                                                                0.2s
 => => transferring context: 684B                                                                                0.2s
 => CACHED [2/6] WORKDIR /code                                                                                0.0s
 => CACHED [3/6] RUN apt-get update                                                                                0.0s
 => CACHED [4/6] RUN go get go.mongodb.org/mongo-driver/mongo                                                                                0.0s
 => CACHED [5/6] RUN go get github.com/google/uuid                                                                                0.0s
 => CACHED [6/6] COPY . .                                                                                0.0s
 => exporting to image                                                                                0.0s
 => => exporting layers                                                                                0.0s
 => => writing image sha256:9e215e06bf4ede636b31706af38497653bcaa5f3407de50ba7cc9a951be614bd                                                   0.0s
 => => naming to docker.io/library/server

But when I'am trying to run it is Exit with go errors
sudo docker run -it server
api/build/build.go:17:2: cannot find package
api/events/events.go:14:2: cannot find package
api/events/events.go:15:2: cannot find package
mongodb/mongodb.go:8:2: cannot find package
mongodb/mongodb.go:9:2: cannot find package

the lines is
import...
"go.mongodb.org/mongo-driver/bson"
"github.com/google/uuid"

Looks like another components imported well, like:
    "net/http"
    api "./api"
    build "./api/build"
    mongodb "./mongodb"
    storage "./storage"
    webChat "./webChat"

But it down on external components:"github.com/google/uuid" and "go.mongodb.org/mongo-driver/bson" on runtime during importing.
The dockerfile
FROM golang:1.16.3-buster
WORKDIR /code
RUN apt-get update
RUN go get go.mongodb.org/mongo-driver/mongo
RUN go get github.com/google/uuid
COPY . .

CMD ["go", "run", "main.go"]

I am noob in dockers and stucked with problem to run server under the docker container. What can be the issue? Thank a lot for any help

A: as mentioned in the comments you are building the container completely wrong.
Im assuming that you are using go modules.
The correct way I to use a multi-stage build in order to create small containers.
In the first stage, we build the binary.
In the second stage, we copy the binary and building the container.
#First stage
FROM golang:1.16-buster as builder
WORKDIR /app
COPY go.* ./
# Download dependencies
RUN go mod download
# Copy local code to the container image.
COPY . .
# Build the binary.
RUN  go build -v -o BINERYNAME

# Secound stage
FROM debian:buster-slim
RUN set -x && apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y \
    ca-certificates && \
    rm -rf /var/lib/apt/lists/*
# Copy the binary  to  production image from the builder stage.
COPY --from=builder /app/BINERYNAME /app/BINERYNAME

# Run app on container startup.
CMD ["/app/BINERYNAME"]


text:
Q: Post processing Wicket response (Rhino, jQuery) My question is if there is a way to simply post process wicket HTML response?
What I want to do is to apply some DOM transformations to the generated HTML using Rhino (http://www.mozilla.org/rhino/) and jQuery.
Anyone ever thought about it? Any suggestions where to start?
Best,
Maciej Wrzalik

OK, I've got this:
public class MyRequestCycle extends WebRequestCycle {
    public MyRequestCycle(WebApplication application, WebRequest request, WebResponse response) {
        super(application, request, response);
    }

    @Override
    protected void onEndRequest() {
        String responseString = response.toString();
        //String newResponseString = process(responseString);
        //replace old response content with the newResponseString
        super.onEndRequest();
    }
}

In method onEndRequest the string responseString contains HTML code that I'm going to alter some way using Rhino, Envjs and jQuery but the question is how can I replace the old response content with the new one?

A: Envjs emulates the browser environment under Rhino, and specifically allows you to do DOM manipulation server-side using jQuery. I have used it before in my projects, and have had good success. Relevant resources:

*

*http://www.envjs.com/

*http://ejohn.org/blog/bringing-the-browser-to-the-server/

A: If you want the post-processing done on the server, your best bet is likely to implement a Servlet Filter which modifies the response before it goes to the client.
As you're working on the rendered HTML, this has nothing particular to do with Wicket, and could be applied to html generated by any Java framework.

A: As suggested, a normal Java EE filter would work fine, if there's nothing Wicket-specific that you need for the processing.
But if you want to do it inside Wicket, for some reason or other, I suppose you could create your own RequestCycle implementation (MyRequestCycle extends WebRequestCycle) and do the processing there (perhaps by overriding onEndRequest and/or getWebResponse).
To use a custom RequestCycle, override newRequestCycle in your Application class:
@Override
public RequestCycle newRequestCycle(Request request, Response response) {
    return new MyRequestCycle(this, (WebRequest) request, response);
}

I'm using custom a RequestCycle for a couple of things (e.g. this) myself—it's simple and straightforward—but I'm not 100% sure if it fits your needs here. (My Wicket experience is still somewhat limited.)


text:
Q: Android SQlite data retrieving error I am developing an Android app.. In which I used SQLite database for storing the values and I have two Button ->Save for Save data and Saved Data to Displaying stored data.
When user click on any row of saved data the particular data has to be displayed but my problem is when user press on any row only the last row will be displayed instead of the pressed row.
Please check and help me.
My Activity is:
public void saveddata(View V)
{
    Cursor c = db.rawQuery("SELECT * from Data", null);
    int count = c.getCount();
    c.moveToFirst();
    TableLayout tableLayout = new TableLayout(getApplicationContext());
    tableLayout.setVerticalScrollBarEnabled(true);
    TableRow tableRow;
    TextView textView1, textView2,textView3,textView4,textView5;
    tableRow = new TableRow(getApplicationContext());
    textView1 = new TextView(getApplicationContext());
    textView1.setText("FirstName");
    textView1.setTextColor(Color.RED);
    textView1.setTypeface(null, Typeface.BOLD);
    textView1.setPadding(10, 10, 10, 10);
    tableRow.addView(textView1);

    textView2 = new TextView(getApplicationContext());
    textView2.setText("LastName");
    textView2.setTextColor(Color.RED);
    textView2.setTypeface(null, Typeface.BOLD);
    textView2.setPadding(10, 10, 10, 10);
    tableRow.addView(textView2);

    tableLayout.addView(tableRow);

    for(Integer j=0; j<count; j++)
    {
        tableRow = new TableRow(getApplicationContext());
        textView3= new TextView(getApplicationContext());
        textView3.setText(c.getString(c.getColumnIndex("fname")));
        textView3.setClickable(true);

        ett1=textView3.getText().toString();
        //datas11=textView3.getText().toString();

        textView4 = new TextView(getApplicationContext());
        textView4.setText(c.getString(c.getColumnIndex("mname")));
        textView4.setClickable(true);
        ett2=textView4.getText().toString();
        //datas12=textView4.getText().toString();

        textView5 = new TextView(getApplicationContext());
        textView5.setText(c.getString(c.getColumnIndex("lname")));
        textView5.setClickable(true);
        ett3=textView5.getText().toString();
        //datas13=textView7.getText().toString();

        textView3.setPadding(10, 10, 10,10);
        textView5.setPadding(10, 10, 10, 10);
        tableRow.addView(textView3);
        tableRow.addView(textView5);
        tableLayout.addView(tableRow);
        c.moveToNext();

        textView3.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent intent = new Intent(MainActivity.this ,SavedDate.class);
                intent.putExtra("ett1",ett1 + "");
                intent.putExtra("ett2",ett2 + "");
                intent.putExtra("ett3",ett3 + "");

                startActivity(intent);
            }
        });
    }

    setContentView(tableLayout);

    db.close();
}

A: Hey here is your new update code this will help you.
 Cursor c = db.rawQuery("SELECT * from Data", null);
int count = c.getCount();
c.moveToFirst();
 TableLayout table=new TableLayout;
                  table.setGravity(Gravity.CENTER);

      table.setStretchAllColumns(true);
      table.setShrinkAllColumns(true);

                TableRow rowLabels = new TableRow(this);
                rowLabels.setLayoutParams(new LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

                rowLabels.setBackgroundDrawable(getResources().getDrawable(
                        R.xml.tablerow));

                TextView srnoLabel = new TextView(this);
                srnoLabel.setText("FirstName");
                srnoLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);
                srnoLabel.setTextColor(Color.RED);
                srnoLabel.setPadding(40, 5, 0, 5);
                srnoLabel.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
                rowLabels.addView(srnoLabel);

                TextView pLabel = new TextView(this);
                pLabel.setText("Middle Name");
                pLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);
                pLabel.setTextColor(Color.RED);
                pLabel.setPadding(20, 5, 0, 5);
                pLabel.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
                rowLabels.addView(pLabel);

                TextView valLabel = new TextView(this);
                valLabel.setText("Last Name");
                valLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);
                valLabel.setTextColor(Color.RED);
                valLabel.setPadding(40, 5, 0, 5);
                valLabel.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
                rowLabels.addView(valLabel);
                rowLabels.setPadding(0, 0, 10, 0);

if (c.moveToFirst()) {
                    do {
                    String f_name = c.getString(c
                                .getColumnIndex("fname"));
                    String l_name = c.getString(c
                                .getColumnIndex("lname"));
                    String m_name = c.getString(c
                                .getColumnIndex("mname"));

                    TableRow rowdata = new TableRow(this);
                        rowdata.setLayoutParams(new LayoutParams(
                                LayoutParams.WRAP_CONTENT,
                                LayoutParams.WRAP_CONTENT));
                        // 1 column
                        TextView f_txt = new TextView(this);

                        f_txt.setText(Integer.toString(count));
                        f_txt.setPadding(50, 3, 10, 3);
                        f_txt.setText(f_name);
                        f_txt.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
                        f_txt.setTextColor(Color.BLACK);
                        f_txt.setClickable(true);
                        rowdata.addView(f_txt);

                    // 2 column
                        final TextView m_txt = new TextView(this);
                        m_txt.setText(m_name);
                        m_txt.setPadding(15, 3, 10, 3);
                        m_txt
                                .setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
                        m_txt.setTextColor(Color.BLACK);
                        rowdata.addView(m_txt);

                            // 3 column
                        final TextView l_txt = new TextView(this);
                        l_txt.setText(l_name);
                                //Annual_crop_loss.toString());
                        l_txt.setPadding(45, 3, 10, 3);
                        l_txt.setTextSize(
                                TypedValue.COMPLEX_UNIT_DIP, 17);
                        l_txt.setTextColor(Color.BLACK);
                        rowdata.addView(m_txt);
                        rowdata.setPadding(1, 1, 1, 1);

                    table.addView(rowLabels);
                        table.addView(rowdata);
                    }

                    } while (c.moveToNext());

                    table.setPadding(10, 10, 10, 10);
                    setContentView(table);
                }
finally {
        if (dbase != null)
            // newDB.execSQL("DELETE FROM " + tableName);
            c.close();
            dbase.close();
    }

A: The reason is that click event of textview is being override by dynamically created textview. Hence at the end of for loop, last click event will point to the last record. Instead of this dynamically generated table row, you can use custom listview and on click of that you display respective data. Let me know if you want to have an example listview and Sqlite database.


text:
Q: If user has certain number of posts, do/don't do something I have a custom post type and users can submit posts from the front end using a button I've created. I want this button to only show if they have submitted less than x number of posts, else it tells them they can't submit anymore.
I am using this code to count the posts for the current user and echo the results.
        <?php
        $authorid = get_current_user_id();
        query_posts(array(
            'post_type' => 'home',
            'author' => $authorid,
        ) );
            $count = 0;
            while (have_posts()) : the_post();
                $count++;
            endwhile;
            echo 'Homes registered: ' . $count;
        wp_reset_query();?>

This is working great. How can I create code similar to the below to achieve this conditional button?
if count=<5 echo 'button'
else
'Sorry youve already submitted too many, greedy'

A: While there are a few ways to do this, perhaps the easiest is to simply use count_user_posts():
if ( count_user_posts($authorid, 'home') < 5 ) {
    // Show the button
} else {
    echo 'Sorry youve already submitted too many, greedy';
}

You should also be able to count the number of posts returned by your query by using something like: $wp_query->post_count, rather than doing another function call.


text:
Q: A is a $2 \times 2$ matrix. Show that there exist $2 \times 2$ matrices with certain rank requirements.
A is a $2 \times 2$ matrix. Show that there exist $2 \times 2$ matrices $B_1$ and $B_2$ such that $\textrm{rank}(A+B_1)=1$ and $\textrm{rank}(A+B_2)=2$.

I can write examples of $B_1$ and $B_2$, but could anyone give me a more thorough answer? Thank you very much!

A: Find any $2$ by $2$ matrix with rank $1$, call it $C$. Find any $2$ by $2$ matrix with rank $2$, call it $D$.
Now, for any $A$, you can let $B_1=C-A$ and $B_2=D-A$. These differences exist because the set of $2$ by $2$ matrices is closed under subtraction, so $B_1$ and $B_2$ exist.


text:
Q: Is it possible to create a Portable class library with Roslyn? This is a very simple code that generates a dll that can be referenced from a Portable class library, but, it is prone error because when I add any reference it accepts non portable references.
How can I tell for sure that what I'm trying to generate is on the Portable profile?,
Here is the code:
using System.IO;
using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;

namespace Ros1
{
    class Program
    {
        static void Main(string[] args)
        {

            SyntaxTree tree = SyntaxTree.ParseText(
@"using System;

namespace HelloWorld
{
    public class A
    {
        public int Sum(int a, int b)
        {
          return a + b;
        }
    }
}");
            var co = new CompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var compilation = Compilation.Create("HelloWorld", co)
                                 .AddReferences(MetadataReference.CreateAssemblyReference("mscorlib"))
                                 .AddSyntaxTrees(tree);

            using (var file = new FileStream("Sum.dll", FileMode.Create))
            {
                compilation.Emit(file);
            }
        }
    }
}

A: Yes. Portable Class Libraries (PCL) as a concept is transparent to the compiler. It's basically a project system and reference assemblies feature only. If you want to create a portable class library that targets, say .NET for Windows Store apps and .NET 4.5, you should compile against the assemblies in this folder:
%ProgramFiles(x86)%\Reference Assemblies\Microsoft\Framework\.NETPortable\v4.5\Profile\Profile7

Every profile folder has a subdirectory called SupportedFrameworks which indicates which frameworks it supports.
To make the PCL work great in Visual Studio, you should also include the TargetFrameworkAttribute. Make sure version and profile are set correctly. For the example above you would need
[assembly: TargetFramework(".NETPortable,Version=v4.5,Profile=Profile7",
                           FrameworkDisplayName=".NET Portable Subset")]

I don't think we ship these assemblies outside of Visual Studio, so you will need an installation of Visual Studio 2010 (with the PCL extension installed) or Visual Studio 2012.

A: I believe Paulo's asking whether it is possible to use Roslyn in a Silverlight/portable app. The answer is no, Roslyn currently only works in full trust on desktop CLR. It's certainly something we'd like to enable in future.


text:
Q: Add data for existing users - Laravel I am adding a new table in my production application called user_settings. For all future users when registering it will create a new record. What is the best way to go about "seeding" the data for existing users?
Laravel docs say the seeders are for testing fake data.
So basically is there an industry standard for how to do this? Because all my existing users will need to have user_settings or the app won't work for them.
Ideas so far are:

*

*Add a query in the migration file that loops over all existing users after the table is created.

*Create a seeder and run it via the command line on the production server.

*The ->default() option on the migrations won't work for me as it can change in time.

A: What you can do is write a migration to insert data into the table,
You will have to tweak the default migration file created,
This way your can then just run that migration on you production server as well to create data for existing users.
Heres an example.
public function up()
{
// Create the table
Schema::create('users', function($table){
    $table->increments('id');
    $table->string('email', 255);
    $table->string('password', 64);
    $table->boolean('verified');
    $table->string('token', 255);
    $table->timestamps();
});

// Insert some stuff
DB::table('users')->insert(
    array(
        'email' => 'name@domain.com',
        'verified' => true
    )
);

}


text:
Q: How to debug VB.NET calculated Function Returns without a return variable It's often the case that I can write a nice tight little VB.NET function, and when it comes time to do the Return statement, it's really natural to just return the result of a quick calculation or a method call.  However, this makes it difficult if I need to step through the debugger to see what is going to be returned from that Function.  For example, take this simple method to illustrate the concept:
Public Shared Function GetAge(ByVal dob As DateTime, ByVal asOfDate As DateTime) As Integer
   If asOfDate.Date < dob.Date Then Return 0
   Dim factor = If(asOfDate.DayOfYear < dob.DayOfYear, 1, 0)
   ' What's going to be returned?
   Return asOfDate.Year - dob.Year - factor ' Imagine that this could be a more complicated calc, or one with side-effects that would prevent me from running it in the immediate window
End Function

I've found myself altering the way I write code just to make debugging easier.  So that method would become:
Public Shared Function GetAge(ByVal dob As DateTime, ByVal asOfDate As DateTime) As Integer
   If asOfDate.Date < dob.Date Then Return 0
   Dim factor = If(asOfDate.DayOfYear < dob.DayOfYear, 1, 0)
   Dim result = asOfDate.Year - dob.Year - factor ' I made this variable just for setting a debugging breakpoint
   Return result ' I can now set a breakpoint here, but it seems awkward
End Function

Is there something I'm missing in the debugger that would make it easier to see what a method is going to return rather than always making a result variable or hopping back to the caller to see what came out?  It seems awkward to alter the way code is written just to make a simple debugging task easier - it feels like I must be missing something.

A: You can set the breakpoint at the End Function line and hover the cursor over the function name.

A: Yes, it is awkward.  Visual Studio 6 could do this but that got lost in later releases.  It isn't that easy to implement, how managed code returns a value is an implementation detail of the JIT compiler.  It is kinda obvious for simple return value types like Integer or objects but it gets convoluted when a method returns a structure or decimal.
There isn't really anything wrong with storing it in a variable first, the JIT optimizer will get rid of that variable in most cases.  But yes, it looks fugly in the source code.
There is one trick you could use if the return value type is simple, like an integer.  Set a breakpoint on the End Function statement, then use Debug + Windows + Registers to display the CPU register values.  The EAX register contains the value.  Right-click the window and choose Floating point.  The ST0 register contains a floating point return type value in 32-bit mode.
Not great, but something to get by when in a pinch.

A: I'd be inclined to go one step further and remove the Return 0 on the first line of the function so that the only place your code exits the function is at the end.
Public Shared Function GetAge(ByVal dob As DateTime, ByVal asOfDate As DateTime) As Integer
   Dim result = 0
   If asOfDate.Date >= dob.Date Then
      Dim factor = If(asOfDate.DayOfYear < dob.DayOfYear, 1, 0)
      result = asOfDate.Year - dob.Year - factor
   End If
   Return result
End Function

Done this way you only have to worry about one exit point - which makes understanding your code easier, so less debugging - and you get your break-point for free!


text:
Q: Create cross section with polygon intersects in QGIS Is it possible to create a cross section that shows the intersected polygons on the relief (in QGIS 2.0.1)? I would like to try this out for a geologic map.
I'm using VoGisProfilTool:
http://plugins.qgis.org/plugins/VoGisProfilTool/
and a NASA-DEM

A: Yes, with the:

*

*qProf plugin of  Mauro Alberti  and Marco Zanieri

*or by Python scripting in the Python console or with processing: PyQGIS (QGIS 2) geological cross-sections (colorization of a topographic profile with the colors of a geological map and placement of the points of intersection with the boundaries of geological layers), in French, but the scripts are universal...

*look at a pure Python solution with shapely in Python Script for getting elevation difference between two points. The PyQGIS script is a simple adaptation of the original script.

In both cases,the scripts use matplotlib.
Example with a geological map and a DEM: line of cross section (in blue):

1) with qProf

*

*you can use a point layer with the dip and dip direction of the layers

But you cannot place the intersections between the geological layers and the cross section line and you cannot adapt or change the resulting figure with the parameters of matplotlib as in the Python script below.
2) with the Python script:

*

*the profile in 3D

*

*cross section (2D) (with the colours extracted from the geological map)

or

*

*Intersections between the profile line and the limits of the geological layers (polygons layer):

*

*with structural values, apparent dip from dip and dip direction

*

*And you can even construct the Down-Plunge profile of a fold (look at Big Elk Anticline Animation):


text:
Q: How can I send a file using http POST request as a formData? I'm using swagger 2.0 to document my API. I defined a resource /getsize as shows the next code snippet:
    post:
      operationId: users.getSize
      tags:
        - Users
      summary: Measure your body
      description: import a photo
      consumes:
         - multipart/form-data
      parameters:
        - in: formData
          name: image1
          type: file
          required: true
        - in: path
          name: height
          type: number
          required: true

When I try to send the request from the sawgger ui I get the expected result. But, the problem occurs when I try to access this resource using angluar component, here a code snippet of the component.ts file:
onSubmit() {
    const formData = new FormData();
    formData.append('image1', this.image);
    console.log(formData.getAll);
    console.log(this.image);
    this.http.post(endpoint,formData);
    .subscribe(res => {
        console.log(res);
        alert('SUCCESS !!');
      })
}

The server response is:
error:
detail: "Missing formdata parameter 'image1'"
status: 400
title: "Bad Request"
type: "about:blank"

Any suggestions ?

A:
You can do this using URLSearchParams as the body of the request
  and angular will automatically set the content type to
  application/x-www-form-urlencoded and encode the body properly.

This post explained the answer in detail


text:
Q: svg not rendering correctly when used with by multiple react components Context
I have an SVG that is used by two different React components (A and B) on the same page.
Problem
When component A is assigned 'display: none' css property, the svg in component B does not render correctly.
Example
componentA {
 display: none;
}
componentB {
 display: block;
}

SVG does not render correctly
componentA {
 display: block;
}
componentB {
 display: block;
}

SVG renders correctly
I suspect it may be an issue with my svg but I am not sure as I am new to react. Below is the svg code.
<svg
  id={id}
  data-name={id}
  xmlns="http://www.w3.org/2000/svg"
  width={width}
  height={height}
  viewBox="0 0 498 305.84">
  <defs>
    <clipPath id="clip-path">
      <path
        fill="none"
        d="M354.47 137.84c1.75-22.18-9.65-52.24-34-73.15-15.94 51.41 30.59 56.14 34 73.15" />
    </clipPath>
    <linearGradient
      id="linear-gradient"
      x1="-146.72"
      y1="416.08"
      x2="-143.8"
      y2="416.08"
      gradientTransform="matrix(7.8 0 0 -7.8 1469.73 3349.9)"
      gradientUnits="userSpaceOnUse">
      <stop offset="0%" stopColor="#62bb46" />
      <stop offset="100%" stopColor="#a2d28a" />
    </linearGradient>
  </defs>
  <g id="Leaf">
    <path
      clipPath="url(#clip-path)"
      fill="url(#linear-gradient)"
      d="M286.058 69.72l66.622-18.076 22.032 81.205-66.622 18.074z" />
    <path
      fill="#62bb46"
      d="M320.48 64.69c23.64 2.71 53.94 33.25 34 73.15 1.76-22.18-9.65-52.24-34-73.15" />
  </g>
</svg>

A: I had a simple workaround that worked for me at least.
The only change I would do is append the unique id to each of the elements with an id attribute,
    <svg
      id={id}
      data-name={id}
      ...
      <defs>
        <clipPath id={`clip-path-${id}`}>
          ...
        </clipPath>
        <linearGradient
          id={`linear-gradient-${id}`}
         ...
        </linearGradient>
      </defs>
      <g id={`Leaf-${id}`}>
        <path
          clipPath={`url(#clip-path-${id})`}
          fill={`url(#linear-gradient-${id})`}
          ...
         />
      </g>
    </svg>

By doing so, it is always assured that SVG will have unique id on different components.

A: As of now there is a feature request in svgo to uniquely allocate id for each svg instance.
Best work around could be not to use clip-path in svg
Another way can be to use following css to hide element

componentA {
 display: block;
 visibility: hidden;
 height: 0;
 width: 0;
}
componentB {
 display: block;
}

Another work around can be to pass unique id as a porp and replacing it with id required for clip-path as answered earlier.
e.g

export const svg = (id) => <svg xmlns="http://www.w3.org/2000/svg" width={width} height={height} viewBox="0 0 498 305.84">
  <defs>
    <clipPath id={`clip-path-&{id}`}>
      <path
        fill="none"
        d="M354.47 137.84c1.75-22.18-9.65-52.24-34-73.15-15.94 51.41 30.59 56.14 34 73.15" />
    </clipPath>
    <linearGradient
      id={`linear-gradient-${id}`}
      x1="-146.72"
      y1="416.08"
      x2="-143.8"
      y2="416.08"
      gradientTransform="matrix(7.8 0 0 -7.8 1469.73 3349.9)"
      gradientUnits="userSpaceOnUse">
      <stop offset="0%" stopColor="#62bb46" />
      <stop offset="100%" stopColor="#a2d28a" />
    </linearGradient>
  </defs>
  <g id="Leaf">
    <path
      clipPath={`url(#clip-path-&{id})`}
      fill={`url(#linear-gradient-${id})`}
      d="M286.058 69.72l66.622-18.076 22.032 81.205-66.622 18.074z" />
    <path
      fill="#62bb46"
      d="M320.48 64.69c23.64 2.71 53.94 33.25 34 73.15 1.76-22.18-9.65-52.24-34-73.15" />
  </g>
</svg>


text:
Q: convex fuction fullfills inequality with gradient Consider a convex function $f$ which is differentiable on closed convex set $Y$. Then it holds
$x$ is minimizer of f if $<\nabla f(x), x-y> \leq 0, \forall y \in Y$.
Proof:
Assume $<\nabla f(x), x-y> > 0$ and consider  $h(t)=f(x + t(y-x)) \Rightarrow h'(t) <0$
Why is this a contradiction?

A: If $h'(0) < 0$ then you can find a $t > 0$ such that $h(t) < h(0)$, which translates to
$$
f(x + t(y - x)) < f(x)
$$
Therefore $x$ can't be the minimizer, which contradicts your assumption.


text:
Q: Installing multiple instances of an Application with Wix Toolset I simply need to install multiple instances of my application saving them in different folders, with no shortcut on desktop.
In other words, when the App is already installed in a Folder, if I double-click the .msi file once again, the installer shouldn't ask me if I want repair or remove my App, but it simply should permit to install it in a new folder.
How can I solve this problem?

A: I used to work with this kind of installations before, and I would agree with @Nikolay - it is rather an exception, than the rule when it comes to Windows Installer based installations. Component rules are often tricky to follow, and multiple instances aspect adds some complexity on top. So, think twice before you go this road.
Being complex, it is still possible. Years ago I published the article of how to start authoring multiple instance installations with WiX 3.6. Note that this version of WiX simplifies it significantly. It's not a short read, so here is a quick digest:

*

*You won't be able to achieve the "install each new instance with double-clicking MSI file" behavior. You have to have a bootstrapper - something that passes correct command line parameters to msiexec.exe.

*Don't try to support unlimited number of instances - try sticking with reasonably big number. Do you imagine someone installing your app 10 times on a machine? 50? 100? Make a sane choice - this will be the number of your <Instance/> elements.

*Although you only have to decorate non-file data components with MultiInstance attribute, I don't think it will break if you add it to all of your components.

*Although I explained the patching of multiple instances in that post, I would only use it in production if I had no other choice.

A: What you are asking for is not normal in Windows. Normally, each program (product) is installed only once. I.e. each installation package has it's ID (called "ProductID"). If that ID already registered in the system as installed, the system will not allow you to install the second product with the same ProductID, but start change/remove.
What you can do:

*

*Don't use Windows Installer (and WIX), use ZIP for example, or some self-extracting archive, or some other program which does not register installed product in the system.

*Use command line to change product id before installing if you want MSI and Windows Installer for whatever reason. Try googling on "use transforms to install the same MSI multiple times". Thus you can have the same MSI per-transformed before installation, so that it looks as a different one to the system.

*Install per-user, if that's good enough for you (i.e. don't install to Program Files, install to user folder)

*Maybe there are other options...


text:
Q: Subset vectors of dates within a list I have a list of vectors of dates. I want to subset each vector within that list to leave only the dates which fall within a certain time interval in all those vectors.
l <- list(a=seq.Date(as.Date('2017-01-01'),as.Date('2017-01-31'),by = 1),
          b=seq.Date(as.Date('2017-01-09'),as.Date('2017-02-28'),by = 1),
          c=seq.Date(as.Date('2017-01-20'),as.Date('2017-03-31'),by = 1))

I tried doing this, but I'm missing smth
library(lubridate)
cond<-lapply(l,FUN=function(x) ymd(x) %within% interval(ymd("2017-01-05"), ymd("2017-02-01")))
l[cond]


text:
Q: Java 8 Stamped Lock: Why this piece of code doesnt result into a deadlock? In my attempt to understand Optimistic locking in Java 8,I came across the below piece of code.
Original Blog Here.
As explained in the blog, this piece of code is attempting to convert a read lock into a write lock.The code requests an explicit write lock if conversion of read lock to write lock failed.
It puzzles me How can it be expected that the explicit write lock get granted when the parent thread is already holding a read lock? It doesn't look like the read lock is getting released at any point before a write lock is forcefully requested. To my flawed understanding, the thread would wait infinitely for write lock as the read lock is never released creating a deadlock.
Why this doesn't result in a deadlock here?
ExecutorService executor = Executors.newFixedThreadPool(2);
StampedLock lock = new StampedLock();

executor.submit(() -> {
    long stamp = lock.readLock();
    try {
        if (count == 0) {
            stamp = lock.tryConvertToWriteLock(stamp);
            if (stamp == 0L) {
                System.out.println("Could not convert to write lock");
                stamp = lock.writeLock();
            }
            count = 23;
        }
        System.out.println(count);
    } finally {
        lock.unlock(stamp);
    }
});

stop(executor);

Thanks in advance!

A: Does this help?  From the API for tryConvertToWriteLock

If the lock state matches the given stamp, atomically performs one of the following actions. If the stamp represents holding a write lock, returns it. Or, if a read lock, if the write lock is available, releases the read lock and returns a write stamp. Or, if an optimistic read, returns a write stamp only if immediately available. This method returns zero in all other cases.


text:
Q: Make double quotes from database value appear properly I have a database type varchar(100), the value contains double quotes "", for example:

TCA CREAM 65 ML FC 24% "A Z A M"

I use sql server 2008.
When I call this data in my web page
the "" can't be read.
The result looks like:

First I thought the font family was not supported, but I tried with many different font families:
html body div.popup_window_css div.popup_window_css_body {
    border: 1px solid black;
    border-width: 0px 1px 0px 1px;
    padding: 6px 6px 0px 6px;
    background: #DBDBBA;
    width: 615px;
    font: 900 14px Trebuchet MS, Sans-Serif, Times New Roman;
    }

But it doesn't work...

A: You have to escape the quotes in your HTML to make this work.
Use javascript to convert these quotes, where you have your value:
var quoteString = myDbValue.replace('"', """);

Or try to turn any " into &quot any way you like.
From your comment:
success: function(data){
    $("#pname").replace('"', """);
    $("#pname").html(data);
}

must change into:
success: function(data){
    escapedData = data.dbValue.replace('"', """);
    $("#pname").html(escapedData);
}

Of course I'm not exactly sure what data looks like in your code, but you should select the right property i.e. dbValue in my code.

A: *

*",',-,_,>,> kind of characters (full list) call special characters in HTML, because some of those may use to some other purpose in HTML/CSS/JS etc... So browsers not promise you to render this characters properly.

*Some of this characters can use for break your web site by using SQL injection kind of method.

So best practice is before you store this characters  to database or before start to process, you have to convert this characters to their HTML entity using server side language (php,c#). By This you can avoid above both issues. you can find HTML entities in the link i given above.


text:
Q: Conditional replacement of labels based on another data set suppose to have the following data set:

 ID          Label
0001        0001_1
0001        0001_1
0001        0001_1
0001        0001_1
0001        0001_1
0001        0001_1
0002        0002_1
0002        0002_1
0002        0002_2
0002        0002_2
0002        0002_3
0002        0002_3

and another one:

 ID          Label
0001        0001_1
0001        0001_1
0001        0001_2
0001        0001_2
0001        0001_3
0001        0001_3
0002        0002_1
0002        0002_1
0002        0002_2
0002        0002_2
0002        0002_3
0002        0002_3

You want the following:
if in the first dataset there is only one type of Label (i.e., 0001_1), the second dataset should have that type. Otherwise if there are multiple labels nothing must be done. The desired output should be:

 ID          Label
0001        0001_1
0001        0001_1
0001        0001_1
0001        0001_1
0001        0001_1
0001        0001_1
0002        0002_1
0002        0002_1
0002        0002_2
0002        0002_2
0002        0002_3
0002        0002_3

Thank you in advance
Best

A: You will want to compute the groups in the first table that have a single label in aggregate and apply that label to the groups in the second table.
Example:
Computation with PROC FREQ and application via MERGE.
data have1;
  call streaminit(20231);

  do id = 1 to 10;
    do seq = 1 to rand('integer', 10) + 2;
      if mod(id,2) = 0
        then label = 'AAA';
        else label = repeat(byte(64+rand('integer', 26)),2);
      output;
    end;
  end;
run;

data have2;
  call streaminit(20232);

  do id = 1 to 10;
    do seq = 1 to rand('integer', 12) + 2;
      label = repeat(byte(64+rand('integer', 26)),2);
      output;
    end;
  end;
run;

proc freq noprint data=have1;
  by id;
  table label / out=one_label(where=(percent=100));
run;

data want2;
  merge
    have2
    one_label(keep=id label rename=(label=have1label) in=reassign)
  ;
  by id;
  if reassign then label = have1label;
  drop have1label;
run;

Same result achieved with SQL code, performing computation in a sub-select and using COALESCE for application.
proc sql;
  create table want2 as
  select
    have2.id
  , coalesce(singular.onelabel, have2.label) as label
  from
    have2
  left join
    ( select unique id, label as onelabel
      from have1
      group by id
      having count(distinct label) = 1
    ) as singular
  on
    have2.id = singular.id
  ;


text:
Q: cabecera de excel usando python Se me presenta el siguiente probrema. estoy leyendo un archivo de excel usando python pero cuanto lo hago se me cambian los nombres de la cabecera. saben esto a que se debe ?
archivo excel original

Este es el codigo
from importlib.resources import path
import pandas as pd

archivo = 'C:/Users/adatos/Desktop/python/Query.xlsx'
df = pd.read_excel(archivo, sheet_name='Query PARAMETRIZACION', header = 0)

print(df)

Este es el resultado


text:
Q: Ordenar campos sin importar si es esta en mayúscula o minúscula Hay alguna manera de decirle a Django que me ordene los campos sin importar si esta en mayúscula o minúscula tengo este modelo:
class Mascota(models.Model):
GENDER_CHOICES = (
    ('macho', 'Macho'),
    ('hembra', 'Hembra'),
)
nombre = models.CharField(max_length=100)
tipomascota = models.ForeignKey(TipoMascota,
                           on_delete=models.CASCADE,
                           related_name='mascotas', blank = True)
raza = models.ForeignKey(Raza,
                           on_delete=models.CASCADE,
                           related_name='mascotas', blank = True)
sexo = models.CharField(blank = True, max_length=10,
                          choices=GENDER_CHOICES,
                          default='macho')
edad = models.IntegerField(blank = True, null = True)

class Meta:
    ordering = ('nombre',)

def __str__(self):
    return self.nombre

def get_absolute_url (self):
    return reverse('mascota_detail', args=[str(self.id)])

con esta función se ven todos en mayúscula todo pero el orden prioriza las mayúsculas y de ultimo comienza con las minúsculas.
class MascotaAdmin(admin.ModelAdmin):
list_display = ('get_nombre', 'edad', 'get_nombre_raza', )
search_fields = ('nombre', 'raza__nombre')
inlines = [VacunaInline]

def get_nombre(self, obj):
    return ("%s" % (obj.nombre)).upper()

def get_nombre_raza(self, obj):
    return ("%s" % (obj.raza.nombre)).upper()
get_nombre_raza.admin_order_field  = 'nombre'  #Allows column order sorting
get_nombre_raza.short_description = 'Raza de Mascota'  #Renames column head

admin.site.register(Mascota, MascotaAdmin)
La única mascota que su nombre fue introducido en minúscula pero que comienza por la letra "a" me lo pone de ultimo, osea prioriza las mayúsculas.

A: Usa lo siguiente
from django.db.models.functions import Lower

ordering = (Lower('myfield'),)


text:
Q: No History for SQL Backup I have some SQL 2005 jobs which run nightly backups of the database to a local drive.
The jobs are running OK (Well, I can see that they are doing something) because I can see a new backup file being written each evening.
When I right click on the the Job and view history there is nothing.
Other jobs do display history, and generally speaking there is history older than the job I'm interested in (i.e. the log is not getting cleared down).
Unless the backup is being run by another process (which therefore WOULD have some history) - which I do not believe it is - where is my history?
I think I'm missing something really simple here (it is a Friday afternoon).

A: Here are some suggestions:

*

*Look at the creation time of the files to see exactly when the job is starting.

*Look at the SQL Error Logs.  That should give the best indication of what is executing the backup (if it is being initiated by anything controlled by SQL Server, such as another job).

*Look at the system's Application log, which would also give some clues.

*It could be that the backup for your database is being run by a catchall job (other than the one you set up specifically for your database).

*Look at the backup history of the database itself (i.e. not the job history), as that may also present a clue.

I hope that helps (there may well be other places I've left out, but by the time you've gone through all of the above, I'm pretty sure you will have figured it out).

A: Check out the contents of the msdb..backupset table in msdb for information on the most recent backup. It contains a backup_finish_date field.  (This is where information is pulled from when you right click on a database and view the last backup date in the properties.)
select *
from msdb..backupset
where
b1.[type] = ('D') -- database backup (not log!)

To figure out what job may be backing up the server, you could try something like this (hopefully this parses, I'm not able to check it right now):
select jobname=j.name
, js.step_id
, js.step_name
, js.command
from msdb..sysjobs j
join msdb..sysjobsteps js on
j.job_id=js.job_id
where js.command like '%backup%'

Here is a blog post I did on checking the last backup date...


text:
Q: How do I supply my password to Bazaar so it can fetch my code from my remote server? I have a codebase on a remote Linux server (in my private home directory). I am traveling and my internet connection is spotty, so I'd like to download the code locally, work on it, and then push changes to the server. Since I'm already managing the codebase with Bazaar, seems like that's the logical tool to use for this task as well. I downloaded Bazaar for Windows, and tried creating a branch, but can't figure out what location to enter in the "From" field. My first guess was to do it the way I do with scp, where I enter:
username@host.com/subfolder-with-code

But that didn't work. Also, where do I enter my password?

A: I think you just needed to add the protocol to that your url:
bzr branch bzr+ssh://username@host.com/subfolder-with-code

should do the trick.
See bzr help urlspec for more info.


text:
Q: CoderByte JavaScript Letter Changes - first steps For those familiar with this quiz, I'm trying to take a string argument and convert each letter to the letter that follows in the alphabet. EG, the argument "abc" should become "bcd".
The first portion of my code works. It takes the first letter of the argument and converts it. Now I'm trying to do this for each letter of the argument and then concatenate the results into one string as the output. This part isn't working. I'm getting the error, "SyntaxError: Unexpected token ;"
function LetterChanges(str) {
   var string = str.toLowerCase()
   var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
   "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
   var n = 0;
   var output = "";
   var currentLetter = string[n];
   var currentAlphaPos = alphabet.indexOf(currentLetter);
   var nextAlphaPos = currentAlphaPos + 1;
   var nextAlpha = alphabet[nextAlphaPos];

   //the code above this works. The code below results in an error

  while (i = 1;i < string.length; i++){
      output += nextAlpha;
      n += 1;
   };

   return output;
}

I'm a beginner, so thanks in advance.

A: You have confused the while and for loops.
You are trying to do for (iterator; condition; step); the while syntax is simply while (condition).


text:
Q: web-browser based GUI I am working on an application in Linux which will interfaces with hardware. One of the requirements is to create the GUI in Web-browser . the application will be c++ based. I m not familiar with web realted stuff so i want to know Is it possible to do such a thing (currently it's a console application take input from txt file/cmd line). gui will be simple using button and showing output messages on browser from the application. i want to know which technologies/languages are involved and how can it be done. some of the idea i read but havn't found anything concrete yet. if u have any idea about these or a better suggestion please share

*

*run the app in background and communicate with browser ?

*call library functions directly from browser ?

any other idea ?

A: I would start by setting up a regular HTTP server, like lighttp or Apache httpd.
You say you already have a command line program that does the actual work - As a first step, I would reuse that, and configure the web server to call your program using CGI - see forexample http://httpd.apache.org/docs/2.2/howto/cgi.html for apache
Finally, I'd pick some javascript framework like jQuery or YUI with Ajax capabilities to do requests to the server to call the CGI script from within a webpage. You could also create a form-based web application without ajax or any framework, but that would require you to stuff all kinds of logic in your program to generate HTML pages. By using Ajax, you can leave the command line application as is, and parse any responses it gives with javascript, and then use that to dynamically change the webpage in a way that would make sense to the user.
If this all works, then I would try to figure out how to package all these components. Perhaps you just want to create a simple archive with all the programs inside, or maybe you want to go as far as actually embedding the webserver in your program. Alternatively, you may want to do it the other way around and rewrite your program as an ISAPI module that you can plug into your webserver. Or if that's not integrated enough still you could write your own (partial) HTTP server. That's really up to you (I'd probably spend time and energy on searching for the leanest, meanest existing open source http serverr and use that instead)
At any rate, the prior steps won't be lost work. Most likely, developing the web page is going form a substantial part of the work, so I would probably create a quick and dirty working solution first using the age-old CGI trick, and then develop the webpage to my satisfaction. At that point you can already have an acceptable distributable solution by simply putting all programs in a single archive (of course you would have to tweak the webserver's configuration too, like changing the default port so it won't interfere with existing webservers.) Only after that I would spend time on creating a more integrated fancy solution.

A: I ended up using Wt though I'd update for future reference.

A: After 12 years, web browser-based GUI started to appear, WebUI is one of them.

A: These are how I thought of doing this, in order of complexity for me:

*

*Create a simple server-side-language (PHP/Python) website that can communicate with (ie launch and process the return of) your application

*Modify your application to have a built-in webserver that just punched out HTML (command line parameters taken through the URL)

*Modify the app to publish JSON and use javascript on a simple HTML page to pull it in.
You could write a Java applet (as you've tagged this thread) but I think you'd be wasting time. This can be quite simple if you're willing to spend 10 minutes looking up a few simple commands.


text:
Q: Obtaining min and max of partitioned data with a filter I've just find this problem in a query: (Sorry, I'll try to simplify the table definitions and shorten the details. If you need some more, please, tell me).
I've a table with (ID, date, status). ID is a FK, date is a date, and status is an int value between 1 and 5. Both date and status allow null values. Repeated values are also allowed.
What I need:
Extract one row for each ID, min(date) having an status of 1 or 2, min(date) having an status of 2 (only), max(status)...
I'm completely lost... I'm trying to use
SELECT
   ID,
   min(date) over (partition by(status)) ?? as min_12_date,
   min(date) over (partition by(status)) ?? as min_2_date,
   max(status) as max_status
FROM table
group by ID

So, the question is: Is this correct? How can I select only the status I want?

A: If I understand your question correctly, you don't need analytic functions for this. You only need conditional aggregation:
select id,
       min(case when status in (1, 2) then date end) as min_12_date,
       min(case when status = 2 then date end) as min_2_date,
       max(status) as max_status
  from tbl
 group by id


text:
Q: Find a conformal mapping to map the intersection of the disks $|z|<1$ and $|z-1|<1$ to the unit disk $|w|<1$. My thinking is to use a composition of mappings to map 1) the given intersection to a sector of the complex plane enclosed by two rays from the origin, 2) the sector to the upper half plane, and 3) the upper half-plane to the unit disk.
To achieve 1), I used
$$
s(z) = \frac{z(1-i\sqrt{3})+i\sqrt{3} + 1}{z(1+i\sqrt{3})-i\sqrt{3} + 1}
$$
which maps the area conformally to all complex numbers $w$ such that $0 \leq \arg(w) \leq \frac{2\pi}{3}$.
For 2),
$$
f(z) = z^{2/3}
$$
to map to the upper half imaginary plane. To get 3), I used
$$
g(z) = \frac{z-i}{z+i}
$$
to map the upper half imaginary plane to the unit disk. I then claim that
$$
T := (g \circ f \circ s)
$$
gives us the desired mapping.
Firstly, does this look correct to others? Secondly, is there a faster way to achieve this without using a composition of 3 mappings?

A: This is not correct. If your computations are correct, and you have that the argument is between $0$ to $\frac{2\pi}{3}$, then the mapping should be:
$$ f(z) = z^{\frac{3}{2}}$$
Then you will map that region to the upper complex plane. Why ? because the powers are multiplied by the argument in the complex exponential and then it cancels out the $\frac{2}{3}$.
And there is no shortcut for this. You should do all these three mappings. I usually do 4, because I never memorize the Cayley and I just rotate and then transform to the unit disk by $f(z) = \frac{z-1}{z+1}$


text:
Q: Can someone explain to me what stty does? I have a shell script inside Docker. This is not mine, unfortunately I get the following error when running it. But only under Ubuntu 20.04 and Docker 19.03.
stty: 'standard input': Inappropriate ioctl for device
Here a cutout of line 126 from the script. What makes the stty echo and stty -echo? And why does the script run without problems on an system without docker?
askNoEcho() {
  PROMPT=$1
  DEFAULT=$2

  stty -echo
  ask "$PROMPT" "$DEFAULT"
  stty echo
  echo ""
}

askNonBlankNoEcho() {
  PROMPT=$1
  DEFAULT=$2

  while true; do
    stty -echo
    ask "$PROMPT" "$DEFAULT"
    stty echo
    echo ""
    if [[ -n "$response" ]]; then
      break
    fi
    echo "A non-blank answer is required"
  done
}

A: stty sets the terminal modes on the terminal connected to stdin.  If stdin is not a terminal (eg, it's been redirected from a file when running your script), then it will display the error you show
stty -echo turns off echoing of input keystrokes.  Normally when you type in a terminal, the characters you type are echoed back so you can see what you typed.  stty echo turns echoing back on.  The net effect is to disable echoing for the line entered in response to the prompt -- so it will print a prompt and wait for input, (and return the input), but that input will not be visible on the screen.  This is commonly done for entering a password or passphrase.
There are many other terminal modes and settings that can be changed or queried with stty with various arguments.  The manual page (man stty) will give you lots of additional info.

A: Try
$ stty echo < ~/tmp/some.file
stty: standard input: Inappropriate ioctl for device

so, stty expects its standard input to be a terminal.
Therefore, if you run on your terminal
$ stty echo

you will receive no errors.


text:
Q: Changing API version on facebook app dashboard The Facebook app dashboard shows that my graph api is set to version 2.3.
When I load the php sdk, I set the default graph version to 2.4.
My question is how do I get the dashboard to show version 2.4? I am being asked to upgrade to 2.3, and I'm not sure what else I need to do.


text:
Q: Vue router not following children paths I'm having problems to  make my http://localhost:8080/myapps/config route load. If I use http://localhost:8080/myapps everything works ok and I get a list of my apps. But when I want to access an app config through http://localhost:8080/myapps/config it loads the content of /myapps again. However, the url in my browser shows the correct path /myapps/config.
I have been checking the routher for some hours but everything seems to be ok. Could anybody shed some light?
My router file:
import Vue from 'vue'
import Router from 'vue-router'

const MyApps = () => import('../views/app/subviews/MyApps');
const AppKeyValue = () => import('../views/app/subviews/AppKeyValue');

import MainView from '../views/app/MainView'

Vue.use(Router)

export default new Router({
    mode: 'history',
    routes:
    [
        {
            path: '/',
            component: MainView,
            redirect: 'myapps',
            children:
            [
                {
                    path: 'myapps',
                    component: MyApps,
                    meta:
                    {
                        requiresAuth: true,
                        breadcrumb: 'My Apps'
                    },
                    children:
                    [
                        {
                            path: 'config',
                            component: AppKeyValue,
                            meta:
                            {
                                requiresAuth: true,
                                breadcrumb: 'App configuration'
                            }
                        },
                    ]

                },
            ]
        },
    ]
})

Everything works ok if I don't use child routes:
export default new Router({
    mode: 'history',
    routes:
    [
        {
            path: '/',
            component: MainView,
            redirect: 'myapps',
            children:
            [
                {
                    path: 'myapps',
                    component: MyApps,
                    meta:
                    {
                        requiresAuth: true,
                        title: 'message.ecommerce',
                        breadcrumb: 'My Apps'
                    },
                },
                {
                    path: 'myapps/config',
                    component: AppKeyValue,
                    meta:
                    {
                        requiresAuth: true,
                        title: 'message.ecommerce',
                        breadcrumb: 'App configuration'
                    }
                }
           ]
     }
]}

A: You didn't post your *.vue components, but I assume you're missing <router-view> in the second level component.
Example:
MainView is mapped to / and has 1 children route (/myapps). You're probably using <router-view> in your MainView.
MyApps is mapped to myapps as a children of the /-route and has 1 children route (/config).
Add a <router-view to your MyApps.vue to let it display its children (which is just /config in your case).

Similarly, a rendered component can also contain its own, nested <router-view>.

https://router.vuejs.org/guide/essentials/nested-routes.html#nested-routes
BTW: That's also why your second router config is working: The main route has two children (/myapps and /myapps/config), which both get displayed by the MainView's <router-view>.
Here is a working example from the documentation:
https://jsfiddle.net/nazgul_mamasheva/zrcLe9z7/1/


text:
Q: Como executar uma procedure em PHP Estou tentando criar uma listagem e estou tendo problema na hora de chamar a procedure de select.
Código conectando no banco:
<?php
 $conexao = mysql_connect("localhost", "admin", "admin") or print (mysql_error());
 print "Conexão OK!";
 mysql_close($conexao);
 mysql_select_db("des_arcamel", $conexao) or print(mysql_error());

?>

Código PHP
<!DOCTYPE html>

 <?php
 REQUIRE_ONCE "conexao.php";
 REQUIRE_ONCE "funcoes.php";

 echo $result = mysqli_query($conexao, "CALL sp_se_lista") or die("Query fail: " . mysqli_error()); die;
 ?>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

   <title>Estoque</title>

<link href="boostrap/css/bootstrap.min.css" rel="stylesheet">

<link href="boostrap/css/bootstrap-theme.min.css" rel="stylesheet">

    Código Produto
    Descrição
    Preço
    Quantidade Estoque

<?php
while ($row = mysqli_fetch_assoc($result)){

<?php echo $row[cod_produto] ?>
<?php echo $row[dsc_produto] ?>
<?php echo $row[preco_produto] ?>
<?php echo $row[qtd_estoque] ?>

 }

E a procedure no banco
DELIMITER $$

USE `des_arcamel`$$

DROP PROCEDURE IF EXISTS `sp_se_lista`$$

CREATE DEFINER=`admin`@`localhost` PROCEDURE `sp_se_lista`()
 BEGIN

SELECT
cod_produto,
dsc_produto,
preco_produto,
qtd_estoque
FROM
estoque;

END$$

 DELIMITER ;

Alguém consegue ajudar?

Editando:
O problema está na hora de puxar a procedure, editei o código e agora tenho isso:
<?php
REQUIRE_ONCE "conexao.php";
REQUIRE_ONCE "funcoes.php";
$result = "CALL sp_se_lista()";
$rstSql = executeStoredProcedure($result);
while ($rows = mysqli_fetch_assoc($rstSql)){

echo $rows[cod_produto]; ?>

e a função é:
<?php

require_once ("conexao.php");

function executeStoredProcedure($strSql) {
global $conexao;
$rstExe = mysqli_query($conexao, $strSql);

}

Quando dou echo no REQUIRE tb não mostra nada...

A: Pelo que pude observar você está misturando mysql_* na conexão e chamando a query com mysqli_*. O método que você precisa utilizar é basicamente esse:
        //conecta no banco
          $connection = mysqli_connect("localhost", "admin", "admin", "des_arcamel", "3306"); //ou 3307

          //executa o store procedure
          $result = mysqli_query($connection,
             "CALL sp_se_lista();") or die("Erro na query da procedure: " . mysqli_error());

          //lista os resultados
          while ($row = mysqli_fetch_array($result)) {
              echo  $row[0] . "
\n" .
                       $row[1] . "
\n";
          }


text:
Q: How to filter a collection by the same property twice with checkboxes? I'm trying to filter a collection with several checkboxes that use the same property. I can not pass the filter properly. To better explain I send a example a link
Thanks


text:
Q: Build GoogleMaps link dynamically I have a HTML page that uses XSLT:
This is a dynamic list that built with XSLT foreach loop.

{FirstName} {LastName}

        Company: {Company}

        Phone: {Phone}

        Street: {Street}

        City: {City}

        Country: {Country}
        <button class="gm">Google map</button>

I need somehow to add a button or a link to Google maps
var loc = Country + "," + State + ","  + Street;
var addr = "https://maps.googleapis.com/maps/api/staticmap?center=" + loc +
    "&zoom=14&size=288x300&sensor=false";

How can I do that with jQuery? Because the list is dynamic I cannot assign ids.

A: Sounds like you want to use $('selector').each(fn) to iterate over the collapsible divs.
Your function fn(index, element) will then use the element argument (or this) to compute Country etc. for the current div.
Finally, you can use something like the following to add the link:
$(this).append('Google maps');

I'm making some guesses as to the conditions and requirements, so if the above doesn't meet your need, let me know in what ways I've guessed wrong.
Update
An example, in response to comment. I resisted giving an example at first, since I have to guess at the specifics. But with that in mind...
$('div[data-role="collapsible"]').each(function(index, element) {
   // ... your code to extract Country etc. from this or element arg. ...

   var loc = Country + "," + State + ","  + Street;
   var addr = "https://maps.googleapis.com/maps/api/staticmap?center=" +
      loc + "&zoom=14&size=288x300&sensor=false";
   $(this).append('Google maps');
});


text:
Q: Valid update query was not executed in psycopg2 I have a update sql query which to be executed by psycopg2 but it seems that its not working or executed.
I debug the query to be executed using mogrify function.
req = cursor.mogrify(request_update_sql, (status, previous_status, request_id) )

which translates to:
b'UPDATE "TBL_COVER" SET status=\'cancelled\', previous_status=\'pending\', date_updated=current_timestamp WHERE cover_id=\'COVER_00008\''

The function that generates the update sql string:
def update_request_status(has_comments=False, has_approver_id=False):
    str_query = f"UPDATE \"TBL_COVER\" SET status=%s, previous_status=%s, date_updated=current_timestamp WHERE cover_id=%s"
    return str_query

that original code should be like below but I test simple update query to check the bug easier:
def update_request_status(has_comments=False, has_approver_id=False):
    str_query = f"UPDATE \"TBL_COVER\" SET status=%s, previous_status=%s, date_updated=current_timestamp"

    if has_comments:
        str_query += f", comments=%s"
    if has_approver_id:
        str_query += f", approver_id=%s"

    str_query += f" WHERE cover_id=%s"

    return str_query

After execution:
cursor.execute(request_update_sql, (status, previous_status, cover_id) )
I try to display the cursor content, it says "DatabaseError: no results to fetch"
Is there anything wrong that I miss?
Any help is appreciated


text:
Q: How do I set a world background texture in Blender 2.49 using Python? I'm trying to set a background World Texture in Blender 2.49.
I've made a texture:
import Blender
from Blender import *
import bpy

world = World.GetCurrent()
worldTex = Texture.New('worldTex')
worldTex.setType('Image')
worldIm = Image.Load('//blender_scene/tex/bg 001.jpg')
worldIm.source = Image.Sources.SEQUENCE
worldTex.setImage(worldIm)

When I try to apply to the world, that will throw and error, because, by default world.textures contains a tuple of None.
so this wouldn't work:
world.textures[0].tex = worldTex

I've made a material so I can get an MTex instance:
worldMat = Material.New('WorldMat')
worldMat.setTexture(worldTex)

If I try to set the first texture:
world.textures[0] = worldMat.textures[0]

That will throw an error, since I can't assign a value to an already initialized tuple.
If I try to replace it:
world.textures = worldMat.textures

I get yet another error:
TypeError: expected tuple or list containing world MTex objects and NONE

'world MTex' objects got me thinking a bit. Is there another kind of MTex object ? a world MTex ? Where is it defined, how can I create an instance ?
Or as the title states...how do I set a texture to a world ?
Thanks

A: Blender 2.5x has a much better Python API. I really recommend watching this video from PyCon talk by Christopher Webber about it.
Setting texture in 2.5x API :
import bpy
# create new clouds texture
bpy.ops.texture.new()
t = bpy.data.textures[-1]
# set World texture
w = bpy.data.world['World']
slot = w.texture_slots.add()
slot.texture = t
slot.use_map_horizon = True


text:
Q: How to test a Bean with @Validated I would like to test the resilience of a Spring Bean which it loads the configuration from a YML file.
In a test, I load a corrupt configuration in order to test if the annotation @Validated run in the proper way:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ServiceExample.class})
@Category({Fast.class})
@ActiveProfiles("profileWithBadConfiguration")
public class ServiceExampleTest {

@Test(expected=IllegalStateException.class)
public void test1() {

}

}

When I try to test execute the test "test1", the JUnit file crash before executing the first tests. The idea is to detect the IllegalStateException in a Test.
Anyone knows, how to test it?
Technical links:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/annotation/Validated.html
https://docs.spring.io/spring/docs/4.1.x/spring-framework-reference/html/validation.html
Many thanks in advance
Juan Antonio

A: Instead of using Springs test annotations, you could load contexts manually inside the test methods. Examples are given in answers to this question: Use different Spring test context configuration for different test methods


text:
Q: actionHero.js Set Http Header I want to know if there is a way to Set the Http.Header in actionHero.js:
in our server we are working with actionHero.js and Go. I need to send on the "Header" two domain name "client domain & mine(actionHero Service)" to the Go service.
or if there is any other way to do it on the Proxy server
thank you in advance

A: assuming you mean the response header to the client, in your actions or initializers you can do:
data.connection.rawConnection.responseHeaders.push(['x-my-header', 'abc123'])
If you want to set persistent headers that the server responds to all requests with, you can set those in api.config.servers.web.httpHeaders


text:
Q: Multi level push menu Auto expandir menu Tengo este menú y necesito saber de https://github.com/adgsm/multi-level-push-menu, y necesito saber lo siguiente:
Como puedo auto expandir el menú automáticamente al cargar una sección especifica, ejemplo, si estoy en el home y entro en la categoría del menu, Devices->Mobile phones, esto me llevaría a la sección Mobile phones, pero al abrirse no se expande automáticamente, si no que se queda en el inicio.

$(function(){
    $('#menu').multilevelpushmenu({
      collapsed: false,
      menuWidth: '300px',
      mode: 'cover',
      fullCollapse: false,
      swipe: 'both'
    });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://rawgit.com/adgsm/multi-level-push-menu/master/jquery.multilevelpushmenu.css" rel="stylesheet"/>

<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Example</title>

All Categories

                    Devices

Devices

                            Mobile Phones

Mobile Phones

                                    Super Smart Phone

                                    Thin Magic Mobile

                                    Performance Crusher

                                    Futuristic Experience

                            Televisions

Televisions

                                    Flat Super Screen

                                    Gigantic LED

                                    Power Eater

                                    3D Experience

                                    Classic Comfort

                            Cameras

Cameras

                                    Smart Shot

                                    Power Shooter

                                    Easy Photo Maker

                                    Super Pixel

                    Magazines

Magazines

                            National Geographics

                            The Spectator

                            Rambler

                            Physics World

                            The New Scientist

                    Store

Store

                            Clothes

Clothes

                                    Women's Clothing

Women's Clothing

                                            Tops

                                            Dresses

                                            Trousers

                                            Shoes

                                            Sale

                                    Men's Clothing

Men's Clothing

                                            Shirts

                                            Trousers

                                            Shoes

                                            Sale

                            Jewelry

                            Music

                            Grocery

                    Collections

                    Credits

A: Si quieres poner a la derecha el menú que por defecto te lo pone Boostrap es lo más sencillo. Por defecto viene así:

Lo que aquí está ordenando con el mr-auto es que el margen derecho sea automático, es decir que todo se vaya a la izquierda. "mr"= Margin Right (margen derecho).
Entonces si tu escribes:

Le estás ordenando que el menú se vaya a la derecha porque ml-auto = margen izquierdo sea automático. "ml" = Margin Left.
En conclusión, todo es a la inversa: "mr" si deseas el menú a la izquierda y "ml" si deseas el menú a la derecha.


text:
Q: Redirect/hide output of called program This question is pretty easy I guess but I can't figure out, how to do it best. I have a JAR file which I use in my program and basically I just call the main() method of one of the classes in this JAR file.
The problem is, that I don't want to have the output of this method on my program's output - it should be hidden.
I call the method just that way:
Main.main(new String[] {"some-arg1", "arg2", "some-argument3"});
Is there any possibility to hide/redirect the output of this method? Can I just set a new temporary stdout or something like that?
Any help is greatly appreciated. Thanks in advance!

A: You can use System.setOut() to redirect stdout. You can also close System.out completely if you want to.


text:
Q: $\int \cos(x) \ln(x) dx$, elementary function? My course book bluntly mentions (freely translation without any proof):

Integral functions with the terms $x^{\alpha} \sin(\beta x)$, $x^{\alpha} \cos(\beta x)$ or $x^{\alpha}e^{\beta x}$ ($\alpha, \beta\in \mathbb R$) are elementary if $\beta=0$ or
  $\alpha\in \mathbb N\cup{0}$.

Unfortunately, I cannot express the function $\int \cos(x) \ln(x) dx$ in any of the forms -- I always get three terms. Is there some elegant way to know whether some function is elementary, not just looking at some constants of certain functions? Could someone explain why the functions in the forms are elementary by which theorems?
References

*

*I am doing the book alone here, ex. 5 on page 529 for future readers (sorry not English book).

A: Integrating by parts:
$$
  \int \cos(x) \ln(x) \mathrm{d} x = \int \ln(x) \mathrm{d} (\sin(x)) = \sin(x) \ln(x) - \int \frac{\sin(x)}{x} \mathrm{d} x
$$
The integral $\int \frac{\sin(x)}{x} \mathrm{d} x$ is known to be non-elementary.

A: Concerning the last question, if $\beta=0$ then the integrand is just $x^{\alpha}$, which I trust you can integrate. Similarly, if $\alpha=0$ then the integrations are not hard. If $\alpha$ is a positive integer, then you can use integration by parts to reduce the exponent on $x$ by one; repeated application brings the exponent down to zero, and the previous sentence applies.


text:
Q: How do I get the values from an arbitrary number of checkboxes? (tkinter, python) I'm currently trying to create n number of checkboxes from n number of sheets in an excel workbook to choose whether or not to use corresponding sheets.
I am having difficulty with accessing the state of each checkbox since it seems like I need a variable predefined for each checkbox's 'variable' to draw the state of the checkbox from. Upon looking for how to create a list of new variables through for loops I have found that this is very bad practice and should not be done because analogous results can be found from using dictionaries.
import openpyxl;
import pandas;
import string;
from openpyxl import Workbook;
from tkinter import *
from tkinter import ttk
from tkinter import filedialog as fd
from tkinter.messagebox import showinfo
from tkinter import font as tkFont

root=Tk()
root.configure(background='black')
style=ttk.Style()
style.theme_use('clam')
masterlst=[]
def selector():
    for i in vardict:
        print(i.get())

wb = openpyxl.load_workbook('Python Test.xlsx');
def choose_sheets(workbook):
    global w
    w=Frame(root,background='black')
    global lst2
    lst2=[]*len(workbook.sheetnames)
    w.pack()
    lst=[]
    global vardict
    vardict={}
    dictvar={}
    for i in range(len(workbook.sheetnames)):
        dictvar['var '+str(i)]=0
    for i in range(len(workbook.sheetnames)):
        vardict['var '+str(i)]=IntVar
    for i,j,k in zip(workbook.sheetnames,vardict,range(len(workbook.sheetnames))):
        j=j
        dictvar['var '+str(k)] = Checkbutton(w, text=str(i),background='black',foreground='white',activebackground='black',activeforeground='white',selectcolor='gray',command=selector,offvalue=0,onvalue=1,variable=vardict[j])
    for i,j in zip(dictvar,range(len(workbook.sheetnames))):
        dictvar[i].pack()

print(masterlst)

I cannot seem to figure out how to do this properly as when running the below code I get the error:
AttributeError: 'str' object has no attribute 'get'
which makes sense considering how I would require a variable to obtain this. I tried lists as well but cannot find a way to access the state of each widget without setting a predefined variable for the state of each widget, something I cannot do for n number of sheets in an excel file unless I decide to create a set number of variables beforehand. Please let me know if there are any workarounds to obtaining the state of each checkbox widget.

A: Thank you @Tim Roberts and @acw1668, both of your solutions have solved my issue and I am now able to get the checkbox states for n number of checkboxes! For anyone that would like to see what the corrected code looks like:
import openpyxl;
import pandas;
import string;
from openpyxl import Workbook;
from tkinter import *
from tkinter import ttk
from tkinter import filedialog as fd
from tkinter.messagebox import showinfo
from tkinter import font as tkFont

root=Tk()
root.configure(background='black')
style=ttk.Style()
style.theme_use('clam')
masterlst=[]
def selector():
    for i in vardict.values():
        print(i.get())

wb = openpyxl.load_workbook('Python Test.xlsx');
def choose_sheets(workbook):
    global w
    w=Frame(root,background='black')
    global lst2
    lst2=[]*len(workbook.sheetnames)
    w.pack()
    lst=[]
    global vardict
    vardict={}
    dictvar={}
    for i in range(len(workbook.sheetnames)):
        dictvar['var '+str(i)]=0
    for i in range(len(workbook.sheetnames)):
        vardict['var '+str(i)]=IntVar()
    for i,j,k in zip(workbook.sheetnames,vardict,range(len(workbook.sheetnames))):
        j=j
        dictvar['var '+str(k)] = Checkbutton(w, text=str(i),background='black',foreground='white',activebackground='black',activeforeground='white',selectcolor='gray',command=selector,offvalue=0,onvalue=1,variable=vardict[j])
    for i,j in zip(dictvar,range(len(workbook.sheetnames))):
        dictvar[i].pack()

print(masterlst)

choose_sheets(wb)

root.mainloop()


text:
Q: How to compare value in Pandas DataFrame against a value in the previous row AND the previous column? I have a dataframe consisting of two columns filled with float values. I need to calculate all the values of 'h' minus all the values of 'c', at the index previous to the current 'h' value.
So for instance, for 'h' in row 1, I need to calculate 1.17322 - 1.17285 (the value of 'c' in the previous row)
I have tried several different methods to accomplish this, including the use of: .iloc, .shift(), .groupby(), and .diff(), but I cannot get exactly what I'm looking for.
If anybody could help, it would be greatly appreciated
    c        h
0   1.17285  1.17310
1   1.17287  1.17322
2   1.17298  1.17340
3   1.17346  1.17348
4   1.17478  1.17511
5   1.17595  1.17700
6   1.17508  1.17633
7   1.17474  1.17545
8   1.17463  1.17546
9   1.17224  1.17468
10  1.17437  1.17456
11  1.17552  1.17641
12  1.17750  1.17784
13  1.17694  1.17770

A: Try this using shift, for as an example:
df['c_shift'] = df['c'].shift()
df['diff'] = df['h'] - df['c_shift']
print(df)

Output:
          c        h  c_shift     diff
0   1.17285  1.17310      NaN      NaN
1   1.17287  1.17322  1.17285  0.00037
2   1.17298  1.17340  1.17287  0.00053
3   1.17346  1.17348  1.17298  0.00050
4   1.17478  1.17511  1.17346  0.00165
5   1.17595  1.17700  1.17478  0.00222
6   1.17508  1.17633  1.17595  0.00038
7   1.17474  1.17545  1.17508  0.00037
8   1.17463  1.17546  1.17474  0.00072
9   1.17224  1.17468  1.17463  0.00005
10  1.17437  1.17456  1.17224  0.00232
11  1.17552  1.17641  1.17437  0.00204
12  1.17750  1.17784  1.17552  0.00232
13  1.17694  1.17770  1.17750  0.00020

Of course, you can do this in one step:
df['diff'] = df['h'] - df['c'].shift()


text:
Q: Unable to get fseek to work with fgetc in c I am trying to write a brainfuck interpreter in c but I can not get fseek to work. I'm not sure what I'm doing wrong and I would prefer to keep using fseek if possible. I am using fgetc to check for each brainfuck character individually and x to hold the value of fgetc. Here is the code:
#include <stdio.h>

main(int argc, char *argv[]){

argc--; argv++;

char array[3000];
char *program = array;
int yo = 0;
fpos_t pos;

FILE *fp;

if(*argv != NULL){
    fp = fopen(*argv,"rb");

    int x;
    int z = 1;

    while(z){

        x = fgetc(fp);

        if(x == 62){
            ++program;
        }else if(x == 60){
            --program;
        }else if(x == 43){
            ++*program;
        }else if(x == 45){
            --*program;
        }else if(x == 46){
            putchar(*program);
        }else if(x == 44){
            *program=getchar();
        }else if(x == 93){
            if(*program != 0){
                int yo = 1;
                while(yo){
                    fseek(fp, -1, SEEK_CUR);
                    if(fgetc(x) == 93){
                        putchar(93);
                        yo++;
                    }else if(fgetc(x) == 91){
                        putchar(91);
                        yo--;
                    }
                }
            }
        }else if(x == EOF){
            break;
        }

    }

    fclose(fp);
}else{
    printf("Error: no input file.\n");
}

return 0;

}

A: Here is working code (it is clear so comment will be redundant):
#include <stdio.h>

int main(){

char array[3000];
char *program = array;

FILE *fp = NULL;
fp = fopen("hi.txt","rb");

if ( fp == NULL)
    printf("Error: no input file.\n");

int x = 0;
int size;

while(1){
    char c = fgetc(fp);
fseek(fp, 0L, SEEK_END);
size = ftell(fp);
fseek(fp, 0L, SEEK_SET);
char j[size];
fscanf(fp, "%s", j);

if(j[x] == 62){
        ++program;
    } else if(j[x] == 60){
          --program;
    } else if(j[x] == 43){
              ++*program;
    } else if(j[x] == 45){
                  --*program;
    } else if(j[x] == 46){
                  putchar(*program);
    } else if(j[x] == 44){
          *program=getchar();
    } else if(j[x] == 93){
           if(*program != 0){
               int yo = 1;
               while(yo){
                   x--;
                   if(j[x] == 93)
                       yo++;
                   else if(j[x] == 91)
                            yo--;
                   if(yo == 0)
                       break;
               }
           }
      }  else if(j[x] == EOF){
            break;
         }
    x++;
    }

    fclose(fp);

return 0;
}

A: when you call fgetc(fp) it reads a character AND ADVANCES THE CURRENT POINTER, so the next read will read the next character.  So when you do:
while(yo) {
    fseek(fp, -1, SEEK_CUR);
    if(fgetc(fp) == 93) {
        putchar(93);
        yo++; }

you back up a character, then read the character you just backed up over, advancing past it.  So you end up looping, reading the exact same character forever, at least until yo overflows and wraps back around to 0 (which may never happen as integer overflow is undefined in C).
You probably actually want fseek(fp, -2, SEEK_CUR) to back up to the character BEFORE the last one read.