text:
Q: Python script to change dictionary content of another python script I have a Python script to create a 'mock ultrasound' machine. It runs on a Raspberry Pi, with a long USB cable at the end with an RFID reader.
The user 'scans' a mannequin with RFID chips under the skin. When it scans a chip, it displays a gif associated with the tag's string. That information is contained in 2 dictionaries. (one dictionary is 'pre-intervention' and the other is 'post intervention'. The script switches which dictionary is in use by pressing a button onscreen. The idea is that a medical learner finds a problem with their first scan, they do something to fix the problem, and then they check to see if it's been fixed.
I want to make a simple way to change which gif is associate with the tags. Something simple so my colleagues who do not know anything about coding could do on their own without me.
Either as a GUI form, or prompt for each dictionary entry (although that would not be preferable as there will eventually be a lot of dictionary entries).
Sorry if this isn't the right place.
#!/usr/bin/python3.7
import sys
import os

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import QMovie, QPixmap
from PyQt5.QtWidgets import *

WINDOW_STYLE = '''
background-color:black;
color:white;
'''

class Ui_Widget(QWidget):

    # You need to change this
    CARD_DICT = {
        # PIN:  IMAGE_PATH
        #### PRE INTERVENTION IMAGES ####
        #### Charlie ####
        #left appex
        '13603414011682': 'images/no-sliding.gif',
        #right appex
        '1360739520482': 'images/Normal-lung-sliding.gif',
        #heart
        '136010319878103': 'images/heart.gif',
        #mid clavicular
        '136073122213110': 'images/placeholder.gif',
        #sub xyphoid
        '136034217194177': 'images/subxiphoid.gif',
        #diaphragm
        '1360352372244': 'images/placeholder.gif',
        #supra umbilicus
        '1360739715155': 'images/placeholder.gif',
        #right lateral
        '136034163207198': 'images/NEGATIVE-FAST-LUQ.gif',
        #left lateral
        '1360738615152': 'images/NEGATIVE-FAST-LUQ.gif',
        # bladder
        '136072188183203': 'images/bladder.gif',

        #### Hagrid ####
        #top heart
        '13607295230121': 'images/---.gif',
        # left of the heart
        '13607311243154': 'images/---.gif',2

        #middle heart
        '13603452226124': 'images/---.gif',
        # sub xiphoid
        '136010456116172': 'images/---.gif',
        #mid clavicular
        '1360739618627': 'images/---.gif',
        # Right appex
        '136034130156180': 'images/---.gif',
        # left appex
        '136034163154147': 'images/---.gif',
        # right lateral
        '1360721779716': 'images/---.gif',
        # left lateral
        '136035225193139': 'images/---.gif',
        # bladder
        '1360341692724': 'images/---.gif'

    }
    # Change this too
    ### POST INTERVENTION IMAGES ###
    CARD_DICT_2 = {
        # PIN:  IMAGE_PATH
        #### Charlie ####
        #left appex
        '13603414011682': 'images/Normal-lung-sliding.gif',
        #right appex
        '1360739520482': 'images/Normal-lung-sliding.gif',
        #heart
        '136010319878103': 'images/heart.gif',
        #mid clavicular
        '136073122213110': 'images/placeholder.gif',
        #sub xyphoid
        '136034217194177': 'images/subxiphoid.gif',
        #diaphragm
        '1360352372244': 'images/placeholder.gif',
        #supra umbilicus
        '1360739715155': 'images/placeholder.gif',
        #right lateral
        '136034163207198': 'images/NEGATIVE-FAST-LUQ.gif',
        #left lateral
        '1360738615152': 'images/NEGATIVE-FAST-LUQ.gif',
        # bladder
        '136072188183203': 'images/bladder.gif',

        #### Hagrid ####
        #top heart
        '13607295230121': 'images/---.gif',
        # left of the heart
        '13607311243154': 'images/---.gif',
        #middle heart
        '13603452226124': 'images/---.gif',
        # sub xiphoid
        '136010456116172': 'images/---.gif',
        #mid clavicular
        '1360739618627': 'images/---.gif',
        # Right appex
        '136034130156180': 'images/---.gif',
        # left appex
        '136034163154147': 'images/---.gif',
        # right lateral
        '1360721779716': 'images/---.gif',
        # left lateral
        '136035225193139': 'images/---.gif',
        # bladder
        '1360341692724': 'images/---.gif',
        '136073148128213': 'images/placeholder.gif'
    }
    step = 1

    def __init__(self):
        super(Ui_Widget, self).__init__()
        self.setWindowTitle('Simulated Ultrasound')
        # Full screen
        self.setWindowState(Qt.WindowMaximized)
        # No close, minimize and miximaze window button
        self.setWindowFlag(Qt.FramelessWindowHint)
        self.setAttribute(QtCore.Qt.WA_StyledBackground, True)
        self.setStyleSheet(WINDOW_STYLE)
        self.setupUi(self)

    def setupUi(self, Widget):
        Widget.setObjectName("Widget")
        Widget.resize(800, 600)

        self.verticalLayout_2 = QtWidgets.QVBoxLayout(Widget)
        self.verticalLayout_2.setObjectName("verticalLayout_2")

        self.gridLayout = QtWidgets.QGridLayout()
        self.gridLayout.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)
        self.gridLayout.setObjectName("gridLayout")

        self.label = QtWidgets.QLabel(Widget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
        self.label.setSizePolicy(sizePolicy)

        font = QtGui.QFont()
        font.setPointSize(50)

        self.label.setFont(font)
        self.label.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)

        self.verticalLayout_2.addLayout(self.gridLayout)

        self.lineEdit = QtWidgets.QLineEdit(Widget)
        sizePolicy = QtWidgets.QSizePolicy(
            QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred
        )
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lineEdit.sizePolicy().hasHeightForWidth())
        self.lineEdit.setSizePolicy(sizePolicy)
        self.lineEdit.setMinimumSize(QtCore.QSize(780, 0))
        self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
        self.lineEdit.setObjectName("lineEdit")
        self.verticalLayout_2.addWidget(self.lineEdit)

        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setSizeConstraint(QtWidgets.QLayout.SetMinimumSize)
        self.horizontalLayout.setSpacing(10)
        self.horizontalLayout.setObjectName("horizontalLayout")

        self.label_2 = QtWidgets.QLabel(Widget)
        sizePolicy = QtWidgets.QSizePolicy(
            QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Maximum
        )
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label_2.sizePolicy().hasHeightForWidth())
        self.label_2.setSizePolicy(sizePolicy)
        self.label_2.setMinimumSize(QtCore.QSize(0, 10))
        self.label_2.setObjectName("label_2")
        self.horizontalLayout.addWidget(self.label_2)

        spacerItem = QtWidgets.QSpacerItem(
            40, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum
        )
        self.horizontalLayout.addItem(spacerItem)

        self.pushButton = QtWidgets.QPushButton(Widget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
        self.pushButton.setSizePolicy(sizePolicy)
        self.pushButton.setMinimumSize(QtCore.QSize(100, 50))
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)

        self.verticalLayout_2.addLayout(self.horizontalLayout)

        self.retranslateUi(Widget)
        QtCore.QMetaObject.connectSlotsByName(Widget)

        self._widget = Widget
        self.pushButton.pressed.connect(self.reset) # type: ignore
        # Check every time the text line input changed
        self.lineEdit.textChanged.connect(self.submit_pass) # type: ignore

    def retranslateUi(self, Widget):
        _translate = QtCore.QCoreApplication.translate

        Widget.setWindowTitle(_translate("Widget", "Widget"))
        self.label.setText(_translate("Widget", "Simulated Ultrasound"))
        self.lineEdit.setPlaceholderText(_translate("Widget", "PIN Phrase"))
        self.label_2.setText(_translate("Widget", "Type your PIN Phrase. Then press ENTER to submit"))
        self.pushButton.setText(_translate("Widget", "Reset"))
        selt.pushButton.setStyleSheet("color = black;")

    def submit_pass_str(self, input_str):
        """here the application accept user input"""
        if input_str in self.CARD_DICT:
            if self.step == 1:
                self.display_image(self.CARD_DICT[input_str])
            else:
                self.display_image(self.CARD_DICT_2[input_str])
            self.label_2.setText('')
        else:
            self.label_2.setText(f'Invalid: {input_str}')

    def display_image(self, path):
        name, ext = os.path.splitext(path)
        if ext and ext.lower() == '.gif':
            movie = QMovie(path)
            self.label.setMovie(movie)
            movie.start()
        else:
            image = QPixmap(path)
            self.label.setPixmap(image)
        self.label.setMinimumSize(1, 1)

    def submit_pass(self):
        """Usage example using PIN Phrase input form"""
        self.submit_pass_str(self.lineEdit.text())

    def reset(self):
        _translate = QtCore.QCoreApplication.translate

        if self.step == 1:
            self.pushButton.setText(_translate("Widget", "Close"))

        self.pushButton.pressed.connect(self._widget.close) # type: ignore
        self.label.setText(_translate("Widget", "Simulated Ultrasound"))
        self.step += 1
        self.lineEdit.setFocus(True)

