text:
Q: How to retrieve max (pk) in python from a table database? Okay it may sound stupid, I am very new to django and database.
What I'm trying to do it delete multiple entries from a database through a template.
Here is my view.py
def names(request):
    e = Clash.objects.all()
    for z in range(0 ,100): ##### need to change this 100 to max(pk)######
        if request.POST.get('check'+str(z), False):
            to_delete = Clash.objects.get(pk=z)
            print (to_delete)
            to_delete.delete()

    return render_to_response("names.html", locals() , context_instance = RequestContext(request))

Clash is my model, and here is the template I am deleting from:
<form method='POST' action=''>
       {% csrf_token %}
    {% for l in e %}

{{l.name }}

    {{l.second_name}}

    <input type='checkbox' id="check{{l.id}}" name="check{{l.id}}"/>

    {% endfor %}

    <input type='submit' value='Delete Selected'/>

</form>

How do I retrieve the max pk from the table? and place it in place of "100":
PS : I know the name and id are same of check-boxes (that don't matter)
PSS: This code works, I am able to delete multiple entries, but this is not good programming. How do I improve it ?

A: Anentropic has pointed out the correct way to loop through things in Python: ie iterate over the list itself, not a range of numbers.
However this is still massively inefficient. What happens if you have a million rows in your database? You really don't want to iterate at all. Instead, you just need to ask the database directly to delete the rows you want.
In your template, change the checkbox so that it puts all the values in the same parameter:
<input type='checkbox' name="to_delete" value="{{l.id}}"/>

And now in your view, just get that list of values and delete it:
def names(request):
    to_delete = request.POST.getlist('to_delete')
    if to_delete:
        Clash.objects.filter(pk__in=to_delete).delete()

    return render_to_response("names.html", locals() , context_instance = RequestContext(request))

A: you don't do it like this:
e = Clash.objects.all()
for z in range(0 ,100): ##### need to change this 100 to max(pk)######

instead you can just iterate over the queryset directly:
for obj in Clash.objects.all():

this also means you also don't need to do this extra query on each iteration of the loop:
to_delete = Clash.objects.get(pk=z)

...because you already have that object loaded from the db, as obj.
So you can do:
def names(request):
    for obj in Clash.objects.all():
        if request.POST.get('check'+str(obj.id), False):
            print obj
            obj.delete()
    return render_to_response("names.html", locals() , context_instance=RequestContext(request))

A: You can do like this:
last_item_pk = Clash.objects.last().pk

Check here for details:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#last


text:
Q: A question about validation process in PyTorch: val_loss lower than train_loss Is it possible that running my deep-learning, at some point during training it happens that my validation loss becomes lower than my training loss? I'm attaching my code for the training process:
def train_model(model, train_loader,val_loader,lr):

    "Model training"

    epochs=100

    model.train()

    train_losses = []

    val_losses = []

    criterion = nn.MSELoss()

    optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=1e-5)

    #Reduce learning rate if no improvement is observed after 10 Epochs.

    scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', patience=2, verbose=True)

    for epoch in range(epochs):

        for data in train_loader:

            y_pred = model.forward(data)

            loss1 = criterion(y_pred[:, 0], data.y[0])

            loss2 = criterion(y_pred[:,1], data.y[1])

            train_loss = 0.8*loss1+0.2*loss2

            optimizer.zero_grad()

            train_loss.backward()

            optimizer.step()

        train_losses.append(train_loss.detach().numpy())

        with torch.no_grad():

            for data in val_loader:

                y_val = model.forward(data)

                loss1 = criterion(y_val[:,0], data.y[0])

                loss2 = criterion(y_val[:,1], data.y[1])

                val_loss = 0.8*loss1+0.2*loss2

            #scheduler.step(loss)

        val_losses.append(val_loss.detach().numpy())

        print(f'Epoch: {epoch}, train_loss: {train_losses[epoch]:.3f} , val_loss: {val_losses[epoch]:.3f}')

    return train_losses, val_losses

It is a multi-task model where I compute separately the two losses and then consider a weighted sum.
What I'm not sure about is the indentation of val_loss that may cause some issues when printing out. In general I would say that I have some perplexities about validation:
1)First I pass all the batches that I have in my train_loader and adjust the training loss.
2)Then, I start iterating over my val_loader to make predictions on single batches of unseen data, but what I append in the val_losses list is the validation loss computed by the model on the last batch inside val_loader. I'm not sure if this is correct.
I'm attaching the printed train and val losses during training:
Epoch: 0, train_loss: 7.315 , val_loss: 7.027
Epoch: 1, train_loss: 7.227 , val_loss: 6.943
Epoch: 2, train_loss: 7.129 , val_loss: 6.847
Epoch: 3, train_loss: 7.021 , val_loss: 6.741
Epoch: 4, train_loss: 6.901 , val_loss: 6.624
Epoch: 5, train_loss: 6.769 , val_loss: 6.493
Epoch: 6, train_loss: 6.620 , val_loss: 6.347
Epoch: 7, train_loss: 6.452 , val_loss: 6.182
Epoch: 8, train_loss: 6.263 , val_loss: 5.996
Epoch: 9, train_loss: 6.051 , val_loss: 5.788
Epoch: 10, train_loss: 5.814 , val_loss: 5.555
Epoch: 11, train_loss: 5.552 , val_loss: 5.298
Epoch: 12, train_loss: 5.270 , val_loss: 5.022
Epoch: 13, train_loss: 4.972 , val_loss: 4.731
Epoch: 14, train_loss: 4.666 , val_loss: 4.431
Epoch: 15, train_loss: 4.357 , val_loss: 4.129
Epoch: 16, train_loss: 4.049 , val_loss: 3.828
Epoch: 17, train_loss: 3.752 , val_loss: 3.539
Epoch: 18, train_loss: 3.474 , val_loss: 3.269
Epoch: 19, train_loss: 3.220 , val_loss: 3.023
Epoch: 20, train_loss: 2.992 , val_loss: 2.803
Epoch: 21, train_loss: 2.793 , val_loss: 2.613
Epoch: 22, train_loss: 2.626 , val_loss: 2.453
Epoch: 23, train_loss: 2.488 , val_loss: 2.323
Epoch: 24, train_loss: 2.378 , val_loss: 2.220
Epoch: 25, train_loss: 2.290 , val_loss: 2.140
Epoch: 26, train_loss: 2.221 , val_loss: 2.078
Epoch: 27, train_loss: 2.166 , val_loss: 2.029
Epoch: 28, train_loss: 2.121 , val_loss: 1.991
Epoch: 29, train_loss: 2.084 , val_loss: 1.959
Epoch: 30, train_loss: 2.051 , val_loss: 1.932
Epoch: 31, train_loss: 2.022 , val_loss: 1.909
Epoch: 32, train_loss: 1.995 , val_loss: 1.887
Epoch: 33, train_loss: 1.970 , val_loss: 1.867
Epoch: 34, train_loss: 1.947 , val_loss: 1.849
Epoch: 35, train_loss: 1.924 , val_loss: 1.831
Epoch: 36, train_loss: 1.902 , val_loss: 1.815
Epoch: 37, train_loss: 1.880 , val_loss: 1.799
Epoch: 38, train_loss: 1.859 , val_loss: 1.783
Epoch: 39, train_loss: 1.839 , val_loss: 1.769
Epoch: 40, train_loss: 1.820 , val_loss: 1.755
Epoch: 41, train_loss: 1.800 , val_loss: 1.742
Epoch: 42, train_loss: 1.781 , val_loss: 1.730
Epoch: 43, train_loss: 1.763 , val_loss: 1.717
Epoch: 44, train_loss: 1.744 , val_loss: 1.705
Epoch: 45, train_loss: 1.726 , val_loss: 1.694
Epoch: 46, train_loss: 1.708 , val_loss: 1.683

...

So I have the suspect that I'm messing up with indentation..

