text:
Q: What are JDBC-mysql Driver settings for sane handling of DATETIME and TIMESTAMP in UTC? Having been burned by mysql timezone and Daylight Savings "hour from hell" issues in the past, I decided my next application would store everything in UTC timezone and only interact with the database using UTC times (not even the closely-related GMT).
I soon ran into some mysterious bugs. After pulling my hair out for a while, I came up with this test code:
try(Connection conn = dao.getDataSource().getConnection();
    Statement stmt = conn.createStatement()) {

    Instant now = Instant.now();

    stmt.execute("set time_zone = '+00:00'");

    stmt.execute("create temporary table some_times("
            + " dt datetime,"
            + " ts timestamp,"
            + " dt_string datetime,"
            + " ts_string timestamp,"
            + " dt_epoch datetime,"
            + " ts_epoch timestamp,"
            + " dt_auto datetime default current_timestamp(),"
            + " ts_auto timestamp default current_timestamp(),"
            + " dtc char(19) generated always as (cast(dt as character)),"
            + " tsc char(19) generated always as (cast(ts as character)),"
            + " dt_autoc char(19) generated always as (cast(dt_auto as character)),"
            + " ts_autoc char(19) generated always as (cast(ts_auto as character))"
            + ")");

    PreparedStatement ps = conn.prepareStatement("insert into some_times "
            + "(dt, ts, dt_string, ts_string, dt_epoch, ts_epoch) values (?,?,?,?,from_unixtime(?),from_unixtime(?))");

    DateTimeFormatter dbFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("UTC"));

    ps.setTimestamp(1, new Timestamp(now.toEpochMilli()));
    ps.setTimestamp(2, new Timestamp(now.toEpochMilli()));
    ps.setString(3, dbFormat.format(now));
    ps.setString(4, dbFormat.format(now));
    ps.setLong(5, now.getEpochSecond());
    ps.setLong(6,  now.getEpochSecond());
    ps.executeUpdate();

    ResultSet rs = stmt.executeQuery("select * from some_times");
    ResultSetMetaData md = rs.getMetaData();

    while(rs.next()) {
        for(int c=1; c <= md.getColumnCount(); ++c) {
            Instant inst1 = Instant.ofEpochMilli(rs.getTimestamp(c).getTime());
            Instant inst2 = Instant.from(dbFormat.parse(rs.getString(c).replaceAll("\\.0$", "")));
            System.out.println(inst1.getEpochSecond() - now.getEpochSecond());
            System.out.println(inst2.getEpochSecond() - now.getEpochSecond());
        }
    }
}

Note how the session timezone is set to UTC, and everything in the Java code is very timezone-aware and forced to UTC. The only thing in this entire environment which is not UTC is the JVM's default timezone.
I expected the output to be a bunch of 0s but instead I get this
0
-28800
0
-28800
28800
0
28800
0
28800
0
28800
0
28800
0
28800
0
0
-28800
0
-28800
28800
0
28800
0

Each line of output is just subtracting the time stored from the time retrieved. The result in each row should be 0.
It seems the JDBC driver is performing inappropriate timezone conversions. For an application which interacts fully in UTC although it runs on a VM that's not in UTC, is there any way to completely disable the TZ conversions?
i.e. Can this test be made to output all-zero rows?
UPDATE
Using useLegacyDatetimeCode=false (cacheDefaultTimezone=false makes no difference) changes the output but still not a fix:
0
-28800
0
-28800
0
-28800
0
-28800
0
-28800
0
-28800
0
-28800
0
-28800
0
0
0
0
0
0
0
0

UPDATE2
Checking the console (after changing the test to create a permanent table), I see all the values are STORED correctly:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 27148
Server version: 5.7.12-log MySQL Community Server (GPL)

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> set time_zone = '-00:00';
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT * FROM some_times \G
*************************** 1. row ***************************
       dt: 2016-11-18 15:39:51
       ts: 2016-11-18 15:39:51
dt_string: 2016-11-18 15:39:51
ts_string: 2016-11-18 15:39:51
 dt_epoch: 2016-11-18 15:39:51
 ts_epoch: 2016-11-18 15:39:51
  dt_auto: 2016-11-18 15:39:51
  ts_auto: 2016-11-18 15:39:51
      dtc: 2016-11-18 15:39:51
      tsc: 2016-11-18 15:39:51
 dt_autoc: 2016-11-18 15:39:51
 ts_autoc: 2016-11-18 15:39:51
1 row in set (0.00 sec)

mysql>

A: The solution is to set JDBC connection parameter noDatetimeStringSync=true with useLegacyDatetimeCode=false. As a bonus I also found sessionVariables=time_zone='-00:00' alleviates the need to set time_zone explicitly on every new connection.
There is some "intelligent" timezone conversion code that gets activated deep inside the ResultSet.getString() method when it detects that the column is a TIMESTAMP column.
Alas, this intelligent code has a bug: TimeUtil.fastTimestampCreate(TimeZone tz, int year, int month, int day, int hour, int minute, int seconds, int secondsPart) returns a Timestamp wrongly tagged to the JVM's default timezone, even when the tz parameter is set to something else:
final static Timestamp fastTimestampCreate(TimeZone tz, int year, int month, int day, int hour, int minute, int seconds, int secondsPart) {
    Calendar cal = (tz == null) ? new GregorianCalendar() : new GregorianCalendar(tz);
    cal.clear();

    // why-oh-why is this different than java.util.date, in the year part, but it still keeps the silly '0' for the start month????
    cal.set(year, month - 1, day, hour, minute, seconds);

    long tsAsMillis = cal.getTimeInMillis();

    Timestamp ts = new Timestamp(tsAsMillis);
    ts.setNanos(secondsPart);

    return ts;
}

The return ts would be perfectly valid except when further up in the call chain, it is converted back to a string using the bare toString() method, which renders the ts as a String representing what a clock would display in the JVM-default timezone, instead of a String representation of the time in UTC. In ResultSetImpl.getStringInternal(int columnIndex, boolean checkDateTypes):
                case Types.TIMESTAMP:
                    Timestamp ts = getTimestampFromString(columnIndex, null, stringVal, this.getDefaultTimeZone(), false);

                    if (ts == null) {
                        this.wasNullFlag = true;

                        return null;
                    }

                    this.wasNullFlag = false;

                    return ts.toString();

Setting noDatetimeStringSync=true disables the entire parse/unparse mess and just returns the string value as-is received from the database.
Test output:
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

The useLegacyDatetimeCode=false is still important because it changes the behaviour of getDefaultTimeZone() to use the database server's TZ.
While chasing this down I also found the documentation for  useJDBCCompliantTimezoneShift is incorrect, although it makes no difference: documentation says [This is part of the legacy date-time code, thus the property has an effect only when "useLegacyDatetimeCode=true."], but that's wrong, see ResultSetImpl.getNativeTimestampViaParseConversion(int, Calendar, TimeZone, boolean).


text:
Q: Overwrite data and setData in Qt's QFileSystemModel What I'am trying to do:
Overwrite QFileSystemModel's setData and data to implement Caching of pictures in the shown directory.
I use a QListView for testing purpose.
Here is the relevant code:
My Class with QFileSystemModel as parent:
.h-file:
#ifndef QPICSINFILESYSTEMMODEL_H
#define QPICSINFILESYSTEMMODEL_H

#include <QFileSystemModel>
#include <QCache>
#include <QDebug>

/* This Model holds all Picturefiles with a cached QPixmap of
 * them.
 */

class PicsInFileSystemModel : public QFileSystemModel
{
public:
    PicsInFileSystemModel();
    QVariant data (const QModelIndex & index, int role);
private:
    QCache<qint64,QPixmap> *cache; //Cache for the pictures

};

#endif // QPICSINFILESYSTEMMODEL_

.cpp-file:
#include "PicsInFileSystemModel.h"

PicsInFileSystemModel::PicsInFileSystemModel()
{
    QStringList myFilter;
    this->setFilter(QDir::Files | QDir::AllDirs);
    this->setRootPath(QDir::rootPath());//QDir::homePath());
    myFilter << "jpeg" << "jpg" << "png";
    //this->setNameFilters(myFilter);
}

/* Reimplement data to send the pictures to the cache */
QVariant PicsInFileSystemModel::data ( const QModelIndex & index, int role = Qt::DisplayRole ) {
    qDebug() << "index: " << index << "role: " << role;

    return ((QFileSystemModel)this).data(index,role);
}

How I call the object:
pics = new PicsInFileSystemModel;
form->listViewPictures->setModel(pics);
form->listViewPictures->setRootIndex(pics->index(
        "mypath"));

So here is the question: In my opinion I should see many debug outputs when the View access the Model. But there is nothing. Has anyone an idea what I'am doing wrong?
Thanks!
EDIT:
The answers work. I also had to change this
return ((QFileSystemModel)this).data(index,role);

into
QFileSystemModel::data(index,role))

A: Signature of the data method is:
QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const

Your method is non-const. Make your method const and mark the variables you need to modify as mutable.

A: Your data function is never called because it doesn't match the original definition. You are not reimplementing data, you provided a non-const version.

A: Use QFileIconProvider for that purpose.
ThumbnailIconProvider.h
#ifndef THUMBNAILICONPROVIDER_H
#define THUMBNAILICONPROVIDER_H

#include <QFileIconProvider>

class ThumbnailIconProvider : public QFileIconProvider
{
public:
    ThumbnailIconProvider();

    QIcon icon(const QFileInfo & info) const;
};

#endif // THUMBNAILICONPROVIDER_H

ThumbnailIconProvider.cpp
#include "thumbnailiconprovider.h"

#include <QDebug>

ThumbnailIconProvider::ThumbnailIconProvider()
{
}

QIcon ThumbnailIconProvider::icon(const QFileInfo & info) const
{
    QIcon ico(info.absoluteFilePath());
    if (ico.isNull())
        return QFileIconProvider::icon(info);
    else {
        qDebug() << "Fetch icon for " << info.absoluteFilePath();
        return ico;
    }
}

To use this class call setIconProvider on your model.
QFileSystemModel * model = new QFileSystemModel(this);
model->setIconProvider(new ThumbnailIconProvider());
model->setRootPath(...);
...

Note that you can easily embed cacheing this way.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Replacing the Java cacerts folder with a new one I have a long time working with a Java Web App in eclipse and i never make change in the java cacerts directory.
C:\Java\jdk1.7.0_51\jre\lib\security
and
C:\Java\jre1.8.0_40\lib\security

But now, i have to work with new web app in eclipse and they giving to me a cacerts file, i have to replace the old one.
So, i wanna know if this action can generate a conflict me as I continue to work with both applications.


text:
Q: Can I use "respectively" when two lists are in the different sentences? I paid one dollar for candy, and I paid two dollars for chocolate.
Can I say like this?
"I paid one dollar(1) and two dollars(2). I bought candy(1) and chocolate(2) respectively."

A: You can, but why would you?  It is just about the most confusing way you express yourself.
So don't do that.
Instead how about:

I paid one dollar for candy, and I paid two dollars for chocolate.

A: The two short statements can/should be joined:

I bought a family pack of candy and chocolate. I paid only two dollars and one dollar respectively.
I bought [a family pack of] candy and chocolate for [only] one dollar and two dollars respectively.

I paid $1 and $2 for [a family pack of] candy and chocolate respectively.