app = QApplication(sys.argv)
window = Ui_Widget()
window.show()
sys.exit(app.exec_())


text:
Q: How to make Twitter app style Quick Actions on Android Is there any code that gives an example about how to implement the Quick Actions and Popdown menu that is displayed in the Twitter for Android app?

A: Funny you should ask that as I just have happened to finish working on this exact thing. You can check out the code here simple quickactions for android

redpajama_set_name: RedPajamaStackExchange


text:
Q: Algorithm expressing a fraction as a sum of unit fractions I am looking for an algorithm to express some fraction $\frac{a}{b}$, with $a,b \in \mathbb{Z}$, as a sum of unit fractions, like:
$$\frac{a}{b} = \frac{1}{w_1} \pm \frac{1}{w_2} \pm \frac{1}{w_3} \pm ... \pm \frac{1}{w_i}$$
I know of the Greedy Algorithm for Egyptian Fractions:
(https://en.wikipedia.org/wiki/Greedy_algorithm_for_Egyptian_fractions#)
but this only generates positive fractions, whereas the ability to use negative fractions can decrease the number of terms needed. Also, the greedy algorithm often generates expansions with terms whose denominators are far larger than necessary.
I do not need the fractions to be positive, and I do need the denominators to be relatively small.
Does anybody know of such an algorithm?
Thanks


text:
Q: Missing older iTunes purchased music on new MacBook I just bought a new MacBook Air and signed into my iTunes account to get my music, but only my most recently purchased songs showed up, and a couple of other random songs.
I tried looking at my previous purchased music not on this device, to see if I could re-download it, but they wouldn't show up. But when I looked up one of the missing albums, it said "purchased" but gave me no little cloud icon to download it.
Please help.


text:
Q: How to debug 'no entities specified' when working with ZSync and CoreData Syncing I'm trying to get ZSync to work between a desktop and iPhone app. I've got my schemas set up and all info matches between my MOM and my schema so I should be good to go. When I initiate my sync, however, I get this error.

|Miscellaneous|Error| SyncServices
  precondition failure in  [ISyncSession
  _validateClient:entityNames:beforeDate:clientHasTruthForEntityNames:target:selector:]:
  no entities specified

Anyone know what this means, and how to debug it?
I'm a novice with this SyncServices stuff.
Cheers!
Update
Ok, I've got it showing in syncrospector, but still getting the unrecognized error.
What do you mean by my clientdescription at the Daemon is wrong?
Thanks.
Update
Alright, I had the clientDescription working , but now when this fires:

ZAssert([[ISyncManager sharedManager]
  registerSchemaWithBundlePath:path],
  @"Failed to register sync schema");

I get this error :(

[NOTE: this exception originated in
  the server.]
  *** -[NSCFArray insertObject:atIndex:]: attempt to
  insert nil

A: This is an issue in your Sync Services settings.  It means that you have not declared what entities need to be synced.  I suggest comparing your SyncSchema subproject (for your desktop app side) to the one included in the SampleDesktop project.
update

I checked all that, to no avail. I am using a versioned mom, would that make a difference? In my ManagedObjectModels, should I use the name of the version or the collection? (mom or momd?) Thanks, I'm almost there!

No, the schema should point to your latest model.  Are you certain that it is pointing to it correctly?  That can be one of the trickiest bits.  Are you including the model in the schema bundle or are you making a reference to it?
update
First, please put these updates into your question, the comment section is really not meant for them.

Alright, got past this problem. Syncing starts now I get "failed to register client because: client named Xmac wants to sync unrecognized entity named: X.Entity" This happens with all my entities, sadly.

This error means that your sync schema is still not completely valid.  Does your desktop client sync?
Can you see its data in the syncrospector?
If so then your clientdescription at the Daemon is wrong.  If it doesn't sync then solve that first as it sounds like your SyncSchema bundle is still incorrect.  I suggest trying to compare it against the sampleDesktop application that is included in the project.
update Syncrospector

Ok, I've got it showing in syncrospector, but still getting the unrecognized error. What do you mean by my clientdescription at the Daemon is wrong? Thanks.

In the syncrospector I am guessing that you are seeing all of your entities and data?
On the Daemon, there is a clientDescription.plist.  This plist describes what data that the Daemon is going to sync with.  That plist needs to be updated (since the default one refers to the sample app, etc.) to reference your data structures just like your desktop application does.
In the very near future, this piece will be moved to a plugin so that you are not modifying the daemon directly.  Expect to see updates on the project itself during the next couple of weeks.  But for now, (and will be reusable), modify the plist inside of the daemon and you should be ready to sync.
update ZAssert
That line unwinds into:
BOOL success = [[ISyncManager sharedManager] registerSchemaWithBundlePath:path];
NSAssert(success, @"Failed to register sync schema");

A few things can cause this:

*

*Your path is nil, check that in the debugger

*There is something wrong with your sync schema.

What other debug comments are you seeing?


text:
Q: Why is there still padding on the righthand side when using Bootstrap? I am trying to build a small, information website using boostrap just to familiarize myself with it.  Everything was working fine until I realized there is a horizontal scrollbar at the bottom of the screen on all of my pages, and, no matter what I try, there seems to be a small gap ever-present on the righthand side.  I have placed my elements within a DIV using the container-fluid class.  I have overridden the container-fluid class and made the left and right padding 0px, as well as the margins.  So I went back to the most bare-bones skeleton of a page, nothing more than a navbar and a few rows and columns with some red-bordered divs.  I have read several similar questions and tried all of their advice, and nothing is working.  Can anyone tell me what I'm missing here?  Below is the skeletal HTML I'm using and the relevant CSS:
HTML:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Black Lotus Designs</title>

    <link rel="stylesheet" href="./bootstrap-5.0.2-dist/css/bootstrap.css">
    <link rel="stylesheet" href="./Javascript/jquery-ui-1.13.0/jquery-ui.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.compat.css"/>

        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Spectral&display=swap" rel="stylesheet">

        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Brawler&family=Caladea&family=Oswald:wght@300&family=Poppins:wght@100;200&family=Roboto:wght@300&family=Spectral&display=swap" rel="stylesheet">

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Brawler&family=Caladea&family=Poppins:wght@100;200&family=Roboto:wght@300&family=Spectral&display=swap" rel="stylesheet">

    <link rel="stylesheet" href="./CSS/globals.css">
    <link rel="stylesheet" href="./CSS/about.css">

    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Home

            Services

Services

Typographic Elements

Basic Animations

          Portfolio

          About

          Blog

          Gallery

          Contact

      <form class="d-flex">
        <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
        <button class="btn btn-outline-success" type="submit">Search</button>
      </form>

CSS:
.red {
    border: 2px solid red;
    width:150px;
    height:150px;
}
.container-fluid {
          padding-left: 0px !important;
          padding-right: 0px !important;
          margin: 0px !important;
      }

Thank you in advance....it has been so frustrating, and I assume it is something very simple that I'm overlooking.  It's always the super obvious thing that gets me.  Here's a screen shot---if there's a better solution than hiding stuff, please let me know
enter image description here

A: I have probably screwed something else up by doing this, but I tried using overflow:hidden and it worked!  I have the feeling this is going to come back to bite me somewhere...so if anyone knows a better way....isn't the whole point of bootstrap to make things easier?


text:
Q: Styling checkboxes that are even children I have a whole bunch of checkboxes and want to style all the ones that are even children i.e 2nd, 4th, 6th, 8th.
I have tried doing the following but to no avail.
.basic li > div .choices input[type="checkbox"] {
    width:14px;
    height:14px;
    float:left;
    border:0 none;
    background:#fff;
    padding:0;
}

.basic li > div .choices input[type="checkbox"]:nth-child(2n-1) {
    margin:0px 0px 0px 60px;
}

A: Use :nth-child(even) or :nth-child(2n+0) (any calculation resulting in an even integer) according to:
http://www.w3.org/TR/css3-selectors/


text:
Q: How do I change the font size of Google Chrome's address bar? I set my system font to GNU Unifont, because I like it's pixelated look. I scaled the fonts to the right size so they don't blur at all, however the font in Google Chrome's address bar is smaller than all the other text. How do I change the font size? Is it possible? (Complicated instructions are okay.)
Image:

A: You don't say what window manager you are using (KDE, GNOME, etc.), but I can see the tag linux-mint.
Tab Font Size
If using KDE Plasma 5, you can change the tab font size via:

*

*Start Menu -> System Settings -> Application Style -> GNOME/GTK Application Style -> Font

However, this does not change font size of the omnibar.

In my Debian/KDE Plasma 5 installation, the default font setting was "Noto Sans 10".
Credit: https://forum.kde.org/viewtopic.php?f=67&t=154062
Omnibar Font Size
You can change the omnibar font size (and all menus / dialogs / labels) with this command:

$ google-chrome-stable --force-device-scale-factor=1.5
Adjust the value (1.5) to something that looks good on your setup.
Credit: https://community.brave.com/t/adjust-address-bar-size/98884


text:
Q: Why does this implementation of COM IUnknown::Release work? From examples I've seen COM IUnknown::Release() function implementation is something like that:
ULONG Release()
{
    InterlockedDecrement(&m_count);
    if(m_count == 0) {
       delete this;
    }
    return m_count;
}

So, if m_count is 0, so we're deleting "this" object, and returning the ref count.
What I don't understand is why it works ?!?!

*

*Deleting the object wouldn't ruin the call stack or is it okay because it is being held by the thread, so it has nothing to do with the object ???

*If the object has been deleted, how is it possible that we can return m_count, it should've been deleted. I could have convinced myself that it's okay if after the delete the code would return hard-coded 0, but how come it can return the member ?!?!
Thanks a lot for your help! :-)

A: That code is bogus. One can never trust m_count after the decrement. The correct code is always like this:
ULONG Release()
{
     ULONG count = InterlockedDecrement(&m_count);
     if(count == 0){ delete this; }
     return count;
}

A: What you observe is undefined behavior. The call stack is not changed by delete this; and delete this by itself is always safe but renders this pointer invalid which means you can't dereference it anymore.
There're two possible explanations of what you observe. Either the implementation in question just doesn't dereference this pointer to obtain m_count when returning from the function - it has it loaded onto a register and just uses that value and so this is not dereferenced and you don't observe any problem or when delete finishes the memory occupied by the object is still mapped into the process address space and remains technically accessible and so dereferencing this succeeds and m_count is read successfully. I suppose the latter is more likely.
Whatever the explanation is that undefined behavior, you can't rely on that, use what user Remus Rusanu suggests in his answer.


text:
Q: Date comparison and showing a list of unique dates from controller to view I have a list of dates that I want to compare with another set of dates (which I got using JS).
Given the range;
Start Date: 11/1/2017 12:00:00 AM
End Date: 11/20/2017 12:00:00 AM

Using the query;
var mod = (from m in lst
                              where m.RId == EN &&  m.Date >= startDate && m.Date <= endDate
                              select m).Distinct();
                   var earlyMod = mod
                    .GroupBy(dt => dt.Date)
                    .Select(z => z.OrderBy(y => y.Date).First())
                    .ToList();
                    var presRowCount = 0; //to get the count

                    presRowCount = earlyMod.Count();
                    ViewBag.presRowCount = presRowCount;
                        return View(earlyMod);

In the View;
 @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.RegisterationId)

                @Html.DisplayFor(modelItem => item.DateTime)
                @ViewBag.Dates

                @Html.DisplayFor(modelItem => item.Date)

