text:
Q: How to add a JButton on my JMenuBar? For a assignment I am to modify an existing java applet.
I'm trying to get a JButton (or a clickable JMenu) on my JMenuBar.
There are a few menu's and one of them should be usable as a button.
I found the same question several times but the winning answer stated that it would be "bad" and should still be an item in a JMenu.
While this is a possibility I really would prefer otherwise.
Thank you.

A: I found this post that (I think) is related to your question:
How to make a JMenu have Button behaviour in a JMenuBar
Is this wat you are trying to accomplish?
Good luck!


text:
Q: I'm getting a "Does not implement IController" error on images and robots.txt in MVC2 I'm getting a strange error on my webserver for seemingly every file but the .aspx files.
Here is an example. Just replace '/robots.txt' with any .jpg name or .gif or whatever and you'll get the idea:

The controller for path '/robots.txt'
  was not found or does not implement
  IController.

I'm sure it's something to do with how I've setup routing but I'm not sure what exactly I need to do about it.
Also, this is a mixed MVC and WebForms site, if that makes a difference.

A: You can ignore robots.txt and all the aspx pages in your routing.
routes.IgnoreRoute("{*allaspx}", new {allaspx=@".*\.aspx(/.*)?"});
routes.IgnoreRoute("{*robotstxt}", new {robotstxt=@"(.*/)?robots.txt(/.*)?"});

You might want to ignore the favicon too.
routes.IgnoreRoute("{*favicon}", new {favicon=@"(.*/)?favicon.ico(/.*)?"});

You can adjust the regular expression to exclude paths.
Haacked from the source.

A: This error could also happen if inside a view in your area, you use the Html.Action helper. This helper will always use the area as a prepend, unless you specifically tell it not to. E.g.,
@Html.Action("Main", "Navigation", new { area = string.Empty })

A: I found another solution too... While I don't think I'll use it, it's worth showing here in the answers:
The following should (in theory) ignore looking for controllers for anything with a '.' in it.
routes.MapRoute(
    "Default",                                              // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = "" },  // Parameter defaults
    new { controller = @"[^\.]*" }                          // Parameter contraints.
);

A: Do you still have:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

... in your Global.asax.cs?
MVC puts it there by default, and it's supposed to handle this.
If you do, then the problem may be how you're mixing MVC and WebForms.

A: The ignore route given above didn't work for me but I found a similar one that did:
routes.IgnoreRoute("{*staticfile}", new { staticfile = @".*\.(css|js|gif|jpg)(/.*)?" });

A: I encountered this error when I request resources that did not exist.
Specifically, I was requesting a custom IE css file:

<!--[if lt IE 8]>@Styles.Render("~/Content/ie7.css")<![endif]-->

(These are condition comments, interpreted by IE)
However, the actual resource existed on ~/Content/ie/ie7.css.
So, without any modifications to the routing, the error was solved by using the correct url of the resource.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How pass the date pick by user (via showDatePicker) to new page in flutter without navigator Tried to use Riverpod didn't work as I don't want to change the UI but use this variable on the second page as DOC id. I don't want to call this function again otherwise I define a custom  widget for it. Just need to access the date the user picks on the second page.WITHOUT a navigator as still there are actions that need to be done on the first page.
On a page user picks the date :
 final initalDate = DateTime.now();
    final newDate = await showDatePicker(
        context: context,
        initialDate: initalDate,
        firstDate: DateTime(DateTime.now().year + 0),
        lastDate: DateTime.now());
    if (newDate == null) return;

As this is defined as Doc id in firestore , how can I access this on the second page without navigation?
class SugarPhotoPage extends StatefulWidget {
  const SugarPhotoPage({
    super.key,
  });

  @override
  State<SugarPhotoPage> createState() => _SugarPhotoPageState();
}

class _SugarPhotoPageState extends State<SugarPhotoPage> {
  final Stream<QuerySnapshot> _photoStream = FirebaseFirestore.instance
      .collection('photos')
      .doc(DateFormat('yyyy-MM-dd').format(newDate))
      .collection('Today Photos')
      .snapshots();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
      ),
      body: StreamBuilder<QuerySnapshot>(
          stream: _photoStream,
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return const Text('Something went wrong');
            }

            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Text("Loading");
            }

            if (snapshot.hasData) {
              return SafeArea(
                child: Center(
                  child: ListView(
                    children: snapshot.data!.docs
                        .map((DocumentSnapshot documentSnapshot) {
                      Map<String, dynamic> data =
                          documentSnapshot.data()! as Map<String, dynamic>;
                      return ListTile(
                        leading: Container(
                          height: 100,
                          width: 100,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: NetworkImage('${data['ImgUrl']}'),
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),
                      );
                    }).toList(),
                  ),
                ),
              );
            }
            return const Text('Loading');
          }),
    );
  }
}

Tried to use Riverpod didn't work  as I don't want to change the UI but use this variable  IN second page as DOC id .

A: If you don't want to share data using the navigator then you can create a single data source that shares the data between screens.
You can create a singleton class that contains a static variable that can be accessed throughout the app.
1 -> create a singleton class
class AppData {
  AppData._();

  static DateTime? userSelectedData;

}

2 -> update date on user selection
final initalDate = DateTime.now();
final newDate = await showDatePicker(
    context: context,
    initialDate: initalDate,
    firstDate: DateTime(DateTime.now().year + 0),
    lastDate: DateTime.now());
if (newDate == null) {return;}
else{
AppData.userSelectedData = newDate;
}

3-> Now you can access the date wherever you want without context by calling AppData.userSelectedData
if you want to save user selection after app is closed you can introduce Shared Preferences as well


text:
Q: Is there a way to place a widget into more than one of the tabs of a QTabWidget? The motivating scenario:  I'm working on a Qt/QWidgets C++ app whose GUI is largely arranged into tabs, via a hierarchy of QTabWidgets.  Many of these tabs are various agglomerations of the same content, (e.g. there's a tab with widget A and B, a tab with widget B and C, and so on).
I have one particular widget class W which is a fairly heavyweight GUI object and it appears in many (but not all) of the tabs.  Currently I handle that by simply creating a separate object of the W class for each tab I want it to appear in, and that basically works, but it's not 100% satisfactory for a couple of reasons:

*

*Since the widget is heavy, creating a number of instances of it slows down the GUI's creation on startup, and uses more system resources than I would like.

*Every time the user changes the layout/state of the widget in one tab, I have to manually echo that change to all of its "clones" in the other tabs; otherwise the user will notice the different states of the different W widgets as he moves back and forth from one tab to another.  This is doable, but it's a maintenance and testing headache.

So what I'd like to do is create just a single instance of W and have it magically appear in its expected location within whichever tab is currently visible.  Since only one tab with W should ever be visible at one time, it seems like a single W instance ought to be enough to accomplish that.
I thought about making a lightweight proxy/container-widget of some sort, and overriding its showEvent() method to setParent() the real W object to be its child as necessary; I think that might work, or it might turn out to be full of gotchas, so I thought I'd ask first if anyone else knows of a more elegant or better-supported way to accomplish the same result.

A: With a little help I was able to make this technique work, as shown in the example code below.  Note that the green label "Shared Widget!" is only created once, but it appears in all 5 tabs (along with various normal QLabels):

#include <QApplication>
#include <QLabel>
#include <QMap>
#include <QSet>
#include <QStackedLayout>
#include <QTabWidget>
#include <QWidget>

/** This is a special container-class that holds a single target widget so that the target widget can be placed
  * into more than one QTabWidget at a time.  This widget will handle moving the target widget around from proxy
  * to proxy as tabs are shown, so that instead of having to create N identical widgets, we can just create one
  * target-widget and have it jump from tab to tab as necessary.
  */
class TabProxyWidget : public QWidget
{
public:
   /** Constructor
     * @param optTargetWidget if non-NULL, this will be passed to SetTargetWidget().  Defaults to NULL.
     */
   TabProxyWidget(QWidget * optTargetWidget = NULL)
      : _layout(new QStackedLayout(this))
      , _targetWidget(NULL)
   {
      SetTargetWidget(optTargetWidget);
   }

   virtual ~TabProxyWidget() {SetTargetWidget(NULL);}

   /** Set the widget that we want to be a proxy for
     * @param optTargetWidget the widget we will proxy for, or NULL to disassociate us from any target widget
     * @note the same pointer for (optTargetWidget) can (and should!) be passed to multiple TabProxyWidget objects
     */
   void SetTargetWidget(QWidget * optTargetWidget);

   virtual void showEvent(QShowEvent *);
   virtual bool eventFilter(QObject * o, QEvent * e);

private:
   void AdoptTargetWidget();
   void UpdateSizeConstraints();

   QStackedLayout * _layout;
   QWidget * _targetWidget;
};

static QMap<QWidget *, QSet<TabProxyWidget *> > _targetWidgetToProxies;

void TabProxyWidget :: SetTargetWidget(QWidget * targetWidget)
{
   if (targetWidget != _targetWidget)
   {
      if (_targetWidget)
      {
         _targetWidget->removeEventFilter(this);

         QSet<TabProxyWidget *> * proxiesForTargetWidget = _targetWidgetToProxies.contains(_targetWidget) ? &_targetWidgetToProxies[_targetWidget] : NULL;
         if ((proxiesForTargetWidget == NULL)||(proxiesForTargetWidget->isEmpty()))
         {
            printf("TabProxyWidget::SetTargetWidget(NULL):  can't proxies-table for target widget %p is %s!\n", targetWidget, proxiesForTargetWidget?"empty":"missing");
            exit(10);
         }

         (void) proxiesForTargetWidget->remove(this);
         if (proxiesForTargetWidget->isEmpty())
         {
            (void) _targetWidgetToProxies.remove(_targetWidget);
            delete _targetWidget;
         }
         else if (dynamic_cast<TabProxyWidget *>(_targetWidget->parentWidget()) == this)
         {
            proxiesForTargetWidget->values()[0]->AdoptTargetWidget();  // hand him off to another proxy to for safekeeping
         }
      }

      _targetWidget = targetWidget;

      if (_targetWidget)
      {
         if (_targetWidgetToProxies.contains(_targetWidget) == false) _targetWidgetToProxies[_targetWidget] = QSet<TabProxyWidget *>();
         _targetWidgetToProxies[_targetWidget].insert(this);

         if ((isHidden() == false)||(_targetWidget->parentWidget() == NULL)||(dynamic_cast<TabProxyWidget *>(_targetWidget->parentWidget()) == NULL)) AdoptTargetWidget();

         UpdateSizeConstraints();
         _targetWidget->installEventFilter(this);
      }
   }
}