A: Validation loss can be lower than the training loss.
As you mentioned in point 2, you are only storing/appending the train and validation loss on the last batch. This may not be what you want, and you may want to store the training loss at each iteration and look at its average value at the end. That would give you a better idea of training progress as that would be the loss on the whole data and single batch

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to test IP-based geolocation (need to test various US states, not just lower 48) We are looking at implementing an IP-based geolocation service.
At this point, it looks like we'll be using a 3rd party DB, MaxMind's GeoIP2 Enterprise (https://www.maxmind.com/en/geoip2-enterprise-database) and a webservice.
We only need to geolocate by US state (and not just lower 48).
What is going to be the easiest way to test this from various states within the US?  Developers are going to need to test as well as non-developers, i.e., marketing types.
Are there any 3rd party, web-based solutions we could subscribe to?  I found one that took screenshots (https://www.geoscreenshot.com/capture), but I think we're going to need the ability (for marketing) to interact/navigate around. Something where you just enter an url and then it proxies that through an iframe might be ideal. I'm just wondering how non-developers can easily test IP-based geolocation.

A: You can test the geolocation from multiple country using http://www.locabrowser.com.
The pro is this web site is free service to test from 15 countries without any setup required.
The con is it does not has different states in United States at this moment.


text:
Q: When i used RelativeLayout addview in Android, the view is extrusion.How can i do it? When I use addView in RelativeLayout like this:
for (BigClicleTagInfoBean info : bean.tags) {
            BigClicleTagView tagView = null;
            boolean isLeftTag = info.isLeftDirection();
            if(isLeftTag) {
                tagView = new BigClicleTagLeftView(this.getContext(), null);
            } else {
                tagView = new BigClicleTagRightView(this.getContext(), null);
            }
            tagView.setData(info);
            tagView.setTagViewListener(this);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

            int marginLeft = 0;
            int marginRight = 0;
            int marginTop = (int)(info.pos_y * pictureHeight) + 10;

            if(isLeftTag) {
                marginLeft = (int) (info.pos_x * Global.widthPixels);
            } else {
                marginRight = (int) ((1 - info.pos_x) * Global.widthPixels);
            }

            params.setMargins(marginLeft, marginTop, marginRight, 0);
            imageRootRL.addView(tagView, params);
            tagViews.add(tagView);
        }

I want photo tag will show intact,but at view border will extruding.
Please help me,Thx


text:
Q: View in the design editor of android studio 2.3.3 I am trying to follow the tutorial of android studio in the android official website. during the time to review View in the android, I found that I have some difficult to enable view in the design editor of android studio 2.3.3.
I only can find view > Tool Windows > Preview. but it is disabled.
How to see the margin value in dp to the top or left of layout for text box added?


text:
Q: Conda ImporrtError whenever I open a new terminal [Edit] Added conda info to question.
Something wrong is happening with my conda setup.
From what I remember, I needed the AI gym library for a lab at my university.
I tried to install it using conda install -c akode gym and I was unable to do so. I used a pip install instead.
Since then, I am having the following error whenever I start a new terminal:
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
ImportError: No module named conda

Conda and all the related software and packages work very fine though.
This is my OS config :
NAME="Ubuntu"
VERSION="18.04.3 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.3 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic

This is the output of conda info :
     active environment : base
    active env location : /home/cnemri/anaconda3
            shell level : 1
       user config file : /home/cnemri/.condarc
 populated config files :
          conda version : 4.8.0
    conda-build version : 3.18.11
         python version : 3.7.5.final.0
       virtual packages : __glibc=2.27
       base environment : /home/cnemri/anaconda3  (writable)
           channel URLs : https://repo.anaconda.com/pkgs/main/linux-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/linux-64
                          https://repo.anaconda.com/pkgs/r/noarch
          package cache : /home/cnemri/anaconda3/pkgs
                          /home/cnemri/.conda/pkgs
       envs directories : /home/cnemri/anaconda3/envs
                          /home/cnemri/.conda/envs
               platform : linux-64
             user-agent : conda/4.8.0 requests/2.22.0 CPython/3.7.5 Linux/4.15.0-1065-oem ubuntu/18.04.3 glibc/2.27
                UID:GID : 1001:1001
             netrc file : None
           offline mode : False

How can I not have this error anymore ?
Thank you.

A: The error has been fixed, I did a conda update conda as advised by @merv and it works very fine. The error disappeared.


text:
Q: SQL: Join/union of two tables, on multiple conditions Provided the following structure and data:
CREATE TABLE "CHANGES" (
  "ID" NUMBER(38),
  "LAST_UPD_DATE" DATE DEFAULT SYSDATE
);

CREATE TABLE "EXPORT_LOG" (
  "ID" NUMBER(38),
  "LAST_EXPORT" DATE DEFAULT SYSDATE
);

Table CHANGES contains:
----------------------------
| ID  |  LAST_UPD_DATE     |
----------------------------
| 123 | 12-MAY-16 12.23.23 |
| 124 | 12-MAY-16 12.24.23 |
| 125 | 12-MAY-16 12.11.23 |
----------------------------

and EXPORT_LOG
----------------------------
| ID  |  LAST_EXPORT       |
----------------------------
| 124 | 12-MAY-16 12.23.12 |
| 125 | 12-MAY-16 12.12.24 |
----------------------------

I need to get the records in CHANGES that either don't exist in EXPORT_LOG or, if exists, get records with LAST_UPD_DATE later than LAST_EXPORT.
So in the above example, I should be getting 123 and 124.
I'm trying different JOINs but I cannot seem to get the result I want:
INNER JOIN is used for intersections, LEFT JOIN gets ALL of first table, but only those of second table that match a condition you set - none of these is what I want. So is the solution some sort of UNION?

A: Try this:
SELECT t1.*
FROM CHANGES AS t1
LEFT JOIN EXPORT_LOG AS t2 ON t1.ID = t2.ID
WHERE (t2.ID IS NULL) OR (t1.LAST_UPD_DATE > t2.LAST_EXPORT)

This will return all records of CHANGES table that don't have a match in EXPORT_LOG table plus the records of CHANGES table that have a LAST_UPD_DATE that is later than LAST_EXPORT.

A: One method is to translate the conditions directly using exists:
select c.*
from changes c
where not exists (select 1 from export_log el where c.id = el.id) or
      not exists (select 1 from export_log el where c.id = el.id and el.last_export > c.last_upd_date);

This can be simplified to:
select c.*
from changes c
where not exists (select 1 from export_log el where c.id = el.id and el.last_export > c.last_upd_date);

A: Please use the below mentioned code and provide me the feedback. It should work as per your requirement.

SELECT CH.ID, CH.LAST_UPD_DATE
FROM CHANGES CH, EXPORT_LOG EL
WHERE CH.ID = EL.ID(+)
AND ((EL.ID IS NULL) OR (CH.LAST_UPD_DATE > EL.LAST_EXPORT));


text:
Q: 20.04 Black screen, no desktop session, org.gnome.keyring.systempropter issue My 20.04 install is suddently not booting into gnome.  It just boots to the dreaded black screen with a blinking cursor.  I can ctrl-alt-F* my way into a virtual console, but that's it.
journalctl -xe produces the following:
Jan 17 15:01:32 Desktop dbus-daemon[1477]: [session uid=1000 pid=1477] Activating service name='org.freedesktop.secrets' requested by ':1.9' (uid=1000 pid=1528 comm="/usr/libexec/goa-daemon " label="unconfined")
Jan 17 15:01:32 Desktop gnome-keyring-daemon[1566]: couldn't access control socket: /run/user/1000/keyring/control: No such file or directory
Jan 17 15:01:32 Desktop gnome-keyring-d[1566]: couldn't access control socket: /run/user/1000/keyring/control: No such file or directory
Jan 17 15:01:32 Desktop dbus-daemon[1477]: [session uid=1000 pid=1477] Successfully activated service 'org.freedesktop.secrets'
Jan 17 15:01:32 Desktop dbus-daemon[1477]: [session uid=1000 pid=1477] Activating service name='org.gnome.keyring.SystemPrompter' requested by ':1.15' (uid=1000 pid=1566 comm="/usr/bin/gnome-keyring-daemon --start --foreground" label="unconfined")
Jan 17 15:01:32 Desktop org.gnome.keyring.SystemPrompter[1573]: Unable to init server: Could not connect: Connection refused
Jan 17 15:01:32 Desktop gcr-prompter[1573]: cannot open display:
Jan 17 15:01:32 Desktop dbus-daemon[1477]: [session uid=1000 pid=1477] Activated service 'org.gnome.keyring.SystemPrompter' failed: Process org.gnome.keyring.SystemPrompter exited with status 1
Jan 17 15:01:32 Desktop gnome-keyring-daemon[1566]: couldn't create system prompt: GDBus.Error:org.freedesktop.DBus.Error.Spawn.ChildExited: Process org.gnome.keyring.SystemPrompter exited with status 1
Jan 17 15:01:32 Desktop gnome-keyring-d[1566]: couldn't create system prompt: GDBus.Error:org.freedesktop.DBus.Error.Spawn.ChildExited: Process org.gnome.keyring.SystemPrompter exited with status 1
Jan 17 15:01:32 Desktop goa-daemon[1528]: secret_password_lookup_sync() returned NULL
Jan 17 15:01:32 Desktop goa-daemon[1528]: /org/gnome/OnlineAccounts/Accounts/account_1598527013_0: Setting AttentionNeeded to TRUE because EnsureCredentials() failed with: No credentials found in the keyring (goa-error-quark, 4)
Jan 17 15:01:42 Desktop systemd[1465]: tracker-extract.service: Succeeded.
-- Subject: Unit succeeded
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- The unit UNIT has successfully entered the 'dead' state.
Jan 17 15:01:56 Desktop pulseaudio[1471]: GetManagedObjects() failed: org.freedesktop.DBus.Error.NoReply: Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.
Jan 17 15:01:56 Desktop dbus-daemon[607]: [system] Failed to activate service 'org.bluez': timed out (service_start_timeout=25000ms)
Jan 17 15:02:04 Desktop tracker-store[1554]: OK
Jan 17 15:02:04 Desktop systemd[1465]: tracker-store.service: Succeeded.
-- Subject: Unit succeeded
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- The unit UNIT has successfully entered the 'dead' state.

I've found some ideas for resolving this in the Arch boards, but that's it.  Any ideas are appreciated.
Thanks!

A: This is also happening to me. I was trying to resolve unwanted printers constantly loading. After stopping the services related to that issue, I rebooted and got the dreaded black screen.
After 4 hours of searching and trying a lot of things, including the above boot repair, I ended up looking at my video drivers. At the command prompt, I entered

sudo apt remove nvidia-340

I rebooted after this and it booted to my desktop environment.
Not sure if this will help you or not, but it did work for me.

A: Do you have an external Ubuntu installation USB? If so, boot into the USB, and select Try Ubuntu. This will create a temporary Ubuntu session. You can now try the following:

*

*Install Boot-Repair to another USB, like explained here: https://help.ubuntu.com/community/Boot-Repair and then try to run this to repair your current system.

or

*Mount the disk where your Ubuntu is installed when running the live USB version and repair it from the command line.

It will be like running a working Ubuntu, where you can download and install all the application you need in order to have full access to repair your main installation.
I suggest you grab the files that are important to you from the main disk via the USB try version and back them up to a third USB before you attempt to repair or otherwise configure and modify the main disk.


text:
Q: How to filter an object with children I have an object retrieved using AJAX. The AJAX will return an object with unlimited nodes and each node can have his own children. I would like to filter this object by Title, so I can get only the title projects.
My idea is, if I have any title: 'project' in the response I do one thing if not I do another thing.
With the snippet below how could I get this multilevel object and filter it? I tried with filter but it didn't work. I was trying to get grep working, but I must be doing something wrong, because it also doesn't work. I am open for ES5/ES6 and TS solutions.

$.mockjax({
  url: '/node/initdata',
  responseTime: 100,
  contentType: 'application/json',
  responseText: {
    "id": "33",
    "collapsed": false,
    "name": "Plan",
    "title": "BusinessPlan",
    "children": [{
      "id": "266",
      "collapsed": false,
      "name": "addd",
      "title": "BusinessPlanObjGoal",
      "children": [{
        "id": "65",
        "collapsed": false,
        "name": "Adding information ",
        "title": "Kpi",
        "children": [],
        "due": 7
      }, {
        "id": "99",
        "collapsed": false,
        "name": "addd",
        "title": "Project",
        "children": []
      }]
    }, {
      "id": "267",
      "collapsed": false,
      "name": "adddasdas",
      "title": "BusinessPlanObjGoal",
      "children": [{
        "id": "55",
        "collapsed": false,
        "name": "Adding new item",
        "title": "Kpi",
        "children": [],
      }]
    }, {
      "id": "268",
      "collapsed": false,
      "name": "plan 2",
      "title": "BusinessPlanObjGoal",
      "children": [{
        "id": "299",
        "collapsed": false,
        "name": "Teste Gui",
        "title": "BusinessPlanObjGoal",
        "children": []
      }]
    }]
  }
});

$.ajax({
  url: '/node/initdata',
  type: 'GET',
  dataType: 'json',
  statusCode: {
    400: function() {
      alert('Wrong Format!!!');
    }
  },
  complete: function(data, status) {
    jsonData = data.responseJSON;
    console.log(jsonData);
    /*
    dt = cdt.filter(function (entry){
      return entry.title==='department manager';
    });
    console.log(dt);
    */
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.6.2/jquery.mockjax.min.js"></script>


text:
Q: MKMarkerAnnotationView title is not showing Why MKMarkerAnnotationView title is getting disappearing. Some times title is appearing when we rotate map. How to make MKMarkerAnnotationView title should always visible.

A: MKMarkerAnnotationView has a property titleVisibility  that can be set to one of the values
.adaptive
.hidden
.visible

.adaptive renders the title when there is space to do so, which is the default behaviour. If you want to see it always, set it to .visible.


text:
Q: JS cannot parse JSON with unicode character I have the following JSON string {"name":""C\u008cUR Carmen"} but \u008c is not parsed. It shows empty character instead.
json = '{"name":"C\u008cUR Carmen"}';
json = JSON && JSON.parse(json) || $.parseJSON(json);

Show : CUR Carmen
Expect : CŒUR Carmen
Please help.
* Note * : The JSON data is returned by the PHP server so there shouldn't be any syntax error because I used json_encode and get the response from AJAX. It works with other characters such as à, é but only this wierd character doesn't display properly
EDIT : Solved! It's not a JS problem it's a charset problem returned by MySQL. You can use mysql_set_charset('utf8') before returning SQL data. Show \u0152 as expected

A: There's no need to escape an unicode character stated in RFC 4627

2.5.  Strings
The representation of strings is similar to conventions used in the C
  family of programming languages.  A string begins and ends with
     quotation marks.  All Unicode characters may be placed within the
     quotation marks except for the characters that must be escaped:
     quotation mark, reverse solidus, and the control characters (U+0000
     through U+001F).

You can use your unicode string directly:
json = '{"name":"CŒUR Carmen"}';
json = JSON && JSON.parse(json) || $.parseJSON(json);

I think there's a transcoding bug in your server side implementation where you change the output to ASCII before using json_encode. It is a requirement of JSON that all data is encoded in Unicode.
Edit
In this fiddle there's an example how to revert the escaped unicode in javascript.

A: You need to escape your " and escape the \:
json = '{"name":""C\u008cUR Carmen"}';

should be
json = '{"name":"\\"C\\u008cUR Carmen"}';

If the 4th " is just a typing an error, just escape the \ that:
json = '{"name":"C\\u008cUR Carmen"}';


text:
Q: finding time complexity of an algorithm I am trying to find big Theta of the following code:
k=0,x=0,y=0
for i=1 to 2n do:
    for j=0 to i^2 do:
        k+=1
    t=k
    while t>=0 do:
        ...(O(1) operations)
        t=t-0.5

I understand that the first loop always runs at O(n)
the second one is at most O((2n)^2) - when i=2n.
and that the while runs 2n^2 ( is this correct?)
so my calculation is : T(n) = O(n)*(O(n^2)+O(n^2)) = O(n^3)
I am not sure whether I am correct and how can I find now the big Omega - to show it is equal to the Big O.

A: You can analyze the T(N) function. (For now I ignore the while t>=0... to be clearer)
We consider as the main operation this one: k+=1 and we count how many times it is done. In math:
T(n) =

=

=

And this is a polynomial function which is  because we can find constants in order that the function is greater than n^3 and find others in order that is smaller than n^3.
Considering the while t>=0 won't change the final result because it modifies only the constant factors


text:
Q: Rspec rubocop error `prefer using verifying doubles over normal doubles` I've a RSpec test
let(:mail_instance) { double(deliver_later: nil) }

before do
  allow(ConfirmationMailer).to receive(:send_email).and_return(mail_instance)
  allow(mail_instance).to receive(:deliver_later)
end

it 'calls mailer, and delivers the mail' do
  call_endpoint
  expect(mail_instance).to have_received(:deliver_later)
end

And it works well but I've got rubocop error - prefer using verifying doubles over normal doubles. According to docs https://www.rubydoc.info/gems/rubocop-rspec/1.7.0/RuboCop/Cop/RSpec/VerifiedDoubles I should use instance_double instead but if I change it my specs will we falls with an error:

ArgumentError:
         Module or String expected, got {:deliver_later=>nil}

A: You need to pass the class you're stubbing to the instance_double:
let(:mail_instance) { instance_double(ActionMailer::MessageDelivery, deliver_later: nil) }

A: The idea it's that you should use instance_double, but I guess that it's important to understand why Rubocop says that.
The main difference between doubles and instance_doubles is
If we try to use/call a method which is NOT implemented by the class of the mocked instance, it will raise an exception. If we decide to use mock objects in our tests, instance_doubles provides us with a bit more confidence in our tests than if we were using spies or regular doubles.
So if in the future someone rename or delete that method, if you use double you probably never know and your will pass, but if you use instance_doubles you will be notified.
Obiously there is a slightly performance trade-off between both, but in 99% of the time for me it's better to use instance_doubles


text:
Q: How to set a Sprite to a specific Frame in Godot I have the Player move around and when he enters a new Room (via Instancing) his Sprite shows him facing in the Default direction (in my Case down). So If you enter a Room from any other direction then it looks weird, cause for a short Moment you can see the Player facing down even if you came from the right. How can I tell Godot to set the Player Sprite to a specific Frame in Code, so I can set it to the proper Frame for each Direction. I'm new to Godot and I used HeartBeast Action RPG Tutorial for my Movement. So it's using an AnimationTree and AnimationPlayer. I tried "set_frame" but Godot just says it doesn't know the Method.

A: If you are following the tutorial series I think you are following (Godot Action RPG)… You are using an AnimationTree with AnimationNodeBlendSpace2D (BlendSpace2D).
The BlendSpace2D picks an animation based on an input vector "blend_position". This way you can use BlendSpace2D to pick an animation based on the direction of motion or the direction the player character is looking at. For example, you can "idle_up", "idle_down", "idle_left", and "idle_right" animations, and use BlendSpace2D to pick one in runtime based on a direction vector.
Thus, you need to set the "blend_position" of the BlendSpace2D like this:
animationTree.set("parameters/NameOfTheBlendSpàce2D/blend_position", vector)

Where:

*

*animationTree is a variable set to the AnimationTree.

*"NameOfTheBlendSpàce2D" is the name of the BlendSpace2D you want to set (e.g. "Idle").

*vector is a Vector2D with the direction you want (e.g. Vector2.UP).

This is shown in the episode 6 of the tutorial series (Animation in all directions with an AnimationTree).

You can find a reference project by HeartBeast at arpg-reference, where you can find a function update_animation_blend_positions that looks like this:
func update_animation_blend_positions():
    animationTree.set("parameters/Idle/blend_position", input_vector)
    animationTree.set("parameters/Run/blend_position", input_vector)
    animationTree.set("parameters/Attack/blend_position", input_vector)
    animationTree.set("parameters/Roll/blend_position", input_vector)

Here "Idle", "Run", "Attack", and "Roll" are BlendSpace2D, each configured with animations for the corresponding actions, and this function updates them in sync so that they are picking the correct animation.
As far as I can tell the code from the repository is further refactored from what is show in the tutorial series. This code from the repository is under MIT licence.


text:
Q: Does a combined pop/top stack already exist in std? I feel like a stack in which pop/top are combined should already exist - am I missing something? Most languages have this. Does C++?
#include <stack>
#include <iostream>
template <typename T>
class gStack : public std::stack<T>
{
public:
    T giveNext()
    {
        T n = std::stack<T>::top();
        std::stack<T>::pop();
        return n;
    }
};

int main()
{
    gStack<int> s;
    s.push(3);
    std::cout << s.giveNext();
    return 0;
}


text:
Q: Android: Picasso doesn't work Case :
I work on app which retrieve info about local venues based on coordinates from Foursquare API. All information is stored in the DB, including venue featured photo stored as prefix and suffix of the link. For the list representation I use recyclerview. I logged url links and they seem work fine. Here is my onBindViewHolder method:
public void onBindViewHolder(ViewHolder holder, int position) {
    if (holder instanceof ItemViewHolder) {
        Venue venue = venueList.get(position);
        String url = venue.getFeaturedPhotos().getItems().get(0).getPrefix() + "120x120" + venue.getFeaturedPhotos().getItems().get(0).getSuffix();
        ((ItemViewHolder) holder).venueName.setText(venue.getName());
        ((ItemViewHolder) holder).streetAdr.setText(venue.getLocation().getAddress());
        ((ItemViewHolder) holder).rating.setText(venue.getRating().toString());
        Context context = ((ItemViewHolder) holder).venuePhoto.getContext();
        Picasso.with(context).load(url).into(((ItemViewHolder) holder).venuePhoto);;
        ((ItemViewHolder) holder).venue = venue;
    } else {
        ((ProgressViewHolder) holder).progressBar.setIndeterminate(true);

    }
}

This is how my item looks like:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/venuePhoto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:contentDescription="@string/imgDescr"
         />

    <TextView
        android:id="@+id/rating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="@string/ratingSample"
        android:textSize="45sp" />

    <TextView
        android:id="@+id/venueName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toLeftOf="@id/rating"
        android:layout_toRightOf="@id/venuePhoto"
        android:text="@string/VenueNameSample"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/streetAdr"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/venueName"
        android:layout_toLeftOf="@id/rating"
        android:layout_toRightOf="@id/venuePhoto"

        android:text="@string/addressSample"
        android:textSize="20sp" />

</RelativeLayout>

A: I found a solution by just adding uri parsing
String url = venue.getFeaturedPhotos().getItems().get(0).getPrefix() + "120x120" + venue.getFeaturedPhotos().getItems().get(0).getSuffix();
Uri uri = Uri.parse(url);


text:
Q: React's Context API re-renders all components that are wrapped inside the Context This is a very common performance problem while using the Context API. Essentially whenever a state value in the context changes, the entire components that are wrapped between the provider re-renders and causes performance slowdown.
If I have a the wrapper as this:
<CounterProvider>
        <SayHello />
        <ShowResult />
        <IncrementCounter />
        <DecrementCounter />
</CounterProvider>

And the value props as:
<CounterContext.Provider value={{increment, decrement, counter, hello }} >
  {children}
</CounterContext.Provider>

Everytime I increment the count value from the IncrementCounter component, the entire set of wrapped components re-renders as it is how the Context API is supposed to work.
I did a bit of research and came across these solutions:

*

*Split the Context into N number of Context according to the use-case : This solution works as expected.

*Wrap the value provider using React.Memo: I saw a lot of articles suggesting to the React.Memo API as follows:

<CounterContext.Provider
  value={useMemo(
    () => ({ increment, decrement, counter, hello }),
    [increment, decrement, counter, hello]
    )}
>
  {children}
</CounterContext.Provider>

This however doesn't work as expected. I still can see all the components getting re-rendered. What I'm doing wrong while using the Memo API? Dan Abramov does recommend to go by this approach in an open React issue
If anyone can help me out on this one. Thanks for reading.

A: "Essentially whenever a state value in the context changes, the entire components that are wrapped between the provider re-renders and causes performance slowdown."
The above statement is true if a context is used like in the below example where components are directly nested in the provider. All of them re-render when count changes, no matter wether they are called useContext(counterContext) or not.

const counterContext = React.createContext();
const CounterContextProvider = () => {
  const [count, setCount] = React.useState(0);
  return (
    <counterContext.Provider value={{ count, setCount }}>
      <button onClick={() => setCount((prev) => prev + 1)}>Change state</button>
      <ComponentOne/>
       <ComponentTwo />
    </counterContext.Provider>
  );
};

const ComponentOne = () => {
  console.log("ComponentOne renders");
  return

;
};

const ComponentTwo = () => {
  console.log("ComponentTwo renders ");
  return

;
};
function App() {
  return (
    <CounterContextProvider/>
  );
}
ReactDOM.render(
  <App />,
  document.getElementById("root")
);

"Essentially whenever a state value in the context changes, the entire components that are wrapped between the provider re-renders and causes performance slowdown."
The statement is false if you are consuming nested components with children. This time when count changes CounterContextProvider renders, but since it's rendering because its state has changed and not because of its parent rendering, and because a component cannot mutate its props, React won't render children. That's it if it was a normal component.
But since there is a context involved here, React will find all components that contain useContext(counterContext) and render them.

const counterContext = React.createContext();
const CounterContextProvider = ({ children }) => {
  const [count, setCount] = React.useState(0);
  return (
    <counterContext.Provider value={{ count, setCount }}>
      <button onClick={() => setCount((prev) => prev + 1)}>Change state</button>
      {children}
    </counterContext.Provider>
  );
};

const ComponentOne = () => {
  const { count } = React.useContext(counterContext);
  console.log("ComponentOne renders");
  return

;
};

const ComponentTwo = () => {
  console.log("ComponentTwo renders ");
  return

;
};
function App() {
  return (
    <CounterContextProvider>
      <ComponentOne />
      <ComponentTwo />
    </CounterContextProvider>
  );
}
ReactDOM.render(
  <App />,
  document.getElementById("root")
);

In the above example only ComponentOne renders when count changes, which is normal cause he is consuming it. Every component that calls useContext(counterContext) renders if one value of the context changes.
Even with useMemo wrapping the context object as you did, that's the behavior you get as soon as one variable in its dependency array changes.


text:
Q: Overriding GetHashCode in a mutable struct - What NOT to do? I am using the XNA Framework to make a learning project. It has a Point struct which exposes an X and Y value; for the purpose of optimization, it breaks the rules for proper struct design, since its a mutable struct.
As Marc Gravell, John Skeet, and Eric Lippert point out in their respective posts about GetHashCode() (which Point overrides), this is a rather bad thing, since if an object's values change while its contained in a hashmap (ie, LINQ queries), it can become "lost".
However, I am making my own Point3D struct, following the design of Point as a guideline. Thus, it too is a mutable struct which overrides GetHashCode(). The only difference is that mine exposes and int for X, Y, and Z values, but is fundamentally the same. The signatures are below:
public struct Point3D : IEquatable<Point3D>
{
    public int X;
    public int Y;
    public int Z;

    public static bool operator !=(Point3D a, Point3D b) { }
    public static bool operator ==(Point3D a, Point3D b) { }

    public Point3D Zero { get; }

    public override int GetHashCode() { }
    public override bool Equals(object obj) { }
    public bool Equals(Point3D other) { }
    public override string ToString() { }
}

I have tried to break my struct in the way they describe, namely by storing it in a List<Point3D>, as well as changing the value via a method using ref, but I did not encounter they behavior they warn about (maybe a pointer might allow me to break it?).
Am I being too cautious in my approach, or should I be okay to use it as is?

A: I see no particular problem in writing a struct like this, once you fully understand the trade-offs. The problem is (presumably) that you want to be to able to store it in a Dict (or similar collection) and you need a HashCode.
One thing you didn't mention is: do your points have identity? That is, if you have two points with the same value, are they the same point? [As two Integers both with the value 7 are the same integer. There is only one Integer with the value 7.]
Mutability implies identity. If a Point3D has identity then its HashCode is derived from its identity. You could use a this pointer or something like a GUID.
If the Point3D has no identity then its HashCode is best derived from its value. If you change the value (say by reusing values from a pool), you better make sure it's not in a Dict-like collection at the time or it will be lost.

Obviously if you don't use hash-based collections then the point is moot.

If you do, consider this code.
public struct ValuePoint {
  public int x;
  public int y;
  public override int GetHashCode() { return (x * 1000 + y) % 97; }
  public ValuePoint(int _x, int _y) { x = _x; y = _y; }
}
public struct IdentityPoint {
  static int nextkey = 0;
  int key;
  public int x;
  public int y;
  public override int GetHashCode() { return key; }
  public IdentityPoint(int _x, int _y) { key = ++nextkey; x = _x; y = _y; }
}
class Program {
  Dictionary<ValuePoint, int> dictv = new Dictionary<ValuePoint,int>();
  Dictionary<IdentityPoint, int> dicti = new Dictionary<IdentityPoint,int>();
  HashSet<ValuePoint> setv = new HashSet<ValuePoint>();
  HashSet<IdentityPoint> seti = new HashSet<IdentityPoint>();

  void exec() {
    ValuePoint vp = new ValuePoint(3, 4);
    dictv[vp] = 777;
    vp.x++;
    dictv[vp] = 888;
    IdentityPoint ip = new IdentityPoint(3, 4);
    dicti[ip] = 777;
    ip.x++;
    dicti[ip] = 888;
  }

ValuePoint uses its value as its hashkey. If you change the value (x++) then the original value is 'lost', and the assigned value '888' adds a new key instead of updating the existing one.
IdentityPoint uses a unique key. If you change the value (x++) then the original entry is still found and overwritten with the assigned value '888'.
This is a contrived example, but illustrates the point about value versus identity. [The code is bad but good enough for the purpose.]
@EricLippert is a highly regarded writer whom I remember from the early days of COM and the design of .NET and his advice is sound. I think he misses the point by using a dictionary in which the key is a string. The issue of GetHashCode() only arises when the mutable object itself is the key.

A: Let's break it down.

Is a mutable struct with public fields a good idea?

No. You already know that it is not, but you're choosing to play with fire while walking on thin ice anyways. I would advise against using Point as a model. Value types should logically be values, and values don't change, variables change.
That said, there can be good performance reasons for doing what you're doing; I would only do so if I had clear empirical evidence that there was no other way to meet my performance goals.

If I put a mutable struct into a dictionary and then mutate it, can the struct be "lost" in the hash code?

The question is not answerable because it presumes a falsehood. You can't put a mutable struct into a dictionary and then mutate it. Asking "what happens when I do something impossible?" doesn't afford answers upon which you can make engineering decisions.

What happens when I try to mutate a mutable struct that I've put into a dictionary?

Value types are copied by value; that's why they're called "value types". When you fetch the value from the dictionary, you make a copy. If you then mutate it, you mutate the copy. If you try to mutate it directly by changing a field, the compiler will tell you that you are mutating a copy and that the mutation will be lost.

So what's the real danger of putting a mutable struct into a dictionary?

The danger of putting a mutable value type in a dictionary is that mutations are lost, not that the object gets lost in the dictionary. That is, when you say:
struct Counter
{
  public int x;
  public void Increment() { x = x + 1; }
  ...
}

...

var c = new Counter();
var d = new Dictionary<string, Counter>();
d["hello"] = c;
c.Increment();
Console.WriteLine(c.x);
Console.WriteLine(d["hello"].x);
d["hello"].Increment();
Console.WriteLine(c.x);
Console.WriteLine(d["hello"].x);

then the increment to c is preserved but not copied to the dictionary, and the increment of the dictionary's copy is lost because it is made to a copy, not to the dictionary.
This is very confusing for people, which is why you should avoid it.


text:
Q: map_blocks with change of dimensions returns IndexError: tuple index out of range I'm trying to create aggregated statistics with dask arrays. map_blocks seems ideal but can't get it to work.
I'm new to dask so trying to understand the way it works. I plan to use custom functions and started with some basics. I've got stuck and can't see a solution after a few hours of trial & error.
import dask
import dask.array as da
from numpy import median,array

def func(a):
    m = median(a)
    print(m)
    return array(m)

x = da.random.random((10000, 10000), chunks=(5000, 5000))

x.map_blocks(func,chunks=(1,1)).compute()

I would expect a new array with the results per block, but get:
nan
0.5001597269075302
0.49996143572562185
0.49994227403711916
0.5001512434686584
Traceback (most recent call last):
  ...
    result.append(tuple([shape(deepfirst(a))[dim] for a in arrays]))
IndexError: tuple index out of range

A: map_blocks can be slightly tricky at first. The problem here is that func returns an array of shape (), while in map_blocks you indicate output chunks of (1,1).
If I understand you correctly, you want to replace each chunk of x by its median (these would be new chunks of size (1,1)). To do so, you need to output an array with that shape. See the following code:
import dask
import dask.array as da
from numpy import median,array

def func(a):
    m = median(a)
    print(m)
    return array(m)[None,None] # add dummy dimensions

# x = da.random.random((10000, 10000), chunks=(5000, 5000))
x = da.random.random((100, 100), chunks=(50, 50)) # try things out on small array

x.map_blocks(func,chunks=(1,1)).compute()

Indexing an array with None adds a dummy dimension to it. Therefore, array(m)[None,None] will have the desired shape (1,1).
Also, for playing with these things until they work out it makes sense to work on small data, which I added in the above example.


text:
Q: Is there a way to write exponentials in a button in html5? We can use the  tag(superscript tag) to represent something like a^b and e^x in html5. But while using the  tag to make a button, we normally use the 'value' attribute to represent what's gonna be on the button something like this:

<input type="button"class="cutedog" value ="x cube">

But we can't really use the sup tag inside the " " because it just prints out the exact thing out something like this: "e(sup)x(/sup)" (I have deliberately put () instead of < and > because stackoverflow does't support this :( )
Anyway can you tell me that how can we put e^x inside "" or is there any way to do this?? Plz help me :))

A:

<button>x3</button>


text:
Q: How to parse file without using eval - PHP? Is there any other way to parse the file without eval()? I'm trying to render the php code without using php tags inside index.gs and so far i can do it only with eval().  The problem is not only to parse vars, but custom template characters.
here is the sample of code below.
 $render = file_get_contents($this->file);

 $render = $this->parse_extends($render);
 $render = $this->parse_assets($render);
 $render = $this->parse_vars($render);
 $render = $this->parse_vars_skip($render);

  try {
        ob_start();
        eval('?>' . $render);
        $render = ob_get_contents();
    } finally {
        ob_get_clean();
    }
    return $render;

The return $render - return to View::class code for response

A: If the allow_url_include directive is enabled in php.ini, then it's possible to execute this code using
include "data://text/plain;base64," . base64_encode($render);

but this setting is disabled by default, and cannot be changed within user code, but only through editing the php.ini file; so unless explicitly enabled in php.ini (and there normally isn't any good reason why it should be), then it isn't really an option.
An alternative is to create a temporary file, write the code there, and then execute it using include:
$tempFilename = tempnam("/tmp", "MyTemplate");
file_put_contents($tempFilename, $render);
include $tempFilename;
unlink($tempFilename);

But both have similar issues and dangers to eval().


text:
Q: Missing version.pm installing Crypt::SSLeay on RHEL7 I am trying to install Crypt::SSLeay that is required to launch PulledPork from Snort. I am working on a fresh Red Hat Linux Enterprise 7 Server (in VM) with Perl 5.16-3.
I am installing every Perl module from search.cpan.org and I need to get source code to compile myself.
At first, I wanted to install Crypt::SSLeay with
perl Makefile.PL
make
sudo make install

Then I got a bunch of dependencies to install first.

*

*ExtUtils::CBuilder

*ExtUtils::MakerMaker

*Perl::OSType

*IPC::Cmd

*Params::Check

*Locale::Maketext::Simple

*Module::Load::Conditional

*Module::Load

*Test::More

*ExtUtils::MM_Unix::tool_xsubpp

But now I am stuck with this.
Can't locate version.pm in @INC (@INC contains: /usr/local/lib64/perl5
/usr/local/share/perl5 /usr/lib64/perl5/vendor_perl
/usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5 .) at
/usr/local/share/perl5/Module/Load/Conditional.pm line 12. BEGIN
failed--compilation aborted at
/usr/local/share/perl5/Module/Load/Conditional.pm line 12. Compilation
failed in require at /usr/local/share/perl5/IPC/Cmd.pm line 60. BEGIN
failed--compilation aborted at /usr/local/share/perl5/IPC/Cmd.pm line
60. Compilation failed in require at /usr/local/share/perl5/ExtUtils/CBuilder/Base.pm line 10. BEGIN
failed--compilation aborted at
/usr/local/share/perl5/ExtUtils/CBuilder/Base.pm line 10. Compilation
failed in require at
/usr/local/share/perl5/ExtUtils/CBuilder/Platform/Unix.pm line 5.
BEGIN failed--compilation aborted at
/usr/local/share/perl5/ExtUtils/CBuilder/Platform/Unix.pm line 5.
Compilation failed in require at (eval 1) line 2. BEGIN
failed--compilation aborted at (eval 1) line 2. Compilation failed in
require at Makefile.PL line 5. BEGIN failed--compilation aborted at
Makefile.PL line 5.

I install version (http://search.cpan.org/~jpeacock/version-0.9917/lib/version.pod) but it told me :
ERROR from evaluation of
/home/pdavid/Downloads/version-0.9917/vutil/Makefile.PL:
ExtUtils::MM_Unix::tool_xsubpp : Can't find xsubpp at
/usr/local/share/perl5/ExtUtils/MM_Unix.pm line 3753.

A: Red Hat Enterprise Linux (and Fedora) ship a subset of Perl in the perl package; this is why you're missing version.pm although the software assumes it's there; that's why Sinan mentions it is in corelist.
The solution is to first install the perl-core package on your system, then your system will have all packages from core installed, and then you can install your software:
sudo yum install perl-core

By the way, you can also install Crypt::SSLeay via yum:
sudo yum install "perl(Crypt::SSLeay)"


text:
Q: How to modify state of a component from a routed component? I'm building a react native application where users can create event and invite people.
But I'm having some problems modifying the state of the component from a routed component.
There is a createEvent screen where user tries to create event...on clicking on invite people button a new screen is rendered let's name it as invitePeopleScreen.
If i'm not wrong...I think I need to use redux.
The createEvent screen:
import React from 'react';
import {Button, Container, Form, Input, Item, Text, Textarea} from "native-base";

export default class createEventScreen extends React.Component{

    constructor(props) {
        super(props);
        this.state = {
            title: '',
            description: '',
            createdBy: '',
            invites: []
        };
    }

    createEvent () {}

    render() {
        return (
            <Container>
                <Text>Create An Event </Text>
                <Form>
                    <Item rounded>
                        <Input keyboardType="default"
                               placeholder="Enter the event title"
                               onChangeText={ title => this.setState({ title: title }) } />
                    </Item>

                    <Item rounded>
                        <Textarea keyboardType="default"
                               placeholder="Enter the event description"
                               onChangeText={ description => this.setState({ description: description }) } />
                    </Item>
                </Form>
                <Button rounded onPress={ () => { this.props.navigation.navigate('invitePeople') }}>
                    <Text>Invite People</Text>
                </Button>
                <Button rounded onPress={this.createEvent}>
                    <Text>Create Event</Text>
                </Button>
            </Container>
        )
    }
}

Here is the invitePeople Screen:
import React from 'react';
import { Container } from "native-base";

export default class inviteUsersScreen extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            username: ''
         }
    }

    addInvite = (username) => {
       // push the username into the invites array of createEventScreen
}
    render() {
        return (

            <Container>
                <Text>Invite People </Text>
                <Form>
                    <Item rounded>
                        <Input keyboardType="default"
                               placeholder="Enter the username"
                               onChangeText={ (username) => {this.setState({ username: username)})} />
                    </Item>
                </Form>

                <Button rounded onPress={ () => { this.addInvite(this.state.username) }}>
                    <Text>Submit</Text>
                </Button>
        );
    }
}

I am exactly not sure what code will go into addInvite function.

A: Something like that perhaps:
addInvite = (e, username) => {
  e.preventDefault();
  this.setState({
  list: [...this.state.list, username]
})
}

Assuming you add to your state a list prop

A: You have three options to achieve this, option 1: pass a function as a prop to the next screen, option 2: use async storage, option 3: Redux.
Option: 1.
in your CreateEventScreen pass a function to the second screen as prop.
addInvite = username => {
  this.setState({
    invites: [...this.state.invites, username],
  });
};

<Button
  rounded
  onPress={() => {
    this.props.navigation.navigate('InvitePeople', {
      addInvite: this.addInvite,
    });
  }}>
    <Text>Invite People</Text>
</Button>

In your InviteUsersScreen, get the function and pass username.
addInvite = username => {
  // push the username into the invites array of createEventScreen
  const addInvite = this.props.navigation.getParam('addInvite', () => {
    alert('No function was passed');
  });

  addInvite(username);
};

Option 2: AsyncStorage
import {AsyncStorage} from 'react-native';

// create function for saving items to storage
export const SaveItem = async (key, value) => {
  try {
      await AsyncStorage.setItem(key, value);
      console.log('saved')
  } catch(e) {
      console.log(e)
  }
};

// create function for saving items to storage
export const ReadItem = async key => {
  try {
    var result = await AsyncStorage.getItem(key);
    return result;
  } catch (e) {
    return e;
  }
};

Then you can add items to the storage in your InviteUsersScreen.
addInviteWithStorge = username => {
  const usernames = [...this.state.storageUsernames, username];

  this.setState({
    storageUsernames: usernames,
    username: '',
  });

  const invites = JSON.stringify(usernames);

  SaveItem('invites', invites)
    .then(res => {
      console.log('saved', res);
    })
    .catch(e => console.warn(e));
};

Retrieve items in your CreateEventScreen.
 ReadItem('invites')
  .then(res => {
    if (res) {
      const invites = JSON.parse(res);
      this.setState({
        invites: invites,
      });
    }
  })
  .catch(e => console.warn(e));

Demo


text:
Q: How do I utilize $.Deferred() / Promise() properly in this case? The problem with this as tested in the debugger, is that it will go in the first function (up to the $.get() without actually getting anything yet) then skip into the second function (once again, up to the $.get()). Then, it will proceed to execute the first function till it's finished retrieving all items, then when it gets into the second function, it will do the same thing but for some mysterious reason, the videoIdChainStr which holds all the video ids in a string from the first function is never retrieved or being executed since I suspected, it executed the second function's $.get(...) already and never did it again a "second time" when it had the values. To resolve that, I thought of async operations and it's a bit confusing at first but after reading some articles, I understand some, but not 100%, and especially not in code yet, but I tried the code below:
I want to really understand how to use $.Deferred, resolve(), and promise() in this case and if applicable, the other methods like then(), since I only need a resolve and promise to return a filled value (videoIdChainStr) to the done() that is needed and executes the second function thereafter.
First Function:
var relatedVidsDefer = function relatedVids(videoId)
{
    var videoIdChainStr = null;
    var deferredVal = $.Deferred(); // instantiate defer object

    $.get( // get related videos related to videoId
        "https://www.googleapis.com/youtube/v3/search",
        {
            part: 'snippet',
            maxResults: vidResults,
            relatedToVideoId: videoId,
            order: 'relevance',
            type: 'video',
            key: 'XXXXXXX'
        },

        function(data)
        {
            $.each(data.items,
                function(i, item)
                {
                    try
                    {
                        console.log(item);
                        var vidTitle = item.snippet.title; // video title

                        var vidThumbUrl = item.snippet.thumbnails.default.url;
                        var channelTitle = item.snippet.channelTitle;
                        var extractVideoId = null; // var to extract video id string from vidThumbUrl

                        // check if vidThumbUrl is not null, empty string, or undefined
                        if(vidThumbUrl)
                        {
                            var split = vidThumbUrl.split("/"); // split string when '/' seen
                            extractVideoId = split[4]; // retrieve the fourth index on the fourth '/'
                        }
                        else console.error("vidThumbUrl is either undefined or null or empty string.");

                        // if video title is longer than 25 characters, insert the three-dotted ellipse
                        if(vidTitle.length > 25)
                        {
                            var strNewVidTitle = vidTitle.substr(0, 25) + "...";
                            vidTitle = strNewVidTitle;
                        }

                        // check whether channelTitle is the same
                        if(channelTitle === "Channel Name")
                        {
                            extractedVideoIdArr.push(extractVideoId); // add the extracted video id to the array

                            // check if extractedVideoIdArr is not empty
                            if(extractedVideoIdArr !== 'undefined' && extractedVideoIdArr.length > 0)
                            {
                                videoIdChainStr = extractedVideoIdArr.join(", "); // change from an array to a chain string of videoIds for the relatedVidsDetails()
                            }
                            deferredVal.resolve(videoIdChainStr); // get the value

                            var vidThumbnail = '

' + vidTitle + '

';

                            // print results
                            $('.thumb-related').append(vidThumbnail);
                            $(item).show(); // show current video thumbnail item
                        }
                        else $(item).hide(); // hide current video thumbnail item
                    }
                    catch(err)
                    {
                        console.error(err.message); // log error but continue operation
                    }
                }
            );
        }
    );
    return deferredVal.promise(); // return the value and execute the second function
};

Second Function:
var relatedVidsDetailsDefer = function relatedVidsDetails(videoIdChainStr)
{
    // change extractvideoid into a string by tostring() or join() for param to recognize
    console.log("initial: ", extractedVideoIdArr);
    $.get(
        "https://www.googleapis.com/youtube/v3/videos",
        {
            part: 'snippet, contentDetails, statistics',
            id: videoIdChainStr, // chain string of video ids to be called upon in a single request
            key: 'XXXXXXX',
        },

        function(data)
        {
            $.each(data.items,
                function(i, item)
                {
                    try
                    {
                        var _vidDuration = item.contentDetails.duration;
                        var _viewCount = item.statistics.viewCount;
                        console.log("id: " + extractedVideoIdArr[i] + " duration: " + _vidDuration);
                        console.log("id: " + extractedVideoIdArr[i] + " viewCount: " + _viewCount);

                        $('.vidDetails').append(convert_time(_vidDuration) + ' / Views: ' + _viewCount);
                    }
                    catch(err)
                    {
                        console.error(err.message); // log error but continue operation
                    }
                }
            );
        }
    );
};

Execution:
relatedVidsDefer(_videoId).done(relatedVidsDetailsDefer); // wait till first function (before .done parameter) is complete before executing the second (in .done paramater)

Update:
Code Updated with @valarauko's answer. Finally, it worked and was able to retrieve the videos' details for one of the videos that duplicated to the rest of the videos. Upon entering the second function, videoIdChainStr only has the first id and not the rest... which I'm assuming, deferredVal.resolve(videoIdChainStr); will resolve right away when it gets an id the first time in the first function's loop, but not the rest of the string, even though it continues to loop and resolve all the items.
For Example:
Suppose to pass ID1, ID2, ID3 to parameter, but only passed ID1. Thus why it only went through the each loop on the second function once. How do I fix this occurrence?

A: The reason why the second function is executing before is because you are appending the parenthesis to the function inside the done statement (this executes inmediately the function and assigns the result of the function in the done callback.
relatedVidsDefer(_videoId).done(relatedVidsDetailsDefer());

should be
relatedVidsDefer(_videoId).done(relatedVidsDetailsDefer);

Also I don't know if you are using the videoIdChainStr a global variable on purpose but I would recommend you to make it locally and feed relatedVidsDetailsDefer a function that receives the parameter (no change should be done to the first function since you are already resolving the promise with that string.
The second function would be like
var relatedVidsDetailsDefer = function relatedVidsDetails(videoIdChainStr) {...}

UPDATE
If you look at the jQuery deferred documentation (link), a resolved/rejected promise will ignore future calls to resolve/reject and return the data used on the first resolved/rejected. Also notice that you had only one done statement so you were only checking for the first one anyway.
For your particular problem you can modify the second function to receive an array of strings and resolve the promise with the array of strings.


text:
Q: Getting Url in the call back function of WebRequesting Let's say I have a web request:
WebRequest webRequest = WebRequest.Create(Url);
webRequest.BeginGetResponse(this.RespCallback, webRequest);

Now is there is any way to retrieve the URL in
private void RespCallback(IAsyncResult asynchronousResult)
{
    // here
}

The idea is I want to provide a sequence id in the url while doing web request and then retrieve it on the call back and match it to know that this call back is from that request.
Any ideas?

A: Since you pass WebRequest as "state" to the BeginXXX cal you can retrive it in callback by accesing AsyncState property of IAsyncResult inside RespCallback. The get Url of your WebRequest.
var wr = asynchronousResult.AsyncState as WebRequest.

A: This should work:
private void RespCallback(IAsyncResult asynchronousResult)
{
    WebRequest wreq = asynchronousResult as WebRequest;
    Uri wreqUri = wreq.RequestUri;
}


text:
Q: Invertibility of frame/sampling operator on Bargmann-Fock spaces Let $F_\alpha ^p (\mathbb{C}^n)$ for $1 < p < \infty$ and $\alpha > 0$ be the Bargmann-Fock space defined as the Banach space of entire functions $f$ such that $f(\cdot) e^{- \frac{\alpha}{2} |\cdot|^2} \in L^p(\mathbb{C}^n, dv) $  where $dv$ is ordinary Lebesgue volume measure and where $F_\alpha ^p (\mathbb{C}^n)$ is given it's natural Banach space norm.
For $\epsilon > 0$ small, treat $\epsilon \mathbb{Z}^{2n}$ canonically as a lattice in $\mathbb{C}^n$.  It is well known that  $\epsilon \mathbb{Z}^{2n}$ is a "sampling set" for $F_\alpha ^p (\mathbb{C}^n)$, so that there exists constants $C_1, C_2 > 0$ independent of $f \in F_\alpha ^p (\mathbb{C}^n)$ where
\begin{align} C_1 \sum_{\sigma \in \epsilon  \mathbb{Z}^{2n} } |f(\sigma)|^p e^{- \frac{\alpha p |\sigma|^2}{2} } \leq \|f\|_ {F_\alpha ^p (\mathbb{C}^n) } ^p \leq C_2 \sum_{\sigma \in \epsilon \mathbb{Z}^{2n} } |f(\sigma)|^p e^{- \frac{\alpha p |\sigma|^2}{2} }.  \end{align}
The question is then whether or not the "sampling operator" mapping $F_\alpha ^p (\mathbb{C}^n)$ to $F_\alpha ^p (\mathbb{C}^n)$ given by \begin{align} f \mapsto \sum_{ \sigma \in \epsilon \mathbb{Z}^{2n} } f(\sigma) e^{ \alpha (z \cdot \overline{\sigma} ) - \alpha |\sigma|^2 } \nonumber \end{align} is invertible for small enough $\epsilon$.
Elementary Hilbert space theory says that for $p = 2$ it is, but I don't find where in the literature it is shown for $p \neq 2$, or shown not to be invertible. It's easy to show that this operator is injective and has dense range, but proving surjectivity seems to no easy task.

A: I think the preprint http://arxiv.org/abs/1012.4283 may ask most of your question even in the polyanalytic setting.


text:
Q: Return updated item from Entity Framework Let's say I have a really simple object which I display in a list in a WPF application. The object looks like this:
class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    // ...some addtional properties, of course

    // Status could be Active, InActive, OnBreak, etc.
    public int StudentStatusId { get; set; }
    public StudentStatusModel { get; set; }
}

Now if I make a method for changing the student status via Entity Framework (or any other ORM I guess), it could look something like this:
class StudentService
{
    public async Task ChangeStudentStatus(int studentId, int newStatusId)
    {
        var student = GetStudent(studentId); // Method which returns the student by id via EF
        student.StudentId = newStudentId;    // Change the student property
        await UpdateStudent(student);        // Method which updates the enity in EF and saves changes
    }
}

The problem is if I call my ChangeStatus() method, then my database will be fine, but the collection in my application will be broken, like this:
class MyViewModel
{
    public List<StudentModel> Students { get; set; }
    public StudentModel SelectedStudent { get; set; }

    public ChangeSelectedStudentStatus(int status)
    {
        var service = ServiceFactory.GetStudentService();
        await service.ChangeStatus(SelectedStudent.StudentId, status);
        // Now both SelectedStudent and Students are out of sync with database
    }
}

What is the best way to deal with this issue? I can think of three options, but I cannot figure out if either of them is a good solution, or if I am going about this in the wrong way entirely.

*

*Make the ChangeStatus method return the updated entity, so it becomes Task<StudentModel> ChangeStatus()

*Refresh the modified item in the List<StudentModel> Students

*Refresh the entire List<StudentModel> Students
Should I do any of the above, or something completely different? I cannot find any good examples of this in the EF documentation.


text:
Q: Regression /Bug in DelaunayMesh from 10.3.1 to 10.4 Bug introduced in 10.4 and persists through 11.1

In answering this question, I realized the OP and I were obtaining different results from the alphaShapes2D code. This question was updated with additional point sets, but when I tried to use my answer there, it failed. The OP used my answer and got really good results which made me realize something has changed between Mathematica versions 10.3.1 and 10.4. I think I may have tracked the problem down to DelaunayMesh. To see what I mean, here are the MeshRegions generated from the data obtained from the linked question using the same alpha parameter (10.4 is on the right of the following images):
alphaShapes2D[points, 3.0]

You can see it's more pronounced if we try to extract the region boundaries:

When I tried to apply the code to the second data set provided (points2), Mathematica 10.3.1 returns the nice result shown in the linked question whereas, 10.4 fails to return any useful result. After spending some time debugging the only thing I could come up with is that DelaunayMesh is doing something different in both versions. For instance the number of mesh cells returned in both versions are different:
$Version
dd = DelaunayMesh[points];
MeshCellCount[dd, All]

Also, as you can see from above, in 10.4 DelaunayMesh claims there's a degenerate polygon but we don't see this error in 10.3.1. Can anyone reproduce this? Is this a change in algorithm in DelaunayMesh?

A: The problem arises from the definition of ellipsePoints in the linked question, which maps over a range of angles Range[0, 2 Pi, 0.02 Pi]. Because the range includes both 0 and 2 Pi, there are duplicate points in the data. Simply changing to Range[0.02 Pi, 2 Pi, 0.02 Pi] makes the problem go away.


text:
Q: How to add Z axis BarGraph using Core Plot in Iphone/iPad I have read the tutorials about making 2D BarGraph using Core Plot in iPhone.
I want to add Z-axis to it to make it 3D.
EDIT :
I searched but I could not find great solution. I want to show something like figure below.

Guide me regarding the same.

A: True 3D is not supported in Core Plot right now. The best you'll be able to do is use gradient or image fills on the various parts of the graph to simulate a 3D appearance.


text:
Q: Sizzle.js ( JQuery Selector Engine ) error/bug Well, I've been trying to make this, maybe I am constructing it wrong or it's a known bug in jquery selector :
$(':not(.class) > *').each( function(){

});

The code meant to get all elements expect those that are children of element with class .class :

     Hi 1

     Hi 2

A: Working fiddle
I think that what you looking for :
$(':not(.class *)').each( function(){

});

Hope this helps.


text:
Q: help with equation simplification, can it be simplified further? I am trying to simplify the expression:
$$\tag{1} \frac{\mu v}{k}r_2 \ln\left(\frac{r_2}{r_1}\right)+\beta \rho v^2 r_2^2 \left(\frac{1}{r_2}-\frac{1}{r_1}\right)+\frac{2\mu v}{k}r_2^2 \left(\frac{1}{r_2}-\frac{1}{r_1}\right)+\beta \rho v^2 r_2^4 \left(\frac{1}{3r_2^2}-\frac{1}{3r_1^2}\right)$$
after substituting the relationship given here for the variable $v$:
$$\tag{2} v=\frac{N\mu}{\rho \beta k}$$
So far I have been able to simplify to:
$$\tag{3} \frac{N \mu^2 }{\rho \beta k^2 }r_2 \left(\ln \left(\frac{r_2}{r_1}\right)+(N+2)\left[r_2 \left(\frac{1}{r_2}-\frac{1}{r_1}\right)\right]+Nr_2^3 \left(\frac{1}{3r_2^2}-\frac{1}{3r_1^2}\right)\right)$$
Can I simplify further?


text:
Q: setting the cursor after an image using javascript I am using a contenteditable element in my code in which text turns into emojis. for example, abc :) should turn into abc . But, after the image appears in the contenteditable, the cursor moves back to the beginning of the conteneditable and the whole code stops working after that.
Here's the code that I am using:

var data = {
  "value": ":)",
  "image": "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSaW1KOeceO85Y7KfUXGyLZm1LfTwjhQspKKXUl3D3a5Mo1uz-AhA"
};
$(document).ready(function() {
  document.body.onkeyup = function(e) {
    if (e.keyCode == 32) {
      //alert("space bar");
      var contenteditable = document.querySelector('[contenteditable]'),
        text = contenteditable.textContent;
      var word = getWord(text);
      console.log(word);
      console.log(data.value);
      if (word.includes(data.value)) {
        //alert("true");
        var img = " ";
        console.log(img);
        $("#text-box").html(function(_, html) {
          return html.replace(data.value, img);
        }); //[0].setSelectionRange($("#text-box").html().length, $("#text-box").html().length);

        var el = document.getElementById("image");
        var range = document.createRange();
        var sel = window.getSelection();
        range.setStart(el.childNodes[2], 2);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);

      }
    }

    function getWord(text) {
      var word = text.split(" ").pop();
      return word;
    }
  }
});
.image {
  position: relative;
  max-height: 1.4em;
  max-width: 1.4em;
}

[contenteditable] {
  -webkit-appearance: textfield;
  appearance: textfield;
  border: 1px solid black;
  line-height: 1.4em;
  min-height: 20px;
}

Here's the link to my Codepen:
Link


text:
Q: Batch Script - Break out of loop when another batch has finished I have a very simple script that merges all .txt files in a folder, as bellow:
copy /b *.txt Merged_output.txt >nul

This does the job and doesn't print anything and this is ok (I don't want it to print the name of every file it merges)
But I would like to see that script is still running until it ends merging all the .txt files.
I have a lot o files to merge (8000+) and this takes some time, and I have no idea if it still runs.
I was thinking of creating another batch script having a loop, that prints over and over again this message: Running...
Something as bellow:
@echo off
cls
:start
cls
echo Running...
goto start

