text:
Q: How to ignore terms in replace if they do not exist in the pandas dataframe? I have the following code to replace one term with another, this only works if the value exists in the pandas dataframe, I assume I need to wrap gdf[montype] = gdf[montype].replace(dict(montype), regex=True) in an if statement? How would I do this, or is there a better way?
    montype = [
        ['HIS_COP_', ''],
        ['_Ply', ''],
        ['_Pt',''],
        ['BURIAL','burial'],
        ['CUT', 'CUT'],
        ['MODERN', 'MODERN'],
        ['NATURAL', 'NATURAL'],
        ['STRUCTURE', 'STRUCTURE'],
        ['SURFACE', 'SURFACE'],
        ['TREETHROW', 'natural feature'],
        ['FURROW', 'FURROW'],
        ['FIELD_DRAIN', 'FIELD_DRAIN'],
        ['DEPOSIT_FILL', 'DEPOSIT_FILL'],
        ['POSTHOLE', ''],
        ['TIMBER', ''],
        ['', '']
    ]

    gdf[montype] = gdf[montype].replace(dict(montype), regex=True)

When the term does not exist I get the error raise KeyError(f"None of [{key}] are in the [{axis_name}]")
Edit:
    mtype = {
                'HIS_COP_': '',
                '_Ply': '',
                '_Pt': '',
                'BURIAL': 'burial',
                'CUT': 'CUT',
                'MODERN': 'MODERN',
                'NATURAL': 'NATURAL',
                'STRUCTURE': 'STRUCTURE',
                'SURFACE': 'SURFACE',
                'TREETHROW': 'natural feature',
                'FURROW': 'FURROW',
                'FIELD_DRAIN': 'FIELD_DRAIN',
                'DEPOSIT_FILL': 'DEPOSIT_FILL',
                'POSTHOLE': '',
                'TIMBER': ''
               }  # dict(montype)

    gdf['montype'] = gdf['montype'].map(mtype).fillna(gdf['montype'])

A: You can try this:
# Convert you list to dict

Montype={'His_cop':'','Modern':'Modern', etc...} # dict(montype)

gdf[montype]=gdf[montype].map(Montype).fillna('whatever value you want')


text:
Q: Benford's Law with more than 1 leading digit I am bit confused on the algorithm of Benford's Law using more than the first leading digit.
I have read a thesis here that states the law for leading 2 digits is:

$\log_{10} \left( 1 + {\small\dfrac 1 {10d_1 \! + d_2}} \right)$
where $d = d_1 d_2$ and $d$ is within the bounds of 10 to 99.
Would that not be equivalent to the original formula of:

$\log_{10} \left( 1 + {\small\dfrac 1 d} \right)$
where $d$ is within the bounds of 10 to 99.
Is that correct? I have tried googling for a good night, but do not seem to be able to find a formula which applies to leading digits > 1.
Appreciate any help, below is the sample code I have used to generate the results in Python.
expected = [log10(1+1/d) for d in range(1,10)]
expected2 = [log10(1+1/(10 *d1+d2)) for d1 in range(1,10)
                                    for d2 in range(0,10)]
expected22 = [log10(1+1/(d1)) for d1 in range(10,100)]

print(expected22,expected2)

A: Yes, under Benford's law
the expected frequency of a specific leading pair of digits
$ d_1d_2 $
$\big( = 10d_1 \! + d_2 = d $,
       with $ d \in \{10,11,12,\ldots,99\} ~\big) $
is just as your program calculated.
\begin{align}
 P ( \text  {first two digits are} ~ d_1 d_2        )
 & = P (  \text {first two digits are} ~ 10d_1 \! + d_2 ) \\[1ex]
 & = P (   \text{first two digits are} ~ d              )  \\[1ex]
 & =   \log_{10} \left( 1 + {1 \over d}\right)
\end{align}
Agreeing with your implicit conjecture,
this holds in general for $n$ leading digits
where $d = d_1 d_2 d_3 ... d_n$
with  $d_1 \in \{ 1,2,3,...,9 \}$,
as gathered from
An Introduction to Benford's Law, Chapter 1,
 Princeton University Press
(no author or year given) — stated
slightly differently here
in a subtractive format
that facilitates many applications.
\begin{align}
 P ( \text {first} ~ n ~ \text{digits are} ~ d_1 d_2 d_3 ... d_n )
 & = P (  \text{first}   ~   \text{digits are} ~ d                   ) \\[1ex]
 & = \log_{10} (d{+}1) - \log_{10} d
\kern 7.5em \end{align}
An example for the original question
gives the same result as the familiar format.
\begin{align}
 P ( \text{first} ~ 2 ~ \text{digits are} ~ 76 )
 & = \log_{10} 77 - \log_{10} 76                          \\[1ex]
 & = \log_{10}            {\small { 77  \over 76 }}        \\[1ex]
 & = \log_{10} \left( 1 + { \small{ 1   \over 76 }} \right)
\kern 6em \end{align}
The subtractive format shows its flexibility
on other conceivable questions about the first two digits.
\begin{align}
            P ( \text  {first 2 digits are equal} )
 & =            P (  \text {first are 11}             )
          + P (   \text{first are 22}             )
          + \cdots
          + P (   \text{first are 99}             ) \\[2ex]
 & =            ( \log_{10}  12 - \log_{10} 11 )
          + ( \log_{10}  23 - \log_{10} 22 )        \\[.5ex]
 & \kern 12em + \cdots
          + ( \log_{10} 100 - \log_{10} 99 )        \\
 & = \log_ {10} {\small{ 12 \cdot 23 \cdots 100 \over
                     11 \cdot 22 \cdots  99 }}      \\[1.5ex]
 & = 10.9 \%
\end{align}
\begin{align} \kern 3.5em  \raise 2ex \strut
            P ( \text  {2nd digit is} ~ 6 )
 & =            P (  \text {first are 16}     )
          + P (   \text{first are 26}     )
          + \cdots
          + P (   \text{first are 96}     )      \\[2ex]
 & =            ( \log_{10} 17 - \log_{10} 16 )
          + ( \log_{10} 27 - \log_{10} 26 )      \\[.5ex]
 & \kern 12em + \cdots
          + ( \log_{10} 97 - \log_{10} 96 )      \\
 & = \log_ {10} {\small{ 17 \cdot 27 \cdots 97 \over
                     16 \cdot 26 \cdots 96 }}    \\[1.5ex]
 & = 9.3 \%
\end{align}
This format also telescopes nicely when verified against
the most famous prediction of Benford's law,
that 1 is the first significant digit
in approximately 30.1% of suitably random numbers.
The first 3 digits are employed this time for variety.
\begin{align} \kern 4.5em
            P ( \text  {first digit is} ~ 1 )
 & =            P (  \text {first are 199}      )
          + P (   \text{first are 198}      )
          + \cdots
          + P  (  \text{first are 100}      ) \\[2ex]
 & =            ( \log_{10} 200 - \log_{10} 199 )
          + ( \log_{10} 199 - \log_{10} 198 ) \\[.5ex]
 & \kern 12em + \cdots
          + ( \log_{10} 101 - \log_{10} 100 ) \\
 & =              \log_{10} 200 - \log_{10} 100    \\[1.5ex]
 & \equiv 30.1 \%
\end{align}

(The material above was learned while applying Benford's law
 to Roman numbers in
 a puzzle.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: `org-agenda-get-day-entries` errors with "Selecting deleted buffer" I'm attempting to gather entries that were scheduled in the past week, similarly to what org-agenda does.  Following org-agenda-list, I defined the following:
(defun weekly-status/get-week-days ()
"Return a list of days for the past week suitable for passing to `org-agenda-get-day-entries."
  (let* ((today (org-today))
         (day-list (list today)))
    (dotimes (n (1- 7) day-list)
      (push (1- (car day-list)) day-list))))

However, executing the follwing results in "Selecting deleted buffer":
ELISP> (let ((this-week-days (weekly-status/get-week-days)))
      (setq this-week-plan-items nil)
      (dolist (day this-week-days this-week-plan-items)
        (let ((date (calendar-gregorian-from-absolute day)))
          (message (format "%s" date))
          (dolist (file (org-agenda-files))
        (message (format "%s" file))
        (message (format "%s" (org-agenda-get-day-entries file date :scheduled)))))))
*** Eval error ***  Selecting deleted buffer

The message output shows:
(4 17 2019)
/Users/dag/lib/dotfiles/dotemacs/org/work.org
nil
/Users/dag/lib/dotfiles/dotemacs/org/career.org
nil
/Users/dag/lib/dotfiles/dotemacs/org/gcal.org
nil
/Users/dag/lib/dotfiles/dotemacs/org/home.org
nil
/Users/dag/lib/dotfiles/dotemacs/org/links.org
nil
/Users/dag/lib/dotfiles/dotemacs/org/notes.org
nil
/Users/dag/lib/dotfiles/dotemacs/org/journal.org
nil
/Users/dag/lib/dotfiles/dotemacs/org/ideas.org
nil
(4 18 2019)
/Users/dag/lib/dotfiles/dotemacs/org/work.org
nil
/Users/dag/lib/dotfiles/dotemacs/org/career.org
nil
/Users/dag/lib/dotfiles/dotemacs/org/gcal.org
nil
/Users/dag/lib/dotfiles/dotemacs/org/home.org
nil
/Users/dag/lib/dotfiles/dotemacs/org/links.org
nil
/Users/dag/lib/dotfiles/dotemacs/org/notes.org
nil
/Users/dag/lib/dotfiles/dotemacs/org/journal.org
nil
/Users/dag/lib/dotfiles/dotemacs/org/ideas.org
nil
(4 19 2019)
/Users/dag/lib/dotfiles/dotemacs/org/work.org

So somehow on the third day things just stop working.   4/19 is the first day with anything scheduled, so that's suspicious.
What is the correct way to use org-agenda-get-day-entries?  Any idea what is going on here?


text:
Q: 'Stretching' an image depending on post size On the World of Warcraft forums they have a neat style set up that I'd like to emulate.  I didn't know how to do it, so I decided to dig through their stylesheets and grab the pieces of it and put them together to learn how to make a style similar.
When digging through the stylesheets, I found this image.  As you can see, it's the background for their forum posts, but it's a fixed size.  Here's my question - how are they dynamically creating more length if a user's post is much longer than the picture is?
On a test website I grabbed the same CSS they used for that section.  They have it set on overflow:hidden; so that it doesn't keep multiplying the image.  Naturally, copying parts of their code gets me this mess on the test website.
It works correctly for smaller posts, since they just have to cut it off, but I'm assuming they have maybe a very thin (set width, perhaps 1 pixel in height) .jpg image that they are multiplying depending on the size of the forum post.
Does anybody know how I might go about doing this?
P.S.  Naturally I'm not going to be using their images and such - I'm only copying it for now just to understand how to make my own.

A: It looks like their background color for the post is the same as the color at the very bottom of that image. That way it just "fades" in - the image does not actually change size.
Example CSS would be:

#yourPostSelector {
  background-image: url('path/to/image.jpg');
  background-position: top left; /* or 'top center' - whatever works for you */
  background-attachment: scroll;
  background-color: #000000; /* pick the bottom color of your background image */
}

A: Something like:
CSS:

.post
 {
   background:#1A0F08 url(http://us.battle.net/wow/static/images/layout/cms/post_bg.jpg) top no-repeat;
 }

(the image and the color are those really used, hope they don't sue me for that :) )
is what you're looking for. The background image is positioned on top and stays there, while the rest of the container's height has the same background color that the image fades to (using a gradient). So it's just an illusion of a stretched image, but effectively is just that you don't see the interruption where the image ends

A: Just change you background color which you have used is #00000*
It should be changed to the color of the background image which you use, basically the bottom part so that it blends perfectly. Presently as per your present image the code would be like this :-
.body {
    background: url("../images/post_bg.jpg") no-repeat scroll 50% 0 #1A0F09;
    clear: both;
    height: 100%;
    margin: 0 auto;
    overflow: hidden;
    width: 990px;
}

Update this class and check the result, if you don't understand comment here would make you understand.


text:
Q: StreamReader vs BinaryReader? Both StreamReader and BinaryReader can be used to get data from binary file ( for example )
BinaryReader :
   using (FileStream fs = File.Open(@"c:\1.bin",FileMode.Open))
            {
                    byte[] data = new BinaryReader(fs).ReadBytes((int)fs.Length);
                    Encoding.getstring....
            }

StreamReader  :
  using (FileStream fs = File.Open(@"c:\1.bin",FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs,Encoding.UTF8))
                {
                       var myString=sr.ReadToEnd();
                }
            }

What is the difference and when should I use which ?

A:
Both StreamReader and BinaryReader can be used to get data from binary file

Well, StreamReader can be used to get text data from a binary representation of text.
BinaryReader can be used to get arbitrary binary data. If some of that binary data happens to be a representation of text, that's fine - but it doesn't have to be.
Bottom line:

*

*If the entirety of your data is a straightforward binary encoding of text data, use StreamReader.

*If you've fundamentally got binary data which may happen to have some portions in text, use BinaryReader
So for example, you wouldn't try to read a JPEG file with StreamReader.


text:
Q: How can I improve my PHP sanitization without using PDO I have written a short function for sanitizing strings/variables before being being used in SQL queries:
function cleanstring($sanitize, $maxlength=10, $minlength=0){
    if(strlen($sanitize) <= $maxlength && strlen($sanitize) >= $minlength){
    $sanitize = substr(mysql_real_escape_string(strip_tags($sanitize)), 0, $maxlength);
}
else{
    include("includes/header.php");
    exit("Error!");
    }

return $sanitize;
}

called using:
$variable = cleanstring($_POST['someInput'], 5, 5)

would define the length of the string, clean it using real_escape_string and strip_tags and then use substr() to ensure that the returned data still matches the length criteria.
Is there any way that I can improve this sanitization function, without using PDOs?

A: I think you are missing the point (or making it too big of a point).  Any time you mix control characters with data, there needs to be a way to escape these control characters so they are interpreted as data.
In web programming, there are a few areas:

*

*SQL (different per database)

*command shell

*URIs

*HTML Attributes

*HTML Content

*JavaScript

Each one calls for a unique method of escaping.  Sometimes there are multiple levels of escaping, like encoding a URI and then encoding that into an href="" attribute.
Your function is technically "safe", but kind of a mess.  Wouldn't you prefer to give the user an error rather than silently truncate their input?  Also, what if someone as making a comment about When I put <strong> tags around the gadget, it breaks? ... your code will remove the <strong>.  But < and > are completely safe to insert into SQL.
I suggest you simply use the methods that have been created for each of the items above.

*

*MySQL: "'" . mysqli_real_escape_string(...) . "'", possibly intval in some cases.

*command shell: escapeshellargI(...)

*URIs: urlencode()

*HTML Attributes: '"' . htmlspecialchars(..., ENT_QUOTES) . '"'