....}

What I get in the View is (Let's call it presentDates);
11/9/2017 8:02:09 AM
11/10/2017 11:23:04 AM
11/14/2017 10:11:11 AM

What I also have in the view is this JS function which has another set of dates (excluding weekends);


text:
Q: ReOpen last active accordion after form submit I am submit a form which is present in 5th accordion and after submitting the form the page is getting reload and default first accordion is getting .active after reload.
I want the last active accordion to be active after page reload.
var query = $('#isOtherOptions').val();
        if(query=='true')
            {
               $(tabPanelNav).find('li').last().addClass('active');
               $('.configTab').addClass('active').show();

            }else{
                $(tabPanelNav).find('li').first().addClass('active');
                $(container).find('dd').first().addClass('active').show();

            $(tabPanelNav).addClass('full');

    });

    $('.panel-tab-list nav a').not('.active').on('click touchstart', function(e){
          e.preventDefault();
          var contentContainer = $('#' + $(this).attr('rel'));
          $(this).closest('nav').find('.active').removeClass('active').end().end().closest('li').addClass('active').closest('.panel-tab-list').find('dd.active').hide();

        $(contentContainer).show().addClass('active');

    });


text:
Q: Matcher overrides other arguments When I try to test below params, It throws different arguments exception. But when I update the document argument from anyString() to "{"date":"2022-10-17"}" test succeeds as expected. I think anyString() matcher somehow overrides other arguments. Is there any way to resolve this issue?
verify(client).createUser(new CreateUserRequest()
        .withName("test")
        .withDocument(anyString())
        .withDescription(""));

Output:
Argument(s) are different! Wanted:
client.createUser(
    <any string>
);

Actual invocation has different arguments:
client.createUser(
    {name: test,Document: {"date":"2022-10-17"},Description: }
);


text:
Q: I'm new to programming and am trying my hand at writing my own reverse function. Not going as planned Below is a bit of code which seems to work at the start but populates my holding variable with half while leaving the other have in the list that I'm trying to give list elements from. The last element specifically. I don't know why this is not iterating through the entire flist. Help?
Thanks
Sembor
def reverse(text):
    flist = []
    holding = ""
    for i in str(text):
      flist.append(i)
    print(flist)

    for i in flist:
      holding = holding + flist[-1]
      del flist[-1]
      print(holding)

    print(flist)
reverse("JamesBond")

A: Instead of trying to modify your list while iterating over it. Instead, what you should do, is simply create a new string, and append the letters in the reverse order. You can do this by counting backwards using range:
def reverse(text):
    reverse_string = ""
    for i in range(len(text) - 1, -1, -1):
        reverse_string += text[i]
    print(reverse_string)
reverse("JamesBond")

However, the best way to do this in python, is by making use of slicing, in which, you can simply do:
reverse_string = text[::-1]

A: As this comment says, the problem is that you're modifying the list as you're iterating over it.
Basically, for i in range plist isn't going through all the elements since you making the list shorter as you loop through it. This is what's happening to your list as you're iterating it.
holding    plist
d          ["J","a","m","e","s","B","o","n","d"]
             ^
dn         ["J","a","m","e","s","B","o","n"]
                 ^
dno        ["J","a","m","e","s","B","o"]
                     ^
dnoB       ["J","a","m","e","s","B"]
                         ^
dnoBs      ["J","a","m","e","s"]
                             ^ #can't loop any further

What you can do instead is something like this
for i in range(len(plist), -1, -1):
    holding = holding + plist[i]

Or this
def reverse(text):
    return text[::-1]

Or you could use the built in reversed function, like equaio did.

A: When creating lists from strings you can use list.comprehension:
[i for i in text]
And you could reverse this by using enumerate for instance:
[text[-ind-1] for ind, i in enumerate(text)]

A: as I understand you want to take the string "JamesBond" and reverse it to "dnoBsemaJ". I am also extremely new to Python. I gave your function a try and came up with the following. It may not be the prettiest but it does reverse the text.
def reverse(_string):
    _stringLen = len(_string)
    i = _stringLen - 1
    _newstring = ""
    while i >= 0:
        _newstring = _newstring + _string[i]
        i -= 1
    return _newstring

print reverse("JamesBond")

Prints out : dnoBsemaJ

A: Splicing can help you unless you do want to write the algorithm to reverse
>>> k = 'JamesBond'
>>> rev_str = k[::-1]
>>> rev_str
'dnoBsemaJ'
>>> type(rev_str)
<type 'str'>


text:
Q: C++: cannot assign index to iterator Okay, a small problem with, hopefully, a quick, simple solution.
In my school textbook, in a chapter about the STL, it gives a simple sample program to input for using lists and for using an iterator with a list, like so:
#include <list>
#include <iostream>
#include <string>
using namespace std;

int main()
{
    list<int> myIntList;

    // Insert to the front of the list.
    myIntList.push_front(4);
    myIntList.push_front(3);
    myIntList.push_front(2);
    myIntList.push_front(1);

    // Insert to the back of the list.
    myIntList.push_back(5);
    myIntList.push_back(7);
    myIntList.push_back(8);
    myIntList.push_back(9);

    // Forgot to add 6 to the list, insert before 7.  But first
    // we must get an iterator that refers to the position
    // we want to insert 6 at.  So do a quick linear search
    // of the list to find that position.
    list<int>::iterator i = 0;
    for( i = myIntList.begin(); i != myIntList.end(); ++i )
        if( *i == 7 ) break;

    // Insert 6 were 7 is (the iterator I refers to the position
    // that 7 is located.  This does not overwrite 7; rather it
    // inserts 6 between 5 and 7.
    myIntList.insert(i, 6);

    // Print the list to the console window.
    for( i = myIntList.begin(); i != myIntList.end(); ++i )
        cout << *i << " ";   cout << endl;
}

Now, at the line that says
list<int>::iterator i = 0;