bool TabProxyWidget :: eventFilter(QObject * o, QEvent * e)
{
   if ((o == _targetWidget)&&(e->type() == QEvent::Resize)) UpdateSizeConstraints();
   return QWidget::eventFilter(o, e);
}

void TabProxyWidget :: UpdateSizeConstraints()
{
   if (_targetWidget)
   {
      setMinimumSize(_targetWidget->minimumSize());
      setMaximumSize(_targetWidget->maximumSize());
      setSizePolicy (_primaryWidget->sizePolicy());
   }
   else
   {
      setMinimumSize(QSize(0,0));
      setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
      setSizePolicy (QSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored));
   }
}

void TabProxyWidget :: showEvent(QShowEvent * e)
{
   AdoptTargetWidget();
   QWidget::showEvent(e);
   if (_targetWidget) _targetWidget->show();
}

void TabProxyWidget :: AdoptTargetWidget()
{
   if ((_targetWidget)&&(_targetWidget->parentWidget() != this))
   {
      QLayout * layout = _targetWidget->layout();
      if (layout) layout->removeWidget(_targetWidget);

      _targetWidget->setParent(this);
      _layout->addWidget(_targetWidget);
   }
}

static void SetWidgetBackgroundColor(QWidget * w, const QColor bc)
{
   QPalette p = w->palette();
   p.setColor(QPalette::Window, bc);
   w->setAutoFillBackground(true);
   w->setPalette(p);
}

int main(int argc, char ** argv)
{
   QApplication app(argc, argv);

   QTabWidget * tabWidget = new QTabWidget;
   tabWidget->setWindowTitle("Proxy Widget test");

   QWidget * proxyMe = new QLabel("Shared Widget!");
   SetWidgetBackgroundColor(proxyMe, Qt::green);

   int counter = 0;
   for (int i=0; i<5; i++)
   {
      QWidget * nextTab = new QWidget;
      QBoxLayout * tabLayout = new QBoxLayout(QBoxLayout::TopToBottom, nextTab);

      const int numAbove = rand()%3;
      for (int i=0; i<numAbove; i++) tabLayout->addWidget(new QLabel(QString("Unshared label #%1 above").arg(++counter)));

      tabLayout->addWidget(new TabProxyWidget(proxyMe));

      const int numBelow = rand()%3;
      for (int i=0; i<numBelow; i++) tabLayout->addWidget(new QLabel(QString("Unshared label #%1 below").arg(++counter)));

      tabWidget->addTab(nextTab, QString("Tab %1").arg(i+1));
   }

   tabWidget->show();
   return app.exec();
}


text:
Q: Python's Matplotlib: Override imshow extent I am plotting a georeferenced image with
import numpy as np
from matplotlib import pyplot as plt

f = plt.figure()
ax = f.add_subplot(111)
ax.imshow( numpy.dstack((R,G,B)), extent=[xmin,xmax,ymin,ymax] )

Then I am plotting (on the same axes instance) a two arrays x and y which only covers a small extent of the figure:
ax.plot( x, y )

I want the size of my picture to match that of the line, but I cannot remove the extent kwarg from the RGB image, otherwise I would lose the coordinates matching.
What I tried to do is
ax.set_xlim( [x.min(), x.max()] )

but it is does not affect the figure. The axes limits I get is stull that of the extent keyword in the imshow method.
How do I set the axis limits without removing the extent named argument from the imshow call? I don't want to reproject my x and y coordinates.


text:
Q: frequency domain interpolation changes the signal spectrum I am working on some experimental data related to a sine-sweep excitation.
I first reconstructed the signal using the amplitude and frequency information I get from the data file:
% finz: frequency
% ginz: amplitude
R = 4; % sweep rate
tz = 60/R*log2(finz/finz(1)); % time
u_swt = sin(2*pi*((60*finz(1)/(R*log(2.))*(2.^(R/60*tz)-1))));
time_sign = ginz.*u_swt;
freq_sign = fft(time_sign);

This is what I obtain:

I then tried to interpolate the frequency data before computing the time signal to obtain a 'nicer' signal (having more samples it should be easier to reconstruct it):
ginz = interp(ginz,200);
finz = interp(finz,200);

But now the spectrum is changed:

Why the frequency spectrum is so different? Am I doing something wrong in the interpolation? Should I not interpolate the data?

A: The details of the signal you are working with are not clear to me. For instance, can you please provide typical examples of finz and ginz? Also, it is not clear what you are hoping to achieve through interpolation, so it is hard to advise on its use.
However, if you interpolate a time series you should expect its spectrum to change as it increases the sampling frequency. The frequency of an interpolated signal will become smaller relative to the new sampling frequency. Therefore, the signal spectrum will be (not being very technical here) pushed towards zero. I have provided a script below which creates white Gaussian noise, and plots the spectrum for different levels of interpolation. In the first subfigure with no interpolation, the spectrum is uniformly occupied (by design - white noise). In subsequent subfigures, with increasing interpolation the occupied spectrum becomes smaller and smaller. Hope this helps.
% white Gaussian noise (WGN)
WGN = randn(1,1000);
% DFT of WGN
DFT_WGN = abs(fft(WGN));
% one-sided spectrum
DFT_WGN = DFT_WGN(1:length(WGN)/2);

% interpolated WGN by factor of 2 (q = 2)
WGN_interp_2 = interp(WGN,2);
% DFT of interpolated WGN
DFT_WGN_interp_2 = abs(fft(WGN_interp_2));
% one-sided spectrum
DFT_WGN_interp_2 = DFT_WGN_interp_2(1:length(DFT_WGN_interp_2 )/2);

% interpolated WGN by factor of 10 (q = 10)
WGN_interp_10 = interp(WGN,10);
% DFT of interpolated WGN
DFT_WGN_interp_10 = abs(fft(WGN_interp_10));
% one-sided spectrum
DFT_WGN_interp_10 = DFT_WGN_interp_10(1:length(DFT_WGN_interp_10 )/2);

figure
subplot(3,1,1)
plot(DFT_WGN)
ylabel('DFT')
subplot(3,1,2)
plot(DFT_WGN_interp_2)
ylabel('DFT (q:2)')
subplot(3,1,3)
plot(DFT_WGN_interp_10)
ylabel('DFT (q:10)')


text:
Q: How to initialize the SQLite3 JDBC driver in JRuby? How do you access SQLite3 via JDBC without using active record?

A: Here's an example that works with JRuby 1.6.6 (in Ruby 1.8 compat mode) with jdbc-sqlite3 3.7.2.
require 'rubygems'
require 'jdbc/sqlite3'
require 'java'

org.sqlite.JDBC                 # load the driver so DriverManager detects it
#Java::OrgSqlite::JDBC          # alternate means of same

connection = java.sql.DriverManager.getConnection 'jdbc:sqlite:test.sqlite3'
begin
  statement = connection.createStatement
  begin
    statement.executeUpdate("create table user (name varchar, pass varchar)")
    statement.executeUpdate("insert into user values ('alice', 1234)")
    statement.executeUpdate("insert into user values ('bob', 5678)")
    statement.executeUpdate("insert into user values ('charlie', 'asdf')")

    rs = statement.executeQuery("select * from user")
    begin
      puts "user\tpass"
      while rs.next
        puts ["#{rs.getString(1)}",
              "#{rs.getString(2)}"].join("\t")
      end
    ensure
      rs.close
    end

  ensure
    statement.close
  end
ensure
  connection.close
end

Output:
$ rm -f test.sqlite3; ruby sql.rb
user    pass
------------
alice   1234
bob     5678
charlie asdf

A: Install the jdbc-sqlite3 gem
Then, in your jruby script:
require 'jdbc/sqlite3'
url = "jdbc:sqlite:path.to.your.db"
begin
    Java::org.sqlite.JDBC #initialize the driver
    connection = JavaLang::DriverManager.getConnection(url) #grab your connection
rescue => error
    #handle error
end

A: The jdbc driver file sqlite-3.5.8.jar gets copied into the gem directory. It needs to be copied into the jruby/lib directory. Application also needs restart.
The driver file can be downloaded directly from here
http://files.zentus.com/sqlitejdbc/sqlitejdbc-v056.jar

http://www.zentus.com/sqlitejdbc/


text:
Q: Why does omitting this "li" CSS selector affect the applied style? The code goes like this,

Menu 1

Menu 1

Menu 2

Menu 3

Menu 4

Menu 2

Menu 3

Menu 4

On the third element at the "li, li a" part, If I remove the "li" selector leaving only the "li a", what happens is, when I hover at my first level list items, the second list items appear, but the text doesn't, I don't know if it's a background influence, or a text influence, because I can't find what influences my 2nd level lists!
Oh and by the way, the first menu called "Menu 1" under the first level list item, is visible, I think its because of the "li a" selector, but as for the part where that I deleted, I don't know how it works, can someone tell me what's causing this trouble when I delete it?