I was wondering if it is possible to start from the Loop Script, printing the Running message and make it stop after it runs the merging.bat script and after the merging finishes.
Any other suggestions would be most appreciated.

A: You don't need another batch file. Instead of hiding the output, mask it
@echo off
    setlocal enableextensions disabledelayedexpansion

    set monitor=cmd /q /v /e /c"for /l %%a in () do set/p.=&&echo !time! working || exit"

    copy /b *.txt merged_output | %monitor%
    echo %time% done

It just pipes the output of the copy command to a separate cmd instance that loops reading each line and printing the current time and the working literal.


text:
Q: Using the "in" operator in Python 3.10 Match Case Is there a "in" operator in python 3.10 Match Case like with if else statements
if "\n" in message:
the in operator doesn't work in match case
match message:
    case "\n" in message:

This doesn't work.
How to have something like the "in" operator in Match-Case.

A: For completeness, it can be done indirectly using guards (as used in the other answer).
match message:
    case message if "\n" in message:
        ... some code...
    case message if "foo" in message:
        ... some other code...

Note using the name message in each case statement is not required (this does have the side effect of binding the name x to a value):
match message:
    case x if "\n" in x:
        ... some code...
    case x if "foo" in x:
        ... some other code...

Or you can also use wildcards (which skips the name binding):
match message:
    case _ if "\n" in message:
        ... some code...
    case _ if "foo" in message:
        ... some other code...