*HTML Content: `htmlspecialchars(...)

*JavaScript: json_encode(...) possibly wrapped in the encoding for HTML, depending on context.

You can wrap some of these into shorter functions for convenience:
function QA($val)
{
    return '"' . htmlspecialchars($val, ENT_QUOTES) . '"';
}

etc...
But the main point is to 100% of the time prevent data from being read as control characters.

A: Don't strip_tags and don't do mysql_real_excape_string!!!
In printing you need to think whether you want to print it with strip_tags, htmlspecialchars or something else, not in the sanitization.
Instead of mysql_real_excape_string use prepared statements.
Use also filters to sanitization the string as Email or something else.


text:
Q: How do I prevent the program from going into infinite loop when writing a char to a float form? I made a Newton-Raphson Method program. But I have a question. As you see, "epsilon" and "x0" are float type and when I try to write something like "a" or "b", the program goes crazy. I want to prevent it. I want to tell "Please enter a number" to the user when something happens like this.
Can you help me about that? Thank you.
Code is below:
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<locale.h>
#include<iostream>
#include<math.h>
#include<sstream>
#include <iomanip>
#include<time.h>
#define f(x) pow(x,5)-pow(x,4)-pow(x,3)+2*pow(x,2)
#define g(x) 5*pow(x,4)-4*pow(x,3)-3*pow(x,2)+4*x
using namespace std;

int main()
{
    setlocale(LC_ALL,"turkish");

    cout << "Problem 4" << endl << "---------" << endl << "Verilen y=(x^2)/(x+1) ve y=(x^3)/(x^3+2) fonksiyonlarının varsa kesim noktalarını bulan C programı\n" << endl;

    float x0, x1, f0, f1, g0, epsilon;
    int tahmin = 1, sinir=1000;

    cout << setprecision(6)<< fixed;

    bastan:

    cout << "Epsilon değerini giriniz: "; //Pay attention here. My question is about here.
    epsilonHata:
    cin >> epsilon;
    cout << endl;
    hata:
    cout << "İlk tahmin değerini giriniz: "; //Just like above, my question is about here too.
    cin >> x0;
    cout << endl;

    bla bla...
}

A: The infinite loop problem occurs because cin and underlying ifstream expects a float in your case. By not providing a float, cin fails and the weird loop occurs. More information here.
Since you cannot control the user and you do not want the program to break if the user inputs characters, you can read the input to string instead of float. This way, no error flag is set by cin.
 Then, you should convert the string to float. atof is suitable for this purpose.
#include <iostream>
#include <string>
#include <cstdlib>
...
std::string epsilon_str;
std::cin >> epsilon_str;
double epsilon = atof(epsilon_str.c_str());

From the documentation of atof:

If the first sequence of non-whitespace characters in str does not form a valid floating-point number as just defined, or if no such sequence exists because either str is empty or contains only whitespace characters, no conversion is performed and the function returns 0.0.

Other general programming issues

*

*There are lots of headers you include. Knowing what is required for which function or class is the best practice. I assume you included them when you needed, but if you won't use setprecision, then there is no reason to #include <iomanip>.

*Using define means simply copy-paste. The compiler is not aware of what you are doing. See the following example.
#define     WRONG_MULTIPLY(a, b)    a * b
#define CORRECTED_MULTIPLY(a, b) ((a) * (b))
...
int wrong_result     =     WRONG_MULTIPLY(1 + 2, 3 + 4); // 11
int corrected_result = CORRECTED_MULTIPLY(1 + 2, 3 + 4); // 21

The best practice is using functions. That is the purpose of functions.
int multiply(int a, int b) {
    return a * b;
}
...
int result = multiply(1 + 2, 3 + 4);

I used uppercase letters for macros to attract attention that they are macros. Seriously, you do not want to deal with compiler errors where the cause is a macro that you are not aware of.
 And at this point, I suggest going through a tutorial, like this one to understand the basic consepts.

*It is advised not to use using namespace std;. If there exists an std::multiply with the same signature as of your function (same input-output), the standard one will be called without you noticing it. There are ways to prevent this but not knowing what happened is the problem in the first place. Let the compiler guide you and do not trick yourself.

*The flow of the code and the uses of the labels seem complicated. Write code that you will understand, for example, two months later. I suggest breaking seperate functionalities into functions, like readFloat, checkEpsilonValid etc.

*Declare variables when they are needed. This way it is easier to follow the code. Also, using meaningful variables instead of two-letter ones improves the readability and you do not even need to comment later.

*Finally, be aware that setprecision affects cout throughout the program. It is about whether you care, but for bigger projects, I suggest using printf("%.06f"), or "%.06g", then flush if necessary.


text: Q: Is there a way to prevent PyDev from modifying my .project file and creating a .pydevproject file? I have a java project that uses a python script as part of the build process. I also have PyDev installed, but it is for other projects. Whenever I update a file in Eclipse PyDev will create a .pydevproject file and alter my existing .project file. Is there a way to prevent this from happening? I cannot find anything that appears related to this behavior in the PyDev preferences page.


text:
Q: Tkinter Treeview not showing newly inserted items, no errors given I'm building a desktop application that lets you insert some data into a form and then the data is displayed in a series (3) of Treeview widgets.
This is the form that I'm using to enter new data:

It's in a Toplevel widget. When the Add button is pressed the new data is stored in a file and it also should insert the new data in the corresponding Treeview Widget.
This is the root window:

It's comprised of 3 Treeview widgets. The purpose of the application is to give the user the opportunity to sort candidates into the right Treeview widget.
The issue that I'm facing is that when the Add button is pressed the new data is not shown in the Treeview widget and no errors are given. I think it may be an issue of class instantiation. This is an excerpt from my app, please see below a Minimal, Complete and Verifiable example
class MainApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        ...
        # frame and menu classes are instantiated here
        self.FrameList = {ViableCandidates: ViableCandidates(self),
                          NotViableCandidates: NotViableCandidates(self),
                          InProgressCandidates: InProgressCandidates(self)}
        ...
    def InstanceLinker(self, frame):
        link = self.FrameList[frame]
        return link
class GUIMenu(tk.Menu):
    def __init__(self, parent):
        ...
    # menu code is here
    addcandidates.add_command(label='Quick Add', command=lambda: QuickAdd(parent))
class QuickAdd(tk.Toplevel):
    def __init__(self, parent):
        ...
    # code for the small Toplevel window
    ...
    # this is the code that I use to add the new item to Treeview when the Add button is pressed
    if CandidateInfo['status'] == 'Viable':
        app.InstanceLinker(ViableCandidates).AddtoList()
    elif CandidateInfo['status'] == 'Not Viable':
        app.InstanceLinker(NotViableCandidates).AddtoList()
    else:
        app.InstanceLinker(InProgressCandidates).AddtoList()
# ViableCandidates, NotViableCandidates, InProgressCandidates are created with the same pattern
class InProgressCandidates(tk.Frame):
    def __init__(self, parent):
        global Counter
        tk.Frame.__init__(self, parent)
        self.columnconfigure(0, weight=1)
        self.rowconfigure(1, weight=1)
        title = tk.Label(self, text="Candidates In Progress", font="Verdana 10 bold")
        title.grid(row=0, column=0, sticky='nesw')
        self.tree = ttk.Treeview(self)
        self.tree.grid(row=1, column=0, sticky='nesw')
        scrollbar = ttk.Scrollbar(self, orient='vertical', command=self.tree.yview)
        scrollbar.grid(row=1, column=1, sticky='nws')
        self.tree.config(columns=('Name', 'Date'), selectmode='browse', height=20, yscrollcommand=scrollbar.set)
        self.tree.column('#0', width=20, minwidth=10, stretch=tk.YES)
        self.tree.column('Name', width=150, minwidth=10, stretch=tk.YES)
        self.tree.column('Date', width=80, minwidth=10, stretch=tk.YES)
        self.tree.heading('#0', text='#', anchor=tk.W)
        self.tree.heading('Name', text='Name', anchor=tk.W)
        self.tree.heading('Date', text='Date', anchor=tk.W)
        if Counter < 4:
            Counter += 1
            self.PopulateList()
    def PopulateList(self):
        selection = Database().SelectFromDB('name, date', "status = 'In progress'")
        for i in range(len(selection)):
            name = list(selection[i])[0]
            date = adjusttotimezone(list(selection[i])[1])
            self.tree.insert("", i, name, text=i + 1)
            self.tree.set(name, 'Name', name)
            self.tree.set(name, 'Date', date)
            CandidateCounter['InProgressCandidates'] = i
    def AddtoList(self):
        CandidateCounter['InProgressCandidates'] += 1
        print('I was here')
        self.tree.insert("", CandidateCounter['InProgressCandidates'], CandidateInfo['name'],
                         text=CandidateCounter['InProgressCandidates'])
        self.tree.set(CandidateInfo['name'], 'Name', CandidateInfo['name'])
        selection = Database().SelectFromDB('date', "name = '" + CandidateInfo['name'] + "'")
        date = adjusttotimezone(list(selection[0])[0])
        self.tree.set(CandidateInfo['name'], 'Date', date)
app = MainApp()
app.mainloop()

When the "Add" button is pressed there are no errors and "I was here" is printed so the AddtoList method is instantiated, but there are no new items added to Treeview. I did check if the variables that I'm using to create the new Treeview item hold the correct data and they do.
EDIT: This is a Minimal, Complete and Verifiable example:
import tkinter as tk
from tkinter import ttk
Bigbadtext = ''
Counter = 0
class MainApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        self.MainWindow = tk.Tk.__init__(self, *args, **kwargs)
        menu = GUIMenu(self)
        self.config(menu=menu)
        frame = InProgressCandidates(self)
        frame.grid(row=0, column=1, sticky='nesw')
        self.FrameList = {InProgressCandidates:InProgressCandidates(self)}
    def InstanceLinker(self, frame):
        link = self.FrameList[frame]
        return link
class GUIMenu(tk.Menu):
    def __init__(self, parent):
        tk.Menu.__init__(self, parent)
        addcandidates = tk.Menu(self, tearoff=0)
        self.add_cascade(label='Add Candidates', menu=addcandidates)
        addcandidates.add_command(label='Quick Add', command=lambda: QuickAdd(parent))
class QuickAdd(tk.Toplevel):
    def __init__(self, parent):
        tk.Toplevel.__init__(self, parent)
        saysomething = tk.Entry(self)
        saysomething.grid(row=1, column=0)
        def addbutton():
            global Bigbadtext
            Bigbadtext = saysomething.get()
            app.InstanceLinker(InProgressCandidates).AddtoList()
        okbutton = ttk.Button(self, text='Add', command=addbutton)
        okbutton.grid(row=2, column=0)
class InProgressCandidates(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.tree = ttk.Treeview(self)
        self.tree.grid(row=1, column=0, sticky='nesw')
        scrollbar = ttk.Scrollbar(self, orient='vertical', command=self.tree.yview)
        scrollbar.grid(row=1, column=1, sticky='nws')
        self.tree.config(columns='something', selectmode='browse', height=20, yscrollcommand=scrollbar.set)
        self.tree.column('#0', width=20, minwidth=10, stretch=tk.YES)
        self.tree.column('something', width=150, minwidth=10, stretch=tk.YES)
        self.tree.heading('#0', text='#', anchor=tk.W)
        self.tree.heading('something', text='Say something', anchor=tk.W)
    def AddtoList(self):
        global Counter
        Counter += 1
        print('I was here')
        self.tree.insert("", Counter, Bigbadtext, text=Counter)
        self.tree.set(Bigbadtext, 'something', Bigbadtext)
app = MainApp()
app.mainloop()

A: The problem is that you are creating two treeview widgets, and then adding items to the one that is invisible.
You create one here:
frame = InProgressCandidates(self)

Then you create another one here:
self.FrameList = {InProgressCandidates:InProgressCandidates(self)}

Since you've already created one, the one you created should be what goes in self.FrameList:
self.FrameList = {InProgressCandidates:frame}

A: It is not really an answer but I up voted the question because it solved me a problem. I wanted to add items to the widget but did not want to show it to the user until I finished to populate the tree. But each insert showed right away. Now I create 2 identical widgets, one visible and the other is not, and once it is populated I change between them. Thus even a mistake can have a benefit.


text:
Q: Why do I get 404 not found error when trying to load my just-deployed Source Bundle in AWS Elastic Beanstalk? Overview
I have a very simple CodePipeline that deploys new versions of an application to my AWS Elastic Beanstalk environment. If I run the pipeline, it works and the application is deployed without errors. But if I then navigate to view the "Application versions" for my application, and click the link for the "Source Bundle" for the just-now-deployed version at the top of the list, I'm just shown a generic AWS 404 not found page. If I click on ANY source bundle links, I see the same error.
What in the world is happening?
Some context
The CodePipeline successfully uploads the build artifacts to the designated artifact bucket. Those artifacts are all still there. The links from the Application Versions page don't seem to be resolving correctly.
I have a Lifecycle defined for my Application Versions to limit to the last 50 versions, and to retain the source bundles in S3. The source bundles are in the bucket mentioned in the previous paragraph, designated for the artifacts, but there are no source bundles in the elasticbeanstalk bucket. This has puzzled more than one AWS Support technicians already.

A: Nevermind, I was using the new fancy redesigned beta console. The link in the old console works perfectly.


text:
Q: How can I overload static methods that take in a base class or its derived classes in C++? Here's a bit of context:
struct Element { /* ... */ };

struct Expr : public Element { /* ... */ };

struct NumberExpr : public Expr { /* ... */ };

struct BinaryExpr : public Expr {
    std::unique_ptr<Expr> lhs;
    /* ... */
};

/* and many more AST nodes... */

class CodeGenerator {
    /* ... */
    static llvm::Value* generate(std::unique_ptr<Element> element) { /* ... */ }

    static llvm::Value* generate(std::unique_ptr<Expr> element) { /* ... */ }

    static llvm::Value* generate(std::unique_ptr<NumberExpr> element)

    static llvm::Value* generate(std::unique_ptr<BinaryExpr> element) {
        // Problem here!!
        auto lhs = generate(std::move(element->lhs));

        /* ... */
    }
    /* ... */
}

Currently, the problematic line will generate(std::unique_ptr<Expr> element) for everything, even if element is std::unique_ptr<NumberExpr>. I understand that this behaviour is by design, but I want to ask how I can implement the expected behaviour that the 'most related' overloaded methods should be used (by 'most related', I mean use the exact class, if unavailable, use its base class Expr (if inherited from it) or Element (the top-level base class)
I think this sounds like a function template problem, but I have never learned/used templates before so I'm a bit stuck; however, I don't mind solution in templates. Thank you.
P.s: I believe one solution is to put generate as a virtual method of Element, but this defeats the whole point of isolating the algorithm from the object.


text:
Q: Keras LocallyConnected1D layer I have a very specific problem that I am trying to solve. It seems very straightforward, but I am not able to implement that in keras. For example I have a an input_dim = 300. On which I have to apply a filter of size 100 with stride 100. So basically use each of the 100 columns of the vector independently and then apply an activation on each of them. So then I have 3 outputs which would then be connected to a fully connected layer, which I know how to do. I tried googling and referring the Keras documentation, but it is very unclear as to what would be the values of the parameters should be. I apologize if the question is a bit vague.

I would also like to add that this is one way that I could think of to get the configuration I mentioned in the figure. Something like 3 perceptrons connected to form a layer and then connected to another dense layer. But there could be other ways.

A: Apparently, I had got the shape of the output all wrong. Once you are that the filter is of size 100 and the stride is of size 100, it is obvious and it is also obvious to keras that the output activation layer is of size 3. The first parameter on the other hand possibly (I haven't tried this) deals with depth of the filter if each input neuron itself is multidimensional. Something like RGB values. Now why it is still called 1D, well that I am not sure. Possibly because the arrangement of the neurons is still 1D. But here is how you do it.
model.add(LocallyConnected1D(1, 100, strides=100, input_shape=(300, 1)))


text:
Q: How to match last occurrence in a string with Regex Hi I am working on RoR project with ruby-2.5.0 and Rails 5. I have a pattern to find time from a string as follows:-
time_pattern = /(\d{2}\:\d{2}:\d{2}|\d{2}\:\d{2})/
time = mystr[time_pattern]

It retuns the first matching time in the string for example if there are two times are present in the string "14:04" and "14:05" it will always return the first one which is "14:04". i need to find the second one. Please help me to find the second match using regex. I have also tried the scan method like:-
time = params.to_s.scan(time_pattern).uniq.flatten.last

But my rubocop throws an error Methods exceeded maximum allowed ABC complexity (1)
Please help. Thanks in advance.

A: Try using the following expression: /(\d{2}:\d{2}(:\d{2})?)/g.
Here is an example of it running in ruby:
re = /(\d{2}:\d{2}(:\d{2})?)/
str = ' "14:04" and "14:05"'

# Get matches
matches = str.scan(re)

# Get last match
matches = str.scan(re)

# Get last match
lastMatch = str.scan(re).last[0]

# Print last match
puts lastMatch.to_s
# OUTPUT => "14:05"

# Print the match result
str.scan(re) do |match|
    puts match.to_s
end

A: Last Regex Match
To get the last match you can simply call #last on the #scan result.
regex = /(\d{2}\:\d{2}:\d{2}|\d{2}\:\d{2})/ # original
# or
regex = /\d{2}(?::\d{2}){1,2}/ # kudos @ctwheels

string = '12:01, 12:02, 12:03:04, 12:05'

string.scan(regex).last
#=> "12:05"

ABC-Metric
The ABC Metric is more complex and would require having a look at your whole method. But here is a blog post that explains it pretty well: Understanding Assignment Branch Condition
Another options is to change the max ABC size in the RuboCop settings. Have a look at the RuboCop Configuration Documentation and the default configuration (Metrics/AbcSize max size is set to 15 by default).


text:
Q: How to write macro to copy data from multiple combo boxes to worksheet I have a userform with multiple comboboxes that I want to use to record data on a worksheet.  How do I write the code in a loop so I do not have to write it for all 60 occurances?  Below is an example of what I have:
Edited to add the whole sub:
Private Sub FltData_Click()

    'Check for empty date boxes
    Dim IsEmptyDateBox As Boolean
    IsEmptyDateBox = IsBlankDateBox()

    If IsEmptyDateBox = True Then
        MsgBox "Empty Date Box Detected"
    End If

    'Check for complete training boxes
    Dim IsEmptyTextBox As Boolean
    IsEmptyTextBox = IsBlankTextBox()

    If IsEmptyTextBox = True Then
        MsgBox "Incomplete Training Info Detected"
    End If

    'Input date function
    Dim DateSelect As String
    Dim Month As String
    Dim Day As String
    Dim Year As String

    If DateMonth.Value = "January" Then
        Month = "01"
        Elseif DateMonth.Value = "February" Then
        Month = "02"
        Elseif DateMonth.Value = "March" Then
        Month = "03"
        Elseif DateMonth.Value = "April" Then
        Month = "04"
        Elseif DateMonth.Value = "May" Then
        Month = "05"
        Elseif DateMonth.Value = "June" Then
        Month = "06"
        Elseif DateMonth.Value = "July" Then
        Month = "07"
        Elseif DateMonth.Value = "August" Then
        Month = "08"
        Elseif DateMonth.Value = "September" Then
        Month = "09"
        Elseif DateMonth.Value = "October" Then
        Month = "10"
        Elseif DateMonth.Value = "November" Then
        Month = "11"
        Elseif DateMonth.Value = "December" Then
        Month = "12"
    End If

    Day = DateDay.Value
    Year = DateYear.Value
    DateSelect = Month + "/" + Day + "/" + Year

    'Is data already inputed/eliminate duplicates
    Call DuplicateCheck

    'Select FltData worksheet
    Worksheets("FltData").Select

    'Select blank row after last entry
    LastRow = Worksheets("FltData").UsedRange.SpecialCells(xlCellTypeLastRow).Row
    Cells(LastRow + 1,1).Select

    'Input UserForm info to Worksheet
    ActiveCell.Value = DateSelect
    ActiveCell.Offset(, 1).Value = Time1.Value
    ActiveCell.Offset(, 2).Value = Crew1.Value
    ActiveCell.Offset(, 3).Value = TR1.Value
    ActiveCell.Offset(, 4).Value = Status1.Value

    If Time2.Value <> "" Then
        ActiveCell.Offset(1, 0).Value = DateSelect
        ActiveCell.Offset(1, 1).Value = Time2.Value
        ActiveCell.Offset(1, 2).Value = Crew2.Value
        ActiveCell.Offset(1, 3).Value = TR2.Value
        ActiveCell.Offset(1, 4).Value = Status2.Value
    End If

    If Time3.Value <> "" Then
        ActiveCell.Offset(2, 0).Value = DateSelect
        ActiveCell.Offset(2, 1).Value = Time3.Value
        ActiveCell.Offset(2, 2).Value = Crew3.Value
        ActiveCell.Offset(2, 3).Value = TR3.Value
        ActiveCell.Offset(2, 4).Value = Status3.Value
    End If

    If Time4.Value <> "" Then
        ActiveCell.Offset(3, 0).Value = DateSelect
        ActiveCell.Offset(3, 1).Value = Time4.Value
        ActiveCell.Offset(3, 2).Value = Crew4.Value
        ActiveCell.Offset(3, 3).Value = TR4.Value
        ActiveCell.Offset(3, 4).Value = Status4.Value
    End If

    Call SortByDateTime

End Sub

...
I think I figured out a way to get this done by using Me.Controls:
Dim x As Integer
Dim y As Integer
Dim z As Integer

x = 1
y = 2

For y = 2 To 48
    If Me.Controls("Time" & y).Value <> "" Then
        ActiveCell.Offset(x, 0).Value = DateSelect
        ActiveCell.Offset(x, 1).Value = Me.Controls("Time" & y).Value
        ActiveCell.Offset(x, 2).Value = Me.Controls("Crew" & y).Value
        ActiveCell.Offset(x, 3).Value = Me.Controls("TR" & y).Value
        ActiveCell.Offset(x, 4).Value = Me.Controls("Status" & y).Value
    End If
    x = x + 1
Next y


text:
Q: How to change the background music as soon as the game starts? Hey so I am playing some background music as soon as my app starts. Like a menu song, and it is looping forever throughout the game. I would like to change the music as soon as you hit the start game button. Just so I can have a different menu and game songs. I tried
backgroundMusicPlayer.play()
playBackgroundMusic("MUSIC.wav")

I did this in my touchesBegan method but of course every time you touch the screen the song is going to start over and over again. Any ideas how I can do this? Thank you in advance

A: While the game starts,if a user touches the initial screen,then it could be identified with a tapGestureRecognizer,in the corresponding class file.
I prefer tap recognising than touchesBegan ,so that, when user touches the screen ,you could play the music via
backgroundMusicPlayer.play()
playBackgroundMusic("MUSIC.wav")

and stop this by backgroundMusicPlayer.stop()when moving on to MENU page.
Then the music wont get played everytime user touches the screen.
I hope this works.

A: Simply use AVFoundation. Follow this basic tutorial to play audio as soon as the ViewController loads, then on clicking the start button stop the audioPlayer.


text:
Q: How can I substitute double backslashes for single backslashes? Example:
example <- "\\begin"
example <- gsub(pattern = "\\\\", replacement = "\\", example)

I know the backslashes need to be escaped, which is why they're duplicated in the gsub function. But this code returns the string "begin" devoid of any backslashes. I've also tried
example <- "\\begin"
example <- gsub(pattern = "\\", replacement = "\", example, fixed = TRUE)

But RStudio (and apparently StackOverflow!) really doesn't like that--it treats "" like an open quotation mark followed by an escaped close quotation mark, rather than treating it as a string of a single backslash.
How can I do this? For better context, I have a .txt file of .tex code (except that every backslash is duplicated) that I am trying to turn into a .tex file within an Rmd document.
I'd be happy to use an implementation using stringr, if that makes things easier.


text:
Q: How to delete a DNS record using Softlayer API with Powershell I need to write a PowerShell script, which deletes DNS record from Softlayer cloud, using Softlayer REST API.
The below command should do my purpose. I have $headers correctly setup. My issue is with $uri and $jsonObject.
Invoke-WebRequest -Uri $uri -Headers $headers -Method POST -ContentType application/json -Body $jsonObject

can anybody please give me an example of values for $jsonObject and $uri?
Should $uri be like below? If yes, what is the Object.json , do I need to define it?
$uri = "https://api.service.softlayer.com/rest/v3.1/SoftLayer_Dns_Domain_ResourceRecord/deleteObject/Object.json"

A: Try following the example
 slcli --format=json call-api SoftLayer_Dns_Domain_ResourceRecord deleteObject --id 123456789

the 123456789 data should change with your DNS domain id
For more information, could you review the link https://softlayer-api-python-client.readthedocs.io/en/latest/cli/call_api/
I hope it helps.

A: I found how:
$uri="https://api.softlayer.com/rest/v3/SoftLayer_Dns_Domain/$domainID/getResourceRecords.json"
Below will return a json file which has all records in our domain:
Invoke-WebRequest -Uri $uri -Headers $headers -Method GET -ContentType application/json
From received json file ,we can extract record ID ($recordID in below) of the record that we want to delete and then run below:
$deleteResoutceURI= "https://api.softlayer.com/rest/v3/SoftLayer_Dns_Domain_ResourceRecord/$recordID/deleteObject.json"
Invoke-WebRequest -Uri $deleteResoutceURI -Headers $headers -Method POST -ContentType application/json


text:
Q: How can I test my Google Analytics integration? I have a customized GA integration in order to work more smoothly with turbolinks. (Based loosely on: http://reed.github.io/turbolinks-compatibility/google_analytics.html)
Now like a good little code monkey I want to cover my code in my tests. After much googling I found a surprising dearth of acceptable testing methods. Mostly just a manual make sure the code/tracking pixel is present sort of thing. Which obviously won't work long term; someone will forget to check a page or an interaction type and broken code will ship.
So how can I automatically test that my integration of GA is working correctly? (I'm already using capybara-webkit for integration testing)

A: There is a version of the GA js that logs all activity to the browser console (ga_debug.js). Capybara-webkit allows you to access the browser console log from the driver which means that you can simply wrap your actions in assert_difference('page.driver.console_messages.select {|m| m[:message] == "Track Pageview" }.length',n) do ... end and get really slick testability of your code.
There's also a version for universal analytics: https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#debug you just have to adjust your message filter to catch the right messages.
While there are other approaches, such as mocking out GA or setting up a proxy server; they are more work and require me to know what the GA server expects from the GA client code, and update when that changes. This way I don't have to change a thing, just use the correct client library for the job.


text:
Q: Teammates and Tourism Victory If I'm playing Brave New World multiplayer as part of a team it appears that, unlike science, our culture and tourism are not combined.  That means the best way for the team to win a culture victory is to give all the great artists to one player, let that player build all tourism benefiting wonders and basically concentrate entirely on that player's civ, which seems like it might not be much fun for the other player(s).  Have I understood this correctly?
Edit: I've just read the question that people have marked this as a duplicate of, sounds like it's even worse - everything I've said is true, plus you need to influence your partner too, yet you can't have open borders with them!  Sounds like this isn't a good way to go in multiplayer.


text:
Q: Get Last Entry in a MySQL table I'm basically trying to make a "goal" bar. The goal is determined by getting the last entry I made in a MySQL table. I want to get the ID of the last entry therefore.
How do I get the last entry in the table and then get the id from that last entry?
(Using PHP)

A: you can use LAST_INSERT_ID() function. example:
$sql = "SELECT * FROM mytable WHERE id = LAST_INSERT_ID()";

A: you can use this query to get the results you want with this sql query as used in this example:
$sql = "SELECT user_id FROM my_users_table ORDER BY user_id DESC LIMIT 0,1";

A: To get the greatest id:
SELECT MAX(id) FROM mytable

Then to get the row:
SELECT * FROM mytable WHERE id = ???

Or, you could do it all in one query:
SELECT * FROM mytable ORDER BY id DESC LIMIT 1

A: if the field is auto-incremented then you can use  LAST_INSERT_ID

A: To do this reliably, you must have some field in the table that you can examine to determine which is last. This could be a time stamp of when you added the record, a sequence number that continually increases (especially an auto-incrementing sequence number), etc.
Then, let's suppose it's a sequence number called "rec_seq". You'd write something like:
select * from my_table
where rec_seq=(select max(rec_seq) from my_table)

A: select all fields from table in reverse order and set limit 0,1
This will give you last result of table field data

A: Get the latest entry of a user
'SELECT user_id FROM table_name WHERE user_id = '.$userid.' ORDER BY user_id DESC LIMIT 1';

A: The above answers show how to get the latest entry by id. If one uses non-incrementing ids such as UUIDs as keys, this does not work. In that case one could use a created_at column instead.
-- highest id
SELECT * FROM some_table ORDER BY id DESC LIMIT 1;

-- latest created at date
SELECT * FROM some_table ORDER BY created_at DESC LIMIT 1;


text:
Q: How to get a square root for 32 bit input in one clock cycle only? I want to design a synthesizable module in Verilog which will take only one cycle in calculating square root of given input of 32 bit.

A: [Edit1] repaired code
Recently found the results where off even if tests determine all was OK so I dig deeper and found out that I had a silly bug in my equation and due to name conflicts with my pgm environment the tests got false positives so I overlooked it before. Now it work in all cases as it should.
The best thing I can think of (except approximation or large LUT) is binary search without multiplication, here C++ code:
//---------------------------------------------------------------------------
WORD u32_sqrt(DWORD xx) // 16 T
    {
    DWORD x,m,a0,a1,i;
    const DWORD lut[16]=
        {
        //     m*m
        0x40000000,
        0x10000000,
        0x04000000,
        0x01000000,
        0x00400000,
        0x00100000,
        0x00040000,
        0x00010000,
        0x00004000,
        0x00001000,
        0x00000400,
        0x00000100,
        0x00000040,
        0x00000010,
        0x00000004,
        0x00000001,
        };
    for (x=0,a0=0,m=0x8000,i=0;m;m>>=1,i++)
        {
        a1=a0+lut[i]+(x<<(16-i));
        if (a1<=xx) { a0=a1; x|=m; }
        }
    return x;
    }
//---------------------------------------------------------------------------

Standard binary search sqrt(xx) is setting bits of x from MSB to LSB so that result of x*x <= xx. Luckily we can avoid the multiplication by simply rewrite the thing as incrementing multiplicant... in each iteration the older x*x result can be used like this:
x1 = x0+m
x1*x1 = (x0+m)*(x0+m) = (x0*x0) + (2*m*x0) + (m*m)

Where x0 is value of x from last iteration and x1 is actual value. The m is weight of actual processed bit. The (2*m) and (m*m) are constant and can be used as LUT and bit-shift so no need to multiply. Only addition is needed. Sadly the iteration is bound to sequential computation forbid paralelisation so the result is 16T at best.
In the code a0 represents last x*x and a1 represents actual iterated x*x
As you can see the sqrt is done in 16 x (BitShiftLeft,BitShiftRight,OR,Plus,Compare) where the bit shift and LUT can be hardwired.
If you got super fast gates for this in comparison to the rest you can multiply the input clock by 16 and use that as internal timing for SQRT module. Something similar to the old days when there was MC clock as Division of source CPU clock in old Intel CPU/MCUs ... This way you can get 1T timing (or multiple of it depends on the multiplication ratio).

A: There is conversion to a logarithm, halving, and converting back.
For an idea how to implement "combinatorial" log and antilog, see Michael Dunn's EDN article showing priority encoder, barrel shifter & lookup table, with three log variants in System Verilog for down-load.
(Priority encoder, barrel shifter & lookup table look promising for "one-step-Babylonian/Heron/Newton/-Raphson. But that would probably still need a 128K by 9 bits lookup table.)
While not featuring "verilog",
Tole Sutikno: "An Optimized Square Root Algorithm for Implementation in FPGA Hardware" shows a combinatorial implementation of a modified (binary) digit-by-digit algorithm.

A: In 2018, T. Bagala, A. Fibich, M. Hagara,
P. Kubinec, O. Ondráček, V. Štofanik and R. Stojanović authored Single Clock Square Root Algorithm Based on Binomial Series and its FPGA Implementation.

Local oscillator runs at 50MHz [… For 16 bit input mantissa,] Values from [the hardware] experiment were the same as values from simulation […] Obtained delay averages were 892ps and 906ps respectively.

(No explanation about the discrepancy between 50MHz and .9ns or the quoted ps resolution and the use of a 10Gsps scope. If it was about 18 cycles (due to pipelining rather than looping?)/~900*ns*, interpretation of Single Clock Square Root… remains open - may be one result per cycle.)
The paper discloses next no details about the evaluation of the binomial series.
While the equations are presented in a general form, too, my guess is that the amount of hardware needed for a greater number of bits gets prohibitive quickly.

A: I got the code
here it is
    module sqrt(
input[31:0]a,
output[15:0]out
    );
reg [31:0]temp;
reg[14:0]x;

always@(a)
begin
if(a<257)x=4;
if(a>256 && a<65537)x=80;
if(a>65536 && a<16777217)x=1000;
if(a>16777216 && a<=4294967295)x=20000;
temp=(x+(a/x))/2;
temp=(temp+(a/temp))/2;
temp=(temp+(a/temp))/2;
temp=(temp+(a/temp))/2;
temp=(temp+(a/temp))/2;
temp=(temp+(a/temp))/2;
temp=(temp+(a/temp))/2;
end

assign out=temp;
endmodule

A: The usual means of doing this in hardware is using a CORDIC.  A general implementation allows the calculation of a variety of transcendental functions (cos/sin/tan) and... square roots depending on how you initialize and operate the CORDIC.
It's an iterative algorithm so to do it in a single cycle you'd unroll the loop into as many iterations as you require for your desired precision and chain the instances together.
Specifically if you operated the CORDIC in vectoring mode, initialize it with [x, 0] and rotate to 45 degrees the [x', y'] final output will be a multiplicative constant away. i.e. sqrt(x) = x' * sqrt(2) * K

A: My version of Spektre with variable bits count in so it can be faster on short squares.
    const unsigned int isqrt_lut[16] =
{
    //     m*m
    0x40000000,
    0x10000000,
    0x04000000,
    0x01000000,
    0x00400000,
    0x00100000,
    0x00040000,
    0x00010000,
    0x00004000,
    0x00001000,
    0x00000400,
    0x00000100,
    0x00000040,
    0x00000010,
    0x00000004,
    0x00000001,
};
/// Our largest golf ball image is about 74 pixels, so lets round up to power of 2 and we get 128.
/// 128 squared is 16384 so out largest sqrt has to handle 16383 or 14 bits. Only positive values.
/// ** maxBits in is 2 to 32 always an even number **
/// Input value mist always be less than (2^maxBits) - 1
unsigned int isqrt(unsigned int xx, int maxBitsIn) {
    DWORD x, m, a0, a1, i;

    for (x = 0, a0 = 0, m = 0x01 << (maxBitsIn / 2 - 1), i = 16 - maxBitsIn / 2; m; m >>= 1, i++)
    {
        a1 = a0 + isqrt_lut[i] + (x << (16 - i));
        if (a1 <= xx) {
            a0 = a1;
            x |= m;
        }
    }
    return x;
}


text:
Q: rails + omniauth: inspect basic info this is my code to get the user's basic information after authorization:
basic_info = request.env['omniauth.auth'].extra.raw_info

first = basic_info.first_name
last = basic_info.last_name
email = basic_info.email
id = basic_info.id

the four variables get the data, so it works.
but when I'm trying basic_info.inspect command, I get:

"#"

why is that? shouldn't it dump all the values?

A: Like Singh suggested in his comment, you should use the to_yaml method to see what is inside a hash of nested hashes. I usually put the following code in the applicable controller:
raise request.env['omniauth.auth'].to_yaml

Now when trying to login the controller just renders the yaml.
EDIT: Now that Rails 4 uses the better_errors gem, this method of inspecting the omniauth hash no longer works so well. A better way now is:
render :text => "<pre>" + env["omniauth.auth"].to_yaml and return


text:
Q: Django HighChart with Api I'm new at Django please help me, I read some articles vlogs seems I cannot find the right code here's my code in views.py and i want it to disply in in HTML index.html and the result is it wont display I dont know what is wrong with my code
from django.shortcuts import render
from django.http import JsonResponse,HttpResponse
import requests
import pandas as pd
import json

def home(request):
    response = requests.get('https:api').text

    # li = list(response.split(","))

    res = json.loads(response)

    maleCount = 0
    femaleCount = 0
    for i in res:
        if i['gender'] == 'M':
            maleCount += 1
        else:
            femaleCount += 1
    TotalCount =[
        {
        "name": "MALE",
        "data": [maleCount]},
        {
            "name": "FEMALE",
            "data": [femaleCount]
        }
    ]

    return render(request,'index.html',{'data':TotalCount})

and here my code in html in index.html tru views.py it wont display my data in html seems my code wont work what is the problem of my code? please help thank you
<!doctype html>

What is wrong with my code?

A: If you want to use contextual data inside html code, you need to put this inside double brackets:
series: {{data}}


text:
Q: Share only a single folder using SMB I want to share my "My Videos" folder using Windows's built in SMB. The problem is that when I decide to share my video folder and check it on another device, the path always is:
networkname > username > My Videos

instead of just:
My Videos

I noticed that indeed sharing gets turned on from the user folder down to the video folder instead of just on the folder I selected.
Why is this happening? How can I just display the "My Videos" folder on my remote device and not the entire path? The device in question is a hacked Apple TV.


text:
Q: A question on op amp selection in an active filter Below is a Sallen-key type active LPF which filters out all the ac components and integrates(averages) the incoming 1kHz 1V pulse train.

There are tools to design these filters, but my question is about the op amp part:
If I change this op amp with any other single supply op amp in LTspice I get totally different results. I must say Im not into details of op amps and active filters so please answer as to a beginner.
Why is any generic op amp doesn't work for this circuit?
What determines us to choose this particular op amp here?
What is so special about LM358 here?
Edit:

A: The LM358 works with inputs that can range from 0 volts (negative supply rail) to Vcc-1.5 volts and, this corresponds with the signal you are feeding the circuit so no problem there. The LM358 output also works pretty much down to 0 volts so there shouldn't be any problem there either.
So, if you tried a different op-amp and it didn't appear to work correctly it's highly likely that its inputs and output do not get close to 0 volts. Not many do but rail-to-rail op-amps can be fairly well relied upon to do what they say on the tin.
Alternatively power the op-amp with a +/- supply and then everything should be fine.

A: I know this is counter-intuitive, but a low pass active filter requires an op amp with good high-frequency response.  You are actively filtering out the high frequency (via C1) and many (most?) newer op amps are low power with correspondingly low bandwidth.  These will be poor choices for active filters, when filtering signals with high frequency components (like square waves).  Check the gain-bandwidth product (sometimes listed as unity-gain bandwidth).


text:
Q: Displaying content of Advanced Custom Fields I'm having a little problem understanding what (my) PHP is doing when I'm trying to display different Custom Posts and Advanced Custom fields on the same page.
I have added different Advanced Custom Fields to a page, and I have custom posts that I am trying to display using the template.
I'm calling my custom fields throughout the template using:
<?php the_field('field-name') ?>

My custom posts are called through loops like this (somewhere around the middle of the template):
<?php
  $args = array(
  'post_type' => 'foo'
);

$foo = new WP_Query( $args );
if( $foo->have_posts() ) {

while( $foo->have_posts() ) {
  $foo->the_post();
?>
  <?php the_content() ?>
<?php
  }
}
else {
  // SOME MESSAGE
}
?>

The content of the Advanced Custom Fields is showing fine, above those loops. Below the loops it just doesn't display.
I can't figure out why the content is not showing up.
I assume it has to do with the while or if statements of the loops. If I remove the loops, the content of any Advanced Custom Field below does display.

A: When you use WP_Query(), you are changing the default $post variable on the page each time you loop through a post. You need to call wp_reset_postdata() after your loop to reset that $post variable so it corresponds to the current page again. You can call the function after your 'while' loop -
<?php
$args = array(
    'post_type' => 'foo'
);
$foo = new WP_Query( $args );

if( $foo->have_posts() ) {

    while( $foo->have_posts() ) { $foo->the_post();

        the_content();

    } wp_reset_postdata();
}
else {
  // SOME MESSAGE
}
?>


text:
Q: React component AMD bundling with Webpack for Require.js Due to some reason, we want to load React component on Backbone view (with Require.js). This React component is being bundled using Webpack 4.x.
We have enable AMD/UMD mode during bundling in Webpack config.
...
...
module.exports = {
  entry: {
    componentName: ['./components/componentName/index.js']
  },
  amd: {
    componentName: true
  },

  output: {
    path: path.resolve(__dirname, './componentName'),
    filename: '[name].js',
    libraryTarget: 'umd',
    library: 'componentName',
    umdNamedDefine: true
  },

  externals: {
    'react': 'react',
    'react-dom': 'react-dom',
    'react-dom-server': 'react-dom-server'
  },
  ...

Now, we are trying to use bundled React component in Backbone+Require.js app where we are loading React and ReactDOM (UMD enabled) as below
define([
  'jquery',
  'underscore',
  'backbone',
  'react',
  'react-dom',
  'componentName'
], function($, _, Backbone, React, ReactDOM, componentName) {

   ...

   render: function() {
      console.log(React, ReactDOM, componentName)
   }

   ...
});

Here componentName always comes as undefined whereas React and ReactDOM are loading correctly. Can anyone help to understand am I missing something here?


text:
Q: Ultrawingrid layout I am working on an ultrawingrid. The grid has two columns Name & Age. The are more than 300 rows in the grid, so user needs to do lot of scrolling. I want to change the layout of the grid to display as much information as possible and with minimum scrolling.
So for example, presently it looks like
 Name     Age
 Sam       25
 Bob       20
 Irvin     45
 Tanya     24
 Mark      30

How, I intend to display it as
Sam   25       Bob   20       Irvin   45
Tanya 24       Mark  30

so essentially, in some form of matrix for which I could set up number of rows and columns and which is scroll-able vertically (and not horizonatally)
I tried to play around with CardView property http://help.infragistics.com/Help/Doc/WinForms/2012.1/CLR2.0/HTML/Infragistics2.Win.UltraWinGrid.v12.1~Infragistics.Win.UltraWinGrid.UltraGridBand~CardView.html and setting its MaxCardAreaCols and MaxcardAreaRows settings, however it doesn't work. I tried to follow Rowlayout property by setting up layout to ColumnLayout and that did not work either.
Is there any way to achieve it?

A: A hack that might work for you is to create a special class just for display purposes.
public class DisplayRow
{
    string Name1 { get; set; }
    string Age1 { get; set; }
    string Name2 { get; set; }
    string Age2 { get; set; }
    // So on...
}

But this complicates the logic and gets quite ugly depending on the complexity of what you're doing.


text:
Q: what is the cin operator order in C++ I have a question about cin and cout order in C++, for example:
int a,b;
std::string c;
std::cin >> a >> b >> c >> c >> a;
std::cout << a << " " << b << " " << c << " " << a;

if the input is "5 10 hello world 15 20", what is the output,
I can see the result, but can anyone explain me how it works?
cin assign 5 variable, but input is 6 values, and what is the order of cin and cout?

A: Output would be:
15 10 world 15

std::cin reads data into the first variable from the left first, and after that it  reads data into the second variable and so on.
std::cin >> a >> b >> c >> c >> a;

is equivalent to the following:
std::cin >> a; //reads 5
std::cin >> b; //reads 10
std::cin >> c; //reads hello
std::cin >> c; //reads world
std::cin >> a; //reads 15

See after reading 15, it doesn't read the 20, because there is no more std::cin >> variable.

A: C++ (ab)uses the shift operators for input and output. They are left-associative, which means the left-most operator gets executed with its two operands, and the result of that form the left operand for the next operator. So something like
std::cin >> a >> b >> c >> c >> a;

essentially is interpreted as
((((std::cin >> a) >> b) >> c) >> c) >> a;

Let's look at this in detail. The expression std::cin >> a invokes
std::istream& operator>>(std::istream& is, int& num);

That operator will read from is into num and return (a reference to) is. That is, the very same is object (std::cin in our case) is then used to read into b: std::cin >> b. This invokes the same operator, which reads into b and then again return it's left operand.
This, in turn, is used for reading into c. That is a string, so the operator invoked will be a bit different:
std::istream& operator>>(std::istream& is, std::string& str);

As you see, what differs from the previous overload is only the right operand (and the implementation, of course.) This, too, returns its left operand. (In fact, so do all input operator overloads, and so should ydo your own ones, too.)
Basically, your code is eqvivalent to this:
std::istream& tmp1 = std::cin >> a ;
std::istream& tmp2 = tmp1 >> b;
std::istream& tmp3 = tmp2 >> c;
std::istream& tmp4 = tmp3 >> c >> a;

For output, the situation is very similar, except that the output operators' signatures are slightl different:
std::ostream& operator<<(std::ostream& os, int num);
std::ostream& operator<<(std::ostream& os, const std::string& num);

A: Because you are writing more than once to a variable between two sequence points, the output is undefined.
The << operator is left-to right associative
Edit: Nonsense. Overloaded operators act like functions and so introduce sequence points. Tho output is like Nawaz wrote.


text:
Q: Readfile() with warning error and html_entity_decode() not working - PHP Im trying to use php for download a file from a ssh server. The download is working but i got a warning with my function readfile() and the characters keep in html style while i use this function html_entity_decode().
If i try this :var_dump($output) it gives me something like this string(xxx)" ". A string with xxx characters but empty.
The error :
Warning:  readfile(<?xml version="1.0" encoding="UTF-8"?><ResultatPEC xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance" dateCreation="02-12-2018" versionFichier="0000842887" xsi:noNamespaceSchemaLocation="Resultats_PEC_2.10.xsd">
<IdentificationDepot CodeOffre="0" CodeSiteDepot="932930" DateDepot="26-11-2018" HeureDepot="07:04" IDDeposant="590226" NiveauService="E" NumDepot="BR099441" NumeroBip="0000793653" NumSTP="21787924" OptionDateDepot="DepotJourCreux" OptionMeca="0" OptionSiteDepot="Standard" TypeDeclaration="DEPOT" ZoneDense="1"/>
  <Publication IDPCD="1174646" NoPublication="0520K87314" NoParution="391" NoParutionConstate="391" PublicationPanelisee="0" TypeParution="NUM" TypeParutionConstate="NUM">
     in D:\www\SAGAPEC\application\modules\supervision\controllers\AdminController.php on line 397

My code :
$connection = ssh2_connect($this->_configFile->ftp->hostname, $this->_configFile->ftp->port);
        if ($connection) {
            $login = ssh2_auth_password($connection, $this->_configFile->ftp->login, $this->_configFile->ftp->password);
            if ($login) {
                $content = true;
                if ($content) {
                    $fileName = $this->_getParam('name');
                    if ($fileName){
                        $stream = ssh2_exec($connection, "cat {$fileName}");
                        stream_set_blocking($stream, true);
                        $output = stream_get_contents($stream);
                        simplexml_load_string($output);
                        $abc = html_entity_decode($output,ENT_QUOTES,"UTF-8");

                        $file = $abc;

                        header("Content-Description: File Transfer");
                        header("Content-Type: application/octet-stream");
                        header('Content-Transfer-Encoding: binary');
                        header("Content-Disposition: attachment; filename=" . basename($file));

                        readfile($file);
                        exit();
                    }


text:
Q: Graphviz Format: "jpeg" not recognized Running the following code (example from https://pypi.org/project/graphviz/):
from graphviz import Digraph
dot = Digraph(comment='The Round Table', format='jpeg')
dot.node('A', 'King Arthur')
dot.node('B', 'Sir Bedevere the Wise')
dot.node('L', 'Sir Lancelot the Brave')
dot.edges(['AB', 'AL'])
dot.edge('B', 'L', constraint='false')
dot.render('test-output/round-table.gv', view=True)

Results in:
Format: "jpeg" not recognized. Use one of:

It seems like graphviz cannot write a file to any format. How to solve this?

A: My method: (I'm win10, other op may skip to step 2)

*

*Add "bin/" of Graphviz into environment path.

*

*My Graphviz installation path: D:\software\graphviz\Graphviz2.44.1\. It has 4 folders: "bin","include","lib","share"

*So I add D:\software\graphviz\Graphviz2.44.1\bin to my environment path

*cmd run command "dot -c" to config.

*

*dot means D:\software\graphviz\Graphviz2.44.1\bin\dot.exe. Due to step 1, I just need to run dot -c, otherwise, I need to run D:\software\graphviz\Graphviz2.44.1\bin\dot.exe -c

*dot -c means: Configure plugins (Writes $prefix/lib/graphviz/config with available plugin information.  Needs write privilege.)

*Add path to your code:
# add
import os
path_graphviz = "D:/software/graphviz/Graphviz2.44.1/bin" # replace by your Graphviz bin path
os.environ["PATH"] += os.pathsep + path_graphviz

# origin code
from graphviz import Digraph
dot = Digraph(comment='The Round Table', format='jpeg')
dot.node('A', 'King Arthur')
dot.node('B', 'Sir Bedevere the Wise')
dot.node('L', 'Sir Lancelot the Brave')
dot.edges(['AB', 'AL'])
dot.edge('B', 'L', constraint='false')
dot.render('test-output/round-table.gv', view=True)

*I success on my computer.
here is result


text:
Q: Web address shows different php file when opened in a new tab I'm starting to learn some web design and integrating PHP scripts with ajax calls to avoid browser refreshes and noticed that my companies site (which I don't have access to the files) has a weird thing going on with the address bar.
So usually the address is like www.site.com/admin.php, and if I click a link that brings me to www.site.com/Users.php (hovering shows this address) BUT the address stays at www.site.com/admin.php.
Heres the weird part. If I middle click the link(open in a new tab) the address will then become www.site.com/Users.php and all of the $_POST and $_GET calls will show up in the address bar like www.site.com/Users.php?user=Adam.
I use this a lot because if i try to refresh the users page, it goes back to the default admin.php page unless I opened it in a new tab.
I was wondering if there is a reason why clicking a link normally keeps the address the same and doesnt change the admin.php to Users.php?

A: The website is probably using frames to load its pages. So although you are navigating to site.com/Users.php, this is all really going on inside a frame view.
See this code for example:

Go to Page

You can click on the link, and although the frame will display the content at Users.php, you will still be on the original page you landed on.


text:
Q: How to fix "git push heroku master"? I've been trying to do it for a long time, and I never can, I keep creating files and folders, new .git, I try but it doesn't work! I've been wanting to host my discord py bot, but the command git push heroku master always gets an ERROR! Now I leave the logs! I have git installed I am logged into HEROKU and registered! I have a GITHUB account and I have repositories
C:\Users\ruben\Desktop\Discord\Bot\ValientBot>git push heroku master Enumerating objects: 4, done.
Counting objects: 100% (4/4), done.
Delta compression using up to 2 threads Compressing objects: 100% (3/3), done.
Writing objects: 100% (4/4), 2.57 KiB | 263.00 KiB/s, done.
Total 4 (delta 0), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-18 stack remote: -----> App not compatible with buildpack:
https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: ! remote: !
## Warning - The same version of this code has already been built: eb6fced64ec14c05dd2f92e7cf40c0e2cd30a1ff remote: ! remote: ! We have detected that you have triggered a build from source code with version eb6fced64ec14c05dd2f92e7cf40c0e2cd30a1ff remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku <branchname>:main remote: ! remote: ! This article goes into details on the behavior: remote: !
https://devcenter.heroku.com/articles/duplicate-build-version remote: remote: Verifying deploy... remote: remote: ! Push rejected to valient-bot. remote: To https://git.heroku.com/valient-bot.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/valient-bot.git'

A: If the project you're deploying uses main as its default branch name, use $ git push heroku main
instead of
$ git push heroku master
Heroku has updated default git branch name to main and this might be a reason for the error that you are having.


text:
Q: IR data from Landis+Gyr E350 I have purchased a ir->serial port cable for reading from the IR-port on electrical meters.
With the included program meter.exe, I can only get this:
C:\extra\Downloads\meter>meter -port=com3
olcdtool version 1.00
Opening: com3, baud: 300
Meter ID: /LGZ4ZMF100AC.M29

then what looks like a question mark in a square.
But no data.
Any clues? Can the power company turn off the port so it sends no data?
EDIT:
The adapter is this: http://www.ebay.co.uk/itm/Optical-Probe-IEC1107-IEC61107-62056-21-with-USB-cable-Windows-10-version-/201922292332?
Here is the reader software: https://www.dropbox.com/s/qjhykezcojkt3g7/meter.zip?dl=0
EDIT:
I have now been told the question is off-topic.
As long as the question and answer stays here for reference, I'm okay with it being locked.

A: For this 300 baud 7E1 counter, you need to trigger the answer. Below example is on my Raspberry Pi system:
echo -n -e '\x2F\x3F\x21\x0D\x0A' > /dev/ttyUSB0

I think the above command is exactly what gives you your output ("LGZ4ZMF100AC.M29"). Then WITHIN 2 s max you need to send the next command:
echo -n -e '\x06\x30\x30\x30\x0D\x0A' > /dev/ttyUSB0

This should then trigger the answer from the device. In my case it gives me
F(00)
C.1.0(38294136)
0.0(70148674        )
C.1.1(        )
1.8.1(000093.853*kWh)
1.8.2(000004.012*kWh)
1.8.3(000004.013*kWh)
1.8.4(000004.013*kWh)
1.8.5(000004.014*kWh)
1.8.6(000004.014*kWh)
1.8.0(000113.919*kWh)
2.8.1(001870.106*kWh)
2.8.2(000000.000*kWh)
2.8.3(000000.000*kWh)
2.8.4(000000.000*kWh)
2.8.5(000000.000*kWh)
2.8.6(000000.000*kWh)
2.8.0(001870.106*kWh)
15.8.0(001984.028*kWh)
C.5.0(4401)
C.7.0(0009)
32.7(232*V)
52.7(231*V)
72.7(230*V)

A: I couldn't get read from serial port to work, so I did this instead: cat /dev/ttyUSB0 to a file, and tail'ing until the end character "!"
#!/bin/bash
EYE=/dev/ireye             #ttyUSB number may change
find /dev -type f -delete  #remove real files in /dev
TMPFILE=`mktemp`
trap 'kill $CHILD; rm $TMPFILE' 0 #cleanup at exit
stty -F $EYE 300 cs7 parenb -parodd clocal -hupcl -opost -onlcr ignbrk ignpar -icrnl -isig -icanon -iexten -echo -echoe -echoctl -echoke

#send output from meter to tempfile
cat $EYE>$TMPFILE &
CHILD=$!
sleep 1
echo -n -e "\x2F\x3F\x21\x0D\x0A">$EYE
sleep 2
echo -n -e '\x06\x30\x30\x30\x0D\x0A'>$EYE
t=0
sleep 1
until tail $TMPFILE|grep "!"
do
    sleep 1
    t=`expr $t + 1`
    echo -n "$t "
    if [ $t -gt 40 ]
    then
        echo "Timeout"
        exit 1
    fi
done
# convert to json and send to mqtt
awk -f /root/j.awk $TMPFILE | mqtt-simple -h localhost -r -p smartmeter
kill $CHILD

echo "done $t polls"


text:
Q: Formatar TextArea JavaFX Estou criando uma especie de notepad, e estou tentando encontrar alguma forma, para que o úsuario consiga formatar sua letra, tamanho, cor etc em um TextArea do JavaFX. Alguém saberia se o JavaFX tem uma biblioteca especifica para isto? para que eu possa inserir acima do TextArea uma barra para formatação de texto?
Se alguém souber, agradeço!!!

A: Você pode utilizar o RichTextFX.
Com ele voce pode definir vários estilos pro seu textArea.
Uma alternativa seria utilizar o HTMLEditor acho que pode resolver seu problema.
Fonte: https://stackoverflow.com/questions/23202828/javafx-multiple-colors-in-textarea-javafx-8


text:
Q: I'm having a blank output when using def functions I'm a newbie in python I'm trying to use def function and every time I run the code it gives me a blank output. I'm using pyroid3 in my phone since I dont have any laptop/desktop.
I'm trying to get thru with this code
def greet():
    print('hi')

A: You have to call your function. With def you only declare it.
In python we calling function by adding ().
Like this:
def greet():
    print('Hello')

greet()

A: I apologize if it is an obvious question but have you tried to call your function? For example try to add greet() at the end of your code. It will look like this:
def greet():
    print('hi')
greet()

Feel free to ask if you need explaination!

A: it's possible that the output isn't displaying because you're not calling the function.
def greet():
    print('hi')

# Call the function
greet()


text:
Q: Resize JavaFX table I have this simple example of a table.
   import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.Callback;

public class MainApp extends Application
{

    private TableView<Person> table = new TableView<>();
    private final ObservableList<Person> data
        = FXCollections.observableArrayList(
            new Person("Processor", "72"),
            new Person("RAM", "78"),
            new Person("HDD Free Space", "890"),
            new Person("Lan Adapter NIC 1", "36"),
            new Person("Lan Adapter NIC 2", "67"));

    public static void main(String[] args)
    {
        launch(args);
    }

    @Override
    public void start(Stage stage)
    {
        Scene scene = new Scene(new Group());
        stage.setTitle("Table View Sample");
        //stage.setWidth(850);
        //stage.setHeight(550);

        final Label label = new Label("Address Book");
        label.setFont(new Font("Arial", 20));

        table.setEditable(false);
        Callback<TableColumn, TableCell> cellFactory
            = new Callback<TableColumn, TableCell>()
            {
                @Override
                public TableCell call(TableColumn p)
                {
                    return new EditingCell();
                }
            };

        table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

        TableColumn firstNameCol = new TableColumn("Credentials");
        //firstNameCol.setPrefWidth(300);
        firstNameCol.setMinWidth(50);
        //firstNameCol.prefWidthProperty().bind(table.widthProperty().divide(2)); // w * 1/2

        firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
        firstNameCol.setCellFactory(cellFactory);
        firstNameCol.setOnEditCommit(
            new EventHandler<CellEditEvent<Person, String>>()
            {
                @Override
                public void handle(CellEditEvent<Person, String> t)
                {
                    ((Person) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())).setFirstName(t.getNewValue());
                }
            }
        );

        TableColumn lastNameCol = new TableColumn("Value");
        //lastNameCol.setPrefWidth(300);
        lastNameCol.setMinWidth(50);
        //lastNameCol.prefWidthProperty().bind(table.widthProperty().divide(2));  // w * 1/2

        lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
        lastNameCol.setCellFactory(cellFactory);
        lastNameCol.setOnEditCommit(
            new EventHandler<CellEditEvent<Person, String>>()
            {
                @Override
                public void handle(CellEditEvent<Person, String> t)
                {
                    ((Person) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())).setLastName(t.getNewValue());
                }
            }
        );

        table.setItems(data);
        table.getColumns().addAll(firstNameCol, lastNameCol);

        final VBox vbox = new VBox();
        VBox.setVgrow(table, Priority.ALWAYS);
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(label, table);

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        stage.setScene(scene);
        stage.show();
    }

    public static class Person
    {

        private final SimpleStringProperty firstName;
        private final SimpleStringProperty lastName;

        private Person(String fName, String lName)
        {
            this.firstName = new SimpleStringProperty(fName);
            this.lastName = new SimpleStringProperty(lName);
        }

        public String getFirstName()
        {
            return firstName.get();
        }

        public void setFirstName(String fName)
        {
            firstName.set(fName);
        }

        public String getLastName()
        {
            return lastName.get();
        }

        public void setLastName(String fName)
        {
            lastName.set(fName);
        }

    }

    class EditingCell extends TableCell<Person, String>
    {

        private TextField textField;

        public EditingCell()
        {
        }

        @Override
        public void startEdit()
        {
            if (!isEmpty())
            {
                super.startEdit();
                createTextField();
                setText(null);
                setGraphic(textField);
                textField.selectAll();
            }
        }

        @Override
        public void cancelEdit()
        {
            super.cancelEdit();

            setText((String) getItem());
            setGraphic(null);
        }

        @Override
        public void updateItem(String item, boolean empty)
        {
            super.updateItem(item, empty);

            if (empty)
            {
                setText(null);
                setGraphic(null);
            }
            else
            {
                if (isEditing())
                {
                    if (textField != null)
                    {
                        textField.setText(getString());
                    }
                    setText(null);
                    setGraphic(textField);
                }
                else
                {
                    setText(getString());
                    setGraphic(null);
                }
            }
        }

        private void createTextField()
        {
            textField = new TextField(getString());
            textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
            textField.focusedProperty().addListener(new ChangeListener<Boolean>()
            {
                @Override
                public void changed(ObservableValue<? extends Boolean> arg0,
                    Boolean arg1, Boolean arg2)
                {
                    if (!arg2)
                    {
                        commitEdit(textField.getText());
                    }
                }
            });
        }

        private String getString()
        {
            return getItem() == null ? "" : getItem().toString();
        }
    }
}

I want resize the table and fit the main stage when I resize the window. How I can do this?
P.S I tested to add table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); but nothing is changed.

A: use vbox as root for scene and set vgrow constraint for table to always.
Sample Code :
Scene scene = new Scene(vbox);
vbox.setVgrow(table, Priority.ALWAYS);

A: If you are using Scenebuilder, then you can easily anchor the anchorpane (where your tableview is residing) to the sides. Or you can set it programatically in the controller.
Select the sides whichever direction you want the table to grow.
AnchorPane.setTopAnchor(<anchorpane>,0.0);
AnchorPane.setBottomAnchor(<anchorpane>,0.0);
AnchorPane.setLeftAnchor(<anchorpane>,0.0);
AnchorPane.setRightAnchor(<anchorpane>,0.0);

ColumnResizePolicy will only resize the tablecolumn according to your tableview size.


text:
Q: C++ exceptions catch clause
Possible Duplicate:
Scope of exception object in C++

I have the following catch clauses:
catch(Widget w);
catch(Widget& w);

void passAndThrowWidget() {
          Widget localWidget;
      throw localWidget;
}

If we catch Widget object by value, compiler will make copy so when we throw exception, localWidget goes out of scope, and we don't see any issues.
If we catch widget object byreference, according to reference concept, "w" points to same local Widget instead of copy. But i have seen most of the exceptions are caught by references in C++. My question how this works as "localWidget" goes out of scope when exception is thrown and catch by referense points to object which is destroyed.
Thanks!

A: throw expr; is similar to return expr; in that it uses copy initialization (list initialization is also possible with C++0x). But that's (mostly) syntax.
When it comes to semantics, then just as returning a value from a function returning a non-reference type is fine, so is throwing:
T f()
{
    // t is local but this is clearly fine
    T t;
    return t;

    // and so is this
    throw t;
}

Additionally it is unspecified whether what is returned or thrown is the result of the expression of the return or throw statement, or a copy (or move) from that expression.
The usual motivation for catching by reference has nothing to do with lifetime -- the lifetime of the thrown object is guaranteed to last at least as long as the catch clause. It is preferred because it allows exceptions to be designed and used polymorphically.

A: The C++ runtime uses a memory location independent of the stack to store exception objects:

2.4.2 Allocating the Exception Object
Storage is needed for exceptions being
thrown. This storage must persist
while stack is being unwound, since it
will be used by the handler, and must
be thread-safe. Exception object
storage will therefore normally be
allocated in the heap, although
implementations may provide an
emergency buffer to support throwing
bad_alloc exceptions under low memory
conditions (see Section 3.3.1).

(from the C++ ABI for Itanium: Exception Handling)
So the reference you get when you "catch by reference" is a reference to that memory location, instead of a reference to a deallocated stack frame. This means exception objects are guaranteed to live long enough to be used by your exception handlers, even when obtained by reference. (They will probably be deallocated once you get out of the catch scope, though, so don't hold on to exception references.)

A: Exceptions are the, well, exception to the rule of local scope:
try
{
    Widget w;
    throw w;
}
catch (const Widget& exc)
{
    // exc is a valid reference to the Widget
}

Even though local scope has ended, exceptions are handled in a special way, so what's thrown is still accessible.

A: In this line, you're creating a copy of your local object,
throw localWidget;

So, It doesn't refer to your local "localWidget" object but a copy of that object (called exception object) which is guaranteed to live until the exception is completely handled by the catch clause.

A: the instance that is thrown is copied when it is thrown.  So you'll always get a copy anyhow.
it's better to catch by reference because the object that was thrown may have been polymorphic and you don't want to be relying on an 'error code' produced by a copy of a polymorphic class.  The 'error code' wouldn't be specific to the derived class thrown at the throw point.


text:
Q: How to delete a record from HTML table? I have this codes so far:
This form is generated during a query loop
 while ($row = mysql_fetch_assoc($result)) {
  echo "
";
  echo "" . $row['name'] . "	";
  echo "" . $row['age'] . "	";
  echo "" . $row['breed'] . "	";
  if($row['neuteredOspayed']=="1"){
  echo "" . "neutered" . "	";
  }else
  echo "" . "spayed". "	";
  echo "" . $row['priceFee'] . "	";
  if($row['housebroken']=="1"){
  echo "" . "yes" . "	";
  }else
  echo "" . "no". "	";
  if($row['goodwithdogs']=="1"){
  echo "" . "yes" . "	";
  }else
  echo "" . "no". "	";
  if($row['goodwithcats']=="1"){
  echo "" . "yes" . "	";
  }else
  echo "" . "no". "	";
  echo "" . $row['status'] . "	";
  echo "
";
  }
echo "
";

Now, is there a way to put a link saying "delete" next to every result? For example next to the status field?
Here is what it's looking like:
To get this deleted I guess that I need to spot the record somehow. What I need is to take the name of the animal. For example, how can I get the value "Sparky" from the table and assign it to a variable? If I have the name I would be able to make the checks and run a query witch will delete the record.

A: You will have to use Javascript and AJAX.
Basically, you'll want to put a button in a cell, one per row, and when it's clicked, pass the id of the record to be deleted back to a PHP script via AJAX, then remove the record from the database. It should also hide the row when it is clicked.
I'd recommend using jQuery's .ajax(), as raw XHR is painful at best.
There is no way to do this with just PHP, because HTTP is stateless. Once your web page is loaded, the HTML and PHP parts are done, and fixed. You'll HAVE to use Javascript to make consecutive requests.
Alternatively, as bcmcfc points out, you can also just have a hyperlink to a script that will delete a record from your database.

A: You'd need something like this in your while loop:
echo 'Delete	';

Using the table's primary key would be better than the name though - is the name unique in the db? Assuming there is a PK and it's called id:
echo 'Delete	';

A: Php just is for page generation, once you have generated that table you cannot modify it.
You could, however, make a new get request, specifying a parameter  with the row name to delete, you have to change your server php code to take in account this parameter, though.
The best, according to me, is using javascript: you assign a td id to each row and then you write a simple function in which you delete that row.

A: You have to submit the form and do this action....
<input type="submit" name="submit" value="Delete" />

After submit the form will redirected to some page. In that page you got all the posted values. In that you can delete the record by using the record id otherwise you use the name for  appropriate record.
$query = "DELETE FROM table_name WHERE name='$_POST['name']'";

                         (or)

$query = "DELETE FROM table_name WHERE id='$_POST['id']'";

After this execution you have to redirect the URL to that page.
                          (or)

Delete

In this file you have to written like this...
$id = $_REQUEST['id'];
$query = "DELETE FROM table_name WHERE id='$id'";

A: //Add this form before the end of the while loop

    <form action="#" method="post">
    <input type="hidden" name="name" value="<?php echo $row['name']?>">
    <input type="submit" name="delete" value="delete">
    </form>

//Add this at the end of the coding

<?php

    if(isset($_POST['delete']))
    {
    //database connection
    $sql="DELETE FROM `table_name` WHERE `name`='{$_POST['name']}'";
    $queryEXE=mysql_query($sql);
    }

?>

A: You add a "elemID" attribute to each of your
s and a new class that would be individual for each row (for example, elem+the id):

...

Then, for the Delete link, you use AJAX to call the page that deletes the row from your DB, passing the elemID as an argument to this function:
function deleteRow(thisElemID) {
 $.ajax({
  url: yourURL,
  data: {'elemID', thisElemID },
  success: function() {
       $('.elem'+thisElemID).remove();
  }
 });
}

More on $.ajax here.

A: Create another cell in your table and call ajax onclik of that button. Inside your ajax call delete the pecific row

A: Use a 'delete' form for each row.
The best way would be to add, for each row, a form with a submit button. Each form has a hidden field containing the id (or name, if you must) of the record to delete. Set the method of the form to 'post'.
Reasons why:

*

*A delete link (a href) can be indexed and bookmarked easily. You
don't want pets to be deleted everytime Google drops by or a user is
browsing through their history.

*A method='get' form also can cause
the url to be bookmarked and/or show up in the history. The method
with a form will work without Javascript altogether.

Apart from that,

*

*Any solution (both forms and links) can easily be 'upgraded' to a solution with Ajax for a better user experience, but that's always an extra and no core functionality.

*If you like, you can style the submit button to look like a link.

*Use the post-redirect-get pattern if you implement this solution.

That is, assuming you want to actually remove the record from the database. If you just want to alter the HTML, a Javascript soliution would make more sense.


text:
Q: How does default redirect URL work in Spring Security 5? I have gone through below posts. Still I am unable to understand redirection URI concept.
https://www.baeldung.com/spring-webclient-oauth2
https://docs.spring.io/spring-security/site/docs/5.0.7.RELEASE/reference/html/oauth2login-advanced.html#oauth2login-advanced-redirection-endpoint
https://docs.spring.io/spring-security/site/docs/5.2.x/reference/html/oauth2.html#oauth2login-sample-redirect-uri
In identity server , we get our client application registered and for code grant type, we tell that this would be our redirect URL i.e. https://someserver:port/
However, spring and other post suggests that to set redirect URI as {baseUrl}/login/oauth2/code/{registrationId}.
I am confused if i have set redirect URI as https://someserver:port/ in identity server , how {baseUrl}/login/oauth2/code/{registrationId} i.e. https://someserver:port/login/oauth2/code/{registrationId} will work.
Should it not give invalid redirect URI?

A: The "redirectUrl" parameter is to protect the exchange of an authorization code with an access token so that it's performed by a service available at one of the URLs approved for redirect.
If you use https://someserver:port/*, then it will match all endpoints on that server. When relying on the default Spring Security endpoint {baseUrl}/login/oauth2/code/{registrationId}, it's better to be specific in the redirect URL configuration and use https://someserver:port/login/oauth2/code/{registrationId} as the value. Both options work correctly, but the latter is more secure.


text: Q: How and when does caret create the final model? If I create a model in caret with R with tuning parameters and k-fold cross validation, when is the final model created? Does caret determine the best set of tuning parameters first and then create the final model on the full dataset?


text:
Q: integrate timepicker with cordova local notifications I have the cordova local notifications plugin installed and working. What I need is to create a timepicker that will allow a user to select a time that they want to set the notification for (ie a reminder). Is there a way to create a timepicker that will allow me to pass values to the cordova local notfications .schedule({})?
I am not providing code as all my code is working, but can't find a way to implement the timepicker.
Many thanks.

A: You may want to use existing solutions to embed a timepicker, for example this one https://github.com/rajeshwarpatlolla/ionic-timepicker


text:
Q: How can I log all imports that are executed in a block of code? I'm writing a test suite, and the code I'm testing makes excessive use of delayed module imports.  So it's possible that with 5 different inputs to the same method, this may end up importing 5 additional modules.  What I'd like to be able to do is set up tests so that I can assert that running the method with one input causes one import, and doesn't cause the other 4.
I had a few ideas of how to start on this, but none so far have been successful.  I already have a custom importer, and I can put the logging code in the importer.  But this doesn't work, because the import statements only run once.  I need the log statement to be executed regardless of if the module has been previously imported.  Just running del sys.modules['modname'] also doesn't work, because that runs in the test code, and I can't reload the module in the code being tested.
The next thing I tried was subclassing dict to do the monitoring, and replace sys.modules with this subclass.  This subclass has a reimplemented __getitem__ method, but calling import module doesn't seem to trigger the __getitem__ call in the subclass.  I also can't assign directly to sys.modules.__getitem__, because it is read-only.
Is what I'm trying to do even possible?
UPDATE
nneonneo's answer seems to only work if the implementation of logImports() is in the same module as where it is used.  If I make a base test class containing this functionality, it has problems.  The first is that it can't find just __import__, erroring with:
#     old_import = __import__
# UnboundLocalError: local variable '__import__' referenced before assignment

When I change that to __builtin__.__import__, I another error:
myunittest.py:
import unittest
class TestCase(unittest.TestCase):
    def logImports(self):
        old_import = __builtins__.__import__
        def __import__(*args, **kwargs):
            print args, kwargs
            return old_import(*args, **kwargs)

        __builtins__.__import__ = __import__

test.py:
import myunittest
import unittest
class RealTest(myunittest.TestCase):
    def setUp(self):
        self.logImports()
    def testSomething(self):
        import unittest
        self.assertTrue(True)
unittest.main()

#     old_import = __builtins__.__import__
# AttributeError: 'dict' object has no attribute '__import__'

A: Try
old_import = __import__
def __import__(*args, **kwargs):
    print args, kwargs
    return old_import(*args, **kwargs)

__builtins__.__import__ = __import__

This overrides __import__ completely, allowing you to monitor every invocation of import.

A: Building on the previous answer, in Python 3, I've had success with the following.
import builtins
old_import = __import__

def importWithLog(*args, **kwargs):
    print(args[0]) # This is the module name
    print(args, kwargs)
    return old_import(*args, **kwargs)

builtins.__import__ = importWithLog

# Rest of the code goes here.
import time
import myModule
...