A: You are applying a tag only to the first sub item of "Menu 1". and you are giving text color as white(#FFF) by the following code:
#nav li:hover > a, #nav li:hover { color:#fff; background:#000; }

Thats why the text is not being visible because the background is also white. but when you hovering on the li's, the text is being visible because you are changing the background color to black by doing the following.
li,li a {color:#000; text-decoration:none;} //assigning text color of li as black

If you remove li from the above code then the text color inside the li elements will remain white color as you mentioned in the very above code.

A: The line li, li a means that the styles are being applied to all LI's and all A's contained inside LI's.
All your styling is being applied relatively.  Meaning anything applied to li, li a is going to affect every LI and ever A nested inside an LI that is present.  Regardless of whether it is a parent, or a child menu.
Since .nav is a class applied to the sub-menu, you can target the li's there by including .nav in your  selector.  For example: #nav .nav li a
To hide your submenu you need simply:
#nav li ul.nav { display: none; }

Then to make it appear on hover (presuming this is what you want)
#nav li:hover ul.nav { display: block; }

Have I answered all questions?


text:
Q: json data error while parsing data Hello I am new to android development I don't know how to use JSON. I was trying an existing to make my own but while trying I was having errors and unable to send the data to server using JSON format. can any one help me solving this problem or suggest me with the working code.
This is my predictionpage.java (Main activity) page
public class PredictionActivity extends Activity {

private String URL_NEW_PREDICTION = "http://127.0.0.1/new_predict.php";
private Button btnAddPrediction;

String numOfGoal = "1";
String numOfCard = "1";
String diffOfPos = "1";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_prediction);

    RadioGroup goal = (RadioGroup) findViewById(R.id.answer1);

    goal.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // TODO Auto-generated method stub

            switch (checkedId) {
                case R.id.answer1A:
                    numOfGoal = "1";
                    break;
                case R.id.answer1B:
                    numOfGoal = "2";
                    break;
                case R.id.answer1C:
                    numOfGoal = "3";
                    break;

            }

        }
    });

    RadioGroup card = (RadioGroup) findViewById(R.id.answer2);

    card.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // TODO Auto-generated method stub

            switch (checkedId) {
                case R.id.answer2A:
                    numOfCard = "1";
                    break;
                case R.id.answer2B:
                    numOfCard = "2";
                    break;
                case R.id.answer2C:
                    numOfCard = "3";
                    break;

            }
        }
    });

    RadioGroup pos = (RadioGroup) findViewById(R.id.answer3);

    pos.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // TODO Auto-generated method stub
            switch (checkedId) {
                case R.id.answer3A:
                    diffOfPos = "1";
                    break;
                case R.id.answer3B:
                    diffOfPos = "2";
                    break;
                case R.id.answer3C:
                    diffOfPos = "3";
                    break;

            }

        }
    });

    btnAddPrediction = (Button) findViewById(R.id.submit);

    btnAddPrediction.setOnClickListener(new View.OnClickListener() {

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

            new AddNewPrediction().execute(numOfGoal, numOfCard, diffOfPos);
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_prediction, menu);
    return true;
}

private class AddNewPrediction extends AsyncTask<String, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected Void doInBackground(String... arg) {
        // TODO Auto-generated method stub
        String goalNo = arg[0];
        String cardNo = arg[1];
        String posDiff = arg[2];

        // Preparing post params
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("goalNo", goalNo));
        params.add(new BasicNameValuePair("cardNo", cardNo));
        params.add(new BasicNameValuePair("posDiff", posDiff));

        ServiceHandler serviceClient = new ServiceHandler();

        String json = serviceClient.makeServiceCall(URL_NEW_PREDICTION,
                ServiceHandler.POST, params);

        Log.d("Create Prediction Request: ", "> " + json);

        if (json != null) {
            try {
                JSONObject jsonObj = new JSONObject(json);
                boolean error = jsonObj.getBoolean("error");
                // checking for error node in json
                if (!error) {
                    // new category created successfully
                    Log.e("Prediction added successfully ",
                            "> " + jsonObj.getString("message"));
                } else {
                    Log.e("Add Prediction Error: ",
                            "> " + jsonObj.getString("message"));
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else {
            Log.e("JSON Data", "JSON data error!");
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
    }
}
}

This is my ServiceHandler.java page
public class ServiceHandler {

static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

public String makeServiceCall(String url, int method,
                              List<NameValuePair> params) {
    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);

            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {

            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        response = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error: " + e.toString());
    }

    return response;
}
}

This is my php server page:
<?php

$fp=fopen('filename.php','wb');
fwrite($fp, "data to be written");
fclose($fp);
if($fp)
    echo 'checkout';
else
    echo 'nothing';
exit;

include_once './DbConnect.php';//This page include db connection file

function createNewPrediction() {
     $response = array();
    $goalNum = $_POST["goalNo"];
    $cardNum = $_POST["cardNo"];
    $posDiff = $_POST["posDiff"];
            $db = new DbConnect();
   // mysql query
    $query = "INSERT INTO prediction(goalNum,cardNum,posDiff) VALUES('$goalNum','$cardNum','$posDiff')";
    $result = mysql_query($query) or die(mysql_error().'hello');
    if ($result) {
        $response["error"] = false;
        $response["message"] = "Prediction added successfully!";
        echo'succes';
    } else {
        $response["error"] = true;
        $response["message"] = "Failed to add prediction!";
    }
   // echo json response
echo json_encode($response);
}
createNewPrediction();
?>

this is my Logcat error response:
03-22 22:59:11.239 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err: org.apache.http.conn.HttpHostConnectException: Connection to http://127.0.0.1 refused
03-22 22:59:11.239 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:193)
03-22 22:59:11.239 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
03-22 22:59:11.240 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
03-22 22:59:11.240 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:366)
03-22 22:59:11.240 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
03-22 22:59:11.240 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
03-22 22:59:11.240 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
03-22 22:59:11.276 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at com.example.muralivss.tjson2_predictionactivity.ServiceHandler.makeServiceCall(ServiceHandler.java:56)
03-22 22:59:11.277 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at com.example.muralivss.tjson2_predictionactivity.PredictionActivity$AddNewPrediction.doInBackground(PredictionActivity.java:143)
03-22 22:59:11.277 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at com.example.muralivss.tjson2_predictionactivity.PredictionActivity$AddNewPrediction.doInBackground(PredictionActivity.java:120)
03-22 22:59:11.278 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
03-22 22:59:11.278 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-22 22:59:11.603 3194-3200/com.example.muralivss.tjson2_predictionactivity W/art: Suspending all threads took: 39.124ms
03-22 22:59:12.196 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
03-22 22:59:12.197 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
03-22 22:59:12.197 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
03-22 22:59:12.197 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at java.lang.Thread.run(Thread.java:818)
03-22 22:59:12.197 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err: Caused by: java.net.ConnectException: failed to connect to /127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
03-22 22:59:12.197 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:124)
03-22 22:59:12.197 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
03-22 22:59:12.198 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
03-22 22:59:12.198 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at java.net.Socket.connect(Socket.java:884)
03-22 22:59:12.198 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:124)
03-22 22:59:12.198 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:149)
03-22 22:59:12.198 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:  ... 15 more
03-22 22:59:12.198 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err: Caused by: android.system.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
03-22 22:59:12.199 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at libcore.io.Posix.connect(Native Method)
03-22 22:59:12.199 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
03-22 22:59:12.199 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
03-22 22:59:12.199 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:122)
03-22 22:59:12.199 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:  ... 20 more
03-22 22:59:12.199 3194-3270/com.example.muralivss.tjson2_predictionactivity E/Buffer Error: Error: java.lang.NullPointerException: lock == null
03-22 22:59:12.200 3194-3270/com.example.muralivss.tjson2_predictionactivity D/Create Prediction Request:: > null
03-22 22:59:12.205 3194-3270/com.example.muralivss.tjson2_predictionactivity E/JSON Data: JSON data error!
03-22 22:59:31.554 3194-3200/com.example.muralivss.tjson2_predictionactivity W/art: Suspending all threads took: 14.009ms

Any solutions provided will be Thankful.

A: Try to close your BufferedReader instance after usage: reader.close()
Besides that it looks alright. Also try to debug line-by-line breakpoints to see exactly where the error is being thrown from.

A: *

*HttpClient is deprecated now. check here for updates http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html

*Check with the following link for handling httpurlconnection , json in android. http://developer.android.com/reference/java/net/HttpURLConnection.html
http://developer.android.com/reference/android/util/JsonReader.html

*Sample code for handling json request in httpurlconnection android
http://danielnugent.blogspot.in/2015/06/updated-jsonparser-with.html

*For receiving value in php
$recValue = file_get_contents('php://input');
$json = json_decode($recValue);
$valueOne = $json["keyOne"];
for more reference check this
http://php.net/manual/en/function.json-decode.php