I get an error in VS 2015 that says:
no suitable constructor exists to convert from"int" to "std::_List_iterator<std::_List_val<std::_List simple_types<int>>>"

What is the problem with the code presented, what is the solution, and why is this a problem to begin with? <-(I'll even settle with a simple grammatical error).

A: The value 0 may not be a valid value for an iterator.  Try either removing the assignment or assigning the iterator to myIntList.begin().
The iterator may not be able to be treated as an index, like with a vector or array.  Usually linked lists are not accessed by index; you have to traverse from the beginning.

A:
What is the problem with the code presented

A simple typo in the example.

what is the solution

Replace this line:
list<int>::iterator i = 0;

With this instead:
list<int>::iterator i;

why is this a problem to begin with?

You cannot initialize an iterator with an integer value.  Only the container knows what its iterators refer to, so only the container can initialize them.  All you can do is request an iterator from a container, assign an iterator to another iterator, and increment/decrement/dereference an iterator.  That is all.

A: From http://www.cplusplus.com/reference/iterator/:

An iterator is any object that, pointing to some element in a range of elements (such as an array or a container), has the ability to iterate through the elements of that range using a set of operators (with at least the increment (++) and dereference (*) operators).

This means that an iterator should be able to do the following:

*

*Return the object it's currently "pointing" to (using the * operator)

*Change itself to "point" to the next object in its list (using the ++ operator)

A reason for the existence of the iterator as a data type is to create a general way of interacting with different kinds of lists.  However, this means that different lists will implement their iterators differently.
In many circumstances, initializing an iterator to a number doesn't make sense because of the implementation under the hood.  As a result, we don't define an assignment operator with our iterator type std::vector<int>::iterator on the left and an int on the right.  So when you try to assign your iterator to an integral value, list<int>::iterator i = 0; your compiler throws an error.
Let's look at an example where assigning an iterator to 0 doesn't make sense.   You could implement an iterator for std::vector<int> as a pointer to an element in your vector.  In this case:

*

** dereferences the pointer stored in vector<int>::iterator and returns its value.

*++ modifies the pointer stored in vector<int>::iterator to point at the next element in the list.

However, assigning this pointer to 0 would be the same as assigning it to NULL, and dereferencing it no longer returns a valid element in your vector.  (In fact, dereferencing NULL will cause an error!)
To avoid this error, simply make sure that you always assign your iterator to a value of the same type.  In the STL, this is usually accomplished by using .begin() to return an iterator that points to the first element in your list.


text:
Q: Need to get the first image link with Python I need to get the link of the first photo from the link "https://www.balticshipping.com/vessel/imo/9127382" using Python.
I am testing with the BeautifullSoup library but there is no way to get it. From what I see, the image is not in JPG or PNG format, therefore, it does not detect it.
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re

html = urlopen('https://www.balticshipping.com/vessel/imo/9127382')
bs = BeautifulSoup(html, 'html.parser')
images = bs.find_all('img', {'src':re.compile('.png')})
for image in images:
    print(image['src']+'\n')

Does anyone have any ideas how to do it?
Full Loop Code: ("s" contains many ships data (IMO, date, shipname...))
def create_geojson_features(s):

features = []

for _, row in s.iterrows():
    vessel_id = row['IMO']

    data = {
        "templates[]": [
            "modal_validation_errors:0",
            "modal_email_verificate:0",
            "r_vessel_types_multi:0",
            "r_positions_single:0",
            "vessel_profile:0",
        ],
        "request[0][module]": "ships",
        "request[0][action]": "list",
        "request[0][id]": "0",
        "request[0][data][0][name]": "imo",
        "request[0][data][0][value]": vessel_id,
        "request[0][sort]": "",
        "request[0][limit]": "1",
        "request[0][stamp]": "0",
        "request[1][module]": "top_stat",
        "request[1][action]": "list",
        "request[1][id]": "0",
        "request[1][data]": "",
        "request[1][sort]": "",
        "request[1][limit]": "",
        "request[1][stamp]": "0",
        "dictionary[]": ["countrys:0", "vessel_types:0", "positions:0"],
    }

    data = requests.post("https://www.balticshipping.com/", data=data).json()
    image = data["data"]["request"][0]["ships"][0]["data"]["gallery"][0]["file"]
    print(image)
    feature = {
        'type': 'Feature',
        'geometry': {
            'type':'Point',
            'coordinates':[row['lon'],row['lat']]
        },
        'properties': {
            'time': pd.to_datetime(row['date']).__str__(),
            'popup': ""+'
'+'
'+'Shipname: '+row['shipname'].__str__() +'
'+ 'MMSI: '+row['mmsi'].__str__() +'
' + 'Group: '+row['group'].__str__() +'
''Speed: '+row['speed'].__str__()+' knots',
            'style': {'color' : ''},
            'icon': 'circle',
            'iconstyle':{
                'fillColor': row['fillColor'],
                'fillOpacity': 0.8,
                'radius': 5
            }
        }
    }
    features.append(feature)
return features

A: The data you see are loaded via Ajax from external source. You can use this example how to get the picture URLs:
import json
import requests

url = "https://www.balticshipping.com/vessel/imo/9127382"
vessel_id = url.split("/")[-1]

data = {
    "templates[]": [
        "modal_validation_errors:0",
        "modal_email_verificate:0",
        "r_vessel_types_multi:0",
        "r_positions_single:0",
        "vessel_profile:0",
    ],
    "request[0][module]": "ships",
    "request[0][action]": "list",
    "request[0][id]": "0",
    "request[0][data][0][name]": "imo",
    "request[0][data][0][value]": vessel_id,
    "request[0][sort]": "",
    "request[0][limit]": "1",
    "request[0][stamp]": "0",
    "request[1][module]": "top_stat",
    "request[1][action]": "list",
    "request[1][id]": "0",
    "request[1][data]": "",
    "request[1][sort]": "",
    "request[1][limit]": "",
    "request[1][stamp]": "0",
    "dictionary[]": ["countrys:0", "vessel_types:0", "positions:0"],
}

data = requests.post("https://www.balticshipping.com/", data=data).json()

# uncomment to print all data:
# print(json.dumps(data, indent=4))

for g in data["data"]["request"][0]["ships"][0]["data"]["gallery"]:
    print(g["file"])

Prints:
https://photos.marinetraffic.com/ais/showphoto.aspx?photoid=2948097
https://photos.marinetraffic.com/ais/showphoto.aspx?photoid=2864147
https://photos.marinetraffic.com/ais/showphoto.aspx?photoid=2830344
https://photos.marinetraffic.com/ais/showphoto.aspx?photoid=2674783
https://photos.marinetraffic.com/ais/showphoto.aspx?photoid=2521379
https://photos.marinetraffic.com/ais/showphoto.aspx?photoid=2083722
https://photos.marinetraffic.com/ais/showphoto.aspx?photoid=2083721
https://photos.marinetraffic.com/ais/showphoto.aspx?photoid=1599301
https://photos.marinetraffic.com/ais/showphoto.aspx?photoid=1464102
https://photos.marinetraffic.com/ais/showphoto.aspx?photoid=1464099
https://photos.marinetraffic.com/ais/showphoto.aspx?photoid=1464093
https://photos.marinetraffic.com/ais/showphoto.aspx?photoid=1464089
https://photos.marinetraffic.com/ais/showphoto.aspx?photoid=1110349
https://photos.marinetraffic.com/ais/showphoto.aspx?photoid=433106


text:
Q: Remove Duplicates by Unique Value in another Column I have a dataframe that looks like this:
  COLA       COLB     COLC
    A         nb       1
    A         nc       0.8
    A         bc       0.7
    A         nb       0.7  <------------
    B         nb       1
    B         nc       0.3  <------------
    B         nc       0.8
    B         aa       0.9

I want to remove the duplicates in COLB by COLA unique ID and keep the maximum value of that duplicate from COLC.
So I want the final result to look like this ( pointed to the rows I want to delete in the previous table):
  COLA       COLB     COLC
    A         nb       1
    A         nc       0.8
    A         bc       0.7
    B         nb       1
    B         nc       0.8
    B         aa       0.9

A: We can use dplyr.  After arrangeing the 'COLA", and descendingly the 'COLC', we group by 'COLA', 'COLB' and get the first row with slice.
library(dplyr)
df1 %>%
   arrange(COLA, desc(COLC)) %>%
   group_by(COLA, COLB) %>%
   slice(1L)


text:
Q: Unhandled Rejection (TypeError): action.assetList is not iterable I don't know why it is giving me this error, I am quite new at this
This is what my 2 files throwing the error looks like
This is my crypto.js file

const crypto = (state = cryptoDefault, action) => {
  switch (action.type) {
    case UPDATE_ASSET_LIST:
      // eslint-disable-next-line
      return [
        ...action.assetList,
      ];
    case UPDATE_CRYPTO_ASSET:
      // eslint-disable-next-line
      return {
        ...action.assetData,
      };
    default:
      return state;
  }
};

export default crypto;

This is my index.js file

const updateApiRenderList = () => (dispatch, getState) => fetchApiCryptoList(
  {
    url: null,
    currency: getState().currencyFilter,
  },
)
  .then((result) => {
    dispatch(updateAssetList(result));
  }).catch((error) => {
    throw (error);
  });

export {
  updateAssetList, updateCryptoAsset,
  nextPage, prevPage, updatePage,
  fetchApiAssets, fetchApiSuccess, fetchApiFailure,
  updateApiRenderList,
  filterUpdate,
  currencyUpdate,
  getCurrenCurrency,
};


text:
Q: MLE by rounding xbar to nearest integer Suppose $X_1, X_2, ..., X_n$ -
$iid ∼ \mathcal{N}(µ, σ2)$, where $µ ∈ Z$ and $σ$ is a power of 10, i.e. $log_{10}(σ) ∈ Z$.
a) Show that $f(a)
=\sum((x_i − \bar{x} - a)^2)$
is a symmetric function with respect to $a$. That is, prove
that $f(a) = f(−a)$.
b) Use your answer in (a) to argue that the MLE can be found by rounding $\bar{x}$ to the nearest integer.
c) Propose an estimator for $σ$ that maximizes the likelihood such that $log_{10}(σ) ∈ Z$.
I solved a, but I'm not quite sure for b and c. Please.