A: The two sentences are clearly and directly related to each other, so yes, you can.
In non-written contexts, you can also refer to an ordered list by gesturing at a set of things, so it can be entirely non-verbal.  The only requirement is that the listener or reader must be able to determine what ordered list you are referring to with the "respectively".


text:
Q: how to bind datatable data in grid using angular this is the datatable for html:
when i debug the typescriptcode works fine no error and it stops at the binding data in gridview .in localhost there is no data in grid
in debug mode extensions:::runtime file shows some error in custom runtime binding
// Custom binding for the runtime API.
var binding = apiBridge || require('binding').Binding.create('runtime');//.Binding.create('runtime');here shows error
in extensions:::webstore
// Custom binding for the webstore API.
var webstoreNatives = requireNative('webstore');//requireNative('webstore') -this shows error

                                <sa-datatable [options]="{
                            data: broacasterall,
                 columns: [
                 {data:'id'},
                 {data:'broadcaster_name'},
                 {data:'broadcaster_channel_name'},

                 ],
                 buttons: [
                 'colvis'
                 ]
                 }" tableClass="table table-striped table-bordered table-hover" >

                                            Id
                                            Broadcaster Name
                                            Channel Name

                                </sa-datatable>

this is my typescript code for grid:
in this broadcaster response am getting fully binding data with respective columns when run the localhost it shows only grid with columns only not data
ngOnInit() {

        this.client_id = this.user.client_id;
        this.getBroadcasterAllGrid();
    }

  getBroadcasterAllGrid()
    {
        this.broadcasterService.getAllBroadcasters()
      .subscribe(
       (broadcasterResponse)=>{

            this.broacasterall=broadcasterResponse;

       }),
      error => this.errorMessage = <any>error;
    };


text:
Q: Postfix ignore relayhost for specific source servers (localhost) Postfix is setup for
relayhost = spamfilter.example.com:25

I have a few php scripts running on the same server as postfix that send emails via the mail command (sendmail) to various email addresses (example@gmail.com). Is it possible to ignore the relayhost for mail originating from 127.0.0.1? I'd like the server to attempt delivery directly instead of relaying to our spam filter (spamfilter.example.com)

A: It's possible to change the transport (sender_dependent_default_transport_maps) or relayhost (sender_dependent_relayhost_maps) used depending on sender envelope address. If the PHP scripts are run as different users than mail users, this is a very suitable solution.
In your PHP script you can even set envelope sender and From: address separate using 5th optional parameter to give envelope sender directly to Sendmail:
mail($to, $subject, $message, $headers,'-f envelope@example.com');


text:
Q: Difficult Recurrence Problem Find all integers $n\geq 3$ for which there exist real numbers $a_{1}, a_{2},...,a_{n+2}$ satisfying $a_{n+1}=a_{1}$ , $a_{n+2}=a_{2}$ and:
$a_{i}a_{i+1}+1=a_{i+2}$
for $i=1,2,..,n$