text:
Q: "Could not resolve dependency" error during npm install i am trying npm install but getting following error. i have tried using the   --force and --legacy-peer-deps arguments but they did not work
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: react-checkmark@1.4.0
npm ERR! Found: react@17.0.2
npm ERR! node_modules/react
npm ERR!   react@"^17.0.2" from the root project
npm ERR!   peer react@">=16.8.0" from @emotion/react@11.10.4
npm ERR!   node_modules/@emotion/react
npm ERR!     @emotion/react@"^11.10.4" from the root project
npm ERR!     peer @emotion/react@"^11.0.0-rc.0" from @emotion/styled@11.10.4
npm ERR!     node_modules/@emotion/styled
npm ERR!       @emotion/styled@"^11.10.4" from the root project
npm ERR!       3 more (@mui/material, @mui/styled-engine, @mui/system)
npm ERR!     3 more (@mui/material, @mui/styled-engine, @mui/system)
npm ERR!   46 more (@emotion/styled, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.8.6" from react-checkmark@1.4.0
npm ERR! node_modules/react-checkmark
npm ERR!   react-checkmark@"^1.4.0" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: react@16.14.0
npm ERR! node_modules/react
npm ERR!   peer react@"^16.8.6" from react-checkmark@1.4.0
npm ERR!   node_modules/react-checkmark
npm ERR!     react-checkmark@"^1.4.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\HRICK SARKAR\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\HRICK SARKAR\AppData\Local\npm-cache\_logs\2022-09-19T15_51_36_949Z-debug-0.log

A: The version of react-checkmark you have has a peer dependency of react 16.14.0 and your project is react 17.0.2. Downgrading your react version until the checkmark library is compatible with react 17 should fix your issue.


text:
Q: (keras) I want to decay learning rate when val_acc stops improving I'm trying to make CNN model, but having low accuarcy :(
So, I want to decay SGD learning rate when validation accuracy stops improving.
How can I make and compile it??

A: If you loop on model.train_on_batch you can change the learning rate manually:
import keras.backend as K
from keras.optimizers import Adam
import sys

epochs = 50
batch_size = 32
iterations_per_epoch = len(x_train) // batch_size

lr = 0.01
model.compile(optimizer=Adam(lr), loss='some loss')

min_val_loss = sys.float_info.max
for epoch in range(epochs):
    for batch in range(iterations_per_epoch):
        model.train_on_batch(x_train, y_train)
        val_loss = model.evaluate(x_val, y_val)
        if val_loss >= min_val_loss:
            K.set_value(model.optimizer.lr, lr / 2.)
            lr /= 2.
        else:
            min_val_loss = val_loss

This is a very naive way to decrease the learning rate once the validation loss had stopped decreasing. I would suggest implementing a bit more sophisticated rule such as validation loss had not decreased for the last X batches or so.


text:
Q: Validating user token from backend I am trying to verify on my backend side (node.js) user's token. Based on the official documentation docs I should download first all JWT from
https://cognito-idp.${region}.amazonaws.com/${UserPoolId}/.well-known/jwks.json
But for some reason this address doesn't exists (of course with valid region and UserPoolId). Everything should be configured well because signup, it's confirmation and login works perfectly, users are added to the pool, I've got token. Any idea what can be wrong ?

A: For me the following works to access the JWK Set (basically replaced the region and user pool id in the url above).
https://cognito-idp.us-east-1.amazonaws.com/us-east-1_O2vEE1sUF/.well-known/jwks.json
https://cognito-idp.us-east-1.amazonaws.com/us-east-1_O2vEE1sUF/ should be coming from your iss field.


text:
Q: Azure AD B2C Audit API Is there any way I can extend the audit logs from Azure Active Directory B2C, like an Api (I know AAD has it own API for this, but B2C doesn't seem to have one)?
So far, I can only see the audit logs from the Azure Console, and I'd also like to know if it's possible to get any more information such as IP for the user authentication.

A: You should be able to use the same API as AAD to get the audit logs for a B2C tenant. Currently the IP is only logged if you use the sign-in policy (not the unified sign-up or sign-in policy). I believe it is in the roadmap to change that in the coming weeks.


text:
Q: 'NoneType' object has no attribute '_meta' while changing models I am attempting to restructure my database models to include more data than django.contrib.auth.models.User. However, making the changes to models.py and views.py, then running python manage.py makemigrations doesn't properly update my migrations. Apparently, Django still thinks I'm using a proxy model.
I had to change users/migrations/0001_initial.py to avoid a dependency error, then I ran python manage.py makemigrations and got No changes detected.
users/migrations/0001_initial.py (before changes)
# Generated by Django 2.2 on 2019-05-01 03:13

from django.db import migrations
import users.managers

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('auth', '0011_update_proxy_permissions'),
    ]

    operations = [
        migrations.CreateModel(
            name='Person',
            fields=[
            ],
            options={
                'proxy': True,
                'constraints': [],
                'indexes': [],
            },
            bases=('auth.user',),
            managers=[
                ('objects', users.managers.PersonManager()),
            ],
        ),
    ]

users/migrations/0001_initial.py (after changes)
# Generated by Django 2.2 on 2019-05-01 03:13

from django.db import migrations
import users.managers

class Migration(migrations.Migration):

    initial = True

    dependencies = []

    operations = []

users/models.py (before changes)
from django.db import models
from django.contrib.auth.models import User
from . import managers

class Person(User):
    objects = managers.PersonManager()

    class Meta:
        proxy = True

users/models.py (after changes)
from django.db import models
from django.contrib.auth.models import User
from users import managers

class Profile:
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phone = models.CharField(max_length=30)
    objects = managers.ProfileManager()

users/views.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from users.models import Profile

def index(request):
    profile = Profile.objects.get(user_pk=request.session['id']) \
        if 'id' in request.session else None

    return render(request, 'users/index.html', {
        'profile': profile,
    })

def login(request):
    valid, response = Profile.objects.login_register(request, 'login')

    if not valid:
        for error in response:
            messages.error(request, error)
        return redirect('users:index')

    profile = Profile.objects.get(pk=response)
    messages.success(request, 'Welcome back, %s!' % profile.user.first_name)
    request.session['id'] = response
    return redirect('users:index')

def register(request):
    valid, response = Profile.objects.login_register(request, 'register')

    if not valid:
        for error in response:
            messages.error(request, error)
        return redirect('users:index')

    messages.success(request, 'You have successfully created an account.')
    request.session['id'] = response
    return redirect('users:index')

def logout(request):
    del request.session['id']

    messages.success(request, 'You have successfully logged out.')
    return redirect('users:index')

When I try to login or register, I expect the page to reload with the login/registration form changed to the user's profile page.
Error message
Internal Server Error: /profile/
Traceback (most recent call last):
  File "/home/matt/Repositories/pharmasseuse/env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/matt/Repositories/pharmasseuse/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/matt/Repositories/pharmasseuse/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/matt/Repositories/pharmasseuse/users/views.py", line 12, in index
    if 'id' in request.session else None
  File "/home/matt/Repositories/pharmasseuse/env/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/matt/Repositories/pharmasseuse/env/lib/python3.5/site-packages/django/db/models/query.py", line 399, in get
    clone = self.filter(*args, **kwargs)
  File "/home/matt/Repositories/pharmasseuse/env/lib/python3.5/site-packages/django/db/models/query.py", line 892, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/home/matt/Repositories/pharmasseuse/env/lib/python3.5/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/home/matt/Repositories/pharmasseuse/env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1290, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/home/matt/Repositories/pharmasseuse/env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1318, in _add_q
    split_subq=split_subq, simple_col=simple_col,
  File "/home/matt/Repositories/pharmasseuse/env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1190, in build_filter
    lookups, parts, reffed_expression = self.solve_lookup_type(arg)
  File "/home/matt/Repositories/pharmasseuse/env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1049, in solve_lookup_type
    _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
  File "/home/matt/Repositories/pharmasseuse/env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 297, in get_meta
    return self.model._meta
AttributeError: 'NoneType' object has no attribute '_meta'

Any help is appreciated.

A: I don't think its a good idea to change in migrations files. You can do the changes in model directly, and after changing the model, run ./manage.py makemigrations to generate new migration files.
Also, you need to subclass the model class from models.Model:
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phone = models.CharField(max_length=30)
    objects = managers.ProfileManager()
Update
(from comments) As your manager has been changed, I think you can proceed with either one of the following solutions:

*

*Keep both ProfileManager and PersonManager in users.manager, then run makemigrations.

*Update the migration file like this(remove managers attribute from dictionary):

# Generated by Django 2.2 on 2019-05-01 03:13

from django.db import migrations
import users.managers

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('auth', '0011_update_proxy_permissions'),
    ]

    operations = [
        migrations.CreateModel(
            name='Person',
            fields=[
            ],
            options={
                'proxy': True,
                'constraints': [],
                'indexes': [],
            },
            bases=('auth.user',),
            # managers=[
            #     ('objects', users.managers.PersonManager()),
            # ],
        ),
    ]


text:
Q: Sending image to PHP server via post I am trying to send an image from my phone gallery to the server.
but i get empty $_FILES and empty $_POST
new Thread(new Runnable() {
                @Override
                public void run() {

                    try {
                        URL url=new URL("server_url");
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("POST");

                        conn.setDoInput(true);
                        conn.setDoOutput(true);

                        conn.setRequestProperty("Connection", "Keep-Alive");
                        conn.setRequestProperty("Cache-Control", "no-cache");
                        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=");
                        conn.setReadTimeout(35000);
                        conn.setConnectTimeout(35000);

                        // directly let .compress write binary image data
                        // to the output-stream
                        OutputStream os = conn.getOutputStream();

                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);

                        os.flush();
                        os.close();

                        System.out.println("Response Code: " + conn.getResponseCode());

                        InputStream in = new BufferedInputStream(conn.getInputStream());
                        BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(in));
                        String line = "";
                        StringBuilder stringBuilder = new StringBuilder();
                        while ((line = responseStreamReader.readLine()) != null)
                            stringBuilder.append(line).append("\n");
                        responseStreamReader.close();

                        String response = stringBuilder.toString();
                       Log.d("WEDDING","response "+response);

                        conn.disconnect();
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

how should i construct the POST request for sending the image.
I have also tried to use loopj library but this doesn't help
Thank you !


text:
Q: React JS error when clicking an image for more information with Imgur API , similar to Imgur wbesite Image.jsx component , is the component rendering the BigImgurPost.jsx component which loads more information about the image.When i click one post and navigate to the route /image/:id. I get an error images.data.find is not a function ,
import { useParams } from "react-router-dom";
import { useSelector } from "react-redux";
import BigImgurPost from "../components/bigImgurPost/BigImgurPost";

function Image() {
  const { id } = useParams();
  const { images } = useSelector((state) => state.images);
  const image = images.data.find((x) => x.id === id);

   return <BigImgurPost image={image} />;
}

export default Image;

This is BigImgurPost.jsx which has the current info and i get an error
import styles from "./BigImgurPost.module.css";
import { fetchImagesVotes } from "../../redux/imageGallery/imageSlice";
import { useDispatch } from "react-redux";
import { useEffect } from "react";
import { useParams } from "react-router-dom";
import Spinner from "../spinner/Spinner";

function BigImgurPost({ image }) {
 // const { id } = useParams();
 const dispatch = useDispatch();

 useEffect(() => {
  dispatch(fetchImagesVotes(image.id));
 });

 return (
   <>

{image.title}

         {image?.images?.[0]?.type &&
         image.images[0].type.startsWith("video") ? (
           <video
            controls
            muted
            autoPlay
            className={styles.video}
            src={image.images[0].link}
           ></video>
          ) : (

          )}

         upvotes
         Downvotes
         comment

    </>
    );
    }

   export default BigImgurPost;


text: Q: How can I sync my Palm Centro phone's calender and tasks to Windows 7? Would like to stick with the Palm Centro on Verizon as it is one of the few decent smart phones with calender and tasks that doesn't require buying the data plan.  I've had luck syncing with Outlook 2000 on XP but now am moving on to Windows 7 and having a hard time.  Willing to buy a newer version of Outlook or a 3rd party tool if that's what it takes.  Not worried as much about syncing contacts but would be nice to back them up to the PC if possible.


text:
Q: How to use php's exec function to start a nodejs process I need to remotely restart the nodejs site on the server via php. It's easy to end this nodejs process, but I can't start it because of lifecycle issues. What should I do about this?
The following code is an api that can be accessed over the network to implement lookup and end nodejs.
<?php
header('Content-Type: text/plain');
$cmd = 'netstat -aon|findstr "0.0.0.0:8888"';
echo 'C:\Users\Server>'.$cmd."\n";
exec($cmd,$out);
if(!empty($out)){
    echo $out[0]."\n";
    $pid = explode(" ",$out[0]);
    $pid = intval(end($pid));
    if($pid>20){
        $cmd = 'taskkill /f /pid '.$pid;
        echo 'C:\Users\Server>'.$cmd."\n";
        exec($cmd,$out);
        echo "killed\n";
    }
}else{
    echo "notfind 8888\n";
}
$cmd = 'cmd /c E:\nodejs\run.bat';
echo 'C:\Users\Server>'.$cmd."\n";
exec($cmd);

A: I write a exe user c#. use exec function
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace run
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Diagnostics.Process.Start(@"node.exe", @"E:\nodejs\index.js");

        }
    }
}