text:
Q: Video server using java I'm making a social media app (currently mobile and soon also web) and it concentrates on videos. I've two problems:
1) from the android app, my current design requests for new feeds from a web service --> the server responds with json data that includes the video url and the other feed data (content, date, ... etc) --> then I set the url for the VideoView which will request the video. Now isn't there a better way so that I fetch a full feed with one request (with one request I return the data and the video/audio/image)?
Also after researching online, some say that you use an IntentService to keep fetching new feeds and cash it locally and some say not. what is the best approach for a social network app in the backend.
2) I read online that http streaming is a very bad idea if you expect multiple concurrent requests for the same video/audio (I don't know if this applies for images too), the limit is almost a dozen of requests. how should the backend store and send videos/audio back to the mobile/web app in an efficient way? how does big social network store their data and send back so that the used can have the best experience (I know my app won't have .01% traffic compared to large social media sites, but I'm expecting thousands of users and hundreds of them might request the same video at the same time)? any link for a server (preferably using Java) to do such thing will be appreciated.
so long story short, if someone can help me find a good resource to design a backend for a soical media app, that would be great. and sorry for the long post.

A: Your approach seems fine if it works for you - you don't need to use the same server for all your content and a typical 'pattern', which may reassure you is:

*

*static content on simple static web hosting or CDN (e.g. Amazon S3 or simple static web server) - this is content which does not change all that often, like pictures, heading text, info text etc

*dynamic content on whatever is your favourite flavour of web server/language technology - this is the content that changes per user or frequently over time.

*Video and audio hosted on a separate dedicated streaming server, linked to a CDN mostly likely, or on a web hosting service that specialises in video/audio.

The reason for separating the video is that the technology for streaming videos is quite specialist and if you really want to support many devices then you actually need multiple versions of your video to support all browser/device and network bandwidth combinations. If you want to get started quickly a good cloud video hosting service will do the hard work for you here and allow your videos appear without any 'YouTube' like branding/ads etc.
If you want to run your own video server then there are open source options like VideoLan and GStreamer or paid versions like Woza:

*

*http://www.videolan.org/vlc/streaming.html

*http://gstreamer.freedesktop.org

*http://www.wowza.com/products/streaming-engine


text:
Q: PHP add key data to json Have a nice day. I have created the following basics:
{
    "1111": {
        "h264": {
            "url": "TEST",
            "expire": 1649453177
        }
    }
}

I need to add the following lines to the same key:
{
    "1111": {
        "h264": {
            "url": "TEST",
            "expire": 1649453177
        },
        "h265": {
            "url": "TEST",
            "expire": 1649456380
        }
    }
}

But whatever I try, it does this to me:
{
    "1111": {
        "h264": {
            "url": "TEST",
            "expire": 1649453177
        },
        "0": {
            "h265": {
                "url": "TEST",
                "expire": 1649456380
            }
        }
    }
}

Here is some sample code:
$time = time();
$codec = "h265";
$url = "TEST";
$id = "1111";
$data = json_decode(file_get_contents('./data.json'), true);
$post_data = array($codec => array('url' => $last_line,'expire' => $time));
array_push($data[$id], $post_data);
$data = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
file_put_contents('./data.json', $data);

Can someone advise me not to add the 0 key to me there

A: Change:
$post_data = array($codec => array('url' => $last_line,'expire' => $time));
array_push($data[$id], $post_data);

To:
$post_data = array($codec => array('url' => $last_line,'expire' => $time));
$data[$id]['h265'] = $post_data;


text:
Q: How can I handle an interface method that may or may not be async? I am attempting to create a serialization interface (similar to Cocoa's NSCoding protocol) so that I can get a quick binary representation of a class to send across a network or store in a database.  However, some cases (especially involving image encoding) have many async-only methods that require awaiting.  However, if the bytes do not get written in order then of course the whole representation is corrupted.  I must make sure that the current object is finished serializing before I continue to the next object.  Here is the main loop of what I am doing.
 public async static Task<byte[]> Serialize(this IList<ISerializable> list) {
        using (Archiver archiver = new Archiver()) {
            archiver.Write(list.Count);
            foreach (ISerializable value in list) {
                await archiver.Write(value);
            }
            return archiver.Result;
        }
    }

Archiver just uses MemoryStream and BitmapWriter under the hood to write either values that BinaryWriter can accept directly, or ISerializable objects, and then spits out the result as a byte array.  ISerializable is just an interface with two methods (Serialize and Deserialize).  They both return Task so that they can be awaited.  The problem is when I have a serialization method that doesn't have any async components.  I can do one of two things:
A)  I can tack on async to that class's serialization methods anyway and put up with the compiler warning saying that it will execute synchronously (I don't like to have compiler warnings).
B) Manually return an empty task at the end of the method (return Task.Run(() => {});).  However, this looks and smells really weird.
Both A and B seem to execute without a problem, but are there any problems with this approach that I may have missed?  I am not aware of a binary serializer in Windows Runtime (I included the tag just to dispel any confusion).  Perhaps there is an option C that I can consider?  Actually I didn't want to make the serialization methods async, but for some reason task.Wait() was not waiting, and I was getting a null reference exception from trying to use an object created with CreateAsync before it was ready.
EDIT I thought of an option C.  I could just wrap the entire method in an await Task.Run(...) call.  Would this be normal?

A: I think the best solution here, assuming you want to execute the method synchronously is to write it normally, except you will return a completed Task at the end of the method.
To get a completed Task with some specific value, you can use Task.FromResult().
If you want a Task with no value (i.e. actually just Task, not Task<TResult>), you can use for example Task.FromResult(true) (which is a Task<bool>) and implicitly cast it to Task.


text:
Q: mysql get minimum date, combine columns with group by I have a MySQL table as follows: id, date and multiple int fields with 0/1. Only one int field in each row will contain a single 1 with the other columns all 0. Dates can be repeated for each id.
id     | date         | isX | isY | isZ
-------+--------------+-----+-----+-----
111111 | '1994-04-09' | 0   | 1   | 0
222222 | '1991-07-29' | 1   | 0   | 0
222222 | '1991-07-29' | 0   | 1   | 0
333333 | '1993-06-29' | 0   | 0   | 1
333333 | '1993-06-29' | 0   | 1   | 0
333333 | '1996-04-09' | 0   | 1   | 0

I want to get a single row for each id, with the earliest date and a 1 in each int column if any row with that id and date have a 1 (0 otherwise).
id     | date         | isX | isY | isZ
-------+--------------+-----+-----+-----
111111 | '1994-04-09' | 0   | 1   | 0
222222 | '1991-07-29' | 1   | 1   | 0
333333 | '1993-06-29' | 0   | 1   | 1

I was using the following command to combine the int columns
select id,
    if(sum(isX)>0,1,0) as isX,
    if(sum(isY)>0,1,0) as isY,
    if(sum(isZ)>0,1,0) as isZ
from table group by id;

but I wasn't sure how to use only those rows with the minimum date and how to add the date to the output.

A: You were there, just add min(date)
select id,
    min(`date`) as mindate,
    if(sum(isX)>0,1,0) as isX,
    if(sum(isY)>0,1,0) as isY,
    if(sum(isZ)>0,1,0) as isZ
from table
group by id;