A: Hint.
Solving backwards we have for
$$
\begin{cases}
n=2\to \{2,-1,-1,2\}\\
n=5\to \{2,-1,-1,2,\frac 12,-1,2\}\\
n=8\to \{2,-1,-1,2,\frac 12,-1,2,\frac 12,-1,2\}\\
\vdots\\
n=2+3k\to \{2,-1,\underbrace{-1,2,\frac 12}_{k},-1,2\}
\end{cases}
$$
NOTE
The real solutions arise from
$$
\left\{
\begin{array}{rcl}
 a_1&=&\frac{a_2-1}{a_1} \\
 a_2&=&1-\frac{a_1}{a_2-1} \\
\end{array}
\right.
$$
the other possibilities
$$
\left\{
\begin{array}{c}
 a_1=1-\frac{a_1}{a_2-1} \\
 a_2=\frac{a_1}{a_1-a_2+1} \\
\end{array}
\right.
\ \ \text{and}\ \ \left\{
\begin{array}{c}
 a_1=\frac{a_1}{a_1-a_2+1} \\
 a_2=\frac{a_2-1}{a_1} \\
\end{array}
\right.
$$
have no real solutions.


text:
Q: Python code to create mirror of an image and blend it with certain amount of white color. I'm a very newbie to Python and i'm trying to learn manipulating pictures with Python. This piece of code below is to create a mirror image of a picture and then fade it to white. But i got bellow error when i execute the code "The error was: 'int' and 'function'
Inappropriate argument type.
An attempt was made to call a function with a parameter of an invalid type. This means that you did something such as trying to pass a string to a method that is expecting an integer." I'm not sure what causes this error and i need help with this.
def blendWhite(pixcel, fadeAmount):
    newRed = 255 * fadeAmount + getRed(pixel) * (1 - fadeAmount)
    newGreen = 255 * fadeAmount + getGreen(pixel) * (1 - fadeAmount)
    newBlue = 255 * fadeAmount + getBlue(pixel) * (1 - fadeAmount)
    setColor(pixel, makeColor(newRed, newGreen, newBlue))

def copyAndMirrorCat():
    catFile = getMediaPath("caterpillarSmall.jpg")
    catPict = makePicture(catFile)
    width = getWidth(catPict)
    height = getHeight(catPict)
    canvas = makeEmptyPicture(width, height * 2)
    # Now, do the actual copying
    for x in range(0, width):
        for y in range(0, height):
            color = getColor(getPixel(catPict, x, y))
            setColor(getPixel(canvas, x, y), color)
            h = height * 2
            fadeAmount(y, h)
            blendWhite(getPixel(canvas, x, (height * 2) - y - 1), fadeAmount)
    show(catPict)
    show(canvas)
    return canvas

def fadeAmount(y, h):
    fm = (h - y) / float(h) + 0.15
    if fm > 1:
        fm = 1
    return fm

This is how result looks like: http://imageshack.us/a/img442/326/mirrorlinearwithwhite.jpg

A: If you look at the lines where you say:
fadeAmount(y,h)
blendWhite(getPixel(canvas,x,(height*2)-y-1),fadeAmount)

You'll see that you call fadeAmount() without storing the value in a variable.  You then try to pass the function to blendWhite().  This just won't work.  You need to either store the value and pass it, like :
fa = fadeAmount(y,h)
blendWhite(getPixel(canvas,x,(height*2)-y-1),fa)

...or just make it all one statement:
blendWhite(getPixel(canvas,x,(height*2)-y-1),fadeAmount(y,h))


text:
Q: Unable to delete a row from a table due to a dependency/reference in another table I have a stored procedure that deletes a record from a table where one of the columns matches a specified value:
ALTER PROCEDURE [dbo].[Sp_DelBranch] @datafield varchar(50)
AS
BEGIN
    DELETE FROM Branch WHERE branchname = @datafield
END

Unfortunately I get the following error on execution:

The DELETE statement conflicted with the REFERENCE constraint "fk_BranchIdDept". The       conflict occurred in database "MproWorkSpace", table "dbo.Department", column 'BranchId'.

Can anyone explain why I'm seeing this error?

A:
conflicted with the REFERENCE constraint "fk_BranchIdDept".

This means, that the value you are trying to delete, is primary key in some other table and is referenced in this table as foreign key,i.e., a primary-foreign key relation is mapped through constraint fk_BranchIdDept ...So unless you delete the referred primary key, foreign key can not be removed from table.
Otherwise, this will lead to data inconsistency!
Look for Cascade Delete to help you in this!
SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

A: The error means that there are some rows in Department table referencing the branch you're trying to delete.
You should either delete the corresponding rows from the Department table first, or change values in BranchId column for these rows, so they point to some other branch.

A:
The DELETE statement conflicted with the REFERENCE constraint "fk_BranchIdDept".

The record you're trying to delete is referenced in other tables; deleting the Branch record would leave the other tables orphaned, and referencing something that no longer exists.
There are two approaches to this:

*

*Delete all records in referenced tables before deleting from the Branch table

*Perform a cascade delete (deleting from the Branch table triggers a delete in every referenced table)


text:
Q: How to share a URL to linkedIn via iOS app In a iOS app I need to share url to LinkedIn via iOS app and LinkedIn native app is not installed in the device.I need to share url without th LinkedIn app installed
Please guide me how cabn I do the same

A: the different options are detailed under:
https://developer.linkedin.com/docs/share-on-linkedin
via opening SAFARI
just call a customized URL with openURL:.
the format of the url is described by the linkedIn Developer Docs:
example:
https://www.linkedin.com/shareArticle?mini=true&url=http://developer.linkedin.com&title=LinkedIn%20Developer%20Network&summary=My%20favorite%20developer%20program&source=LinkedIn

via REST API
e.g. call via NSURLSession
https://api.linkedin.com/v1/people/~/shares?format=json

and pass JSON body
e.g.
{
  "comment": "Check out developer.linkedin.com! http://linkd.in/1FC2PyG",
  "visibility": {
    "code": "anyone"
  }
}

Note that with the REST API, you need to register your app with linkedin (all described in the docs)


text:
Q: How to automatically merge two Excel Worksheets with the Same First Column? Before anyone states that this problem has already been answered before, I am looking for a automatic (macro, program, etc) system that can achieve the following:

*

*Merge multiple workbooks (separate files, not sheets) by a common column.

The first column is the same for all the files. However, there are 500 individual csv files, each with about 7000 rows
I am aware of the VLOOKUP() function, the Consolidate function, and programs like Kutools and Ablebits. However, none of these seem to suit my purpose of creating a single workbook with all of these files combined by the common column.
Does anyone know of a VBA macro or other program that can assist me with this?
EDIT: Below are links to two of the 500 files:
1.https://docs.google.com/spreadsheets/d/1rRdNS9K6QYjfH2_P9wmR5YS0-Ectl1SnVn2SfFz9UUY/edit?usp=sharing
2.https://docs.google.com/spreadsheets/d/13Dmc6hKHCG4RBF2an3NZ7nux5ffI5F5cigbz5fFyaPI/edit?usp=sharing

A: On a Linux shell, combine paste and awk.
paste -d , *.csv | awk -F , '{for (i=3;i<=NF;i+=2) $i=""} {print}'
The paste command puts all columns of all files next to each other. The awk script deletes all odd columns, starting with the third one.


text:
Q: Decimal expansions of $0.999\cdot\cdot$ and $1.000\cdot \cdot$ (infinite digits) I am reading a passage from the book Foundation of Mathematics by Ian Stewart, and I need some help to make sure I understand it properly.
A real number can be expresed by the following unique decimal expansion:
$a_0.a_1a_2\cdot \cdot \cdot a_n \le x \lt a_0.a_1a_2\cdot \cdot \cdot a_n + \frac{1}{10^n}$  [formula 1]
Apparently this approach does not allow for the expansion of $0.9999 \cdot \cdot \cdot\cdot $ i.e. infinite $9$s.
That is because if we try to express it like that we have ($0.999999..9$ means $n$ $9s$):
$0.999999..9 \le  0.9999 \cdot \cdot \cdot\cdot  \lt 0.999999..9 + \frac{1}{10^n} \implies 0 \lt 1 - 0.9999 \cdot \cdot \cdot\cdot \le \frac{1}{10^n}$ for all $n \in N$
This last condition is impossible by Archimides' condition: since $1 - 0.9999 \cdot \cdot \cdot\cdot \gt 0$ which means that the $2$ numbers are different then it means there must exist $n$ with $\frac{1}{10^n} \lt 1 - 0.9999 \cdot \cdot \cdot\cdot$.
But according to the inequality we have $ 1 - 0.9999 \cdot \cdot \cdot\cdot \le \frac{1}{10^n}$
Is my explanation so far correct? The book just mentions it is impossible but I want to make sure my understanding of why it is impossible is correct.
Now an alternative way that could allow to express $0.9999 \cdot \cdot \cdot\cdot$ would be to change the equality signs i.e.:
$a_0.a_1a_2\cdot \cdot \cdot a_n \lt x \le a_0.a_1a_2\cdot \cdot \cdot a_n + \frac{1}{10^n}$   [formula 2]
This would lead to:
$0 \le 1 - 0.9999 \cdot \cdot \cdot\cdot \lt \frac{1}{10^n}$
Now since $0 \le 1 - 0.9999 \cdot \cdot \cdot\cdot$ we have $2$ cases:
Case $1$: $0 \lt 1 - 0.9999\cdot \cdot \cdot\cdot$ which is the same case mentioned earlier which leads to impossibility
Case $2$: $0 = 1 - 0.9999\cdot \cdot \cdot\cdot$ which means that $1$ and $0.999\cdot \cdot \cdot\cdot$ are the same number.
Hence we are able to express $0.999\cdot \cdot \cdot\cdot$ as a decimal expression of $1$.
Is my understanding so far correct?
Then the text follows saying that the [formula 2] does not allow the expansion of $1.000\cdot\cdot\cdot$ i.e. infinite $0$s
This part I am not sure I get it either.
I suppose the equation becomes (with $n$ digits at left and right side of the inequality) :
$1.0000 \lt 1.000\cdot \cdot \cdot \le 1.0001$
and by doing the same manipulation as earlier we end up with:
$0 \le 1.0001 - 1.000\cdot \cdot \cdot \cdot \cdot\cdot\lt \frac{1}{10^n}$
and by applying the same use case we get that $1.0001$ with the $n$ digits is the same expression as $1.000\cdot \cdot \cdot \cdot$
But somehow I don't think I understand the idea properly.
Could someone please help me?
Update:
I realized that this is has to be wrong:
$1.0000 \lt 1.000\cdot \cdot \cdot \le 1.0001$
Because $1.000\cdot \cdot \cdot$ is actually $1$ hence we can't have $1.0000 \lt 1.000\cdot \cdot \cdot$ and so the formula 2 is invalid.
But formula 1 should hold because $1.0000 \le 1.000\cdot \cdot \cdot \cdot$


text:
Q: Do we know, for sure, if Godzilla is a male? Godzilla is always referred to as male and referenced with "he" or "him."
Do we know, for sure, if Godzilla is a male? Has beast gender ever been a factor within any kaiju movies?

A: In the 1998 Godzilla film (starring Matthew Broderick) it's made abundantly clear that the titular giant monster is in fact a giant lady monster:

NICK : Well, we know he eats fish, he's of reptile genus, he's a burrower, he's amphibious and...
Nick points out the litmus paper. It turns RED.
NICK : *...he's pregnant?*

Elsewhere in the Kaiju category there are a wide range of female monsters but Godzilla always seems to be portrayed (and referred to) as male.

A: Short answer: No, we don't. Mostly because the Godzilla series has no decent continuity.
Long answer:
In the original Japanese versions of the movies Godzilla and other kaiju are mostly referred to by the gender-neutral it. In the English translated versions they refer to Godzilla mostly as he, hence the confusion.
So basically they (the creators/trademark owners) don't really want to put a gender on Godzilla.
He has a son, however, who hatched from an egg. This again enhances the confusion about its gender, especially since it's never cleared up where the egg came from and if Godzillas son is actually his offspring or just another member of his species.
According to my Google-Fu the 1998 Hollywood remake movie is so far the only one to put a gender on Godzilla (asexual reproduction, egg-laying and all that). However, since the creature from that movie is officially no longer recognized as Godzilla, it' doesn't count.
Toho (the company which created Godzilla and made all the movies) apparently didn't like the 1998 depiction of Godzilla very much. Saying among other things, that they took the "God" out of Godzilla. This is why they created a new monster named Zilla for the 2004 movie Godzilla: Final Wars (marking the 50th anniversary of Godzilla) as kind of a mockery of the 1998 American version.
He's one of the monsters Godzilla fights in the movie and is defeated in what is apparently one of the shortest fights in Godzilla history.
In fact, the Hollywood Godzilla from 1998 has officially been renamed Zilla by Toho (check here for sources) and in all newer depictions of the creature (which is apparently still used) it's called Zilla. Only the 1998 movie itself still calls the creature Godzilla.
All the original Godzilla movies give no indication as to its gender. In fact, there are even several origin stories, some of which would allow for the eggs (from which the baby Godzillas hatch) to be artifacts of pre-historic times, just like Godzilla itself.
It should be noted that the Shōwa series movies (from the original movie up to 1975, including Son of Godzilla) featured no real continuity at all but are rather movies based on the successful first movie.
In 1984 Toho began the so called Heisei series with The Return of Godzilla and rebooted the Godzilla universe. Starting with this movie all but the very first Godzilla movie (which is the only one tying all timelines together) never happened. Toho established a continuity between the movies which was later messed up again by introducing time travel.
Baby Godzilla was also reintroduced later in the series, but once again only as an egg that is one day just found. Nothing on what Godzilla's actual relation to the baby is and also no information on the gender.
A common factor in all the different continuities (there is also the Millennium series after 1999 up to the 2004 movie) is, that there is more than one Godzilla. The Godzilla from the original 1954 movie died at the end of the movie (killed by a device which apparently couldn't be reproduced since the plans were destroyed as well) and originally no sequels were planned.
In the second movie it was specifically stated that Godzilla is dead and that this time Japan is under attack from a second Godzilla. In one of the later movies the first Godzilla's bones are even used as the core of Mechagodzilla which then goes on to fight the current Godzilla.
There are also several plot holes in the movies themselves. For example, if there have been at least two Godzillas, why did they end up with the exact same mutation? Or why did Godzilla mutate the exact same way during the time travel plot, when he was not irradiated by a nuclear bomb but by a soviet submarine some time later.
Combined with the general lack of continuity this allows for additional speculation. If there were at least two Godzillas at one point, one of them might have been male and the other female. That Godzilla has a son seems to indicate that there are indeed two genders. So the counter question to the question of Godzilla's gender might be: Which Godzilla?
In summary: A clear answer is never given and that is most likely deliberate. Godzilla is not really supposed to have a fixed background. It changes with the movies and for the movies, reflecting the message the film makers wished to convey. Just like he became a good guy and then turned back to be more of a villain. They wanted him to have a son to make him more family friendly (this was also during a period where Godzilla became friendlier in general, turning more and more into a kind of guardian). So they gave him a son from an egg and to this day nobody bothered to explain exactly the why and how.


text:
Q: Wordpress not logged in locally with correct username and password I'm unable to logged in wordpress in locally with correct username and password. When I enter the username and password and click the login button, it displays same log in page with empty password field. It doesn't display the error message also. please help me to resolve this issue.

A: There are a few things you can try. One of them you have already tried.
Clear your browser cache (which you have stated you have tried), just make sure you cleared everything, cookies and cache.
Try deactivating all plugins by either logging in via SSH or FTP to your server and rename wp-content/plugins to wp-content/plugins_backup.
Change wp theme, it maybe an issue with your current theme. Try changing to one of the defaults like twentyfifteen.
.htaccess could be causing problems so you can once again SSH or FTP to your server and rename .htaccess to htaccess.backup.
Also check your wp-config.php making sure that your site url is defined properly, eg:
define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');


text:
Q: Why is Banshee Miro guide slow? Just updated Banshee to 2.2.1 in Ubuntu 11.10.
Miro guide is still unusable and slow, and freezes.
The play button in the sound indicator menu keeps turning round and round and round!
What's the problem with banshee ?

A: It seems to me like you are getting a bug with Banshee. Delete the ~/.config/banshee or ~/.config/banshee-1 directory, and try starting Banshee again. Don't enable the Miro guide plugin, if it is broken.
I enable the Dbus Mpris interface in Banshee and the issue with the play botton diseapered.
Is it official that miro guide is broken ?


text:
Q: Cannot Replay recorded Coded UI Test action for the button that is the part of the custom control I used VS 2010 Coded UI Test to record Click action to the combobox of Custom Control that consists  of combobox and button and generated a code.
Then I used VS 2010 Coded UI Test to record Click action to the button of Custom Control that consists  of combobox and button and generated code.
When I did Replay of the Click on the combobox it is working fine.
When I did Replay of the Click on the button I got an exception:
Cannot perform 'Click' on the hidden control

Coded UI Test after refresh can find and highlight the button.
It seems UIMap.Designer generates proper declaration of the Control.
Before performing "Click" on the Button I tried SetFocus.
If I get ControlCollection and show message with BoundingRectangle properties of every control in the collection then BoundingRectangle point to the different Control.
How to make recorded "Click" on the Button of the custom control to be re-playable.

A: Sometimes controls are rendered as composites of other controls.
After the recorder finds your button, see if it has child controls (click on the Down arrow, or Alt + Down), . This happened to me several times while testing a Silverlight application, an image or text blocks the actual button.
Hope this helps.

A: Try the below solution once as the bounding rectangle is correct or not:-

*

*Do a ButtonControl.DrawHighlight(). Check if the entire correct button boundary is getting highlighted.

*ButtonControl.BoundingRectangle. Does this return non-zero values ?

*If [2] is true,
Rectangle r = ButtonControl.BoundingRectangle.

ButtonControl.SetFocus()
Mouse.Click(new Point(r.X + r.Width/2, r.Y + r.Height/2));


text:
Q: JavaFX XYChart warnings Lets take this small example, what are those warnings / what am i doing wrong here?
Raw use of parameterized class 'XYChart.Data'
Unchecked assignment: 'javafx.scene.chart.XYChart.Data' to 'javafx.scene.chart.XYChart.Data<java.lang.String,java.lang.Number>'
Unchecked call to 'Data(X, Y)' as a member of raw type 'javafx.scene.chart.XYChart.Data'

This would be the code
private final XYChart.Series<String, Number> courseSeries = new XYChart.Series<>();
private final LinkedList<XYChart.Series<String, Number>> courseSeriesTimespan = new LinkedList<>();
@FXML
public BarChart<String, Number> course;

private void test(){
    courseSeriesTimespan.get(1).getData().add(new XYChart.Data("Jän", 1));
}

A: Use parameterized type
courseSeriesTimespan.get(1).getData().add(new XYChart.Data<String,Number>("Jän", 1));

Update. Or without specifying specific types
courseSeriesTimespan.get(1).getData().add(new XYChart.Data<>("Jän", 1));


text:
Q: ODI master repository dropped By mistake the ODI master repository schema has got dropped and now I dont see any of the work which was done in ODI studio. My work repository is still intact. Is there anyway I can get all my work back by creating the same master repository and link with my work repository. There is 2 months of development work which I don't want to lose just because master repository is removed.

A: If it's a production instance of ODI, I guess the DBA has daily backups of the database and can restore the schema holding your master repository. Or there might be some regular exports of the repository in XML files.
Otherwise, you can try creating a new one and recreate a similar topology and security model. You will need to reattach the work repository to it : https://docs.oracle.com/middleware/1221/odi/administer-develop/admin_reps.htm#ODIAD163
Then go in the model pane of the designer and make sure all the models are linked to a logical schema.


text:
Q: query related has_many model in rails 3 I have two models User And Service. User has_and_belongs_to_many Services same goes for Services:
class User < ActiveRecord::Base
  has_and_belongs_to_many :services
end

class Service < ActiveRecord::Base
  has_and_belongs_to_many :users
end

I need to find all users who provide selected services. Something like:

@users = User.where(:services_ids => [2,3,4])

A: This should work:
User.join(:services).where(:services.id => [2,3,4]).uniq

A: Try this:
@users = Service.where(:id => [2,3,4])).map{|svc| svc.users}.uniq.flatten

or
@users = User.all(:include => :services, :conditions => ["services.id in ?", (2,3,4)])


text:
Q: How to use SVG sprite as CSS pseudo elements? I'm trying to use SVG icons (located in a SVG sprite) as CSS pseudo elements. They're working well in HTML, but when I import them in my CSS nothing is appearing. Where could be the problem?
Working HTML:
<svg width="48px" height="48px">
    <use xlink:href="/assets/images/icons-sprite.svg#icon-name"></use>
</svg>

SVG sprite:
<svg width="0" height="0" class="hidden">
    <symbol xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" id="icon-name">
        <path ... fill="currentColor"></path>
    </symbol>
</svg>

CSS:
.test-icon:before {
    content: "";
    display: inline-block;
    width: 48px;
    height: 48px;
    background-image: url(/assets/images/icons-sprite.svg#icon-name);
}

Thanks for your answers!
EDIT: I made a GitHub repo here, normally it should always be the same icon in red

A: Try this
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='48px' height='48px'%3E%3Cuse xlink:href='/assets/images/icons-sprite.svg%23icon-name'%3E%3C/use%3E%3C/svg%3E");

Follow this link and paste your svg link. You can get your code for background-image property. https://yoksel.github.io/url-encoder/


text:
Q: Dialog and SQL output on Linux Shell Scripting I have the following script:
VAR=$(mysql -u root -e " use <database_name>; select column1,column2,column3 from <table_name>;")

dialog --title "something" --msgbox "$VAR" 50 50

and the output that I got is like this.
this
but i'm expecting the output to be like this instead inside the dialog command
this
I can get this output by not storing the sql commands in a variable.
where am I wrong here?

A: On your VAR=$(mysql ...), you can add --table to get the disired effect.
VAR=$(mysql -u root -t -e ...)


text:
Q: How to read a file from USB Device using Mac OS X? I am very new to Mac OS X development. I am implementing a USB based application. In my application When my USB device is connected to the system I need to read a file from USB and upload it to a web server.
I go through Google and some documents but I didn't get any information on this. Can you guys please suggest a best document or sample code to do this?

A: Probably the best places where to start are
USB Device Interface Guide
Networking & Internet Starting Point
There you can also find links for further information and sample projects


text:
Q: How to find a discrete Morse function on this simplicial complex I have a graph called partition graph. This graph gives rise to a simplicial complex called box complex $B_{edge}$. Since this simplicial complex is too big and studying the topological features of it is too difficult I want to simplify this simplicial complex using a discrete Morse function.
Definition.
Every vertex of a partition graph $\mathcal{P}(3^3)$ is a partition of $\{1,2, ..., 9 \}$ into $3$ cells of size $3$. Two vertices $u$ and $v$ are adjacent if the intersection of each cell of $u$ with each cell of $v$ is nonempty.
This graph is vertex- edge- arc transitive.
Definition. The box complex $B_{edge}(G)$ of a graph $G$ is a simplicial complex which vertices are the directed edges of $G$; that is, ordered pairs $(u,v)$ with $\{u,v\}\in E$. The simplices of this box complex are subsets of edge sets of complete bipartite subgraphs of $G$, where the edges are oriented from the first shore to the second shore.
\begin{align*}
    B_{edge}(G):=&\{ \overrightarrow{F} \subset A'\times A'': \varnothing \neq A',A'' \subset V,\\
    &A'\cap A''=\varnothing, G[A',A'']\ \text{is complete}\}
\end{align*}
I want to find a discrete Morse function on the box complex $B_{edge}(\mathcal{P}(3^3))$. A function with less critical simplicies is better.


text:
Q: SetValue for BindableProperty doesn't trigger PropertyChanged event when set to null in a Xamarin.Forms project i develop, i created a NullableDatePicker which works with a DateTime? value. Until XF 3.3 the DatePicker was able to set the DateTime? property of the ViewModel to null. This no longer works with XF 3.5 Now when my platformrenderer sets the BindableProperty of the XF Control to null, the bound property of the viewmodel isn't updated. Changing the value to a DateTime works.
As searching through the changes between XF 3.3 and the current XF 3.5 didn't brought any breaking changes for the binding to light, i hope someone here on stackoverflow can help. I already searched quite a lot for a possible cause of my problem.
public class ViewModel {
    private DateTime? _date;
    public DateTime? Date{
        get => _date;
        set => SetProperty(ref _date, value);
    }
}

NullableDatePicker : DatePicker {
    public static readonly BindableProperty NullableDateProperty = BindableProperty.Create(nameof(NullableDate), typeof(DateTime?), typeof(NullableDatePicker), null, BindingMode.TwoWay);

public class DateTime? NullableDate
    {
        get { return (DateTime?)GetValue(NullableDateProperty); }
        set { SetValue(NullableDateProperty, value); }
    }
}

public class NullableDatePickerRenderer : DatePickerRenderer
{
    ...
    public void OnClearDateTimeSelection(){
        ((IElementController) Element).SetValueFromRenderer(NullableDatePicker.NullableDateProperty, null);
    ...
    }
}

A: I had the same problem when updating from 3.4.0.1008975 to 3.5.X. I didn't find the reason of that yet, but I also didn't need the update, and that's what I recommend to you.
Version 3.5.X basically add bindable layouts to XF. If you don't need it, I recommend you to downgrade to 3.4.0.1008975 that it'll work.


text:
Q: Backbone 1.1.2: 'undefined is not a function' for behavior that worked in earlier versions I am a novice to Backbone, and I am in the midst of migrating a project written using BB 0.5.3 to 1.1.2. In 1.1.2, I get the following error:
Uncaught TypeError: undefined is not a function
The relevant extracts:
reportGen = {
....
initialize: function() {
    var reports = [
        this.Views.Report1,
        this.Views.Report2,
        this.Views.Report3
    ];
    new this.Views.App({reports: reports});
}
};

and:
reportGen.Views.App = Backbone.View.extend({
....

initialize: function(reportList) {
    _.bindAll(this, 'render', 'switchReports');
    this.reports = reportList['reports'];
    this.render();
},
render: function() {
    var i = 0;
    var reportList = {reports : []};
    _.each(this.reports, function(r) {
        var R = new r;
        reportList.reports.push({name: R.name, label: R.label, index:i});
        R.close();
        i++;
    }, this);

    var out = $.tmpl( this.template(), reportList  );
    $(this.el).append(out);

    // now render the default Report
    var defaultReport = this.reports[0];
    this.currentReport = new defaultReport();
    $("div#report-container").html(this.currentReport.render().el);
    this.afterReportRender();

},
....
});

When I run this in Backbone 0.5.3, or in fact, versions prior to 0.9.10, everything seems all right. I get the interface and behaviors I expect. But in versions 0.9.10 and thereafter, I get the aforementioned error.
I've looked at the contents of the report objects in 0.5.3 and 1.1.2, and I can access the same items (for example, the name of the report). But I do not know what has changed from 0.9.9 to 0.9.10 and beyond to cause the code to fail.
The error occurs on the line:
var R = new r
the same error occurs if I use
var R = new r()
instead.
The changelog for 0.9.10 doesn't have anything that seems to apply to my case.
Any advice?
Update: I am still considerably confused about what's happening. I feel that I must be missing something conceptually. Inspecting the contents of this at each level hasn't led me anywhere.
Update 2: I have created plunk with the error, but the behavior is somewhat different -- this time, the error shows up, but I can see the report names in the drop-down. Still, there is the "undefined is not a function" error in 1.1.2, but not in 0.9.9 and earlier.


text:
Q: No request bound thread error I have two spring boot services.
A and B.
From A service, I am calling B Service(Using Feign Client).
I have one request interceptor which adds custom headers to the request before sending it.
This is my interceptor:
public class HeaderInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        try {
            Object encrypyedData = RequestContextHolder.currentRequestAttributes().getAttribute(""headerName", 0);
            if(encrypyedData != null) {
                template.header("headerName", encrypyedData.toString());
            }else {
                System.out.println("Encrypted Data is NULL");
            }
        } catch(Exception e) {
            System.out.println("ankit === "+e.getMessage());
        }

    }

}

But when I am running this code, I am getting exception : No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
I have also tried adding this in Service A
@Bean public RequestContextListener requestContextListener(){
   return new RequestContextListener();
}

I have added this in Main Application File(file annotated with @SpringBootApplication).
Still the same issue. What am i missing?

A: Probably you're running your spring cloud feign on Hystrix.
Hystrix's default isolation mode is thread, so actual HTTP request will be called on the different thread that is managed by hystrix. And HeaderInterceptor also run on that thread.
But, you are accessing RequestContextHolder and it is using ThreadLocal. That is probably the reason for your error.
Try to use one of the the below properties on A service.
It will disable hystrix for feign.
feign:
  hystrix:
    enabled: false

Or, you can just change isolation mode of your hystrix like below.
hystrix:
  command:
    default:
      execution:
        isolation:
          strategy: SEMAPHORE

If it works, you need to choose the way that you apply to. Just disable hystrix or change isolation strategy or just passing attribute via another way.


text:
Q: Ruby 2.0 + Rails 4 + Devise 3.1.1 logout issue if I click on the logout button i get this error: inspected result must be ASCII only or use the same encoding with default external
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.

  before_action :authenticate_user!
  before_action :configure_permitted_parameters, if: :devise_controller?

  protect_from_forgery with: :exception

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email) }
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation) }
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :email, :password, :password_confirmation, :current_password) }
  end