text:
Q: ¿Cómo actualizar una dataframe con otra? Tengo una dataframe con preguntas numeradas (QID), pero esos números ya no significaban nada, otro con los números correctos. Me gustaría actualizar el ultima con los numeros correctos. Y una vez encontrada esta coincidencia, añadimos todas las columnas que faltan de df_original a df.
df es df_original con una differencia: cambio unas pocas líneas que en realidad fue títulos de QuestionGrid, con nuevas líneas que también representan las respuestas de QuestionGrid. Pueden ver como lo hice en esta pregunta. Así que debería haber más lineas en df que en df_original.
Aqui es un estracto de la dataframe original:
 >>> df_original.iloc[18:25,:10]
    QID     URL     Questions   Answers     Section     QType   Theme   Topics  Answer0     Answer1
18  17  https://docs.google.com/forms/d/1MYSjxAMCXMXB0...   What is you preference of room/suites with bal...   ['Preferred', 'Not preferred']  Consumer Intentions     Multiple Choice     Hotel ABC   ['prefer', 'room', 'suit', 'balconi']   Preferred   Not preferred
19  18  https://docs.google.com/forms/d/1MYSjxAMCXMXB0...   How do you want your guestroom to look like?    ['Contemporary style guestrooms', 'Traditional...   Consumer Intentions     Multiple Choice     Hotel ABC   ['want', 'guestroom', 'look', 'like']   Contemporary style guestrooms   NaN
20  19  https://docs.google.com/forms/d/1MYSjxAMCXMXB0...   How do you want to know about our recent offer...   ['Personalized emails', 'Text messages', 'Web ...   Media Consumption   Multiple Choice     Hotel ABC   ['want', 'know', 'recent', 'offer']     Personalized emails     Text messages
21  20  https://docs.google.com/forms/d/1MYSjxAMCXMXB0...   What are new offers you are most interested in?     ['Not Interested', 'Somewhat Interested', 'Int...   Media Consumption   Multiple Choice     Hotel ABC   ['offer', 'interest']   Not Interested  Somewhat Interested
22  21  https://docs.google.com/forms/d/1MYSjxAMCXMXB0...   How often do you want to hear on these offerings?   ['Weekly', 'Bi-Weekly', 'Monthly', 'Quarterly']     Media Consumption   Multiple Choice     Hotel ABC   ['want', 'hear', 'offer']   Weekly  Bi-Weekly
23  22  https://docs.google.com/forms/d/1MYSjxAMCXMXB0...   What medium do you prefer for any change / ca...    ['Through calls', 'Through text messages', 'Th...   Media Consumption   Multiple Choice     Hotel ABC   ['medium', 'prefer', 'chang', 'cancel', 'book']     Through calls   Through text messages
24  23  https://docs.google.com/forms/d/1MYSjxAMCXMXB0...   Gender  ['Male', 'Female', "Others (Don't Wish to Spec...   Name (Optional)     Multiple Choice     Hotel ABC   ['gender']  Male    Female

Y aqui es una parte de df:
 >>>df.iloc[23:30,:10]
        QID     Questions   QType   Answer0     Answer1     Answer2     Answer3     Answer4     Answer5
23      22  How do you want to know about our recent offer...   Multiple Choice     Personalized emails     Text messages   Web Blogs   Paper advertisements    Video advertisements    Advertisements on social media
24      23  What are new offers you are most interested in?     Question Grid   Not Interested  Somewhat Interested     Interested  Highly Interested   Very Highly Interested  NaN
25      23_1    Discount on hotel's room charges    Question Grid   Not Interested  Somewhat Interested     Interested  Highly Interested   Very Highly Interested  NaN
26      23_2    Hotel's reward points (Loyalty program)     Question Grid   Not Interested  Somewhat Interested     Interested  Highly Interested   Very Highly Interested  NaN
27      23_3    Hotel's hygiene policy  Question Grid   Not Interested  Somewhat Interested     Interested  Highly Interested   Very Highly Interested  NaN
28      23_4    Hotel medical services  Question Grid   Not Interested  Somewhat Interested     Interested  Highly Interested   Very Highly Interested  NaN
29      23_5    In-hotel services offerings     Question Grid   Not Interested  Somewhat Interested     Interested  Highly Interested   Very Highly Interested  NaN

Y me gustaria:
 >>>df.iloc[23:30,:10]
        QID     Questions   QType   Answer0     Answer1     Answer2     Answer3     Answer4     Answer5
24      20    https://docs.google.com/forms/d/1MYSjxAMCXMXB0...     What are new offers you are most interested in?     ['Not Interested', 'Somewhat Interested', 'Int...   Media Consumption   Question Grid   Not Interested  Somewhat Interested     Interested  Highly Interested   Very Highly Interested  NaN
25      20_1    https://docs.google.com/forms/d/1MYSjxAMCXMXB0...   Discount on hotel's room charges    ['Not Interested', 'Somewhat Interested', 'Int...   Media Consumption    Discount on hotel's room charges   Question Grid   Not Interested  Somewhat Interested     Interested  Highly Interested   Very Highly Interested  NaN
26      20_2    https://docs.google.com/forms/d/1MYSjxAMCXMXB0...   Hotel's reward points (Loyalty program)     ['Not Interested', 'Somewhat Interested', 'Int...   Media Consumption    Hotel's reward points (Loyalty program)    Question Grid   Not Interested  Somewhat Interested     Interested  Highly Interested   Very Highly Interested  NaN
27      20_3    https://docs.google.com/forms/d/1MYSjxAMCXMXB0...   Hotel's hygiene policy  ['Not Interested', 'Somewhat Interested', 'Int...   Media Consumption     Hotel's hygiene policy    Question Grid   Not Interested  Somewhat Interested     Interested  Highly Interested   Very Highly Interested  NaN
28      23_4    https://docs.google.com/forms/d/1MYSjxAMCXMXB0...   Hotel medical services  ['Not Interested', 'Somewhat Interested', 'Int...   Media Consumption    Hotel medical services     Question Grid   Not Interested  Somewhat Interested     Interested  Highly Interested   Very Highly Interested  NaN
29      23_5    https://docs.google.com/forms/d/1MYSjxAMCXMXB0...   In-hotel services offerings     ['Not Interested', 'Somewhat Interested', 'Int...   Media Consumption    In-hotel services offerings    Question Grid   Not Interested  Somewhat Interested     Interested  Highly Interested   Very Highly Interested  NaN

Hasta hoy intenté:
def verify_qid(row, df_original):
    for i, row_original in df_original.iterrows():
        if row_original['Questions'] == row['Questions']:
            row['QID'] = row_original['QID']
            print(type(row_original), row_original)
            for key in row_original.keys() not in row.keys():
                # si la columna ya no existe en row la puestamos
                row[key] = row_original[key]

for i, row in df.iterrows():
    qid = row['QID']
    # Verificamos qid con el de df_original
    verify_qid(row, df_original) # si la pregunta es la misma pero el QID no lo es