But you're probably better off just using an if statement since using match-case is more code and has worse readability for this situation
if "\n" in message:
    ... some code ...
elif "foo" in message:
    ... some code ...
else:
    ... some code ...

A: In match-case we can use the split() method on the message string.
Example:
def match_case_with_if(command):
    match command.split():
        case [*command_list] if 'install' in command_list:
            print(f"Hey you are installing {command_list[-1]}....")
        case [*command_list] if 'uninstall' in command_list:
            print(f"Are you sure you want to uninstall {command_list[-1]} ?")

match_case_with_if('pip install numpy')
# Output: Hey you are installing numpy....
match_case_with_if('pip uninstall numpy')
# Output: Are you sure you want to uninstall numpy ?

Here, the string can be split into a list and if condition can be applied on it's contents.
Hope this helps!!


text:
Q: Flip background using CSS or LESS Is there a way to programmatically flip the background of an element using CSS or LESS? Specifically, I would like to invert the background gradient of a button. I do not want the content of the button to be flipped - just the background.
For example, this:
.button {background-image:linear-gradient(top, #000, #fff);}

should become:
.button:active {background-image:linear-gradient(top, #fff, #000);}

-----------  EDIT: Adding more detail. -----------
Take this LESS code:
.button {

  background-image:linear-gradient(top, red, green);

  &.primary {background-image:linear-gradient(top, blue, yellow);}
  &.secondary {background-image:linear-gradient(top, brown, grey);}

  &:active {background-image:linear-gradient(top, ..., ...);}

}

Is there a way for me to reverse the direction of the gradient without having to define the ":active" state separately for the ".button", ".primary" and ".secondary" classes?

A: With Newer Browsers
This post is over a year old, but I thought I would note there is a solution now for some of the newer browsers. The following has been tested in IE10 (does not work in IE9 and under), FF21, and Chrome27.
Using a pseudo element and a transform, you can get what you originally desired. Originally, some issues did not allow transforms on pseudo elements, so this will not function in some older versions.
Here is the example fiddle. Though for fallback support, you may still want the additional vendor prefixes.
LESS
.button {

  background-image:linear-gradient(to bottom, red, green);
  position: relative;

  &:after {
     content: '';
     position: absolute;
     top: 0;
     right: 0;
     bottom: 0;
     left: 0;
     z-index: -1;

     &:active {
       -webkit-transform: rotate(180deg);
          -moz-transform: rotate(180deg);
           -ms-transform: rotate(180deg);
            -o-transform: rotate(180deg);
               transform: rotate(180deg);
     }
  }

  &.primary {background-image:linear-gradient(to bottom, blue, yellow);}
  &.secondary {background-image:linear-gradient(to bottom, brown, grey);}

}

A: I am not sure about your background-image:linear-gradient(top, #fff, #000); css rule but if you want to change button's background I guess this is the way - instead of .class selector use [type=''] otherwise :active wont work:
input[type="button"] {background:#fff;}
input[type="button"]:active {background:#000}
[...]
<input type="button" value="Test"/>

A: You mean like this:
http://jsfiddle.net/UgQvg/2
?

A: Unfortunately, I don't think LESS can work that way. You're basically trying to reference the colors of a nested scope using an outside scope - or rather, trying to get a polymorphism-like behavior. LESS just doesn't do that. It's cumbersome, but you'll probably have to define the :active portion for each button type. See this JsFiddle.
Now, I think you can do something like this using SASS (like LESS, but server-side, Ruby-based), perhaps using a list variable containing the specialized button classes, and then an @each loop to generate the :active styles. But that's probably overkill, unless you have  a lot of specialized styles.
Nonetheless, if you're using LESS, you might want to take a look at LESS Elements - a useful set of mixins, which includes gradient support.


text:
Q: 401 Unauthorized using oauth-python-twitter I'm trying to implement "twitter oauth" in appengine(python) using http://code.google.com/p/oauth-python-twitter.
I use the following code to redirect the user into twitter:
twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET)
request_token = twitter.getRequestToken()
response.set_cookie('request_token', request_token.to_string())
signin_url = twitter.getAuthorizationURL(request_token)
return redirect_to(signin_url)

the user is successfully redirected but when he returns in my application i receive the following error:
HTTP Error 401: Unauthorized
  File "/base/data/home/apps/app/controllers/users.py", line 46, in authenticate
    access_token = twitter.getAccessToken()
  File "/base/data/home/apps/app/lib/python/oauthtwitter.py", line 183, in getAccessToken
    token = self._FetchUrl(url, no_cache=True)
    ......
  File "/base/python_dist/lib/python2.5/urllib2.py", line 506, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)

the error occurate when i try to get an access token.
request_token = request.cookies['request_token']
token = oauth.OAuthToken.from_string(request_token)
twitter = OAuthApi(app_globals.CONSUMER_KEY, app_globals.CONSUMER_SECRET, token) # everything works good
access_token = twitter.getAccessToken()  # then, i receive the error.

Any idea?
Thank you!

A: i solved the problem just using the trunk version of oauth-python-twitter and python-twitter.

A: Make sure the user (or your self) has entered your app name in the Twitter authenticated section of their/your Twitter account so that your application has permission to connect.


text:
Q: How to get an error when creating an array with duplicate keys? reader,
I recently lost 40 minutes in debugging because a coworker did a little mistake duplicating rows and PHP didn't triggered any error.
Original lines were similar to
$files = [
    'identifier1' => '/path/to/file1'
];

Intended lines after duplication
$files = [
    'identifier1' => '/path/to/file1',
    'identifier2' => '/path/to/file2',
    'identifier3' => '/path/to/file3'
];

How the lines really were
$files = [
    'identifier1' => '/path/to/file1',
    'identifier1' => '/path/to/file2',
    'identifier1' => '/path/to/file3'
];

Which is the same as
$files = [
    'identifier1' => '/path/to/file3'
];

Is there a way to make php trigger an error (even if it's only a warning) when you mistakenly try to define an array with duplicate keys?
We would like to enable that option globally, and error_reporting(E_ALL) don't work sadly.

A: This is not considered an error in PHP. It is simply overwriting a key/value pair.
The only way to check this is to check the count() of $files after you define it to verify it has however many items you think it should. You can then throw an Exception or log an error if the count is too low.

A: If you provide your source as a pre-built array:
$list = [
    'one' => 1,
    'two' => 2,
    'one' => 3,
];

Then it is simply not possible to detect duplicate keys with a run-time check, as this code is compiled as if it were:
$list = [
    'two' => 2,
    'one' => 3,
];

I.e., the duplicate key essentially disappears before your code runs and any code you write will simply never see the first entry. If you write your code as individual lines:
$list['one'] = 1;
$list['two'] = 2;
$list['one'] = 3;

Then you have a few options. You could create a class that implements ArrayAccess, then write the offsetSet() method to check to see if the given offset already exists whenever a new offset is written. The class would essentially be usable wherever an array is.
class UniqueArray implements ArrayAccess
{

    protected $data = [];

    public function offsetExists($key)
    {
        return array_key_exists($key, $this->data);
    }

    public function offsetGet($key)
    {
        return $this->data[$key];
    }

    public function offsetSet($key, $value)
    {
        if ($this->offsetExists($key)) {
            throw new Exception("key '$key' already exists");
        }
        $this->data[$key] = $value;
    }

    public function offsetUnset($key)
    {
        unset($this->data[$key]);
    }

}

$list = new UniqueArray();
$list['one'] = 1;
$list['one'] = 2; // throws an exception

I imagine that's probably more trouble than it's worth though.
Your only real option is static code analysis. You might write your own sniff for PHPCS that attempts to find these duplicate key instances in the actual source code. Note this will require running the analysis tool on the source code to detect the issues.


text:
Q: SOPS won't decrypt a file if encrypted with an AssumedRole (and trying to decrypt without it using the same key) I'm looking into SOPS as a possible solution for us to encrypt secrets and push them to our repo.
I've been playing around with it and it's exactly what I need, except for a small issue. I'm hoping this is me just not finding the right documentation.
For the sake of simplicity let's say we have 2 AWS accounts, A and B.
In account A we've got:

*

*Our "human" users who will be encrypting/decrypting secrets from their local machines.

*KMS key

*Role that users from other accounts can assume to use that KMS key.

In account B:

*

*User a Jenkins script will use to decrypt secrets

To encrypt a file with my local user I'm doing:
sops --kms arnofthekey -e -i filename.yaml

And to decrypt it:
 sops --kms arnofthekey -d -i filename.yaml

Works like a charm.
If I do it as my Jenkins user:
sops --kms arnOfTheKey+arnOfTheRole -e -i filename.yaml
sops --kms arnOfTheKey+arnOfTheRole -d -i filename.yaml

Everything works like a charm as long as I encrypt/decrypt in the same place.
I then tried to encrypt with Jenkins and decrypt locally. I got an error informing me I'm not allowed to asssume the role Jenkins used. Which is absolutely true.
Here's what I don't understand, the KMS key is the same one in both cases. However, I can see the encrypted file keeps a record of the role. I thought since the key is the same, this should work.
Is there some sort of configuration I'm missing?
Thanks!

A: Digging a bit more I found an open ticket from a year ago. I guess, at the moment, this is something that can't be done directly with sops.
https://github.com/mozilla/sops/issues/555
The solution I found was allowing my human users to assume the same role Jenkins does. Should've thought about it earlier :)


text:
Q: Adjusting CSS design with view change I've the below code:

function exportTableToExcel(tableID, filename = ''){
    var downloadLink;
    var dataType = 'application/vnd.ms-excel';
    var tableSelect = document.getElementById(tableID);
    var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');

    // Specify file name
    filename = filename?filename+'.xls':'excel_data.xls';

    // Create download link element
    downloadLink = document.createElement("a");

    document.body.appendChild(downloadLink);

    if(navigator.msSaveOrOpenBlob){
        var blob = new Blob(['\ufeff', tableHTML], {
            type: dataType
        });
        navigator.msSaveOrOpenBlob( blob, filename);
    }else{
        // Create a link to the file
        downloadLink.href = 'data:' + dataType + ', ' + tableHTML;

        // Setting the file name
        downloadLink.download = filename;

        //triggering the function
        downloadLink.click();
    }
}
        .flex-container {
            width: 100%;
            height:98vh;
            display: flex;
            flex-wrap: wrap;
            background-color: DodgerBlue;
        }

        .flex-container > div {
            max-width: 100%;
            display: flex;
            flex-direction: column;
            background-color: #f1f1f1;
            margin: 10px;
            padding: 20px;
            font-size: 30px;
        }
        #path, #skills {
               /* will prevent resizing horizontally */
               /* resize:vertical; */
               width: 250px;
               max-width: 250px;
               min-width: 250px;
        }
        table, td, th {
            border: 1px solid #ddd;
            text-align: left;
        }
        table {
            border-collapse: collapse;
            width: 100%;
        }

            <input id="path" placeholder="cvs path"/>
            <textarea id="skills" placeholder="Key skills" rows="4" cols="50"></textarea>

                    Name
                    Email
                    Country

                    John Doe
                    john@gmail.com
                    USA

                    Michael Addison
                    michael@gmail.com
                    UK

                    Sam Farmer
                    sam@gmail.com
                    France

            <button onclick="exportTableToExcel('tblData', 'members-data')">Export Table Data To Excel File</button>

The design is more or else what I need on full browser screen:

But once the view size is changed, it does not look pretty, I need 2 changes to happen once the flex split into vertical view:

*

*The "input" and "textarea" in the first flex item to be expanded horizontally to 90% of the flex view

*The font size of the data in the table to be adjusted, so that font size became lesser but readable

A: Like said idfurw, need write the responsive CSS and I did improve few your CSS code.

function exportTableToExcel(tableID, filename = ''){
    var downloadLink;
    var dataType = 'application/vnd.ms-excel';
    var tableSelect = document.getElementById(tableID);
    var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');

    // Specify file name
    filename = filename?filename+'.xls':'excel_data.xls';

    // Create download link element
    downloadLink = document.createElement("a");

    document.body.appendChild(downloadLink);

    if(navigator.msSaveOrOpenBlob){
        var blob = new Blob(['\ufeff', tableHTML], {
            type: dataType
        });
        navigator.msSaveOrOpenBlob( blob, filename);
    }else{
        // Create a link to the file
        downloadLink.href = 'data:' + dataType + ', ' + tableHTML;

        // Setting the file name
        downloadLink.download = filename;

        //triggering the function
        downloadLink.click();
    }
}
/* added */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.flex-container {
  width: 100%;
  min-height: 100vh; /* changed */
  display: flex;
  flex-wrap: wrap;
  background-color: DodgerBlue;
}

.flex-container > div {
  /* max-width: 100%;  can remove  */
  display: flex;
  flex-direction: column;
  padding: 20px;
  margin: 10px;
  background-color: #f1f1f1;
  font-size: clamp(1rem, 3vw, 2em); /* changed */
}

#path,
#skills {
  /* will prevent resizing horizontally */
  /* resize:vertical; */
  /* width: 250px; */
  /* max-width: 250px; */
  /* min-width: 250px; */
  width: 100%; /* added */
}
table,
td,
th {
  border: 1px solid #ddd;
  text-align: left;
}
table {
  border-collapse: collapse;
  width: 100%;
}

            <input id="path" placeholder="cvs path"/>
            <textarea id="skills" placeholder="Key skills" rows="4" cols="50"></textarea>

                    Name
                    Email
                    Country

                    John Doe
                    john@gmail.com
                    USA

                    Michael Addison
                    michael@gmail.com
                    UK

                    Sam Farmer
                    sam@gmail.com
                    France

            <button onclick="exportTableToExcel('tblData', 'members-data')">Export Table Data To Excel File</button>

A: Write the responsive CSS for those elements
@media screen and (max-width:768px)