end

Link:
<%= link_to "Logout", logout_path, title: "Logout", method: :delete %>

Routes:
devise_scope :user do
  get 'register', to: 'devise/registrations#new', as: 'register'
  get 'login', to: 'devise/sessions#new', as: 'login'
  delete 'logout', to: 'devise/sessions#destroy', as: 'logout'
end

I have no idea where the problem is.
If I remove this 3 lines then it works but i can't register a new user:
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email) }
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation) }
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :email, :password, :password_confirmation, :current_password) }

Thank you!

A: Try using the following
devise_parameter_sanitizer.for(:sign_up) << :username

And if you need yet another field, add a line like the one above

A: Im not sure if this is the cause but I noticed that you don't allow a password to be whitelisted upon sign in. I assume that you would want that because you a password in the sign up and account update. It should look like this
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email, :password) }


text:
Q: how to receive just one result from a query in a mysql database? i´ve been using java to connect to a remote database in mysql, i´ve done a lot of diferents queries but today i´ve figured out that every time i wanted to look for a result, i have been always storing the result/s in a resulset,although in some cases my queries just have to return 0 or 1 result,that means that is not possible to receive an array of registers that meet the querie, so what kind of variable should i use to store JUST ONE RESULT?
Below i will post a portion of my code that describe the situation, it have to be understood that in the table "tareas", every register have a DIFFERENT title, like a PK.
Thanks in advance...
ps = c.prepareStatement("SELECT * FROM tareas WHERE titulo='" + title + "'");
rr = ps.executeQuery();
while (rr.next()) {
    JOptionPane.showMessageDialog(null, "Titulo: " + rr.getString("titulo") + newline +
              "Creador: " + rr.getString("nombre") + newline +
              "Receptor: " + rr.getString("receptor") + newline +
              "Tarea: " + nuevacadena(rr.getString("tarea")) + newline +
              "fecha de creación:" + lafecha(rr.getString("fecha")));
}