Pero me devuelve:
<class 'pandas.core.series.Series'> QID                                                                  0
URL                  https://docs.google.com/forms/d/1MYSjxAMCXMXB0...
Questions              When do you think your next vacation can start?
Answers              ['In next 3 months', 'In next 6 months', 'In n...
Section                                                            NaN
                                           ...
11e                                                                NaN
Sum                                                                  2
Comment              google forum seems broken at points needs to b...
Beyond repair                                                      NaN
Not scrapped well                                                  NaN
Name: 0, Length: 333, dtype: object

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-72-f7d6a63c90da> in <module>
     13     qid = row['QID']
     14     # Verificamos qid con el de df_original
---> 15     verify_qid(row, df_original) # si la pregunta es la misma pero el QID no lo es
     16
     17

<ipython-input-72-f7d6a63c90da> in verify_qid(row, df_original)
      4             row['QID'] = row_original['QID']
      5             print(type(row_original), row_original)
----> 6             for key in row_original.keys() not in row.keys():
      7                 # si la columna ya no existe en row la puestamos
      8                 row[key] = row_original[key]

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in __contains__(self, key)
   3898     @Appender(_index_shared_docs["contains"] % _index_doc_kwargs)
   3899     def __contains__(self, key) -> bool:
-> 3900         hash(key)
   3901         try:
   3902             return key in self._engine

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in __hash__(self)
   3905
   3906     def __hash__(self):
-> 3907         raise TypeError(f"unhashable type: {repr(type(self).__name__)}")
   3908
   3909     def __setitem__(self, key, value):

TypeError: unhashable type: 'Index'

Tambien intenté:
for i, row_original in df_original.iterrows():
    for i, row in df.iterrows():
        if row_original['Questions'] == row['Questions']:
            qid = str(row['QID']).split("_")
            # get the sub dataframe where the first part of the QID is the same with qid
            sub_df = df.loc[df['QID'].split("_")[0] == qid[0]] # df['QID'].split("_")[0], to get the qgrid rows
            # for each question in sub_df adapt their qid with row_original qid respecting "_" and provide the row values
            for sub_row in sub_df.iterrows():
                sub_qid = str(sub_row['QID']).split("_")
                new_qid = str(row['QID'])+"_"+sub_qid[1]
                sub_row['QID'] = new_qid
                for key in row_original.keys() not in sub_row.keys():
                    # si la columna ya no existe en row la puestamos
                    sub_row[key] = row_original[key]

Pero me devuelve:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-77-da20e669a107> in <module>
      4             qid = str(row['QID']).split("_")
      5             # get the sub dataframe where the first part of the QID is the same with qid
----> 6             sub_df = df.loc[df['QID'].split("_")[0] == qid[0]] # df['QID'].split("_")[0], to get the qgrid rows
      7             # for each question in sub_df adapt their qid with row_original qid respecting "_" and provide the row values
      8             for sub_row in sub_df.iterrows():

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
   5272             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   5273                 return self[name]
-> 5274             return object.__getattribute__(self, name)
   5275
   5276     def __setattr__(self, name: str, value) -> None:

AttributeError: 'Series' object has no attribute 'split'

Actualizacion
Tambien intenté la respuesta de ansev:
#Seleccionamos la columnas de df_original a unir
#tomamos todas las que no estan en df y adicionalmente Questions y QID
cols_original_merge = ['Questions', 'QID'] + [col for col in df_original
                                              if col not in df.columns]

#creamos una copia de df_orginal seleccionando solo las columnas
#de cols_original_merge.
#Hacemos la fusión en función de Questions.
df = df.merge(df_original[cols_original_merge], on = 'Questions', how='left')

# Se crean dos columnas QID: QID_X y QID_Y
# QID_x contiene los valores anteriores de QID
# QID_y contiene los valores nuevos de QID

# Escribimos los valores faltantes de QID_y con los valores de QID_x
# Eliminamos QID_x
# Renombramos QID_y a QID

df = (df.assign(QID_y = df['QID_y'].fillna(df['QID_x']))
        .drop('QID_x', axis=1)
        .rename({'QID_y' : 'QID'}, axis = 1)
     )

Esta es praticamente perfecto pero ciertos numeros aparecen varias veces y otras como los alfanumericos:
>>>df.head()
    QID     Questions   QType   Answer0     Answer1     Answer2     Answer3     Answer4     Answer5     Answer6     ...     10f     11a     11b     11c     11d     11e     Sum     Comment     Beyond repair   Not scrapped well
0   0   How do you feel about your next vacation after...   Checkboxes  1   2   3   4   5   6   7   ...     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
1   0   When do you think your next vacation can start?     Multiple Choice     In next 3 months    In next 6 months    In next 1 year  Only once COVID-19 is under control     Only once COVID-19 vaccine is developed     NaN     NaN     ...     NaN     NaN     NaN     1.0     NaN     NaN     2.0     google forum seems broken at points needs to b...   NaN     NaN
2   1   What are your preferences regarding medical tr...   Likert Scale    Doctor's availability in hotel  Ventilator availability in hotel    Tie-ups with nearby hospitals   Availability of medical rooms with primary fir...   NaN     NaN     NaN     ...     NaN     NaN     NaN     NaN     NaN     NaN     7.0     NaN     1.0     NaN
3   2   What is your preferences of complementary brea...   Multiple Choice     Buffet breakfast with social distancing     Buffet breakfast replaced with Ala-carte with ...   Breakfast to be delivered in room with limited...   Packaged breakfast only     NaN     NaN     NaN     ...     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
4   2   What is your preference for a in-hotel grocery...   Multiple Choice     1   2   3   4   5   6   7   ...     NaN     NaN     NaN     NaN     NaN     NaN     3.0     This could be replaced with a binary question   NaN     NaN

A: Para este tipo de tareas utlizamos DataFrame.merge
Creo que simplemente podemos hacer:
#Seleccionamos la columnas de df_original a unir
#tomamos todas las que no estan en df y adicionalmente Questions y QID
cols_original_merge = ['Questions', 'QID'] + [col for col in df_original
                                              if col not in df.columns]

#creamos una copia de df_orginal seleccionando solo las columnas
#de cols_original_merge.
#Hacemos la fusión en función de Questions.
df = df.merge(df_original[cols_original_merge], on='Questions', how='left')

# Se crean dos columnas QID: QID_X y QID_Y
# QID_x contiene los valores anteriores de QID
# QID_y contiene los valores nuevos de QID

# Escribimos los valores faltantes de QID_y con los valores de QID_x
# Eliminamos QID_x
# Renombramos QID_y a QID

df = (df.assign(QID_y = df['QID_y'].fillna(df['QID_x']))
        .drop('QID_x', axis=1)
        .rename({'QID_y' : 'QID'}, axis=1)
     )

*

*utilizamos left para conservar las filas de df donde Questions no coincide con df_original (para ninguna combinación de filas).

*Tenga en cuenta que puede resultar muy costoso computacionalmente utilizar .iterrows() aquí. Para hacer este tipo de cosas tenemos merge, join etc. Le recomiendo que consulte esta excelente pregunta (pandas merging 101) e incluso la estudie.
No he ejecutado el código para ver si funciona porque tengo dudas acerca del ejemplo y creo que deberia ser simplificado, de todas formas compruebelo y comente cualquier duda.

A: Me costo entender bastante el patrón que relaciona ambas tablas, entiendo que es algo así:
╔══════════════════╦══════════════════╦══════════════════════════════════════╗
║ Pregunta Tabla A ║ Pregunta Tabla B ║ Detalle                              ║
╠══════════════════╬══════════════════╬══════════════════════════════════════╣
║ AA               ║                  ║ Preguntas en A que no existen en B   ║
╠══════════════════╬══════════════════╬══════════════════════════════════════╣
║ BA               ║ BA               ║ Preguntas en A que existen en B      ║
╠══════════════════╬══════════════════╬══════════════════════════════════════╣
║ CD               ║ CD               ║ Caso anterior pero pregunta padre    ║
╠══════════════════╬══════════════════╬══════════════════════════════════════╣
║ CD               ║ CD_1             ║ B que no existen en A (subpreguntas) ║
╠══════════════════╬══════════════════╬══════════════════════════════════════╣
║ CD               ║ CD_2             ║ B que no existen en A (subpreguntas) ║
╠══════════════════╬══════════════════╬══════════════════════════════════════╣
║ DR               ║ DR               ║ Preguntas en A y B pero repetidas    ║
╚══════════════════╩══════════════════╩══════════════════════════════════════╝

La tabla A son las preguntas Originales. Vemos más en detalle cada caso:

*

*Preguntas en A que no existen en B: Hay varas líneas o preguntas que no existen en la tabla B, parecen ser caso particulares dónde además estas no tienen un a URL por lo que son fáciles de identificar. Por ejemplo Thinking about this callendar year, what of the following applies to you?

*Preguntas en A que existen en B, pero sin repeticiones (relación 1=1) este es el caso ideal, ya que simplemente podríamos relacionar ambas tablas, por medio de algún tipo de join basándonos en Questions como clave de la relación y usando merge(). Por ejemplo What are your preferences regarding medical treatment policy (with additional cost)?

*Pregunta en B que no existen en A (subpreguntas), en este caso hay que encontrar la relación con la pregunta "padre" y "expandir" los resultados con todas las subpreguntas. Ejemplo What are new offers you are most interested in?. Es un caso dónde no tendremos un QID en A pero hay que trasladar igualmente las filas de B con el QID_<nro>.

*Preguntas en A y B pero repetidas este podría ser como el caso 2, salvo por el hecho que la Questions es un texto que se repite en varias encuestas, por ejemplo el término Gender como texto aparece unas 17 veces. Esto es una complicación importante para resolverlo todo mediante merge(), y hay que atacarlo de otra forma
Yo creo que deberías replantear el proceso ya que en la práctica tranquilamente se podría decir que no hay forma de relacionar univocamente todas las filas de A con las de B. No al menos desde una visón relacional clásica.
¿Esto significa que no se pueden relacionar ambas tablas? No, pero tenemos que intentar una solución bastante más compleja y que puede o no funcionar del todo.
Los casos 1, 2, y 3 son relativamente sencillos de resolver, el 4 es el que necesita un poco más de trabajo, vamos a asumir para este caso, un orden secuencial de las preguntas que se repiten, de forma tal que los 17 Gender de A serán relacionados a los 17 Gender de B con el mismo orden (siempre que en ambas tablas existan la misma cantidad de filas).
La idea final sería llegar a una tabla que pueda funcionar de pivote, luego, para unir cada fila. La idea es que tenga:

*

*Questions: El texto de la pregunta

*QID_A: El QID en en el df original (salvo en el caso de las subpreguntas, dónde no existe este dato en B)

*QID_B: El QID en el df B, salvo en el caso de las preguntas que no existen en B, este en la mayoría de los casos representa el nuevo QID que buscas.

*QUID_PADRE: En el caso de las subpreguntas, para control, será el QID de la pregunta "padre".

Esta sería más o menos la idea:
import pandas as pd
import numpy as np
import os

df1 = pd.read_csv('~/Descargas/QuestionBank.csv', low_memory=False)
df2 = pd.read_csv('~/Descargas/QuestionBank_31072020_1220.csv', low_memory=False)

A = df1[ ['Questions', 'QID', 'URL']].astype(str)
B = df2[['Questions', 'QID']].astype(str)
A['Questions'] = A['Questions'].str.strip()
B['Questions'] = B['Questions'].str.strip()

# Dividimos el QID de las subpreguntas en QID y número de subpregunta
B[['QID_B','nr']] = pd.DataFrame(B.QID.str.split('_',1).tolist(),columns = ['QID_B','nr'])

 # 1. Preguntas en A que no están en B
A1 = A[~A.Questions.isin(B.Questions)].dropna()
A1 = A1[["Questions", "QID"]]
A1.columns = ["Questions", "QID_A"]
A1["QID_B"] = pd.NA
A1["QID_PADRE"] = pd.NA

# 2. Preguntas en A que están en B y no se repiten
A2 = A[A.Questions.isin(B.Questions)].dropna().groupby('Questions').filter(lambda x: len(x) == 1)
A2 = A2.merge(B, on = 'Questions', how='inner')[["Questions", "QID_x", "QID_y"]]
A2["QID_PADRE"] = pd.NA
A2.columns = ["Questions", "QID_A", "QID_B", "QID_PADRE"]

# 3. Preguntas en A que están en B y no se repiten y tienen subpreguntas
A3 = A2.merge(B[B["QID"].str.contains("_")], on = 'QID_B', how='inner')[["Questions_y", "QID_A", "QID_B", "QID"]]
A3["QID_A"] = pd.NA
A3 = A3[["Questions_y", "QID_A", "QID", "QID_B"]]
A3.columns = ["Questions", "QID_A", "QID_B", "QID_PADRE"]

# 4. Preguntas que se repiten las relacionamos si se puede de manera secuencial
A4 = pd.DataFrame(data=None, columns=A3.columns)
TMP = A[A.Questions.isin(B.Questions)].dropna().groupby('Questions').filter(lambda x: len(x) > 1)
batches = []
for _, r in TMP.iterrows():
    q = r.Questions

    a = A[A.Questions == q].reset_index()
    b = B[B.Questions == q].reset_index()

    rows_a, rows_b = a.shape[0], b.shape[0]
    if rows_a == rows_b:
        c = pd.merge(a, b, left_index=True, right_index=True)[["Questions_x", "QID_x", "QID_y"]]
        c["QID_PADRE"] = pd.NA
        c.columns = ["Questions", "QID_A", "QID_B", "QID_PADRE"]
        batches.append(c)

A4 = pd.concat(batches)

# Unimos los tres lotes
FINAL = pd.concat([A1, A2, A3, A4])

print(FINAL)

La salida de FINAL:
                                             Questions QID_A QID_B QID_PADRE
1    Thinking about this callendar year, what of th...    0R  <NA>      <NA>
6    What of the following measures, would make you...    5R  <NA>      <NA>
274  In the last two years have you stayed in any o...  267R  <NA>      <NA>
276  In the last two years how often have you staye...  268R  <NA>      <NA>
278  If you stay at ABC Hotels which type of room d...  269R  <NA>      <NA>
..                                                 ...   ...   ...       ...
6                                     How old are you?  1715  1628      <NA>
7                                     How old are you?  1895  1829      <NA>
8                                     How old are you?  2551  2443      <NA>
0                     How do you usually book a hotel?  2288  2206      <NA>
1                     How do you usually book a hotel?  2613  2509      <NA>

[4507 rows x 4 columns]

El QID_B en la mayoría de los casos (Salvo en las preguntas de A que no existen en B) es lo que deberíamos considerar como nuevo QID.
Con esta tabla "pivote" tranquilamente podrías unir las columnas de los dos df con los que arrancamos:
UNION = FINAL.merge(df1.dropna(subset=['QID']), how="left", left_on="QID_A", right_on="QID")
UNION = UNION.merge(df2.dropna(subset=['QID']), how="left", left_on="QID_B", right_on="QID")

Ten en cuenta que UNION vas a tener todas las columnas de A y de B, las columas que se repiten, tendrán un sufijo _x e _y respectivamente, si quieres que queden algunas solas en particular, simplemente agrégalas en la selección final.
Finalmente ¿Esto resuelve todos los casos?, al menos los indicados más arriba Sí, deberías analizar claro, si los casos que mencionados son todos los posibles.


text:
Q: Specifying test dependencies in pyproject.toml and getting them installed with pip install -e I have a Python project with a pyproject.toml similar to the one below. I use python build to generate an package I use to install in production environments. For development environments, I use pip install -e .
I'm trying to figure out how to make sure test dependencies are installed for development environments, but not as part of a production environment.
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

[tool.setuptools]
package-dir = {"" = "src"}
packages = [
    "package-a",
    "package-b",
]

[tool.setuptools.package-data]
"*" = [
    "path/to/*.txt"
]

[project]
name = "my-project"
version = "0.0.1"

authors = [
  { name="devnectar", email="a@b.com" },
]

description = "description goes here"
readme = "README.md"
requires-python = ">=3.10"

classifiers = [
    "Programming Language :: Python :: 3",
    "License :: OSI Approved :: MIT License",
    "Operating System :: OS Independent",
]

dependencies = [
    "dep",
    "another-dep",
    "yet-another-dep"
]

[project.optional-dependencies]
dev = [
    "tox"
]

[project.urls]
"Homepage" = "https://some_url.com"
"Bug Tracker" = "https://some_url.com"

[project.scripts]
nectarserver = "entry-point-script"

[tool.tox]
legacy_tox_ini = """
    [tox]
    min_version = 4.0
    env_list = test_env

    [testenv]
    deps = pytest
    commands = pytest -s
"""

I also tried test and tests instead of dev when trying to get this to work.
I'm running into two issues:

*

*When I run pip install -e ., tox is not installed

*The requires.txt generated by the install command ends up having a [dev] section in it, which causes pip install -r mypackage/mypackage.egg-info/requires.txt to error out. This causes other issues down the road in my build chain, which relies on requirements.txt files generated during the build to generate a Docker layer with project dependencies in it.

How should I capture the dev only dependency on tox in my pyproject.toml?

A: Extra dependencies work the same for local packages as they do for packages on PyPI; try
pip install -e .[dev]


text:
Q: Errorbar plot for Likert scale confidence values I have the following dataset, for 36 fragments in total (36 rows × 3 columns):
    Fragment    lower   upper
0   1           1       5
1   2           2       5
2   3           3       5
3   4           2       5
4   5           1       5
5   6           1       5

I've calculated these lower and upper bounds from this dataset (966 rows × 2 columns):
    Fragment    Confidence Value
0   33         4
1   26         4
2   23         3
3   16         2
4   36         3

which contains multiple instance of a fragment and an associated Confidence value.
The confidence values are data from a Likert scale, i.e. 1-5. I want to create an error bar plot, for example like this:

So on the y-axis to have each fragment 1-36 and on the x-axis to show the range/std/mean (?) of the confidence values for each fragment.
I've tried this, but it's not exactly what I want, I think using the lower and upper bounds isn't the best idea, maybe I need std/range...
#confpd is the second dataset from above
meanconfs = confpd.groupby('Fragment', as_index=False)['Confidence Value'].mean()
minconfs = confpd.groupby(Fragment', as_index=False)['Confidence Value'].min()
maxconfs = confpd.groupby('Fragment', as_index=False)['Confidence Value'].max()

data_dict = {}
data_dict['Fragment'] = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18',
                        '19','20','21','22','23','24','25','26','27','28','29','39','31','32','33','34','35','36']
data_dict['lower'] = minconfs['Confidence Value']
data_dict['upper'] = maxconfs['Confidence Value']
dataset = pd.DataFrame(data_dict)

##dataset is the first dataset I show above

for lower,upper,y in zip(dataset['lower'],dataset['upper'],range(len(dataset))):
    plt.plot((lower,upper),(y,y),'ro-',color='orange')
plt.yticks(range(len(dataset)),list(dataset['Fragment']))

The result of this code is this, which is not what I want.

Any help is greatly appreciated!!


text:
Q: I am scraping the korea flight website through api is not getting the required data I want to scrape the korea flight website which have given hidden api of contuniue flights
but when i check it in postman it works and show the results and when i try it in requests using python it show me blank records.
this is the website https://suvarnabhumi.airportthai.co.th/flight and this is the api
'https://apis.airportthai.co.th/' with request payload given in the following code:
import requests
from requests import session
import json
from pprint import pprint

headers = {
  #"Content-Type": "application/text;",
  "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36",
  "Accept" : "*/*",
  "Accept-Encoding": "gzip, deflate, br",
  "Connection": "keep-alive",
  "Accept-Language": "en-US,en;q=0.9,ur;q=0.8",
  "sec-ch-ua": 'Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"',
  "Sec-Fetch-Mode": "cors",
  "Referer": "https://suvarnabhumi.airportthai.co.th/"
}

data = {"query":"\n      query ($site: String, $type: FlightType, $search: String, $schedule_start: String, $schedule_end: String) {\n        flights(site: $site, type: $type, search: $search, schedule_start: $schedule_start, schedule_end: $schedule_end) {\n          flight_id\n          number\n          airline_id\n          aircraft_id\n          departure_scheduled_at\n          arrival_scheduled_at\n          flight_departure {\n            id\n            site_id\n            remark\n            terminal\n            gate\n            check_in_counter\n            status_color\n            estimated_at\n            actual_at\n            scheduled_at\n            updated_at\n            flight_shares\n            __typename\n          }\n          flight_arrival {\n            id\n            site_id\n            belt\n            terminal\n            remark\n            status_color\n            estimated_at\n            first_bag_at\n            last_bag_at\n            flight_shares\n            __typename\n          }\n          origin_airport {\n            id\n            name\n            city\n            iata_code\n            icao_code\n            __typename\n          }\n          destination_airport {\n            id\n            name\n            city\n            iata_code\n            icao_code\n            __typename\n          }\n          airline {\n            id\n            iata\n            icao\n            name\n            logo\n            __typename\n          }\n          aircraft {\n            id\n            name\n            iata\n            icao\n            __typename\n          }\n          updated_at\n          __typename\n        }\n      }\n      ","variables":{"site":"bkk","type":"A","search":"","schedule_start":"2021-08-24 11:49:00","schedule_end":"2021-08-24 23:59:59"}}

url = " https://apis.airportthai.co.th/"

r = requests.post(url,  data = data, headers = headers)

print(r.json())

when it run it give me blank results:
{'data': {'flights': []}}

In postman it shows all the data but here it does not work
here is the api in website

A: Try this:-
data = {"query":"query($site: String, $type: FlightType, $search: String, $schedule_start: String, $schedule_end: String) {flights(site: $site, type: $type, search: $search, schedule_start: $schedule_start, schedule_end: $schedule_end) {flight_id number airline_id aircraft_id departure_scheduled_at arrival_scheduled_at flight_departure {id site_id remark terminal gate check_in_counter status_color estimated_at actual_at scheduled_at updated_at flight_shares __typename}flight_arrival {id site_id belt terminal remark status_color estimated_at first_bag_at last_bag_at flight_shares __typename}origin_airport {id name city iata_code icao_code  __typename}destination_airport {id name city iata_code icao_code __typename}airline {id iata icao name logo  __typename}aircraft {id name iata icao __typename}updated_at __typename}}","variables":{"site":"bkk","type":"A","search":"","schedule_start":"2021-09-10 00:00:00","schedule_end":"2021-09-10 23:59:59"}}

url = " https://apis.airportthai.co.th/"

from urllib import request
import json

req = request.Request(url, method='POST')
req.add_header('Content-Type', 'application/json')
r = request.urlopen(req, data=json.dumps(data).encode())
print(r.read())

A: This worked for me.
import requests

    url = "https://apis.airportthai.co.th/"
    data = {"query":"\n      query ($site: String, $type: FlightType, $search: String,"
                    " $schedule_start: String, $schedule_end: String) {\n        "
                    "flights(site: $site, type: $type, search: $search, schedule_start: "
                    "$schedule_start, schedule_end: $schedule_end) {\n          flight_id\n         "
                    " number\n          airline_id\n          aircraft_id\n        "
                    "  departure_scheduled_at\n          arrival_scheduled_at\n         "
                    " flight_departure {\n            id\n            site_id\n           "
                    " remark\n            terminal\n            gate\n            check_in_counter\n   "
                    "         status_color\n            estimated_at\n            actual_at\n           "
                    " scheduled_at\n            updated_at\n            flight_shares\n           "
                    " __typename\n          }\n          flight_arrival {\n            id\n           "
                    " site_id\n            belt\n            terminal\n            remark\n            "
                    "status_color\n            estimated_at\n            first_bag_at\n            "
                    "last_bag_at\n            flight_shares\n            __typename\n          }\n         "
                    " origin_airport {\n            id\n            name\n            city\n            "
                    "iata_code\n            icao_code\n            __typename\n          }\n        "
                    "  destination_airport {\n            id\n            name\n            city\n            "
                    "iata_code\n            icao_code\n            __typename\n          }\n          airline {\n"
                    "            id\n            iata\n            icao\n            name\n            logo\n         "
                    "   __typename\n          }\n          aircraft {\n            id\n            name\n           "
                    " iata\n            icao\n            __typename\n          }\n          updated_at\n          "
                    "__typename\n        }\n      }\n      ",
            "variables":{"site":"bkk","type":"A","search":"","schedule_start":"2021-09-10 17:10:00","schedule_end":"2021-09-10 23:59:59"}}
    response = requests.post(url, json=data)
    print(response.json())

Probably the length of the data line is to big.
The headers you're providing are not necessary.
Also while submitting the payload use json format not row form data

A: Here is the working solution from my side:
Code:
import requests
import pandas as pd
import json

body = {"query": "\n      query ($site: String, $type: FlightType, $search: String, $schedule_start: String, $schedule_end: String) {\n        flights(site: $site, type: $type, search: $search, schedule_start: $schedule_start, schedule_end: $schedule_end) {\n          flight_id\n          number\n          airline_id\n          aircraft_id\n          departure_scheduled_at\n          arrival_scheduled_at\n          flight_departure {\n            id\n            site_id\n            remark\n            terminal\n            gate\n            check_in_counter\n            status_color\n            estimated_at\n            actual_at\n            scheduled_at\n            updated_at\n            flight_shares\n            __typename\n          }\n          flight_arrival {\n            id\n            site_id\n            belt\n            terminal\n            remark\n            status_color\n            estimated_at\n            first_bag_at\n            last_bag_at\n            flight_shares\n            __typename\n          }\n          origin_airport {\n            id\n            name\n            city\n            iata_code\n            icao_code\n            __typename\n          }\n          destination_airport {\n            id\n            name\n            city\n            iata_code\n            icao_code\n            __typename\n          }\n          airline {\n            id\n            iata\n            icao\n            name\n            logo\n            __typename\n          }\n          aircraft {\n            id\n            name\n            iata\n            icao\n            __typename\n          }\n          updated_at\n          __typename\n        }\n      }\n      ", "variables": {"site": "bkk", "type": "A", "search": "", "schedule_start": "2021-09-10 21:38:00", "schedule_end": "2021-09-10 23:59:59"}}
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36",
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "en-US,en;q=0.9,bn;q=0.8,es;q=0.7,ar;q=0.6",
    "Connection": "keep-alive",
    "Content-Length": "1843",
    "Content-Type": "application/json",
    "Host": "apis.airportthai.co.th",
    "Origin": "https://suvarnabhumi.airportthai.co.th",
    "Referer": "https://suvarnabhumi.airportthai.co.th/",
    "sec-ch-ua-mobile": "?0"
    }