If you didn't want rows for each id where the rows date is not the id's min(date) then you'll need a subquery:
select id,
    `date`
    if(sum(isX)>0,1,0) as isX,
    if(sum(isY)>0,1,0) as isY,
    if(sum(isZ)>0,1,0) as isZ
from table
  INNER JOIN (SELECT id, min(date) as mindate FROM table GROUP BY id) sub1 ON
      table.id = sub1.id AND
      table.`date` = sub1.`date`
group by id, `date`;

Now the if(sum(isx... logic will only be used against records where the date is the min(date) for the id.


text:
Q: How to remove  from a PHP page I'm developing a small website and to include the header in using PHP's include() function. However directly before any code brought in from the include, there's this weird   on the page.
Here's code for page where it's happening
<!DOCTYPE html>
<html>

<head>
    <title>Things and Stuff | Source Files</title>
    <!-- Style Sheets/Scripts/Misc Stuff -->
    <link rel="stylesheet" type="text/css" href="css/main.css">
    <link rel="stylesheet" type="text/css" href="css/gmod.css">
    <link rel="stylesheet" type="text/css" href="css/alerts.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script src="scripts/cycle.js"></script>
</head>

<body>

<?php include('./utilities/header.php'); ?>

<!-- rest of the page from here down... -->

EDIT W/ SOLUTION
I figured it out thanks to help from below.
To fix I opened the file in Notepad++, set it to PHP, and at the top under Encoding, selected ANSI (found that was = to UTF-8 w/o BOM) and it worked!

A: Your header file contains a Byte Order Mark header, not clearly visible be text editors which understand them and do not print them.
Compilers/parser, on the other hand, expect full ASCII, and don't understand BOM marks.
Solution: Remove the 3 first bytes of your header file with an hex editor  or a text editor set to ASCII or UTF8 without BOM encoding and it will work.
below screenshot of the file encoded in UTF8 with BOM with 3 first chars highlighted (using frHed)

If I remove the 3 first bytes it works.
OR: open with Notepad++ and change encoding to ASCII, save, voilà.

A: Check your PHP file encoding. Try using UTF8 without boom, and make sure your php has no empty spaces at the top of the file.


text:
Q: How to get the number of clicks on a link from wikipedia? Now we have the code that scrapes the links in an article. We need also the number of clicks on a link. Can some one help?
Sow far we have this code:
String[] articles = {"Abdominal_pain"};

void setup() {

    for (int i = 0; i < articles.length; i++) {

        String article = articles[i];
        String start = "20160101"; // YYYYMMDD
        String end = "20170101"; // YYYYMMDD

        // documentation: https://wikimedia.org/api/rest_v1/?doc#!/Pageviews_data/get_metrics_pageviews_per_article_project_access_agent_article_granularity_start_end
        // >> https://en.wikipedia.org/w/api.php?action=query&format=json&prop=links&meta=&titles=Albert+Einstein&pllimit=500
        String query = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=links&meta=&titles="+article+"&pllimit=500";

        String[] lines = loadStrings(query);

        for (int j = 0; j < lines.length; j++) {
            String line = lines[j];

            if (line.contains("\"title\":")) {

                    println(line);
                    // java string split
            }
        }
    }
}

A: The query you're using apparently gives you a bunch of articles that your main article "Abdominal_pain" links to.
You need to go a step further and loop through all of those links. You can make your life a lot easier by using JSONObjects instead of parsing Strings like you're currently doing. Check out the loadJSONArray() function for more info, but basically you'd do this:
JSONArray links = loadJSONArray(query);
for (int i = 0; i < values.size(); i++) {
   JSONObject link = values.getJSONObject(i);
   String title = link.getString("title");
   //fetch the info for that title
}

Once you have the title, you can then fetch the information for that page. An example query url is https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/Abdominal_pain/daily/20151010/20151012 which returns this JSON:
{"items":[{"project":"en.wikipedia","article":"Abdominal_pain","granularity":"daily","timestamp":"2015101000","access":"all-access","agent":"all-agents","views":1134},{"project":"en.wikipedia","article":"Abdominal_pain","granularity":"daily","timestamp":"2015101100","access":"all-access","agent":"all-agents","views":1160},{"project":"en.wikipedia","article":"Abdominal_pain","granularity":"daily","timestamp":"2015101200","access":"all-access","agent":"all-agents","views":1313}]}

You'll have to do some aggregating to get the totals, or maybe the total is somewhere else in the API.
You're going to have to do a little bit of research on exactly what the API can return. Reading through the documentation is a big part of programming. Luckily the Wikipedia API has great documentation, and that's where you should be looking.
I'd recommend trying something out and posting another question, along with an MCVE, if you get stuck. Good luck.
See also: How to use Wikipedia API to get the page view statistics of a particular page in wikipedia?


text:
Q: Unable to load style.css in Django 1.9 I am trying to load the style.css on my page.
I've added the path for STATICFILES_DIRS like below,
STATIC_URL = '/static/'

STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
 ]

STATIC_ROOT = os.path.join(BASE_DIR, "static_cdn")

index.html
{% load staticfiles %}
`<link rel='stylesheet' href='{% static "css/style.css" %}' type='text/css'>`

When I ran the collectstatic and it collected the style.css.
When I do inspect element and open a link of style.css (http://127.0.0.1:8000/static/css/style.css), it gives me not found message.
I tried hard-coding the path to style.css but, no luck.
I created the another sample project and followed the same steps and style.css loaded successfully.
When I do inspect element and open a link of style.css, it shows me html code.
I am really helpless. Any help is really appreciated.
Edit
setting.py template settings:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},

]
Directory structure:
 |myproject
  |----- MyApp/
  |---- myProject/
  |---- static/
  |---- static_cdn/
  |----manage.py

https://github.com/prafullarkamble/UnableToLoadStyle.css/

A: If i remember correctly, the collectstatic command is only used for production. So the collected statifiles do not affect the development.
In your project structure, the path to the style.css is :
Salmon/static/Salmon/style.css.
So you should find the file with the URL:
http://127.0.0.1:8000/static/Salmon/style.css
which should be equivalent to {% static "Salmon/style.css" %} in your template.

A: 1) Select the folder(s) where you want the static assets from  where you want them to be collected:
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "i_will_collect_from_here"),
    ... yet another folder
]

2) Select the folder where you want the static assets to be collected:
STATIC_ROOT = os.path.join(BASE_DIR, "here_my_static_will_be_collected")

3) Run python manage.py collectstatic
Note:
In STATICFILES_DIRS you can add any path you want, it can be an absolute path. collectstatic will place the static in your STATIC_ROOT.
STATICFILES_DIRS = [
    '/var/www/assets/bootstrap/'
    ...
]


text:
Q: SwiftCoreDataHelper.swift error in xcode 7 Could help me guys with the following three errors in SwiftCoreDataHelper.swift. I am using xcode 7 but its seems that the code for older versions of xcode. thanks in advance.
1 . . .