A: Add a LIMIT; without that the JDBC driver may pre-fetch more than one row regardless of option 2 (which you can also do). That is,
ps = c.prepareStatement("SELECT * FROM tareas WHERE titulo='" + title + "' LIMIT 1");

and then change (for option 2)
while (rr.next())

to
if (rr.next())

Also, since you are using a PreparedStatement, you should bind your parameters instead of writing them literally into the query; for example,
ps = c.prepareStatement("SELECT * FROM tareas WHERE titulo=? LIMIT 1");
ps.setString(1, title);


text:
Q: Xcode app for macOS. This is how I setup to get audio from usb mic input. Worked a year ago, now doesn't. Why Here is my audio init code.  My app responds when queue buffers are ready, but all data in buffer is zero.  Checking   sound in system preferences shows that USB Audio CODEC in sound input dialog is active.  AudioInit() is called right after app launches.
{
    #pragma mark user data struct
    typedef struct MyRecorder
    {
        AudioFileID recordFile;
        SInt64 recordPacket;
        Float32 *pSampledData;
        MorseDecode *pMorseDecoder;

    } MyRecorder;

    #pragma mark utility functions
    void CheckError(OSStatus error, const char *operation)
    {
        if(error == noErr) return;

        char errorString[20];
        // see if it appears to be a 4 char code
        *(UInt32*)(errorString + 1) = CFSwapInt32HostToBig(error);
        if (isprint(errorString[1]) && isprint(errorString[2]) &&
            isprint(errorString[3]) && isprint(errorString[4]))
        {
            errorString[0] = errorString[5] = '\'';
            errorString[6] = '\0';
        }

        else
        {
            sprintf(errorString, "%d", (int)error);

        }
        fprintf(stderr, "Error: %s (%s)\n", operation, errorString);
    }

    OSStatus MyGetDefaultInputDeviceSampleRate(Float64 *outSampleRate)
    {
        OSStatus error;
        AudioDeviceID deviceID = 0;
        AudioObjectPropertyAddress propertyAddress;
        UInt32 propertySize;
        propertyAddress.mSelector = kAudioHardwarePropertyDefaultInputDevice;
        propertyAddress.mScope = kAudioObjectPropertyScopeGlobal;
        propertyAddress.mElement = 0;
        propertySize = sizeof(AudioDeviceID);
        error = AudioObjectGetPropertyData(kAudioObjectSystemObject,
                                                    &propertyAddress,
                                                    0,
                                                    NULL,
                                                    &propertySize,
                                                    &deviceID);

        if(error)
            return error;

        propertyAddress.mSelector = kAudioDevicePropertyNominalSampleRate;
        propertyAddress.mScope = kAudioObjectPropertyScopeGlobal;
        propertyAddress.mElement = 0;
        propertySize = sizeof(Float64);
        error = AudioObjectGetPropertyData(deviceID,
                                                    &propertyAddress,
                                                    0,
                                                    NULL,
                                                    &propertySize,
                                                    outSampleRate);

        return error;
    }

    static int MyComputeRecordBufferSize(const AudioStreamBasicDescription *format,
                                         AudioQueueRef queue,
                                         float seconds)
    {
        int packets, frames, bytes;
        frames = (int)ceil(seconds * format->mSampleRate);
        if(format->mBytesPerFrame > 0)
        {
            bytes = frames * format->mBytesPerFrame;
        }
        else
        {
            UInt32 maxPacketSize;
            if(format->mBytesPerPacket > 0)
            {
                // constant packet size
                maxPacketSize = format->mBytesPerPacket;
            }
            else
            {
                // get the largest single packet size possible
                UInt32 propertySize = sizeof(maxPacketSize);
                CheckError(AudioQueueGetProperty(queue,
                                                 kAudioConverterPropertyMaximumOutputPacketSize,
                                                 &maxPacketSize,
                                                 &propertySize),
                           "Couldn't get queues max output packet size");
            }
            if(format->mFramesPerPacket > 0)
                packets = frames / format->mFramesPerPacket;
            else
                // worst case scenario: 1 frame in a packet
                packets = frames;
            // sanity check
            if(packets == 0)
                packets = 1;
            bytes = packets * maxPacketSize;

        }
        return bytes;
    }

    extern void bridgeToMainThread(MorseDecode *pDecode);

    static int callBacks = 0;
    // ---------------------------------------------
    static void MyAQInputCallback(void *inUserData,
                                  AudioQueueRef inQueue,
                                  AudioQueueBufferRef inBuffer,
                                  const AudioTimeStamp *inStartTime,
                                  UInt32 inNumPackets,
                                  const AudioStreamPacketDescription *inPacketDesc)
    {
        MyRecorder *recorder = (MyRecorder*)inUserData;
        Float32 *pAudioData = (Float32*)(inBuffer->mAudioData);
        recorder->pMorseDecoder->pBuffer = pAudioData;
        recorder->pMorseDecoder->bufferSize = inNumPackets;
        bridgeToMainThread(recorder->pMorseDecoder);
        CheckError(AudioQueueEnqueueBuffer(inQueue,
                                           inBuffer,
                                           0,
                                           NULL),
                   "AudioQueueEnqueueBuffer failed");
        printf("packets = %ld, bytes = %ld\n",(long)inNumPackets,(long)inBuffer->mAudioDataByteSize);
        callBacks++;
        //printf("\ncallBacks = %d\n",callBacks);
        //if(callBacks == 0)
            //audioStop();
    }

    static AudioQueueRef queue = {0};
    static MyRecorder recorder = {0};
    static AudioStreamBasicDescription recordFormat;

    void audioInit()
    {
        // set up format
        memset(&recordFormat,0,sizeof(recordFormat));
        recordFormat.mFormatID = kAudioFormatLinearPCM;
        recordFormat.mChannelsPerFrame = 2;
        recordFormat.mBitsPerChannel = 32;
        recordFormat.mBytesPerPacket = recordFormat.mBytesPerFrame = recordFormat.mChannelsPerFrame * sizeof(Float32);
        recordFormat.mFramesPerPacket = 1;
        //recordFormat.mFormatFlags = kAudioFormatFlagsCanonical;
        recordFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
        MyGetDefaultInputDeviceSampleRate(&recordFormat.mSampleRate);
        UInt32 propSize = sizeof(recordFormat);
        CheckError(AudioFormatGetProperty(kAudioFormatProperty_FormatInfo,
                                          0,
                                          NULL,
                                          &propSize,
                                          &recordFormat),
                    "AudioFormatProperty failed");

        recorder.pMorseDecoder = MorseDecode::pInstance();
        recorder.pMorseDecoder->m_sampleRate = recordFormat.mSampleRate;
        //    recorder.pMorseDecoder->setCircularBuffer();

        //set up queue

        CheckError(AudioQueueNewInput(&recordFormat,
                                      MyAQInputCallback,
                                      &recorder,
                                      NULL,
                                      kCFRunLoopCommonModes,
                                      0,
                                      &queue),
                   "AudioQueueNewInput failed");
        UInt32 size = sizeof(recordFormat);
        CheckError(AudioQueueGetProperty(queue,
                                         kAudioConverterCurrentOutputStreamDescription,
                                         &recordFormat,
                                         &size), "Couldn't get queue's format");

        // set up buffers and enqueue

        const int kNumberRecordBuffers = 3;

        int bufferByteSize = MyComputeRecordBufferSize(&recordFormat, queue, AUDIO_BUFFER_DURATION);
        for(int bufferIndex = 0; bufferIndex < kNumberRecordBuffers; bufferIndex++)
        {
            AudioQueueBufferRef buffer;
            CheckError(AudioQueueAllocateBuffer(queue,
                                                bufferByteSize,
                                                &buffer),
                       "AudioQueueAllocateBuffer failed");
            CheckError(AudioQueueEnqueueBuffer(queue,
                                               buffer,
                                               0,
                                               NULL),
                       "AudioQueueEnqueueBuffer failed");
        }
    }

    void audioRun()
    {
        CheckError(AudioQueueStart(queue, NULL), "AudioQueueStart failed");
    }

    void audioStop()
    {
        CheckError(AudioQueuePause(queue), "AudioQueuePause failed");
    }

}

A: This sounds like the new macOS 'microphone privacy' setting, which, if set to 'no access' for your app, will cause precisely this behaviour.  So:

*

*Open the System Preferences pane.

*Click on 'Security and Privacy'.

*Select the Privacy tab.

*Click on 'Microphone' in the left-hand pane.

*Locate your app in the right-hand pane and tick the checkbox next to it.
Then restart your app and test it.
Tedious, no?

Edit: As stated in the comments, you can't directly request microphone access, but you can detect whether it has been granted to your app or not by calling [AVCaptureDevice authorizationStatusForMediaType: AVMediaTypeAudio].


text: Q: Get query from sqlite3_stmt of SQLite in c/cpp I am using SQLite database with c/cpp and sqlite3 library from https://www.sqlite.org/index.html. For debugging purpose I want to print actual query from either sqlite3_stmt*  or sqlite3* object. How can i do that?


text:
Q: xPack QEMU Arm UART test on MacOS I am a very beginner of QEMU and mcu programming, recently practicing uart control on QEMU.
What I'm trying to do is virtually connect QEMU with host PC through USART2.
I have learned that  option -serial is probably able to do so and tried adding
-serial mon:stdio  => nothing happened
-serial stdio  => error, but nothing shown in console.
Processor: STM32F407VG
Board: STM32F4-Discovery
IDE: Eclipse IDE
Host device os: macOS Catalina 10.15.7
Following are my codes and run configuration
#include "stm32f4xx.h"

void UART2_Init(void);
void UART2_Write(int ch);
void delayMs(int delay);

int main(void){

    UART2_Init();
    while(1){
        UART2_Write('H');
        delayMs(500);
        UART2_Write('i');
        delayMs(500);
    }
}

void UART2_Init(void){

    RCC -> APB1ENR |= 0x20000;  // Enable usart2 clock
    RCC -> AHB1ENR |= 0x8;      // Enable PD5 clock
    GPIOD -> AFR[0] = 0x700000; // access PD5 AF7
    GPIOD -> MODER |= 0x800;

    USART2 -> BRR = 0x0683;     // Set buad rate to 9600
    USART2 -> CR1 =  0x8;       // Tx enable
    USART2 -> CR1 =  0x2000;    // USART enable
}

void UART2_Write(int ch){
    // wait until Tx buffer is empty
    while(!(USART2 -> SR & 0x80)){
        USART2 -> DR = (ch & 0xff);
    }
}

enter image description here