url = "https://apis.airportthai.co.th/"

r = requests.post(url, data=json.dumps(body), headers=headers)
response = r.json()['data']['flights']
for resp in response:
    print(resp['number'])

OUTPUT: Example
FLIGHT NUMBER
SG 089
VZ 317
TG 466
WE 137
ZE 761
LJ 011
TG 677
TR 850
KL 820
TG 222
TG 625
ZG 051
TG 418
TG 410
WE 121
KL 804
FD 4127
TG 482
TG 585
VZ 345
TG 607
KE 651
TG 436
WE 591
VZ 2107
WE 288
TG 635
WE 268
JL 707
TG 679
OZ 741
VZ 311
FD 4303
NH 805
RJ 181
VZ 329
VZ 3971
FD 4109
LJ 001
EK 385
7C 2215
CX 617
KE 659
VZ 121


text:
Q: QuarkusTest ignores custom Maven user settings file Running a QuarkusTest fails, when Maven settings are set in a user settings file (i.e. ~/.m2/settings-custom.xml as opposed to a more standard scenario ~/.m2/settings.xml).
This is also the case when a .mvn/maven.config file with a reference to the settings file is defined at project level with contents as follows: -s /Users/johndoe/.m2/settings-custom.xml.
Also, IntelliJ has a setting, which allows setting custom Maven settings files:

That setting does not seem to work either.
Any ideas?
If I replace settings.xml with the contents of settings-custom.xml, everything works as expected.


text:
Q: Completion of incomplete claim about General Set Theory (GST) in Wiki article In the Wikipedia article on General Set Theory (GST), there is a claim in the section on metamathematics that seems to be missing a disjunct (or shouldn't be a disjunction at all):

GST is:

*

*Not finitely axiomatizable. Montague (1961) showed that ZFC is not finitely axiomatizable, and his argument carries over to GST. Hence any axiomatization of GST must either include at least one axiom schema such as Separation; [emphasis added]

My question is what is the other disjunct such that GST must "...either include at least one axiom schema such as Separation..." OR ____? Is it something like "...or the second-order closure of such a schema"? Something else? Unclear and safe to ignore? (Or is the "either" just a mistake?)

A: The "either" is likely a typo. An axiom schema is a rule for constructing an infinite number of axioms, all of which must have a given form. Not "finitely axiomatizable" means exactly what it sounds like. The set of consequences of the theory are not provable from a finite set of axioms. So here what it is saying is that it needs at least one axiom that is actually an infinite set of axioms. Sometimes the definition of "finitely axiomatizable" is actually taken to be a theory that can be axiomatized without the use of an axiom schema.


text:
Q: Sails lift error 'Cannot find module 'express/node_modules/cookie' I am trying to create my first sails app and I've followed the steps on the sails getting started (http://sailsjs.org/get-started). But when i try to do a sails lift, i get the following error:
(node:11291) fs: re-evaluating native module sources is not supported.     If you are using the graceful-fs module, please update it to a more recent   version.
module.js:442
    throw err;
^

Error: Cannot find module 'express/node_modules/cookie'
at Function.Module._resolveFilename (module.js:440:15)
at Function.Module._load (module.js:388:25)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Users/master/Desktop/Developer/NodeJS/HelloSails/node_modules/sails/lib/hooks/session/index.js:9:12)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at /Users/master/Desktop/Developer/NodeJS/HelloSails/node_modules/sails/lib/app/configuration/index.js:54:28
at Function.reduce (/Users/master/Desktop/Developer/NodeJS/HelloSails/node_modules/sails/node_modules/lodash/dist/lodash.js:3735:25)
at Configuration.defaultConfig (/Users/master/Desktop/Developer/NodeJS/HelloSails/node_modules/sails/lib/app/configuration/index.js:53:18)
at Configuration.bound [as defaults] (/Users/master/Desktop/Developer/NodeJS/HelloSails/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21)

I tried manually removing the 'node_modules' folder, inserting express as a dependency in my package.json and running 'npm install', but that did not work.
Im running  Node v6.2.2 Sail v0.10.5 and NPM v3.10.6
What am i missing here?

A: update sails version to latest, it is issue of npm structure, old version use tree level dependency while new version use same level structure
sails upgrade version

A: It's a dependency issue with npm, this worked for me when I had the issue.
npm -g install npm@latest


text:
Q: text: "intelligent" search and replace I want to do a "bulk" search and replace (notepad++) in many text files but that search and replace has to be "intelligent" and do the replacement in the following way:
I search for a pattern "source" and want to replace with "target". The search for "source" should be without check upper/lower - so the search should find "Source", "source" or "SOURCE"
The automatic replacement then should be done in the following way:
"Source" -> "Target"
"source" -> "target"
"SOURCE" -> "TARGET"

Is that possible? And if yes, how to do it?

A: Every programming language is case sensitive like python, C etc., so:
    with open("nameofdocu.txt") as f:
    data = f.read()
    change = input("Type a word you want to replace")
    if(change == Source):
      data.replace(Source,Target)
    elif(change == source):
      data.replace(source,target)
    elif(change == SOURCE)
      data.replace(SOURCE,TARGET)


text:
Q: Swift: UITextField is hidden by Keyboard I have two UItextFields on my ViewController. The first one is in the top half of the ViewController but the second one is towards the bottom.
I have managed to get the keyboard to hide on return however, When I click into the second (lower down) UItextField the keyboard comes up and covers it. This means it is no longer possible to see what you are typing.
How do I move the ViewController up when the second UItextField is clicked so that the user can see what they are typing and then move the ViewController back down when the user presses return?

A: use scrollView and scroll the textfield when keyboard will show

A: Add scrollView in your Hole View (ViewController view)
and then add notifications for hiding and showing keyboard
when keyboard will show change the scrollView Content insets by minusing keyboard hide: scrollView.ContentInsets.height - keyboard.height:
   func registerForKeyboardNotifications() {

    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIWindow.keyboardWillShowNotification, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIWindow.keyboardWillHideNotification, object: nil)
}

@objc
func keyboardWillShow(notification: NSNotification) {

    guard let keyboareRect =  notification.userInfo?[UIWindow.keyboardFrameBeginUserInfoKey] as? CGRect else { return }
    let keyboardSize = keyboareRect.size

    let insets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
    scrollView.contentInset = insets
    scrollView.scrollIndicatorInsets = insets

    var aRect = self.view.frame
    aRect.size.height -= keyboardSize.height

    guard let activeTextField = self.activeTextField else { return }

    if !aRect.contains(activeTextField.frame.origin) {
        scrollView.scrollRectToVisible(activeTextField.frame, animated: true)
    }
}

@objc
func keyboardWillHide(notification: NSNotification) {
    scrollView.contentInset = UIEdgeInsets.zero
    scrollView.scrollIndicatorInsets = UIEdgeInsets.zero
}