line error: let items: NSArray = managedObjectContext.executeFetchRequest(<#T##request: NSFetchRequest##NSFetchRequest#>)
   error: Call can throw, but it is not marked with 'try' and the error
  is not handled

 class func fetchEntities(className:NSString, withPredicate predicate:NSPredicate?, managedObjectContext:NSManagedObjectContext)->NSArray{
    let fetchRequest:NSFetchRequest = NSFetchRequest()
    let entetyDescription:NSEntityDescription = NSEntityDescription.entityForName(className as String, inManagedObjectContext: managedObjectContext)!

    fetchRequest.entity = entetyDescription
    if predicate != nil {
        fetchRequest.predicate = predicate!
    }

    fetchRequest.returnsObjectsAsFaults = false
    let items: NSArray = managedObjectContext.executeFetchRequest(<#T##request: NSFetchRequest##NSFetchRequest#>)

    return items
}

2 . . .
line error: if managedObjectContext.save(nil) {

error: Nil is not compatible with expected argument type '()'

class func saveManagedObjectContext(managedObjectContext:NSManagedObjectContext)->Bool{
    if managedObjectContext.save(nil) {
        return true
    }
    else {
        return false
    }
}

3 . . .

line error: if storeCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error:&error ) != nil {
error: Contextual type '[NSObject : AnyObject]' cannot be used with
  array literal

 if storeCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error:&error ) != nil {

    if error != nil {
        print(error!.localizedDescription)
        abort()
    }
 }

A: *

*Read about do try throw and catch. If a call throws you should enclose it in a do block and handle the error with catch.

*Remove the nil. No argument is expected. You may then have to handle thrown errors.

*Not quite sure what the error is here but again this needs converting to Swift 2 error handling and should probably look something like this. Note the error argument has become a thrown error. This is untested no promises that it is absolutely correct.
do {
  let coordinator = try storeCoordinator.addPersistentStoreWithType(
        NSSQLiteStoreType,
        configuration: nil,
        URL: url, options: nil)
} catch {
  print(error)
  abort()
}


text:
Q: what does private[wikipedia] mean in sacla? I am new to scala and don't know what does private[wikipedia]mean,could anyone please tell me?Is it a generic type?
package wikipedia

import scala.io.Source

object WikipediaData {

  private[wikipedia] def lines: List[String] = ???

A: It's a way to scope the privacy of a given object. So private[wiki] means only code defined within wiki has access to lines.
See here: https://alvinalexander.com/scala/how-to-control-scala-method-scope-object-private-package/

A: private[packageX] means the following method/class/object/constructor is accessible only from within that package - in this case syntax is the package name, and this constructor is only accessible from other code inside syntax package.


text:
Q: GWT - Google visualization problems using layout panels? I'm having troubles in my GWT app with a Google Visualization chart not showing up until after the user has some sort of interaction with the window (e.g. moves the mouse across the screen or presses a button). This would be fine except that the chart is suppose to show up as the first thing the user sees and since it's meant to be seen on a mobile device, it's likely they will not see the chart because their first interaction will be clicking a button that hides the chart to show other information.
Using the "Getting started tutorial" over at the Visualization code's page, the chart loads immediately fine (once some slight changes are made the fix the problems from the slightly out of date tutorial). After some trial and error to find where the difference between my code and the example code that was causing the problem, I found that it's happening because my code is using the newer layout panels instead of just regular panels in GWT.
The below code is the working tutorial code changed so that it uses a RootLayoutPanel.get() instead of a RootPanel.get(). With this, the chart doesn't load until you click to reload the page, then you can see the chart for an instant before the page reloads. This should be easily tested with the below code. To get the chart to show up for the entire time, simply change RootLayoutPanel.get() to RootPanel.get().
Something in my app is allowing the chart to load after user interaction (I'm not sure what). However, the layout panel is certainly the problem as if I change it to a regular panel it works fine. Unfortunately, my entire app is built using layout panels.
What's going on and how might I be able to make the chart show up from the start using layout panels? Thank you much!
package com.test.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.visualization.client.AbstractDataTable;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.Selection;
import com.google.gwt.visualization.client.AbstractDataTable.ColumnType;
import com.google.gwt.visualization.client.events.SelectHandler;
import com.google.gwt.visualization.client.visualizations.corechart.PieChart;
import com.google.gwt.visualization.client.visualizations.corechart.Options;

public class SimpleViz implements EntryPoint {
  public void onModuleLoad() {
    // Create a callback to be called when the visualization API
    // has been loaded.
    Runnable onLoadCallback = new Runnable() {
      public void run() {
        LayoutPanel panel = RootLayoutPanel.get();

        // Create a pie chart visualization.
        PieChart pie = new PieChart(createTable(), createOptions());

        pie.addSelectHandler(createSelectHandler(pie));
        panel.add(pie);
      }
    };

    // Load the visualization api, passing the onLoadCallback to be called
    // when loading is done.
    VisualizationUtils.loadVisualizationApi(onLoadCallback, PieChart.PACKAGE);
  }

  private Options createOptions() {
    Options options = Options.create();
    options.setWidth(400);
    options.setHeight(240);
    options.setTitle("My Daily Activities");
    return options;
  }

  private SelectHandler createSelectHandler(final PieChart chart) {
    return new SelectHandler() {
      @Override
      public void onSelect(SelectEvent event) {
        String message = "";

        // May be multiple selections.
        JsArray<Selection> selections = chart.getSelections();

        for (int i = 0; i < selections.length(); i++) {
          // add a new line for each selection
          message += i == 0 ? "" : "\n";

          Selection selection = selections.get(i);

          if (selection.isCell()) {
            // isCell() returns true if a cell has been selected.

            // getRow() returns the row number of the selected cell.
            int row = selection.getRow();
            // getColumn() returns the column number of the selected cell.
            int column = selection.getColumn();
            message += "cell " + row + ":" + column + " selected";
          } else if (selection.isRow()) {
            // isRow() returns true if an entire row has been selected.

            // getRow() returns the row number of the selected row.
            int row = selection.getRow();
            message += "row " + row + " selected";
          } else {
            // unreachable
            message += "Pie chart selections should be either row selections or cell selections.";
            message += "  Other visualizations support column selections as well.";
          }
        }

        Window.alert(message);
      }
    };
  }

  private AbstractDataTable createTable() {
    DataTable data = DataTable.create();
    data.addColumn(ColumnType.STRING, "Task");
    data.addColumn(ColumnType.NUMBER, "Hours per Day");
    data.addRows(2);
    data.setValue(0, 0, "Work");
    data.setValue(0, 1, 14);
    data.setValue(1, 0, "Sleep");
    data.setValue(1, 1, 10);
    return data;
  }
}

A: With the Layout panels the sizing of the widgets is done in JavaScript. When the initial page is loaded the initial sizing is done after everything else is finished. However in your case the pie is added when the library is loaded and that runs after the initial sizing. Therefor your widget isn't sized and won't show up. You need to call panel.forceLayout(); explicitly as the last method in you run method.

A: The google chart tools definately work with LayoutPanels. I am using it myself.
It's really difficult to say what's wrong but here are a couple of suggestions:

*

*Check with Chrome Dev Tools (Console) if an exception is thrown.

*Do you have standard mode enabled. That's important with LayoutPanels (make sure you have <!DOCTYPE html> in your HTML host page

*You could try a 3rd party wrapper (supports automatic resizes)


text:
Q: Generating Dynamic Table Rows for HTML Table Im having a Html Email Template for Invoice Like Bellow.

   Item ID
   Name
   Qty
   Unit Price

   {ItemID}
   {Name}
   {Qty}
   {UnitPrice}

I have an Item List with 5 Items,

List<ItemList> ItemList = new List<ItemList>();

The class Structure for Item List

public Class ItemList{
 public int ItemID {get;set;}
 public string Name {get;set;}
 public int Qty {get;set;}
 public decimal UnitPrice {get;set}
}

My Question is how to dynamically generate the table rows for the tbody based on  the item list which i have by replacing the values with {ItemID},{Name},{Qty},{UnitPrice}?
Im using ASp.Net MVC4, I have came across a library called Html Agility Pack, please any body let me know how to archive this using Html Agility Pack.


text:
Q: How do I upgrade a mac mini from OSX 10.4.11 to 10.6.8 I have an old 2007 mac mini that I am using as a media/music hub, and I'd like to be able to sync it with my iphone. But to do that I need to upgrade its old itunes (v8), but to do that I need to upgrade 2 steps from OS 10.4.11 to OS 10.6.8.
How do I do this?
thanks!

A: I believe your mac mini supports 10.6 snow leopard. So all you have to do is buy the snow leopard install disc like from amazon (http://www.amazon.com/Mac-version-10-6-3-Snow-Leopard/dp/B001AMHWP8/ref=sr_1_1?ie=UTF8&qid=1358911973&sr=8-1&keywords=snowleopard), then plug the disc in and do the upgrade.


text:
Q: Can't figure out why array length is undefined I keep receiving the following message in my console, "Uncaught (in promise) TypeError: Cannot read property 'length' of undefined"
quotesData.quotes should be the key for an array, however, so I'm unsure as to why its length property is undefined.
quotesData should be a JSON object that looks like: { "quotes": [Object1, Object2, ...etc.]}
Is there something wrong with how I'm using axios? I'm still very new to programming in general and quite new to react.js
getQuote() {
    let _this = this;
    _this.serverRequest =
        axios
        .get("https://raw.githubusercontent.com/dwgillette/quotes/master/library")
        .then(function(quotesData) {
            console.log(quotesData);
            let newQuote = quotesData.quotes[Math.floor(Math.random() * quotesData.quotes.length)];
            _this.setState({
                quote: newQuote.quote,
                author: newQuote.author
            });
        })
}

A: Because the promise resolves to response object. Try doing:
getQuote() {
let _this = this;
_this.serverRequest =
    axios
    .get("https://raw.githubusercontent.com/dwgillette/quotes/master/library")
    .then(function(response) {
        let newQuote = response.data.quotes[Math.floor(Math.random() * response.data.quotes.length)];
        _this.setState({
            quote: newQuote.quote,
            author: newQuote.author
        });
    })
}

A: So the data you want is actually going to be on a .data attribute of the response. So if you fix your code up like this you will be good to go :)
getQuote() {
    let _this = this;
    _this.serverRequest =
        axios
        .get("https://raw.githubusercontent.com/dwgillette/quotes/master/library")
        .then(function(q) {
            quotesData = q.data;
            console.log(quotesData);
            let newQuote = quotesData.quotes[Math.floor(Math.random() * quotesData.quotes.length)];
            _this.setState({
                quote: newQuote.quote,
                author: newQuote.author
            });
        })
}

A: Here is a screenshot of the response object you are getting back.
I refactored your code to work. you need to use res.data.
getQuote = () => {axios.get("https://raw.githubusercontent.com/dwgillette/quotes/master/library")
.then(res => {
  let newQuote =
    res.data.quotes[Math.floor(Math.random() * res.data.quotes.length)];

  this.setState({
    quote: newQuote.quote,
    author: newQuote.author
  });
});
};


text:
Q: How to highlight selected text in pdf using PDFKit? I have set up a PDFViewer and would like to add a highlight functionality so that when a user selects text, they could highlight it. When you highlight text in notes, iMessages etc. you have the option to select all, copy, paste etc. How would you edit this so that you could have a highlight functionality as well? Also, how would the application save the highlighting so when a user closed and reopened the app, they would still be able to view the highlighted text? Would this involve using core data or something else? Thanks!
this is a screenshot of the default functionalities that Apple provides but I would like to add an additional highlighting functionality

A: let select = pdfView.currentSelection?.selectionsByLine()
    //assuming for single-page pdf.
    guard let page = select?.first?.pages.first else { return }

    select?.forEach({ selection in
        let highlight = PDFAnnotation(bounds: select.bounds(for: page), forType: .highlight, withProperties: nil)
        highlight.endLineStyle = .square
        highlight.color = UIColor.orange.withAlphaComponent(0.5)

        page.addAnnotation(highlight)
    })


text:
Q: Centerline Addressing I work for a local government and am in the process of cleaning up / updating addressing data. I have a MXD for the purpose of 'point addressing' and 'centerline addressing'.
It is the centerline data that I am concerned about. My workflow can either consists of "rolling my sleeves up" and manually digitizing the data or what I wan to do is find an automated way to complete this work.
The city has theoretical and actual address ranges. The issue is that the actual address range data is filled in the theoretical fields, thus the theoretical address ranges are wrong.
What I am trying to accomplish is writing or using attribute assistant to identify all actual address records that are Null and copy the records from the theoretical address fields to the actual address fields. Further since the theoretical address fields are partially wrong I would like to have a TRIGGER event that if the process where the Null values are converted = TRUE then the last two digit of the Left_to and Right_to fields for the theoretical addresses will be changed to -98 and 99.
Example:
Actual Address Range:
Left side of road = 800-832 ; Right side of road = 801-835
Theoretical Address Range:
Left side of road = 800-898 ; Right side of road = 801-899


text:
Q: how to change the text in an AbstractCell created using uibinder getting error Cannot set property 'textContent' of null I created an abstract cell using uibinder and UiRenderer. My datasource is a list of a list. Lets say list of cars and each car has a list of models. I adding the cells to a CellList.
Each cell is like like a card with forward and backward button on top(Im using  arrow images and handling click event using uihandler) and the card display model's property. The forward and backward image on click show the next and the previous model respectively.
Im not been able to change the model_name(and other divs) when images are clicked.

<ui:with field="model_name" type="java.lang.String" />

<ui:with field="leftArrow" type="com.google.gwt.safehtml.shared.SafeHtml" />
<ui:with field="rightArrow" type="com.google.gwt.safehtml.shared.SafeHtml" />

                                     <ui:safehtml from='{leftArrow}' />

<ui:text from="{model_name}" />

                                    <ui:safehtml from='{rightArrow}' />

Im not sure how to access the text inside the model div. And subsequently there are more divs whose value/text changes when the images are clicked.
public class NewCompCell extends AbstractCell<String> {

@UiField
String model_name;

@UiField
DivElement model;

static interface Images extends ClientBundle {
    @Source("LeftArrow.png")
    ImageResource LeftArrow();

    @Source("rightArrow.png")
    ImageResource rightArrow();
}

private Images images = GWT.create(Images.class);
private Renderer uiRenderer = GWT.create(Renderer.class);

public static interface Renderer extends UiRenderer {

    void render(SafeHtmlBuilder sb, String value, String model_name,
            SafeHtml leftArrow, SafeHtml rightArrow);

    void onBrowserEvent(NewCompCell o, NativeEvent e, Element p, String n);

}

public NewCompCell() {

    super(BrowserEvents.CLICK);

}

@Override
public void onBrowserEvent(Context context, Element parent, String value,
        NativeEvent event,

        ValueUpdater<String> valueUpdater) {

    uiRenderer.onBrowserEvent(this, event, parent, value);

}

@Override
public void render(com.google.gwt.cell.client.Cell.Context context,
        String value, SafeHtmlBuilder sb) {

    uiRenderer
            .render(sb, value, value,
                    AbstractImagePrototype.create(images.LeftArrow())
                            .getSafeHtml(),
                    AbstractImagePrototype.create(images.rightArrow())
                            .getSafeHtml());
}

@UiHandler({ "right" })
void onRightArrowClicked(ClickEvent event, Element parent, String string) {

    model.setInnerText("next model");

}

@UiHandler({ "left" })
void onLeftArrowClicked(ClickEvent event, Element parent, String string) {

    model.setInnerText("previous model");

}

}
When I click the images Im getting the below error.
com.google.gwt.core.client.JavaScriptException: (TypeError) @com.google.gwt.core.client.impl.Impl::apply(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)([JavaScript object(36), JavaScript object(2), JavaScript object(204)]): Cannot set property 'textContent' of null
    at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:249)
    at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
    at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:576)
    at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:284)
    at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
    at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
    at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:356)
    at sun.reflect.GeneratedMethodAccessor52.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
    at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
    at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
    at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:293)
    at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:547)
    at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
    at java.lang.Thread.run(Unknown Source)