text:
Q: How to determine the current user keyboard focus (e.g. which text box)? I would like to figure out which UI element (of any other program currently running) currently has the user's keyboard focus - as an example, let's say I'd like to write a small tool that puts a green border around the currently active text field.
Another post makes me think I could achieve this partially by setting up a hook via SetWindowsHookEx to determine where the user clicked, but that would already fail for figuring out where TAB moved the focus to. I was also thinking about using pywinauto's inspection features to determine which UI elements are text input fields at all, and maybe there is an inverse GetFocus to its SetFocus. But all this seems rather hackish and unnecessarily complicated, so I thought I'd stop and ask here first:

How to find the UI element that currently has the keyboard focus?


text: Q: when scale the application in cloud foundry then fetch multiple time the same record from one database and write multiple in other database I have one application to fetch data from one database and write to other database. when i scale the instance of application then fetch the same record in multiple and write multiple times in database.


text:
Q: How to set seaborn styles on existing matplotlib axes I'm trying to use seaborn to set axes properties for a (potentially large) number of matplotlib subfigures. What I would like to be able to do is generate all the plots with a single call to plt.subplots, and then set the subplot style when each actual plot is generated. Unfortunately it seems that the sns style only matters when the subplot is generated.
The code below is a minimum (non)working example. Ideally the two subfigures would have two different styles, but they do not.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

def makeplt(sub, dat):
    sub.contour(dat)

def makepltwith(sub, dat, style):
    with sns.axes_style(style) as sty:
        sub.contour(dat)

dat = np.arange(100).reshape(10, 10)
with sns.axes_style('ticks'):
    fig, subs = plt.subplots(ncols=2)
makeplt(subs[0], dat)
makepltwith(subs[1], dat, 'darkgrid')
plt.show()

Is there a way to ensure that the second plot has the formatting I want it to have? The best idea I have on my own is to make some use of the sty object to manually reformat the sub object, but I can't come up with a pithy way of running through the formatting.
seaborn.__version__=0.7,
matplotlib.__version__=1.5 if that matters.

A: I encountered a similar problem and solved it like this:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

def add_sp_default(fig,pos):
    ax = fig.add_subplot(pos)
    return ax

def add_sp_image(fig,pos):
    ax = fig.add_subplot(pos)
    img=mpimg.imread('http://static.wixstatic.com/media/4afb41_998a1c7c0835c6eae5e159be3c2cfc07.png_1024')
    ax.imshow(img)
    ax.set_axis_off()
    return ax

def add_sp_polar(fig,pos):
    ax = fig.add_subplot(pos,projection='polar')
    return ax

def add_sp_xkcd(fig,pos):
    with plt.xkcd():
        ax = fig.add_subplot(pos)
    return ax

fig = plt.figure(figsize=(10,7))
ax1 = add_sp_default(fig,221)
ax2 = add_sp_image(fig,222)
ax3 = add_sp_polar(fig,223)
ax4 = add_sp_xkcd(fig,224)

plt.show()

A: No, it is not possible to do that. Axes styles are applied when the axes is created.
Of course, there are other ways to set up the subplots that don't involve making them all in one line of code, which would be more amenable to subplot-specific styles.


text:
Q: Finding the full conditonal distribution when there are multiple distributions involved 6 neighboring countries have the following disease instances: $y = (y_1, y_2,...,y_n)$ with a population of $x = (x_1, x_2,...,x_n)$.
The following model and prior distributions are considered:
$y_i|\theta_i,p_i  \sim \text{Poisson}(\theta_i x_i)$
$\theta_i | \alpha, \beta \sim \text{gamma}(\alpha, \beta)$
$\alpha \sim \text{gamma}(1,1)$
$\beta \sim \text{gamma}(10,1)$
a) Find the full conditional rate $p(\theta_i | \theta_{-i}, \alpha, \beta, x, y)$
b) Find the posterior distribution.
Attempt:
a) For finding the conditional rate with two variables, I would use Bayes' theory. I am not sure if this applies with multiple distributions.
$$p(\theta_i | \theta_{-i}, \alpha, \beta, x, y) = \frac{P(\theta_i \bigcap \theta_{-i} \bigcap \alpha \bigcap \beta \bigcap x \bigcap y)}{P( \theta_{-i}, \alpha, \beta, x, y)}$$
$$ = \frac{P(\theta_{-i}, \alpha, \beta, x, y | \theta_i)P(\theta_i)}{\sum_{i=1}^6 P(\theta_{-i}, \alpha, \beta, x, y | \theta_i)P(\theta_i)}$$
b) The posterior probability is the (prior)x(likelihood). So this would be $$\text{Poisson}(\theta_i x_i) \times L(\theta_i x_i)$$
I'm not sure how to do the pdf of a Poisson variable as it is variable. The likelihood function is $L(\theta_i y_i) = \frac{\theta_i^{\sum_{i=1}^n y_i} e^{-n \theta_i}}{y_1!,y_2!,..,y_n!}$


text:
Q: process stops, see "killed" in temrinal window I have 20.04 LTS and was running yolov5 model as root ( to rule out permissins issues ) and the model starts fine, then the first epoch of training starts, nothing happens, then I see the word "killed" and it all stops.
linux is still running and the terminal is OK.
How would I find out why linux would kill a process?

A: I diagnosed the issue - out of memory ( 8GB memory ).
I used :
dmesg -T| grep -E -i -B100 'killed process'

And an out of memory message was displayed.
I determined my model training batch size was too large, so I dropped it from 32 to 4 , and then it started and ran OK.
Hope this helps someone.


text:
Q: UseEffect Running infinitely I have to make an api call that gets me a list.
So i am dispatching an action inside useEffect that makes an api call and then dispatches an action that is consumed by the reducer, which in turn returns updated state..
But the problem is when the component gets mounted useEffect is called infinitely..
I have tried-
1- Adding the dependencies inside the UseEffect
2- Passing empty array of dependencies..
This is the component in Question-
import * as React from 'react';
import { TableBody, TableRow, TableCell, Toolbar, Grid, Typography, Box, MenuItem, FormControl } from '@mui/material';
import { useState } from 'react';
import useTable from 'components/common/useTable';
import Controls from 'components/common/controls/Controls';
import { InputAdornment } from '@material-ui/core';
import { CloudDownload, Search } from '@material-ui/icons';
import TableDropdown from 'components/common/tableDropdown/TableDropdown';
import useNavTabs from 'components/common/useNavTabs';
import BasicModal from 'components/common/usePopper'
import { Button } from '@mui/material';
import { useSelector } from 'react-redux';
import { useDispatch } from 'react-redux';
import { getDSAList, dsaCommentAndStatusUpdate } from 'containers/DSA/actions';
import {MultiSelect} from 'components/common/controls/MultiSelect'
import { makeStyles } from '@material-ui/styles';
import { DetailsModel } from 'components/common/detailsModel';
import { IconButton } from '@mui/material';
import { Autocomplete } from '@mui/material';
import { TextField } from '@mui/material';
import theme from 'assets/theme';
import {useEffect} from 'react'

const useStyles = makeStyles({
  clearFilterBtn: {
    color: '#f58720',
    padding: '0.7rem 2.2rem',
    display: 'block',
    margin: '0.4rem auto',
    "&:hover": {
      color: '#f58720',
    },
    "&:active": {
      color: '#f58720',
    },
    "&:focus:not(:hover)": {
      color: '#f58720',
    },
  },
    'MuiTableCell-root': {
        color: "#000"
    },
    "MuiIconButton-Root": {
      color: theme.palette.light.orange,
      "&:hover": {
        color: theme.palette.light.yellow
      },
      "&:active": {
        color: theme.palette.light.yellow,
      },
      "&:focus:not(:hover)": {
        color: theme.palette.light.orange
      }
    },
    "MuiInputBase-root": {
        height: '7vh'
    },
    ".MuiFormControl-root": {
      marginTop: '1rem'
    }
})

const headCells = [
  {id:'sno', label:'S.No.'},
  {id:'dsaId', label: 'DSA ID' },
  {id:'dsaName', label: 'DSA Name'},
  {id:'primarySourcingBusiness', label: 'Primary Sourcing Business'},
  {id:'dsaType', label: 'DSA Type'},
  {id:'bdmName', label:'BDM Name'},
  {id:'date', label:'Date'},
  {id:'registrationStatus', label: 'Registration Status'}
]
const headCellsMapping = [
  {id:'sno', label:'S.No.'},
  {id:'dsaId', label: 'DSA ID' },
  {id:'dsaName', label: 'DSA Name'},
  {id:'dsaContact', label: 'DSA Contact'},
  {id:'dsaType', label: 'DSA Type'},
  {id:'bdmName', label:'BDM Name'},
]