A: A much easier way to implement these requirements is to create a custom widget as opposed to a custom cell. This custom widget (e.g. "CarCard") may consist of two icons, any number of labels, etc. It will also have methods for setting the text for each label, click handlers for left and right arrows, etc. You can use a UiBinder to create this custom widget.
Then, as you load your list of cars, you can do something like:
for (Car car : cars) {
    CarCard carCard = new CarCard();
    carCard.setCar(car);
    myContainerPanel.add(carCard);
}

A custom cell is more useful in a situation where you need to render data and update it based on events that happen outside of a cell or with the entire cell (e.g. click on a cell itself). It is not a good option when you want to have a widget-like behavior inside a cell.

A: The uiField defined in UiBinder can be access by defining a getter for that field in the UiRenderer.
I was getting the error because I was trying it access the uifield directly.
public static interface Renderer extends UiRenderer {

    void render(SafeHtmlBuilder sb, String value, String model_name,
            SafeHtml leftArrow, SafeHtml rightArrow);
    DivElement getModel(Element parent); //make sure the uifield name matches the getter

    void onBrowserEvent(NewCompCell o, NativeEvent e, Element p, String n);

}

This field can be access
    @UiHandler({ "right" })
void onRightArrowClicked(ClickEvent event, Element parent, String string) {

    uiRenderer.getModel(parent).setInnerText("next model");

}


text:
Q: Connecting to Amazon AWS PostgreSQL database from R session I have a database instance running on Amazon AWS. I use the RPostgreSQL package to connect my R session to my AWS database.
My issue is that every time I attempt to connect to my database instance after not having done so for a while, I get a "Connection timed out" error.
I can then use a browser to go to my AWS Console, edit the Inbound and Outbound rules for my security group to allow my IP Inbound & Outbound access. Then I can connect again just fine.
But then if I don't work on my database for a day or two, when I try to connect to my DB, it doesn't work, and the permissions for Inbound/Outbound access no longer match my IP address (which I'm sure is the cause of the problem).
So... is my IP address changing? Or are the edits I'm making to my security group's inbound/outbound permissions not being saved correctly?
To be clear, here's the order of events of how things have been going:

*

*Haven't worked on DB for a few days, attempt to connect from my R sessions. I get an error.

*Use browser to go to AWS Console and edit my security group's Inbound/Outbound rules by selecting "My IP"

*Try again to connect to my DB from my R session. Hooray! It works.

*A few days later - pick up the project again, attempt to reconnect to my AWS DB from R, and it no longer works...

*Repeat this cycle of madness

*Make post on SO hoping for an angel to help me

This isn't a debilitating problem, it's just extremely annoying to have to re-do my security settings every time I want to connect to my AWS DB.
Thanks in advance for any help you can provide!

A: It depends, but most possibly it seems to be that your IP is changing. Most of the ISP have Dynamic IP allocation, which means the IP can change if the router is restarted.
It is hence recommended to use DNS name instead of IP address in the security group setting.
It is easier to note down your IP address and check back after two days.
Can you see your IP address which you added two days ago in the Security Group page? If yes, you can just goto google "what is my IP" and see if both the values are same. Security Group (SG) setting does not get refreshed or changed on it's own(unless you are allocating a new Security Group).
One more thing you can try. Allow all connection (0.0.0.0) just to test. After two days or so, try again. If it works, it means there is issue with the IP address changing.