export default function DSARegistrationVerification() {

  const [filterFn, setFilterFn] = useState({ fn: items => { return items; } })
  const [enteredSearch, setEnteredSearch] = React.useState('')
  const [cityNames, setCityNames] = React.useState([])
  const[PSBNames,setPSBNames] = React.useState([])
  const[DSAType, setDSAType] = React.useState([])
  const[regStatus, setRegStatus] = React.useState([])
  const[selectedValue, setSelectedValue] = React.useState()
  const dispatch = useDispatch()

  useEffect(() => {
    console.log(enteredSearch)
    const identifier = setTimeout(() => {
      console.log('sending request')
          dispatch(getDSAList({
            page: 1,
            pageSize: 10,
            searchString: enteredSearch
          }))
        }, 500);
        return () => {
          console.log('cleanup')
          clearTimeout(identifier)
        }
    }, [enteredSearch])
    const dsaRecord = useSelector((state) => state.dsa)

    const handleChange = (values) => {
      console.log(values);
    };

    const handleSubmission = () => {
      console.log(DSAType, regStatus, PSBNames, cityName)
      dispatch(getDSAList({
        page: 1,
        pageSize: 10,
        filters: `${cityName.length > 0 ? 'cityName:'+cityName[0]:''}${PSBNames.length > 0 ? ',primarySourcingBusiness:'+PSBNames[0]: ''}${dsaType.length > 0 ? ',dsaType:' + dsaType[0]: ''}${regStatus.length > 0 ? ',registrationStatus'+regStatus[0]: ''}`
      }))
    }
  const classes = useStyles()
  const {
    TblContainer,
    TblHead,
    TblPagination,
    TblSort,
  } = useTable(dsaRecord.dsaList || [], headCells,filterFn)

  const {NavTabsHead,NavTabPanel} = useNavTabs()

  const fetchData= () =>{
    dispatch(getDSAList({
      page: 1,
      pageSize: 10,
      searchString: enteredSearch
    }))
  }

  // const handleSubmission = () => {
  //   console.log(DSAType, regStatus, PSBNames, cityName)
  //   dispatch(getDSAList({
  //     page: 1,
  //     pageSize: 10,
  //     filters: `${cityName.length > 0 ? 'cityName:'+cityName[0]:''}${PSBNames.length > 0 ? ',primarySourcingBusiness:'+PSBNames[0]: ''}${dsaType.length > 0 ? ',dsaType:' + dsaType[0]: ''}${regStatus.length > 0 ? ',registrationStatus'+regStatus[0]: ''}`
  //   }))
  // }

  // const handleChange = (e, v) => {
  //     console.log('......................>',v)
  //     setSelectedValue(v)
  // }

  const handleDSAMapping = () => {
    dispatch(dsaCommentAndStatusUpdate(
      {
        dsaUserId: 'DSA1',
        bdmUserId: 'BDM1',
        registrationStatus:'Approved',
        comment:"any thing"
    }
    ))
  }

  const cityName = ['Mumbai', 'Banglore', 'Pune']
  const primarySourcingBusiness = ['Gold Loan', 'Car Loan', 'Home Loan', 'abc', 'xyz', '123', 'antidisestablishmentarianism']
  const dsaType=['Individual', 'Test', 'Test 2']
  const registrationStatus=['Pending', 'Approved','Rejected']
  const dsaNames= ['Enrique Jefferson','Keyan Ingram','Gemma Holland','Radhika Keenan','Aryaan Sheehan','Lacy Rivas']
  const selectRef = React.useRef()

  const handleSearch = (value) => {
    setEnteredSearch(value)
  }
  const handleChangePage = (page) => {
    dispatch(getDSAList({
      page: page,
      pageSize: "10",
      searchString: enteredSearch
    }))
  }

  const selected = event => {
    console.log(event.target.innerText)
    setSelectedValue(event.target.innerText)
  }
  return (
    <>
      <Toolbar disableGutters>
              <Grid container>
                  <Grid item md={4}>
                    <Controls.InputEl
                        label="Search DSA"
                        sx={{width: '80%'}}
                        InputProps={{
                            endAdornment: (
                                <InputAdornment position='start'>
                                    <Search/>
                                </InputAdornment>
                            )
                        }}
                        handleSearch={handleSearch}
                    />
                  </Grid>
                  <Grid item md={4} sx={{paddingTop: 3}}>
                    <TblSort/> <span> </span>
                    <BasicModal
                      triggerName={"Filter"}
                      triggerIcon={"filterList"}
                      heading={'Filter'}
                      footerButtonName={'Apply'}
                      placement={'bottom-start'}
                      onFormAction={handleSubmission}>
                      <Grid item md={12} sx={{padding: '0.3rem 0.5rem'}}>
                        <MultiSelect
                          label="City Name"
                          options={cityName}
                          handleChange={(values) => setCityNames(values)}
                          selectProps={{
                            msgNoOptionsAvailable: 'All cities are selected',
                            msgNoOptionsMatchFilter: 'No city name matches the filter',
                          }}
                        />
                      </Grid>
                      <Grid item md={12} sx={{padding: '0.3rem 0.5rem'}}>
                        <MultiSelect
                          label="Primary Sourcing Business"
                          options={primarySourcingBusiness}
                          handleChange={(value) => setPSBNames(value)}
                          selectProps={{
                            msgNoOptionsAvailable: 'All cities are selected',
                            msgNoOptionsMatchFilter: 'No city name matches the filter',
                          }}
                        />
                      </Grid>
                      <Grid item md={12} sx={{padding: '0.3rem 0.5rem'}}>
                        <MultiSelect
                          label="DSA Type"
                          options={dsaType}
                          handleChange={(value) => setDSAType(value)}
                          selectProps={{
                            msgNoOptionsAvailable: 'All cities are selected',
                            msgNoOptionsMatchFilter: 'No city name matches the filter',
                          }}
                        />
                      </Grid>
                      <Grid item md={12} sx={{padding: '0.3rem 0.5rem'}}>
                        <MultiSelect
                          label="Registration Status"
                          options={registrationStatus}
                          handleChange={(value) => setRegStatus(value)}
                          selectProps={{
                            msgNoOptionsAvailable: 'All Status Selected',
                            msgNoOptionsMatchFilter: 'No Status Type Matched The filter',
                          }}
                        />
                      </Grid>
                      <Grid item md={12}>
                          <Button fullWidth className={classes.clearFilterBtn}>
                              Clear All filters
                          </Button>
                      </Grid>
                    </BasicModal>
                  </Grid>
                  <Grid item md={4} sx={{paddingTop: 3, display:'flex', justifyContent: 'end'}} >
                  <IconButton
                    id="download-button"
                    className={classes['MuiIconButton-Root']}
                  >
                    <CloudDownload/>
                  <Typography sx={{color: theme.palette.light.orange, fontSize: '0.8rem'}} variant='h6' ml={1}>
                    Download Excel
                  </Typography>
                </IconButton>
                  </Grid>
                </Grid>
            </Toolbar>
            <Grid item md={12}>
              <TblContainer>
                  <TblHead/>
                  <TableBody>
                    {dsaRecord && dsaRecord.dsaList?
                      dsaRecord.dsaList.map(
                        (record, index) =>
                        <TableRow key={index}>
                          <TableCell className={classes['MuiTableCell-root']}>{index}</TableCell>
                          <TableCell>
                            <Typography sx={{color: theme.palette.light.orange, fontSize: '0.9rem'}}>
                              <DetailsModel triggerName={record.dsaUserId} tabCount={3}/>
                            </Typography>
                          </TableCell>
                          <TableCell className={classes['MuiTableCell-root']}>
                              {record.dsaName}
                          </TableCell>
                          <TableCell className={classes['MuiTableCell-root']}>{record.primarySourcingBusiness}</TableCell>
                          <TableCell className={classes['MuiTableCell-root']}>{record.dsaType}</TableCell>
                          <TableCell className={classes['MuiTableCell-root']}>
                            <Box component="div" sx={{display: 'flex', justifyContent: 'space-between'}}>
                                <Typography variant={'body2'}>
                                  {record.bdmUserName}
                                </Typography>
                                <BasicModal
                                triggerName={""}
                                triggerIcon={"edit"}
                                dsaUserId={record.dsaUserId}
                                heading={'BDM Name'}
                                footerButtonName={'Done'}
                                onFormAction={handleDSAMapping}
                                >
                                  <Grid item md={12} sx={{padding: '0.3rem 0.5rem'}}>
                                  <Autocomplete
                                    disablePortal
                                    id="combo-box-demo"
                                    options={dsaNames}
                                    sx={{ width: 300 }}
                                    onChange={handleChange}
                                    renderInput={(params) => <TextField {...params} label="BDM" />}
                                  />
                                  </Grid>
                                </BasicModal>
                            </Box>
                          </TableCell>
                          <TableCell className={classes['MuiTableCell-root']}>{record.registrationDate}</TableCell>
                          <TableCell>
                              <TableDropdown status ={record.registrationStatus} />
                          </TableCell>
                      </TableRow>
                      ): ''}
                  </TableBody>
              </TblContainer>
            </Grid>
            <Grid item md={12}>
              <TblPagination pageSize={dsaRecord && dsaRecord.pageSize} totalPages={dsaRecord && dsaRecord.totalPages} pageNumber={dsaRecord.currentPage || 1}
              handleChangePage={(page) => handleChangePage(page-1)}/>
            </Grid>
    </>
  );
}

This is my useEffect
useEffect(() => {
  console.log(enteredSearch)
  const identifier = setTimeout(() => {
    console.log('sending request')
    dispatch(getDSAList({
      page: 1,
      pageSize: 10,
      searchString: enteredSearch
    }))
  }, 500);
  return () => {
    console.log('cleanup')
    clearTimeout(identifier)
  }
}, [enteredSearch])

This is the Action
export const getDSAList = (searchData) => {
    return async (dispatch) => {
        const fetchData = async () => {
            console.log('Fetching Data')
            const response = await webApiCall.post('https://a30fa91e-ae8b-42fb-8439-c2cc2d3cedfe.mock.pstmn.io/dsa/api/user/list',searchData)
            if(response.data.status !== 200) {
                throw new Error('Could not fetch DSA List')
            }
            return response.data.dsaResponse
        }

        try {
            const dsaData = await fetchData()
            dispatch(dsaActions.fetchDSAList(dsaData))
        }
        catch(error) {
            console.log(error)
        }
    }
}

This is the Reducer
import { createSlice } from "@reduxjs/toolkit";

const dsaSlice = createSlice({
    name: 'dsa',
    initialState: {},
    reducers: {
        fetchDSAList(state, action) {
            state.dsaList = action.payload.dsaList
        },
        commentAndStatusUpdate(state, action) {
            state.commentAndStatusUpdate = action.payload
        }
    }
})
export const dsaActions = dsaSlice.actions
export default dsaSlice;

This is the store
import {configureStore} from '@reduxjs/toolkit'
import { loginSlice } from 'containers/signin/reducer'
import { logoutSlice } from 'containers/signout/reducer'
import dsaSlice from 'containers/DSA/reducer'
// Export store with reducers
export const store = configureStore({
    preloadedState:{},
    reducer: {
        signin: loginSlice.reducer,
        signout: logoutSlice.reducer,
        dsa: dsaSlice.reducer
    }
})

export const loginActions = loginSlice.actions
export const logoutActions = logoutSlice.actions

A: try to remove enteredSearch and put the code like this i think it will work , it worked on my side
useEffect(() => {
    console.log(enteredSearch)
    const identifier = setTimeout(() => {
      console.log('sending request')
          dispatch(getDSAList({
            page: 1,
            pageSize: 10,
            searchString: enteredSearch
          }))
        }, 500);
        return () => {
          console.log('cleanup')
          clearTimeout(identifier)
        }
    }, [])


text:
Q: How to create custom url structure for custom post type categories? I am basically trying to rewrite the url structure for a custom taxonomy in wordpress from:
https://dev.energypages.com/specialization/energy-supply-distribution
To:
https://dev.energypages.com/specialization?specializingin=(parent category slug here)
And:
https://dev.energypages.com/specialization?specializingin=(parent category slug here)&specialitiesin=(Child category slug here)
I have been looking in to query vars but can't seem to figure out the code structure for what i need.
Any help on how to get started would be much appreciated thank you.

A: You can use this plugin for custom permalinks for the custom post type.
https://wordpress.org/plugins/custom-permalinks/
I think it will work for you.


text:
Q: Usage of SuppressFinalize with DisposeAsync I'm getting a message

DisposeAsync() calls GC.SuppressFinalize(object), a method that is typically only called within an
implementation of 'IDisposable.Dispose'. Refer to the IDisposable
pattern for more information.

from Visual Studio. Yes it is not Dispose but DisposeAsync but still the documentation states to call SuppressFinalize. https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-disposeasync
So who is correct the documentation or the compiler?
Implementation of IAsyncDisposable.DisposeAsync in my class along the line of the documentated pattern in the docs linked above
    public async ValueTask DisposeAsync()
    {
        await DisposeAsyncCore();

        Dispose(disposing: false);
        GC.SuppressFinalize(this);
    }

Message from Visual Studio (16.9.1) taken from Error List

Description of the message https://learn.microsoft.com/de-de/dotnet/fundamentals/code-analysis/quality-rules/ca1816


text:
Q: Using button push to update tkinter label (help for a homebrew RPG) I'm trying to build a simple tkinter UI that both displays the attributes of a simple RPG character and allows the player to update those attributes for a homebrew RPG. I have gone through a lot of the answers to similar questions but I'm missing something (probably obvious) and my buttons don't change the UI.
I am doing this little project as a follow on from finishing python crash course (which was really helpful) but this one has me stumped.
I have tested the functions in a separate script and the do what I want, but when I try to make them work within the UI nothing happens, no error or traceback, just no change to the UI either.
I'm sorry I think some of the indentations in the longer lines might be wrong in this example but I promise it's good in the actual script. I have made a separate module called character that contains the Character class and the functions associated. As I said above, they work fine when I just run that script but they don't affect the UI (even though they import fine and don't cause any errors).
    from tkinter import LEFT, RIGHT, CENTER, X, Y, SUNKEN
    import tkinter as tk
    from character import Character

    class GlobalFrequency:
        """The overall class for the app"""
        def __init__(self, master):
            """intialise the attributes of the variable"""
            self.master = master
            master.title = "Global Frequency"

    #trying to set this up with a character
            self.character = Character('Miranda zero')

            self.name_label = tk.Label(master, text =
                                       self.character.name.title(),
                                       font=("Helvetica", 20))
            self.name_label.pack()

    #This is where the buttons and stuff start,
            self.str_frame = tk.Frame(master, width=400)#strength frame
            self.str_frame.pack(fill=X)
     #This is the only button with a function so far
            self.st_btn_1 = tk.Button(self.str_frame, text = 'Strength
                                      up', font=("System", 16),
                                      command = lambda:
                            self.character.increase_attribute('strength'))
            self.st_btn_1.pack(side = LEFT)
     #This is a second button, not assigned a function yet
            self.st_btn_2 = tk.Button(self.str_frame, text = 'Strength
                                      down', font=("System", 16))
            self.st_btn_2.pack(side = LEFT)

            self.str_label = tk.Label(self.str_frame)
            self.str_label.configure(
                               text=self.character.attributes['Strength'],
                              font=("System", 16))
            self.str_label.pack()

    root = tk.Tk()
    root.geometry("400x600")
    gui = GlobalFrequency(root)
    root.mainloop()

What should happen when self.st_btn_1 is pressed is that the label next to it should update to say:
    Strenght: 2

As I've said, when I just run the function outside of the tkinter code the character attribute does update but it just doesn't effect the UI.
I'm sorry if this question is really stupid, or if my code is shoddy, but I'm trying to learn by doing.
Thanks in advance for any help you can offer.

A: You need to bind your label to a tk variable that can raise events and update when it's value is changed. In your code you set the label text value to a constant string. Use something like the example below with a tk.IntVar or tk.StringVar
import tkinter as tk

def increment(var):
    var.set(var.get() + 1)

def main():
    root = tk.Tk()
    value = tk.IntVar()
    label = tk.Label(root, textvariable=value, width=10, anchor=tk.W)
    button = tk.Button(root, text="Increment", command=lambda: increment(value))
    label.grid(row=0, column=0, sticky=tk.NSEW)
    button.grid(row=0, column=1, sticky=tk.W)
    root.mainloop()

if __name__ == '__main__':
    main()


text:
Q: How to drag and drop items between FlatLists on React Native I am developing react native app like photo below. I have a positions flatlist. Each Positions item has orange point which is drag and drop and can add to timeline area. I am using "react-native-draggable" package. But I can not drag orange point out of the flatlist. Also positions flatlist can be reorder in my scenario and delete items when I move to trash.
I know it's a very common scenario but as I'm quite new to React-Native so I am struggling to get any library or create the same by myself.
My scenario
I will be glad if you can help

A: try this package https://github.com/computerjazz/react-native-draggable-flatlist hope it will solve your problem


text:
Q: Open the as (action script) from fla file The question can sound a little bit stupid, but I can't figure it out!
I have a fla file (http://red5.googlecode.com/svn/flash/trunk/simpleBroadcaster.fla ) and I follow a tutorial to edit this file (http://blog.endpoint.com/2012/04/streaming-live-with-red5-media-server.html ) and I can't begin to step 2 because I can't find the file or folders.
Please, help. I downloaded the trials of both Flash builder and Flash Professional CS6 but still couldn't find it.
This solution gives something empty. So I taught there should be some swc file (this post) but I couldn't find it.
edit: I found the as file, it's not in the fla file but in a separate directory. I had to download the whole trunk. I found the file and can open and edit it in a texteditor. But I'd like to get it in Flashbuilder to compile at the end.

A: Step 2.
Let's now open the "red5" directory that we checked out in FlashBuilder.

RED5! You need download and install "Red5 Media Server" http://www.red5.org/
Exploring Red5 Media Server
Download and install Red5 Media Server for your environment from here. Now it is time to implement a sweeping live stream between our two laptops.


text:
Q: Find a matrix whose null space is equal to the range of the matrix A? So here is the solution:

I don't understand how the null space relates to consistency of the matrix A. In another word, I don't understand how this method of solving leads to answer.

A: Notice that the range of the matrix $A$ is the span of the two column vectors:
$$\operatorname{span}(1,1,0)^T,(2,0,1)^T)$$
Now $(x,y,z)^T$ will be in the range of $A$ if the augmented matrix is not invertible so by the row echeloned matrix we see that this will be if
$$  -x+y+2z=0\iff [-1\; 1\;2](x,y,z)^T=0\iff(x,y,z)^T\in\ker [-1\; 1\;2]$$

A: This approach makes more sense to me since I can visualize it geometrically:
The range of $A$ is the span of its two column vectors $(1, 1, 0)^T$ and $(2, 0, 1)^T$, which is a plane $P$ that passes through the origin in $\mathbf{R}^3$. We're then looking for a matrix $B$ whose nullspace is equal to this plane, i.e. $Bx = 0$ for any $x \in P$. It should be apparent that the $B$ that accomplishes this is $B = n^T$ where $n$ is the normal vector to the plane ($n$ is orthogonal to all points on the plane and thus the dot product of any point on the plane with $n$ is 0). You can compute $n$ by taking the cross product of the columns of $A$ which gives you $(2, 0, 1)^T \times (1, 1, 0)^T = (-1, 1, 2)^T$. Thus $B = (-1, 1, 2)$. Hope this makes sense.


text:
Q: Building Kaa application for esp8266 I am trying to build a demo application using Kaa C SDK for esp8266. I am following official the programming guide. I am facing error while making the application (terminal screen shot is added).
I have tried changing the compile options as mentioned here Compiler options for esp8266. Also I have changed the linker file as mentioned in this post. Other notifications are gone and overflow is significantly reduced but it still it overflows by 4964 bytes while showing this error.

/opt/Espressif/crosstool-NG/builds/xtensa-lx106-elf/lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld: kaa_demo section '.irom0.text' will not fit in region `irom0_0_seg'
/opt/Espressif/crosstool-NG/builds/xtensa-lx106-elf/lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld: region `irom0_0_seg' overflowed by 4964 bytes
collect2: error: ld returned 1 exit status
  `make2: * [kaa_demo] Error 1
    make1: * [CMakeFiles/kaa_demo.dir/all] Error 2
    make: *** [all] Error 2

Please help.

A: In my case, I eliminated rest of the overflow by disabling some of the compile options. My compile options are
cmake .. \

-DCMAKE_TOOLCHAIN_FILE=../kaa/toolchains/esp8266.cmake \
-DKAA_PLATFORM=esp8266 \
-DBUILD_TESTING=OFF \
-DCMAKE_BUILD_TYPE=MinSizeRel \
-DKAA_MAX_LOG_LEVEL=3 \
-DWITH_ENCRYPTION=OFF \
-DWITH_EXTENSION_NOTIFICATION=OFF \
-DWITH_EXTENSION_PROFILE=OFF \
-DWITH_EXTENSION_CONFIGURATION=OFF \
-DWITH_EXTENSION_EVENT=ON \
-DWITH_EXTENSION_LOGGING=OFF

Hope this helps.


text:
Q: Subclass from a class decorated by a class I have a decorator, a class decorated by that decorator, and a subclass:
def decorated_by_function(cls):
    return cls

@decorated_by_function
class F(object):
    pass

class G(F):
    pass

No problem there.
Now, I change the decorator's implementation to be class-based:
class decorated_by_class(object):
    def __init__(self, cls):
        self._cls = cls

    def __call__(self, *args, **kwargs):
        return self._cls(*args, **kwargs)

@decorated_by_class
class C(object):
    pass

class D(C):
    pass

And Python gives this error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "h.py", line 23, in <module>
    class D(C):
TypeError: Error when calling the metaclass bases
    __init__() takes exactly 2 arguments (4 given)

Edit:
@donkopotamus has given a partial answer below, that C is an instance instead of a class. That is why C cannot be subclassed. I understand that. My question is: Is it possible to keep the class-based approach, while also allowing the decorated class to be subclassed?
The advantage of using a class is that it can be extended. Imagine a decorator with more complicated logic. What is a natural way to modify some of its behavior, but retains most of the logic? Using a class-based approach enables a tree of similar decorators with slightly different functionalities. That is why I want to investigate the possibility.

A: In this case
@decorated_by_class
class C(object):
    pass

is roughly equivalent to:
class C(object):
    pass

C = decorated_by_class(C)

So in this case C is now an instance of the class decorated_by_class ... it is not a class itself.  Hence, you cannot create another class D inheriting from C.
I believe what you're probably really wanting to do is use an instance of a class as a decorator, for example:
class decorated_by_class(object):
    def __init__(self, *some_decorator_args):
        self.args = some_decorator_args

    def compute_something(self):
        return self.args

    def __call__(self, cls):
        # do something with the class
        cls.decorated_with_args = self.compute_something()
        return cls

@decorated_by_class("hello")
class C(object):
    pass

print(C.decorated_with_args)    # => ('hello',)

class decorated_by_subclass(decorated_by_class):
    def compute_something(self):
        return self.args * 2

@decorated_by_subclass("hello")
class D(object):
    pass

print(D.decorated_with_args)    # => ('hello', 'hello')


text:
Q: Can't change the icon of a console app in Visual Studio Community Edition I am making a console app in using C# .NET version 4.5 in Visual Studio.
Whenever I try to add a 32x32 or 256x256 icon file (converted from 24-bit bitmap using MS paint) it says "C:\Users\ipass\Desktop\icon32.ico is not a valid icon file." I have tried using different icons, switching from a console app to a Windows app type, restarting my computer, moving the icon to a different directory, changing the icon of a different console app, and using SharpDevelop instead of Visual Studio. Nothing seems to be working.
Let me know if you need more info. I am attempting to change the icon by Right clicking the project in solution explorer>clicking 'Properties'>navigating to 'Application'>and clicking browse under 'Icon and Manifest'.

A: If so it is probably giving the error because the actual file type is not what Visual Studio expects a .ico to be (the size of or information in the file header, for example). Also, the image may have to be a certain size, like 64x64 pixels.
You could try an online converter to convert an image file into a .ico file
http://www.convertico.com/
http://www.icoconverter.com/
The wikipedia page for .ico has more information that might help - http://en.wikipedia.org/wiki/ICO_(file_format)


text:
Q: Meaning of f[u] in DFS algorithm I wonder what the $f[u]$ row means here, in this table that represents the DFS algorithm of the following graph.
I know $u$ is the order of visit of each node, $d[u]$ the cumulative time needed, and $\Pi[u]$ the father node, but I'm completely clueless about $f[u]$.

A: $d[u]$ is the time in which $u$ was visited, and $f[u]$ is the time in which the algorithm was done with $u$ (i.e., finished visiting all vertices reachable from $u$)
Using the table you can see exactly how the algorithm went (and thus you know how to build the DFS tree/forest) : vertices 1,2,4,8 were visited (time 1-4) then got back from 8, then visited 12, then back from 12 etc.