text:
Q: Pyqt5 qthread + signal not working + gui freeze I am trying to make a mailbox checker with imap lib, it work pretty fine with python, queue and multithread without gui.
But when I try to put a gui, every fonction i made, make the gui freeze until finish .
I tried many thing from various doc(add qthread, signal, cursorr etcc) and tutorials none worked for me .
Can someone help me to understand how to set or append a text to a QtextEdit while running a function coz it work only after finish .
Here is my code :
class Checker(QtCore.QThread):
    signal = QtCore.pyqtSignal(object)

    def __init__(self, lignesmailtocheck):
        QtCore.QThread.__init__(self)
        self.lignesmailtocheck = lignesmailtocheck

    def run(self):
            lignemailtocheck = self.lignesmailtocheck.strip()
            maillo, passo = lignemailtocheck.split(":",1)
            debmail, finmail = maillo.split("@",1)
            setimap =["oultook.com:imap-mail.outlook.com", "gmail.com:imap.gmail.com"]
            for lignesimaptocheck in sorted(setimap):
                    ligneimaptocheck = lignesimaptocheck.strip()
                    fai, imap = ligneimaptocheck.split(":",1)
                    if finmail == fai:
                            passo0 = passo.rstrip()
                            try :
                                    mail = imaplib.IMAP4_SSL(imap)
                                    mail.login(maillo, passo)
                                    mailboxok = open("MailBoxOk.txt", "a+", encoding='utf-8', errors='ignore')
                                    mailboxok.write(maillo+":"+passo+"\n")
                                    mailboxok.close()
                                    totaly = maillo+":"+passo0+":"+imap
                                    print(maillo+":"+passo+"\n")

                                    self.send_text.emit(totaly)
                                    time.sleep(1)
                            except imaplib.IMAP4.error:
                                           print ("LOGIN FAILED!!! ")
class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 300)

        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(150, 210, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.gogogo)

        self.openliste = QtWidgets.QToolButton(Form)
        self.openliste.setGeometry(QtCore.QRect(40, 110, 71, 21))
        self.openliste.setObjectName("openliste")

        self.textEdit = QtWidgets.QTextEdit(Form)
        self.textEdit.setGeometry(QtCore.QRect(170, 50, 201, 121))
        self.textEdit.setObjectName("textEdit")

        self.progressBar = QtWidgets.QProgressBar(Form)
        self.progressBar.setGeometry(QtCore.QRect(10, 260, 381, 23))
        self.progressBar.setValue(0)
        self.progressBar.setObjectName("progressBar")

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

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.pushButton.setText(_translate("Form", "PushButton"))
        self.openliste.setText(_translate("Form", "..."))

    def gogogo(self):

        mailtocheck = open('File/toCheck.txt', 'r', encoding='utf-8', errors='ignore').readlines()
        setmailtocheck = set(mailtocheck)
        for lignesmailtocheck in sorted(setmailtocheck):
            checker = Checker(lignesmailtocheck)

            thread = QThread()
            checker.moveToThread(thread)
            # connections after move so cross-thread:
            thread.started.connect(checker.run)
            checker.signal.connect(self.checkedok)
            thread.start()

    def checkedok(self, data):
        print(data)
        self.textEdit.append(data)
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

A: Since there are often questions about using QThread in PyQt, similar to yours, here is an example that shows how to correctly use threads in PyQt. I'm hoping it can be useful as a goto-answer for similar questions so I spent a bit more time than usual preparing this.
The example creates a number of worker objects that execute in non-main threads and communicate with the main (ie GUI) thread via Qt's asynchronous signals.
import time
import sys

from PyQt5.QtCore import QObject, QThread, pyqtSignal, pyqtSlot
from PyQt5.QtWidgets import QApplication, QPushButton, QTextEdit, QVBoxLayout, QWidget

def trap_exc_during_debug(*args):
    # when app raises uncaught exception, print info
    print(args)

# install exception hook: without this, uncaught exception would cause application to exit
sys.excepthook = trap_exc_during_debug

class Worker(QObject):
    """
    Must derive from QObject in order to emit signals, connect slots to other signals, and operate in a QThread.
    """

    sig_step = pyqtSignal(int, str)  # worker id, step description: emitted every step through work() loop
    sig_done = pyqtSignal(int)  # worker id: emitted at end of work()
    sig_msg = pyqtSignal(str)  # message to be shown to user

    def __init__(self, id: int):
        super().__init__()
        self.__id = id
        self.__abort = False

    @pyqtSlot()
    def work(self):
        """
        Pretend this worker method does work that takes a long time. During this time, the thread's
        event loop is blocked, except if the application's processEvents() is called: this gives every
        thread (incl. main) a chance to process events, which in this sample means processing signals
        received from GUI (such as abort).
        """
        thread_name = QThread.currentThread().objectName()
        thread_id = int(QThread.currentThreadId())  # cast to int() is necessary
        self.sig_msg.emit('Running worker #{} from thread "{}" (#{})'.format(self.__id, thread_name, thread_id))

        for step in range(100):
            time.sleep(0.1)
            self.sig_step.emit(self.__id, 'step ' + str(step))

            # check if we need to abort the loop; need to process events to receive signals;
            app.processEvents()  # this could cause change to self.__abort
            if self.__abort:
                # note that "step" value will not necessarily be same for every thread
                self.sig_msg.emit('Worker #{} aborting work at step {}'.format(self.__id, step))
                break

        self.sig_done.emit(self.__id)

    def abort(self):
        self.sig_msg.emit('Worker #{} notified to abort'.format(self.__id))
        self.__abort = True

class MyWidget(QWidget):
    NUM_THREADS = 5

    # sig_start = pyqtSignal()  # needed only due to PyCharm debugger bug (!)
    sig_abort_workers = pyqtSignal()

    def __init__(self):
        super().__init__()

        self.setWindowTitle("Thread Example")
        form_layout = QVBoxLayout()
        self.setLayout(form_layout)
        self.resize(400, 800)

        self.button_start_threads = QPushButton()
        self.button_start_threads.clicked.connect(self.start_threads)
        self.button_start_threads.setText("Start {} threads".format(self.NUM_THREADS))
        form_layout.addWidget(self.button_start_threads)

        self.button_stop_threads = QPushButton()
        self.button_stop_threads.clicked.connect(self.abort_workers)
        self.button_stop_threads.setText("Stop threads")
        self.button_stop_threads.setDisabled(True)
        form_layout.addWidget(self.button_stop_threads)

        self.log = QTextEdit()
        form_layout.addWidget(self.log)

        self.progress = QTextEdit()
        form_layout.addWidget(self.progress)

        QThread.currentThread().setObjectName('main')  # threads can be named, useful for log output
        self.__workers_done = None
        self.__threads = None

    def start_threads(self):
        self.log.append('starting {} threads'.format(self.NUM_THREADS))
        self.button_start_threads.setDisabled(True)
        self.button_stop_threads.setEnabled(True)

        self.__workers_done = 0
        self.__threads = []
        for idx in range(self.NUM_THREADS):
            worker = Worker(idx)
            thread = QThread()
            thread.setObjectName('thread_' + str(idx))
            self.__threads.append((thread, worker))  # need to store worker too otherwise will be gc'd
            worker.moveToThread(thread)

            # get progress messages from worker:
            worker.sig_step.connect(self.on_worker_step)
            worker.sig_done.connect(self.on_worker_done)
            worker.sig_msg.connect(self.log.append)

            # control worker:
            self.sig_abort_workers.connect(worker.abort)

            # get read to start worker:
            # self.sig_start.connect(worker.work)  # needed due to PyCharm debugger bug (!); comment out next line
            thread.started.connect(worker.work)
            thread.start()  # this will emit 'started' and start thread's event loop

        # self.sig_start.emit()  # needed due to PyCharm debugger bug (!)

    @pyqtSlot(int, str)
    def on_worker_step(self, worker_id: int, data: str):
        self.log.append('Worker #{}: {}'.format(worker_id, data))
        self.progress.append('{}: {}'.format(worker_id, data))

    @pyqtSlot(int)
    def on_worker_done(self, worker_id):
        self.log.append('worker #{} done'.format(worker_id))
        self.progress.append('-- Worker {} DONE'.format(worker_id))
        self.__workers_done += 1
        if self.__workers_done == self.NUM_THREADS:
            self.log.append('No more workers active')
            self.button_start_threads.setEnabled(True)
            self.button_stop_threads.setDisabled(True)
            # self.__threads = None

    @pyqtSlot()
    def abort_workers(self):
        self.sig_abort_workers.emit()
        self.log.append('Asking each worker to abort')
        for thread, worker in self.__threads:  # note nice unpacking by Python, avoids indexing
            thread.quit()  # this will quit **as soon as thread event loop unblocks**
            thread.wait()  # <- so you need to wait for it to *actually* quit

        # even though threads have exited, there may still be messages on the main thread's
        # queue (messages that threads emitted before the abort):
        self.log.append('All threads exited')

if __name__ == "__main__":
    app = QApplication([])

    form = MyWidget()
    form.show()

    sys.exit(app.exec_())

The main concepts necessary to understand multi-thread programming in PyQt are the following:

*

*Qt threads have their own event loop (specific to each thread). The main thread, aka the GUI thread, is also a QThread, and its event loop is managed by that thread.

*Signals between threads are transmitted (asynchronously) via the receiving thread's event loop. Hence responsiveness of GUI or any thread = ability to process events. E.g., if a thread is busy in a function loop, it can't process events, so it won't respond to signals from the GUI until the function returns.

*If a worker object (method) in a thread may have to change its course of action based on signals from the GUI (say, to interrupt a loop or a wait), it  must call processEvents() on the QApplication instance. This will allow the QThread to process events, and hence to call slots in response to async signals from the GUI. Note that QApplication.instance().processEvents() seems to call processEvents() on every thread, if this is not desired then QThread.currentThread().processEvents() is a valid alternative.

*A call to QThread.quit() does not immediately quit its event loop: it must wait for currently executing slot (if any) to return. Hence once a thread is told to quit, you must wait() on it. So aborting a worker thread usually involves signaling it (via a custom signal) to stop whatever it is doing: this requires a custom signal on a GUI object, a connection of that signal to a worker slot, and worker work method must call thread's processEvents() to allow the emitted signal to reach the slot while doing work.

A: I can't test because setimap is not available on my system. I renamed CheckerThread to Checker since it is no longer a thread (it just "lives" in a thread):
class Checker(QtCore.QObject):

Then just replace the contents of the loop in gogogo(self) with this:
for lignesmailtocheck in sorted(setmailtocheck):
    checker = Checker(lignesmailtocheck)

    thread = QThread()
    checker.moveToThread(thread)
    # connections after move so cross-thread:
    thread.started.connect(checker.run)
    checker.signal.connect(self.checkedok)
    thread.start()

    self.threads.append(thread)

It is almost always a good idea to decorate slots with pyqtSlot so both run and checkedok should be thus decorated.
The SO answer about Qt threads is quite handy to remind yourself of details (note however that it uses old-style connections -- you have to translate C++ connect( sender, SIGNAL(sig), receiver, SLOT(slot)); to PyQt5 sender.sig.connect(receiver.slot)).

A: Sorry for late answer but it is a technique that can solve similar problems.
The problem is clear. The GUI freezes because its thread has to do another job.
An abstracted(from the PyQt point) solution is given below:

*

*Create a class inheriting from threading.Thread which will be the worker.

*Pass to the constructor a queue(queue.Queue) as a means of communication.

*You can start the worker thread from the GUI thread and pass messages by using the queue.

*To make the GUI thread read the messages, create a QTimer with interval of your choice and register a callback function. In the callback function read the queue.

Example Code:
class Worker(threading.Thread):

    def __init__(self, queue):
        super().init()
        self.queue = queue

    def run(self):
         # Your code that uses self.queue.put(object)

class Gui:

    def __init__(self):
        self.timer = Qtimer()
        self.timer.setInterval(milliseconds)
        self.timer.timeout.connect(self.read_data)

    def start_worker(self):
        self.queue = queue.Queue()

        thr = Worker(self.queue)

        thr.start()

    def read_data(self):
        data = self.queue.get()

self.timer.timeout.connect registers the callback function.


text:
Q: add module in a layout not globaly in the nuxt.config.js How can I add a module in a layout in nuxt and it works with the same layout and its pages and components?
I have tow layouts. One of them should work with "bootstrap-vue" with some component and another should work without that.
especially for vue-bootstrap. thx in advance

A: I found the solution maybe it is useful for the others.
I added bootstrap-vue like this to my layout.
You can add more plugins if you want or the whole package.
some packages that I needed
import Vue from 'vue'
import 'bootstrap/dist/css/bootstrap.css'
import { LayoutPlugin, NavbarPlugin,CardPlugin,BAlert } from 'bootstrap-vue'
Vue.use(LayoutPlugin)
Vue.use(NavbarPlugin)
Vue.use(CardPlugin)

for all bootstrap-vue you can do like this
import Vue from 'vue'
import { BootstrapVue, IconsPlugin } from 'bootstrap-vue'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
Vue.use(BootstrapVue)
Vue.use(IconsPlugin)

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the connection's identifier when creating a TCP server? I am using node.js to create a TCP server and each connection would be persistent. Known that node.js is single process, how to tell apart each connection? Is there something like connection ID?

A: you can create one yourself
var net = require('net');

var connects_count = 0;

var server = net.createServer(function (socket) {
  socket.connectionId = connects_count;
  connects_count++;
  socket.write("Echo server\r\n");
  socket.pipe(socket);
});

server.listen(1337, "127.0.0.1");

A: socket.remoteAddress?
http://nodejs.org/docs/v0.4.8/api/net.html#net.Socket


text:
Q: Haskell program hangs when mixing compiled and interpreted code Consider the following trivial modules:
module Fail1 where
identity x = x

module Main where
import Fail1
main = print (identity 7)

I save these as Fail1.hs and Fail2.hs. If I try to run this program, all is well:
> runhaskell Fail2
7

But take a look at this:
> ghc -O2 --make Fail1
[1 of 1] Compiling Fail1     ( Fail1.hs, Fail1.o )

> runhaskell Fail2
_

The program now hangs forever, with ghc.exe consuming 100% of one CPU core. What the heck?
It gets better though:
> ghc -O2 --make Fail2
[2 of 2] Compiling Main     ( Fail2.hs, Fail2.o )

> runhaskell Fail2

Access violation in generated code when reading 0xffffffffffffffff

 Attempting to reconstruct a stack trace...

   Frame        Code address
 * 0x71fdd90    0x3d7ce28 C:\Program Files\Haskell Platform\8.6.3\bin\ghc.exe+0x397ce28

Er... wat?
Ironically, if I just run Fail2.exe itself, it works perfectly:
> Fail2
7

What in the heck is going on? Am I going mad? This really, really looks like some kind of GHC bug. Can anyone else reproduce this, or is it just my system?
> ghc --version
The Glorious Glasgow Haskell Compilation System, version 8.6.3

(Wow, OK. That really doesn't display much info. I'm running Windows 7 Pro 64-bit, and I believe I've installed the 64-bit build of GHC.)

A: This is a bug in GHC and it has been fixed in GHC 8.6.4.
I have tested it with GHC 8.6.3, GHC 8.6.4 and GHC 8.6.5 and the latter two versions work as expected.
I used the x64 Windows haskell stack, and I'm running Windows 10 with all updates installed (as of 2019-05-25.)
(For all GHC versions: wether I write runhaskell Fail2 or runhaskell Fail2.hs doesn't make any difference.)
GHC 8.6.3
this works:
stack --resolver lts-13.11 runhaskell Fail2

then I compile Fail1:
stack --resolver lts-13.11 ghc -- -O2 --make Fail1

then the original runhaskell command hangs when running Fail2.
then I compile Fail2:
stack --resolver lts-13.11 ghc -- -O2 --make Fail2

then the original runhaskell command crashes, just like the question describes it.
GHC 8.6.4
With --resolver lts-13.19 (which uses GHC 8.6.4), the commands all work as expected.
GHC 8.6.5
The same for --resolver lts-13.23 (which uses GHC 8.6.5).
Solution
Just update to the newest GHC version, or at least update to ghc 8.6.4 .


text:
Q: Good way to determine max characters to allow in user generated area on a web page I'm working on a coupon app and it has an area where business owners can enter a short "tag line" for what the coupon is for. For example:

*

*10% off one entree!

*$5 off

*2 for 1 sake before 7PM

*15 free flapjacks if your name is Gary

Again, this is user generated. It will show up on a screen their customers can see. I'd like it to display on one line within a certain amount of pixels. It will be in Arial.
What is the best way to determine the max amount of characters to allow them to include so that it doesn't take up extra lines or overflow, considering lots of browsers...?

A: If you know the font, font-size, and total width of the one line then you could just do a trial and error calculation (that is, enter characters until the end of the line).
Once you know that, you can check for the total # of characters on keyup and alert if that amount is reached.
For instance, as an example only, let's say you choose Arial 14px and you've tested it to see that 10 characters is about all that one line can hold.  Then you can add something like this
$('textarea').keyup(function(){
    if($(this).val().length == 10){
        alert('You\'ve reached the limit');
    }
});

Working Example: http://jsfiddle.net/uGDKn/


text:
Q: Not able to assign text to UITextView error when try to assign a string to the UITextView.
coding as below:-
class ViewController: UIViewController{

        @IBOutlet weak var txtResult: UITextView!

     override func viewDidLoad() {
         super.viewDidLoad()

         txtResult.text = "ABC"
     }
}

A: *

*Go to your code and delete the @IBOutlet line of code that you created

*Delete this in Storyboard:

I think you have few referencing outlets there for 1 object. You need to have only 1. So better to remove all of them.

*Add new outlet again.

*It should work.

A: Providing more error details might help to solve your issue. But you can still solve it by checking few things-:
1) Check for UITextView outlet in storyboard-:

2) Check if you have given correct class to controller . In my case it's UnderlineViewController check for yours. Your controller should have same class.
2.a) Go to storyboard click on controller and select identity inspector.
2.b) check class name.

Now add text in controller class-:
import UIKit

class UnderlineViewController: UIViewController {

    @IBOutlet weak var textViewData: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        textViewData.text = "Tushar"
        }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

OUTPUT-:

MAKE SURE YOU HAVE NO MORE THEN 1 OUTLET FOR ANY VIEW IN SIMILAR
CONTROLLER.


text:
Q: C# CSVhelper unable to write using a custom mapping I have recently moved from CSVHelper version 16.0.0 to 27.2.1. It seems to me for the CSV writer the mappings are lost as they are contained in the CSVContext now, instead of the CSVConfiguration.
I would like to use a custom Mapping to write to the CSV and not an autogenerated Mapping, is there a way to do this now?
using (StreamWriter _stream = new StreamWriter(_fileLocation))
{
  using (CsvWriter _csvWriter = new CsvWriter(_stream, CsvContext.Configuration))
  {
      _csvWriter.WriteRecords(items);
      _csvWriter.Flush();
  }
}

I added the code as context, as you can see the CSVWriter only accepts the Configuration, which no longer contains the mapping, so when I check the CSVWriter's context, there is no mapping. If I check the CSVContextitself, I do see a mapping, the custom one I made earlier.
example:
public class Foo
{
    public Guid id {get;set;}
    public string name {get;set;}
    public DateTime created {get;set;}
}

So let's say I have the class Foo as above and I create a custom class mapping using the factory so:
private static ClassMap CreateMap()
{
    Factory _factory = new Factory();

    IHasMap<Foo> _mapper = _factory.CreateClassMapBuilder<Foo>();

    _mapper.Map(x => x.id);
    _mapper.Map(x => x.name);

    return _mapper.Build();
}

And then i register the Mapping as such:
_context.RegisterClassMap(CreateMap());

I will end up with the result:
Id,name,Date
d2e0b6d5-356c-4c34-9437-92942ee9232c,SomeName,2020-01-01

but the result I want is:
Id,name
d2e0b6d5-356c-4c34-9437-92942ee9232c,SomeName

I want to make one thing clear, this was working under version 16.0.0.0

A: RegisterClassMap moved from the Configuration to the Context. You have to register it on the CsvWriter.Context.
public static void Main(string[] args)
{
    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
        // Configuration settings
    };

    using (CsvWriter _csvWriter = new CsvWriter(Console.Out, config))
    {
        var fooRecords = new List<Foo> { new Foo { id = new Guid("d2e0b6d5-356c-4c34-9437-92942ee9232c"), name = "SomeName", created = new DateTime(2020,1,1)} };

        _csvWriter.Context.RegisterClassMap(CreateMap());

        _csvWriter.WriteRecords(fooRecords);

        _csvWriter.Flush();

        Console.Read();
    }
}

public class Foo
{
    public Guid id {get;set;}
    public string name {get;set;}
    public DateTime created { get; set; }
}

private static ClassMap CreateMap()
{
    Factory _factory = new Factory();

    IHasMap<Foo> _mapper = _factory.CreateClassMapBuilder<Foo>();

    _mapper.Map(x => x.id);
    _mapper.Map(x => x.name);

    return _mapper.Build();
}


text:
Q: How can send Authorize.net slient post URL at payment page I am doing Server Integration Method (SIM)
I need to know what field i need to mention for telling authorize the payment confirmation page and silent post page.
the code below will not do silent post callback
<?php
require_once 'anet_php_sdk/AuthorizeNet.php'; // Include the SDK you downloaded in Step 2
$api_login_id = 'YOUR_API_LOGIN_ID';
$transaction_key = 'YOUR_TRANSACTION_KEY';
$amount = "5.99";
$fp_timestamp = time();
$fp_sequence = "123" . time(); // Enter an invoice or other unique number.
$fingerprint = AuthorizeNetSIM_Form::getFingerprint($api_login_id,
  $transaction_key, $amount, $fp_sequence, $fp_timestamp)
?>

<form method='post' action="https://test.authorize.net/gateway/transact.dll">
<input type='hidden' name="x_login" value="<?php echo $api_login_id?>" />
<input type='hidden' name="x_fp_hash" value="<?php echo $fingerprint?>" />
<input type='hidden' name="x_amount" value="<?php echo $amount?>" />
<input type='hidden' name="x_fp_timestamp" value="<?php echo $fp_timestamp?>" />
<input type='hidden' name="x_fp_sequence" value="<?php echo $fp_sequence?>" />
<input type='hidden' name="x_version" value="3.1">
<input type='hidden' name="x_show_form" value="payment_form">
<input type='hidden' name="x_test_request" value="false" />
<input type='hidden' name="x_method" value="cc">
<input type='submit' value="Click here for the secure payment form">
</form>

A: Okey i have found this one
x_Relay_URL for silent post handling URL
x_Receipt_Link_URL

for success page on website.


text:
Q: Slideout menu links not working I'm working on a site, http://six03.com/ART which is currently in development. I thought I had everything all wrapped up for deployment until I had gone back in 320x480 mode on mobile and none of the links on the slideout menu do not work on any mobile device I have tested, at any resolution, on any page.
I have updated and reverted back to a working copy of jQuery, I have tried z-index:1; I have thought of all I could and researched all I could with no avail. Now I am asking for some help here.
I'll do some research in here as well to see if there are any similar problems, or if anyone knows of a thread similar to this, a point in that direction would be greatly appreciated also. Thanks.

A: I'm going to assume that you mean only the 'testimonials' and 'contact' links in the menu don't work, on the homepage only.
If this is the case, your problem has nothing to do with jQuery.
Your .region element is also positioned, and so it is being rendered over the menu.
Setting nav {z-index: 1} and .region {z-index: 0} should fix the problem, as it will bring the menu over the other positioned content.

A: I ended up getting rid of the repetitive icon that I had in the menu, I didn't need it, placed a z-index: 1; on the nav container. I also changed the positioning of the menu-icon to relative instead of fixed and that fixed the problem in the mobile devices I have been able to test in.

A: unless this was a design feature, the hamburger icon is no longer on the top left and in the hero image when the desktop browser is scaled to narrow width.


text:
Q: Необходимо ли использовать AppCompatActivity Для чего Android Studio по умолчанию генерирует AppCompatActivity, когда я создаю любую активность через окно создания активностей?
На сколько я понимаю, AppCompatActivity используется для того, чтобы внедрить новые "плюшки" андроида в старые версии (будь то фрагменты в версии ниже 3-тей или материальный дизайн ниже 5-ой) и ToolBar (если я правильно понял, это тот же ActionBar).
Может есть еще какая-то задумка в генерации, даже если я ничего такого не использую, неспроста же она?

A: AppCompatActivity применяется для обратной совместимости в плане дизайна. Также ActionbarActivity с API 21 deprecated, чем подталкивают на использование AppCompatActivity. Плюс некоторые изменения "под капотом", как то использование Toolbar и пр.
Многие помешались на этом Material design, поэтому и инструмент для разработки приложений также не отстает от модных тенденций.

A: Если вам не нужны все те возможности, которые представлены библиотекой поддержки AppCompat (а их не так уж и много:Toolbar, виджеты в стиле Material Design и темы Material Design, в основном) вы можете не использовать AppCompatActivity.
При этом вы можете использовать другие библиотеки поддержки из секции v7, вроде RecyclerView, CardView, GridLayout, Pallete и пр., так как они подключаются отдельно.
Так же вы можете использовать фрагменты в версиях ниже API 10, так как они входят в библиотеку поддержки v4 Support, AppCompat просто включает в себя зависимость к этой библиотеке, поэтому подключив первую не требуется отдельно подключать вторую.
Виджет Toolbar это очень далеко не тот же ActionBar, сходство только в назначении - инструмент намного гибче и "приятнее" в использовании (с точки зрения разработчика)

A: На версиях ниже 5й можно подключить библиотеку RecyclerView. Подробнее по ссылке
[https://habrahabr.ru/post/237101/ ]


text:
Q: improving efficiency of algorithm for generating minHeaps over some interval For a given natural number n, for generating all of the min heaps for example for n=4, total heaps are 3, For a bigger value of n the limited heaps should be generated like 20-30 over reasonable interva

*

*1 2 3 4

*1 2 4 3

*1 3 2 4
I came up with the following idea to generate all heaps.
start with a loop in i from 1 to n and push i to a vector also mark it as used. Now recurse in the function and if marked continue, so in case of adding i if the parent is already greater then continue with next value as this will make an invalid heap. Please refer to below code, I think I did a terrible job explaining that. The problem is it takes too much time for n=16 or n=17. I tried to optimise it by reducing computation where the first element of the vector was anything other than 1.
I would like to have suggestions for improving its efficiency or any other algorithms to effectively generate all min Heaps.
#include <bits/stdc++.h>

using namespace std;

vector<int> v;
int n,k ;
int cnt = 0 ;
vector<int> p(100,0);

void gen(){
    if(v.size() == n){
        cnt++;
        if(cnt % k == 0){
            for(auto x : v){
                cout<<x<<" ";
            }
            cout<<endl;
        }

    }
    else{

        for(int i = 1 ; i <= n ; i++){

            if(v.size() and v[0] != 1 ){
                return ;
            }
            if(p[i])
                continue;

            int x = v.size();
            int parent ;
            if(x & 1){
                parent = (x-1)/2;
            }
            else
                parent = (x-2)/2;

            if(x==0)
                parent = 0 ;

            if(v.size() and v[parent] > i ){
                continue ;
            }

            p[i] = 1;
            v.push_back(i);
            gen();
            p[i] = 0;
            v.pop_back();
        }
    }
}
int main(){
    //ios_base::sync_with_stdio(false);cin.tie(NULL);
    cin>>n>>k;
    gen();
    cout<<"TOTAL "<<cnt<<endl;

}

A: When you're working with heaps of 10 or more items, one easy way that might work very well is to randomize an array and then use the build-heap function to turn it into a heap. Lather, rinse, repeat.
You'll have to check each time to see if the new heap matches any of the existing heaps, but if you're only generating 20 or 30 heaps, that's not going to be a huge performance problem.
I'll grant that this solution isn't the most efficient, but it should get the job done reasonably quickly.
For reference, the build-heap function:
for (int i = v.size/2; i >= 0; --i)
{
    siftDown(i);
}


text:
Q: Writing chained mutation/modification functions for Mutable Vectors So I want to create a method that works the same way as
import Data.Vector as V
import Data.Vector.Mutable as MV
import Control.Monad.ST

type DoubleVec = V.Vector Double

incrAndSwap :: DoubleVec -> Int -> Int -> Int -> DoubleVec
incrAndSwap vec i a b = runST $ do
  mvec <- V.thaw vec
  oldval <- MV.read mvec i                          -- 1
  MV.write mvec i (val + 1)                         -- 2
  MV.swap mvec a b
  V.freeze mvec

but being able to "condense" the two marked lines into one function, and be able to say:
incrAndSwap :: DoubleVec -> Int -> Int -> Int -> DoubleVec
incrAndSwap vec i a b = runST $ do
  mvec <- V.thaw vec
  incrAt mvec i
  MV.swap mvec a b
  V.freeze mvec

Basically, write that incrAt i function.
I've tried copying the type signature of MV.write but I haven't been able to get anything to work with the type signatures; nothing compiles.
Here is my most recent attempt
import Control.Monad.Primitive

type MDoubleVec s = MV.STVector s Double

incrAt :: (PrimMonad m) => MDoubleVec (PrimState m) -> Int -> m ()
incrAt mvec i = MV.write mvec i (val + 1)
  where
    val = MV.read mvec i          -- val is stuck in monad m0

But I don't know how to get val out of the monad m0 -- which it's in, apparently, according to the compiler.  Which makes sense.
Does anyone know how I can do this?

A: You need to do the MV.read inside the m monad, and bind its result to val. Basically, it is a matter of taking the two lines of the original code and moving them verbatim:
incrAt :: (PrimMonad m) => MDoubleVec (PrimState m) -> Int -> m ()
incrAt path i = do
    val <- MV.read path i
    MV.write path i (val + 1)

BTW, just for your information, the reason the type error mentions m0 as opposed to m (which might be confusing at first), is that in your code there is nothing linking the monad where val is defined to the monad where you do MV.read. But the real problem is that MV.read is monadic so you need to bind its result to be able to use it in the also monadic MV.write.


text:
Q: Cakephp 3 How to access deep contain associations in where clause? I have an issue with Cakephp 3.3 in which I do not know how to access linked data by using contain in a where clause.
Here is the request :
$cables = TableRegistry::get('cable_schedule');

    $cablemark = 'test1';
    $equipement = 'test2';
    $compartment = 'test3';
    $system = 'test4';

    $query = $cables->find('all')->contain(['CableType', 'Contract', 'EquipementSource' => ['Compartment', 'System'], 'EquipementDest' => ['Compartment', 'System']])
        ->where(['EquipementSource.Description like' => '%'.$equipement.'%'])
        ->orWhere(['EquipementDest.Description like' => '%'.$equipement.'%'])
        ->andWhere(['Cable_Mark like' => '%'.$cablemark.'%'])
        ->andWhere(['EquipementSource.Compartment.Description like' => '%'.$compartment.'%'])
        ->orWhere(['EquipementDest.Compartment.Description like' => '%'.$compartment.'%'])
        ->andWhere(['EquipementSource.System.Description like' => '%'.$system.'%'])
        ->orWhere(['EquipementDest.System.Description like' => '%'.$system.'%']);

    $this->set('cables', $query);

The error is :

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'EquipementDest.System.Description' in 'where clause'

A: You need to use the matching() method (see the CakePHP manual).
For example, if you have table articles and it has many tags, you could filter results like this:
$query = $articles->find();
$query->matching('Tags', function ($q) {
    return $q->where(['Tags.name' => 'CakePHP']);
});


text:
Q: Using built-in icons for mime type or UTI type in iOS Problem:
I would like to be able to use the built-in iOS icons for standard mime types (or UTI types) in my listing of binary file content.
Background:
I have looked into using the new (since 3.2) document architecture, but using the UIDocumentInteractionController it seems that the assumption is that the actual binaries are already on the local device.
In my case I have a file listing from a remote server and know the mime type, name, title, etc for the remote file so I just want to show a file listing with icons (the actual binary is only loaded as needed).
The meta data I get from the server contains proper mime types for the binaries so in theory I just want to get the system icon based on the type.
Work around?
I have tried the following "hack" as a proof of concept and it seems to work but this doesn't seem like the best way to go...
//Need to initialize this way or the doc controller doesn't work
NSURL*fooUrl = [NSURL URLWithString:@"file://foot.dat"];
UIDocumentInteractionController* docController = [[UIDocumentInteractionController interactionControllerWithURL:fooUrl] retain];

UIImage* thumbnail = nil;
//Need to convert from mime type to a UTI to be able to get icons for the document
NSString *uti = [NSMakeCollectable(UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, (CFStringRef)self.contentType, NULL)) autorelease];

//Tell the doc controller what UTI type we want
docController.UTI = uti;

//The doc controller now seems to have icon(s) for the type I ask for...
NSArray* icons = docController.icons;
if([icons count] > 0) {
    thumbnail = [icons objectAtIndex:0];
}
return thumbnail;

A: You can create a UIDocumentInteractionController without needing to specify a URL. The header for the class says the icons are determined by name if set, URL otherwise.
UIDocumentInteractionController* docController = [[UIDocumentInteractionController alloc] init];
docController.name = @"foo.dat";
NSArray* icons = docController.icons;
// Do something with icons
...
[docController release];

A: I tried Ben Lings's solution, but it didn't work on iOS6.1 in either the simulator or on my iPad3. You need to provide an NSURL to the UIDocumentInteractionController, but that  URL doesn't need to exist. Its last path component just needs to have the extension that you want.
The following code worked for me
NSString *extension = @"pptx"; // or something else
NSString *dummyPath = [@"~/foo" stringByAppendingPathExtension:extension]; // doesn't exist
NSURL *URL = [NSURL fileURLWithPath:dummyPath];
UIDocumentInteractionController *documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:URL];
NSArray *systemIconImages = documentInteractionController.icons;

return systemIconImages;

A: So we are talking about hacks uh? I did this by doing some bad stuff, but it's working...
I copied the icons from /system/library/frameworks/QuickLook.framework and added to my project. Inside this same folder, there is some property lists, that make the link between the UTI/extension/mime-type with the png file. With the plist and the pngs, all you have to do is make a logic to read the plists and show the correct png.


text:
Q: New Colours for SharePoint calendar overlays I would like to change a couple of the 9 OOB colours for our SharePoint calendar overlays. I can do that by overriding the calendar CSS classes.
The parent calendar div does not get this class assigned as expected:
.ms-acal-color1

Instead it gets this class only:
.ms-acal-item

...which every overlay div has so i can't override the top one without explicitly defining each other class (.ms-acal-color1 - .ms-acal-color9)
Also, I'm not sure how to change the names in this drop down to match the new colours:

A: Currently changing the colors listed in the drop down box within one site theme is not available, both in SharePoint Online and SharePoint
.ms-acal-color# {
 BACKGROUND-COLOR: #xxxxxx
}
.ms-acal-selcolor# {
 BACKGROUND-COLOR: #xxxxxx
}
.ms-acal-apanel-color# {
 BORDER-COLOR: #xxxxxx;
 BACKGROUND-COLOR: #xxxxxx;
}

The above 3 classes of styles represent one color.So to change color you have to change above CSS
http://davidlozzi.com/2012/06/20/customize-the-sharepoint-calendar-colors/

A: Ok Can you just go to your color coded calendar.Edit that page and add HTML Form webpart and inside
<style type=text\css></style>.Add following CSS
.ms-acal-color3{
 BACKGROUND-COLOR: #C0362C
}

.ms-acal-selcolor3{
 BACKGROUND-COLOR: #C0362C
}

.ms-acal-apanel-color3{
 BORDER-COLOR: #C3B7AC; BACKGROUND-COLOR: #C0362C;
}

.ms-acal-color4{
 BACKGROUND-COLOR: #816C5B
}

.ms-acal-selcolor4{
 BACKGROUND-COLOR: #816C5B
}

.ms-acal-apanel-color4{
 BORDER-COLOR: #C3B7AC; BACKGROUND-COLOR: #816C5B;
}

.ms-acal-color8{
 BACKGROUND-COLOR: #668D3C
}

.ms-acal-selcolor8{
 BACKGROUND-COLOR: #668D3C
}

.ms-acal-apanel-color8{
 BORDER-COLOR: #C3B7AC; BACKGROUND-COLOR: #668D3C;
}

.ms-acal-color9{
 BACKGROUND-COLOR: #007996
}

.ms-acal-selcolor9{
 BACKGROUND-COLOR: #007996
}

.ms-acal-apanel-color9{
 BORDER-COLOR: #C3B7AC; BACKGROUND-COLOR: #007996;
}

See if any changes are getting reflected

A: Here's the way you set it up, using color1 as an example:
.ms-acal-apanel-color1,
.ms-acal-color1 {
    background-color: #f19d00; // Orange;
}

This will change it both in the "Calendars in view" section of the Quick Launch and on the calendar itself. It took a bit of experimenting with the Web Inspector to nail it down. You can deploy an entirely new color scheme by creating a similar class for each color.


text:
Q: laravel - make an script to automatically send request as test to all api s I have some APIs that I want to test. I know that all of them working but if I want to test all together is there a way to make a test request and send it to all urls and get the response from it some how the job that we do with post man 1 by 1 I want to do it automatically for all of the routes and APIs
here is my route list :
/*************************************************
 *
 * Accommodation Api Crud
 *
 **************************************************/
Route::resource('accommodation','AccommodationController');
/*************************************************
 *
 * AccommodationFacilities Api Crud
 *
 **************************************************/
Route::resource('accommodationfacilities','AccommodationFacilityController');
/*************************************************
 *
 * AccommodationRoom Api Crud
 *
 **************************************************/
Route::resource('accommodationroom','AccommodationRoomController');
/*************************************************
 *
 * accommodationbooking Api Crud
 *
 **************************************************/
Route::resource('accommodationbooking','AccommodationBookingController');
/*************************************************
 *
 * accommodationstatuslog Api Crud
 *
 **************************************************/
Route::resource('accommodationstatuslog','AccommodationStatusLogController');
/*************************************************
 *
 * accommodationbookingstatuslog Api Crud
 *
 **************************************************/
Route::resource('accommodationbookingstatuslog','AccommodationBookingStatusLogController');
/*************************************************
 *
 * RoomCapacity History Api Crud
 *
 **************************************************/
Route::resource('roomcapacityhistory','RoomCapacityHistoryController');

A: You should read the documentation, and especially the section about testing. This is what that part of Laravel is made for!


text:
Q: CSS Rotate Transform Blurs Text I am rotating a div a small amount, but want the text inside to be straight.
I have used the following...
.content {
  padding:20px;
  background:#F9ECDA;
  transform:rotate(-2deg);
  -ms-transform:rotate(-2deg);
  -webkit-transform:rotate(-2deg);
  -webkit-backface-visibility: hidden;
}

.contentinner {
  transform:rotate(2deg);
  -ms-transform:rotate(2deg);
  -webkit-transform:rotate(2deg);
}

Note that I have used -webkit-backface-visibility: hidden; to combat the Anti Aliasing issues (jagged edges) i was experiencing in Chrome. The problem with this, is that it blurs all of my text.
Take a look at this in Chrome... http://jsfiddle.net/Collins405/a9qnmp5k/
Is there any tricks to stop the text blurring?
I considered making the background div a psuedo :before, but as its in Drupal, the content will need to adjust the height depending on how much content my client enters, and a :before element wont do that.
EDIT: Also happening in Opera, but pretty good in FF

A: use -webkit-backface-visibility: hidden; also in .contentinner


text:
Q: sliding panels in Loop, open all together I am trying to create for each member of my site a sliding panel where some infos are showed. I have no problem in showing the panels however when I click on one all of them open.
Its probably an error with the class tag as when they render they have the same class.
How can I give unique classes to the panel? Or I can I approach this issue?
My code is
$(document).ready(function(){
$(".flip").click(function(){
$(".panel").slideToggle("slow");
});
});'

'<?php if ( bp_has_members( "search_terms={$_POST['category']}")) : ?>
<?php while ( bp_members() ) : bp_the_member(); ?>

Click to slide the panel down or up

Hello world!

<?php endwhile; ?>
<?php endif; ?>

A: You can use the jQuery find method for this. You'll want to wrap the two divs in a parent div, and then use the parent method from your clicked flip class.
$(document).ready(function(){
    $(".flip").click(function(){
        $(this).parent().find(".panel").slideToggle("slow");
    });
});'

'<?php if ( bp_has_members( "search_terms={$_POST['category']}")) : ?>
<?php while ( bp_members() ) : bp_the_member(); ?>

Click to slide the panel down or up

Hello world!

<?php endwhile; ?>
<?php endif; ?>

That will:

*

*Get the parent of the clicked flip element.

*Find a panel class inside it

*Perform slideToggle on it


text:
Q: Problem understanding the proof of the principle of virtual work I'm having some trouble understanding the proof of the Principle of Virtual Work for deformable bodies. I'll give below the proof that I've read, and, next, I'll remark what I'm not understanding. I asked this question on Physics and Engineering Stack Exchange, but the answers given didn't convince me.
The first thing to remember before going through the proof is that the virtual work done by a system of virtual forces in equilibrium as a rigid body undergoes a small, compatible displacement is zero.
PROOF:
Suppose that a deformable body is in static equilibrium under the external loads of a virtual $Q$-force system.
Since the body as a whole is in equilibrium, any particular particle can be isolated and will be in equilibrium under the internal virtual $Q$ stresses developed by the external virtual $Q$ forces.
Now suppose that the body is subjected to a small change in shape caused by some other source than the virtual $Q$-force system. Owing to this change in shape, any particle might be deformed as well as translated and rotated as a rigid particle. Hence, the boundaries of such a particle would move and hence do virtual work. Let the virtual work done by the $Q$ stresses on the boundaries of the differential particle be designated by $\text{d}W_s$. Part of this virtual work will be done because of the movements of the boundaries of the particle caused by the deformation of the particle itself; this part will be called $\text{d}W_d$. The remaining part of $\text{d}W_s$ will be the virtual work done by the $Q$ stresses during the remaining part of the displacement of the boundaries and will be equal to $\text{d}W_s-\text{d}W_d$. However, this remaining is caused by the translation and rotation of the particle as a rigid body, and, as reminded above, the virtual work done in such a case is equal to zero. Hence
$$\text{d}W_s=\text{d}W_d$$
If the virtual work done by the $Q$ stresses on all particles of the body is now added, this equation becomes
$$W_s=W_d$$
To evaluate first $W_s$, we recognize that this term represents the total virtual work done by the virtual $Q$ stresses on all the boundaries of all the particles. However, for every internal boundary of a particle there is an adjoining particle whose adjacent boundary is actual the same line on the body as whole, and therefore these adjacent boundaries are displaced exactly the same amount. Since the forces acting on the two adjacent internal boundaries are numerically equal but opposite in direction, the total virtual work done on the pair of adjoining internal boundaries is zero. Hence, since all internal boundaries occur in pairs, there is no net virtual work done by the forces on all the internal boundaries. $W_s$ therefore consists only of the work done by the external $Q$ forces on the external boundaries.
$W_d$, on the other hand, was obtained by integrating the virtual work associated with deformation of the element. This work includes the effects of all forces on the element, both stress resultants and external forces. However, when an element deforms, only the stress resultants perform any work. Thus, $W_d$ represents the virtual work done by the stress resultants alone.
END OF PROOF
I understood the part concerning $W_s$.
Next, it is said that "$W_d$ represents the virtual work done by the stress resultants alone". But, according to the paragraph pertaining to $W_s$, this work should be zero, since all particle's internal boundaries occur in pairs and that one side of an internal boundary of a particle undergoes the same displacement as the common side of a neighboring particle and such two sides are subjected to equal and opposite stresses, respectively.
If we were to apply this principle according to my (flawed) conclusion, all points of the deformable body would undergo no displacement at all: a complete nonsense.
Where's the flaw in my reasoning?

A: I realized that people around here weren't really interested by my question, but I'll give an answer to it anyway, as I finally understood the proof. Here it goes:
The original proof given above is, as it should be expected, correct. But it can be made clearer if broken down in additional steps.
Consider, again, a small particle of the deformable body. The total work done by the virtual forces, $\text{d}W_t,$  system is such that $$\text{d}W_t=\text{d}W_r+\text{d}W_d$$where $\text{d}W_r$ is the work done due to the displacement of the particle as a rigid body, and $\text{d}W_d$ is the work done due to the displacement of the points on the boundaries of the particle as they deform. As said before, $\text{d}W_r=0$, and so $$\text{d}W_t=\text{d}W_d$$.
Integration of the last equation over the entire volume gives $$W_t=W_d.$$
To evaluate $W_t$ let's consider one of the internal boundaries of the particle in question. Call it boundary $B$. The total work done at such boundary by the internal virtual stresses, $\text{d}W_t^B,$ is such that  $$\text{d}W_t^B=\text{d}W_r^B+\text{d}W_d^B,$$ where $\text{d}W_r^B$ is the work done by the internal virtual stresses due to the displacement of the points of boundary $B$ as the particle undergoes a displacement as a rigid body, and $\text{d}W_d^B$ is the work done by the internal virtual stresses as boundary $B$ deforms. It should be noted that both both $\text{d}W_r^B$, $\text{d}W_d^B$ and $\text{d}W_r^B+\text{d}W_d^B$ are generally not equal to zero.
Now, for every internal boundary of a particle there is an adjoining particle whose adjacent boundary is actual the same line on the body as whole, and therefore these adjacent boundaries are displaced exactly the same amount. Since the forces acting on the two adjacent internal boundaries are numerically equal but opposite in direction, the total virtual work done on the pair of adjoining internal boundaries is zero. Hence, since all internal boundaries occur in pairs, there is no net virtual work done by the forces on all the internal boundaries. Hence, since all internal boundaries occur in pairs, there is no net virtual work done by the forces on all the internal boundaries. $W_t$ therefore consists only of the work done by the external
forces on the external boundaries.
So, what should be noted in the proof is that it is the total work done at boundary $B$ at the original particle plus the total work done at boundary $B$ of the adjoining particle that adds up to zero. If we were to consider the sum $\text{d}W_d^B + \text[{d}W_d^B]'$ ($\text[{d}W_d^B]'$ being the work done by the virtual stresses on the adjoining particle as its boundary $B$ deforms), then, for the reasons pointed by Brian Moths in his answer, such sum would not be zero.


text:
Q: Pandas Data Frame Convert Data in Long format to Wide format for specific Date Range I am trying to convert a time series data from long to wide format. The data is given below as follows.
+======+==========+======+======+
| Name |   Date   | Val1 | Val2 |
+======+==========+======+======+
| A    | 1/1/2018 |    1 |    2 |
+------+----------+------+------+
| B    | 1/1/2018 |    2 |    3 |
+------+----------+------+------+
| C    | 1/1/2018 |    3 |    4 |
+------+----------+------+------+
| D    | 1/4/2018 |    4 |    5 |
+------+----------+------+------+
| A    | 1/4/2018 |    5 |    6 |
+------+----------+------+------+
| B    | 1/4/2018 |    6 |    7 |
+------+----------+------+------+
| C    | 1/4/2018 |    7 |    8 |
+------+----------+------+------+

My end goal is to create a pivot table for a date range of 01/01/2018 to 01/04/2018. Since there is no value at dates 01/02/2018 or 01/03/2018 I would expect them to be filled with NaN. For further simplicity this is what my final table would look like:
+---+---------------+---------------+---------------+---------------+---------------+---------------+---------------+---------------+
|   | Val1.1/1/2018 | Val2.1/1/2018 | Val1.1/2/2018 | Val2.1/2/2018 | Val1.1/3/2018 | Val2.1/3/2018 | Val1.1/4/2018 | Val2.1/4/2018 |
+---+---------------+---------------+---------------+---------------+---------------+---------------+---------------+---------------+
| A | 1             | 2             | NULL          | NULL          | NULL          | NULL          |             5 |             6 |
| B | 2             | 3             | NULL          | NULL          | NULL          | NULL          |             6 |             7 |
| C | 3             | 4             | NULL          | NULL          | NULL          | NULL          |             7 |             8 |
| D | NULL          | NULL          | NULL          | NULL          | NULL          | NULL          |             4 |             5 |
+---+---------------+---------------+---------------+---------------+---------------+---------------+---------------+---------------+

There are two steps as per my understanding to get above table.
First is to fill data in long format with dates not present in range between 01/01/2018 to 01/04/2018 i.e. is 01/02/2018 and 01/03/2018.
Second and the final step would be to pivot data in wide format.
To achieve the first step I referred to this post.
As per the answer if there are similar dates in multiple rows df.reindex(date_range)would raise following error, ValueError: cannot reindex from a duplicate axis which is true and to overcome that I followed the following piece of code.
df['Date'] =  pd.to_datetime(df['Date'], format='%m/%d/%Y')
df.set_index('Date', inplace = True)

date_range = pd.date_range('2018-01-01', '2018-01-04', freq='D')
df = df.loc(date_range)

The above code goves me the following error:
TypeError: unhashable type: 'DatetimeIndex'

I resolved the above issue using this line of code
df = df.loc[date_range,:]

While the I am able to get the desired long format but Python gives a warning as follows:
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.

The above warning, I think suggests that my way of achieving the long format table with missing dates is not correct, is that correct? If yes, than how should I go about doing it? Moreover, how would I reach to to wide format table which I want as my final table?
Edit:
I've reached to the pivot table containing dates only '01/01/2018' and '01/04/2018'. Following is the piece of code.
df1 = df.pivot_table(index='Name', columns='Date', aggfunc='sum')

A: First reindex the Dataframe to add missing dates. Then pivot and combine columns.
idx = pd.MultiIndex.from_product([df.Name.unique(), pd.date_range(df.Date.min(), df.Date.max())])

df = df.set_index(['Name','Date']).reindex(idx).reset_index().rename(columns = {'level_0':'Name', 'level_1':'Date'})

df.Date = df.Date.dt.strftime('%m/%d/%Y')
new_df = df.pivot('Name', 'Date', ['Val1', 'Val2'])
new_df.columns = new_df.columns.map('.'.join)

    Val1.01/01/2018 Val1.01/02/2018 Val1.01/03/2018 Val1.01/04/2018 Val2.01/01/2018 Val2.01/02/2018 Val2.01/03/2018 Val2.01/04/2018
Name
A   1.0             NaN             NaN              5.0            2.0 NaN NaN 6.0
B   2.0             NaN             NaN              6.0            3.0 NaN NaN 7.0
C   3.0             NaN             NaN              7.0            4.0 NaN NaN 8.0
D   NaN             NaN             NaN              4.0            NaN NaN NaN 5.0


text:
Q: Solr: Facet one field with two outputs I'm using Solr for indexing products and organising them into several categories. Each document has a taxon_names multi value field, where the categories are stored as human readable strings for a product.
Now I want to fetch all the categories from Solr and display them with clickable links to the user, without hitting the database again. At index time, I get the permalinks for every category from the MySQL database, which is stored as a multi value field taxon_permalinks. For generating the links to the products, I need the human readable format of the category and its permalink (otherwise you would have such ugly URLs in your browser, when just using the plain human readable name of the category, e.g. %20 for space).
When I do a facet search with http://localhost:8982/solr/default/select?q=*%3A*&rows=0&wt=xml&facet=true&facet.field=taxon_names, I get a list of human readable taxons with its counts. Based on this list, I want to create the links, so that I don't have to hit the database again.
So, is it possible to retrieve the matching permalinks from Solr for the different categories? For example, I get a XML like this:
<response>
<lst name="responseHeader">
  <int name="status">0</int>
  <int name="QTime">0</int>
</lst>
<result name="response" numFound="6580" start="0"/>
  <lst name="facet_counts">
  <lst name="facet_queries"/>
  <lst name="facet_fields">
  <lst name="taxon_names">
    <int name="Books">2831</int>
    <int name="Music">984</int>
      ...
  </lst>
</result>

And inside the taxon_names array I would need the name of the permalink.
Maybe it's possible by defining a custom field type in the config XMLs. But for this, I don't have enough experience with Solr.

A: Since it appears from your description that you are faceting permalink in the taxon_permalink field and the values in that field should correspond to the same category names in the taxon_names field. Solr allows you to facet on multiple fields, so you can just facet on both fields and walk the two facet results grabbing the display name from the taxon_names facet values and the permalink from the taxon_permalink facet values.
Query:
 http://localhost:8982/solr/default/selectq=*%3A*&rows=0&wt=xml
   &facet=true&facet.field=taxon_names&facet.field=taxon_permalink

Your output should then look like similar to the following:
<response>
<lst name="responseHeader">
  <int name="status">0</int>
  <int name="QTime">0</int>
</lst>
<result name="response" numFound="6580" start="0"/>
  <lst name="facet_counts">
  <lst name="facet_queries"/>
  <lst name="facet_fields">
  <lst name="taxon_names">
    <int name="Books">2831</int>
    <int name="Music">984</int>
      ...
  </lst>
  <lst name="taxon_permalink">
    <int name="permalink1">2831</int>
    <int name="permalink2">984</int>
      ...
  </lst>
</result>


text:
Q: Multiple Category Search I'm trying to create a search feature that will allow users to enter a search term and select a couple of categories. The script searches a single category just fine, but when I add more than one I hit a roadblock.
My code is as follows:
<form method="get" id="searchform" action="<?php echo home_url(); ?>">
    <input type="text" onclick="this.value='';" onfocus="this.select()" onblur="this.value=!this.value?'Search...':this.value;" value="Search..." name="s" id="s" />
    <input type="hidden" name="post_type" value="product" />
    <?php wp_dropdown_categories('taxonomy=product_cat&id=make&child_of=15&show_option_all=Select Make...'); ?>
    <?php wp_dropdown_categories('taxonomy=product_cat&id=model&child_of=21&show_option_all=Select Model...'); ?>
    <input type="submit" id="searchsubmit" value="Search" />
</form>

As I was searching around I discovered: Wordpress Multiple Category Search, which seems to do exactly what I want...however I'm not sure how to incorporate the suggestion.
I'm pretty sure you add the following to your functions file:
add_action( 'parse_request', 'category_search_logic', 11 );
function category_search_logic( $query ) {

    if ( ! isset( $query->query_vars[ 'cat' ] ) )
        return $query;

    // split cat query on a space to get IDs separated by '+' in URL
    $cats = explode( ' ', $query->query_vars[ 'cat' ] );

    if ( count( $cats ) > 1 ) {
        unset( $query->query_vars[ 'cat' ] );
        $query->query_vars[ 'category__and' ] = $cats;
    }

    return $query;
}

But, how do I incorporate this into the search form? I'm sure it's something simple, but I'm lost...anyone have any ideas?
Thanks,
Josh

A: I found the solution...
My functions page now looks like:
<?php
    class dropdown extends Walker_CategoryDropdown {
        function start_el(&$output, $category, $depth, $args) {
            $pad = str_repeat(' ', $depth * 3);
            $cat_name = apply_filters( 'list_cats', $category->name, $category );
            $output .= "\t<option class=\"level-$depth\" value=\"".$category->slug."\"";
            $output .= '>';
            $output .= $pad.$cat_name;
            if ( $args['show_count'] )
                $output .= '  ('. $category->count .')';
            if ( $args['show_last_update'] ) {
                $format = 'Y-m-d';
            $output .= '  ' . gmdate($format, $category->last_update_timestamp);
            }
            $output .= "</option>\n";
        }
    }
?>

My form now looks like:
<form method="get" id="searchform" action="<?php echo home_url(); ?>">
    <input type="text" onclick="this.value='';" onfocus="this.select()" onblur="this.value=!this.value?'Product Search...':this.value;" value="Product Search..." name="s" id="s" class="left" />
    <input type="image" src="<?php bloginfo('template_directory') ?>/images/icosearch.png" id="searchsubmit" value=""/>
    <?php
        wp_dropdown_categories(
            array(
                'child_of' => 426,
                'class' => 'styled',
                'id' => 'make',
                'name' => 'make',
                'show_option_all' => 'Make...',
                'taxonomy' => 'product_cat',
                'walker' => new dropdown
            ))
    ?>
    <?php
        wp_dropdown_categories(
            array(
                'child_of' => 427,
                'class' => 'styled',
                'id' => 'model',
                'name' => 'model',
                'show_option_all' => 'Model...',
                'taxonomy' => 'product_cat',
                'walker' => new dropdown
            ))
    ?>
</form>

My search page now looks like:
<?php
    $tmp[]=$_GET["model"];
    $tmp[]=$_GET["make"];
    $product_cat=array();
    foreach($tmp as $v) {
        if($v!="0")
        $product_cat[]=$v;
    }
    if(count($product_cat)>0) {
        $product_cat="&product_cat=".implode(",",$product_cat);
    }
    else {
        $product_cat="";
    }
    $query=query_posts("s=$text".$product_cat);
    $count =count($query);
    if ($count == 0) {
        echo 'No Results';
    }
    elseif ($count == 1) {
        echo ''.$count.' Result';
    }
    else {
        echo ''.$count.' Results';
    }
?>


text:
Q: Is it safe to uninstall everything associated with MySql? I've started learning php recently and will be using MySql. But I have a lot of MySql 'things' installed on my computer (in the screenshot). I want to completely uninstall everything and have XAMPP handle whatever is needed. I want to know would it be a good practice to do so and is it actually safe to remove everything, making sure that nothing would break and is there a way to check if some software depends on any of those?

A: Your Version is very old, so update it urgently.
You only need the Server and the shell.
Workbench is helpful as it provides a gui, even when phpmyadmin doesn't work.
If you decide to use Java c++ or other languages you can always come back and install them again. Them same goes for samples and Documentation


text:
Q: Intersection of multiple arrays in PostgreSQL I have a view defined as:
 CREATE VIEW View1 AS
 SELECT Field1, Field2, array_agg(Field3) AS AggField
 FROM Table1
 GROUP BY Field1, Field2;

What I would like to do is get the intersection of the arrays in AggField with something like:
SELECT intersection(AggField) FROM View1 WHERE Field2 = 'SomeValue';

Is this at all possible, or is there a better way to achieve what I want?

A: The closest thing to an array intersection that I can think of is this:
select array_agg(e)
from (
    select unnest(a1)
    intersect
    select unnest(a2)
) as dt(e)

This assumes that a1 and a2 are single dimension arrays with the same type of elements. You could wrap that up in a function something like this:
create function array_intersect(a1 int[], a2 int[]) returns int[] as $$
declare
    ret int[];
begin
    -- The reason for the kludgy NULL handling comes later.
    if a1 is null then
        return a2;
    elseif a2 is null then
        return a1;
    end if;
    select array_agg(e) into ret
    from (
        select unnest(a1)
        intersect
        select unnest(a2)
    ) as dt(e);
    return ret;
end;
$$ language plpgsql;

Then you could do things like this:
=> select array_intersect(ARRAY[2,4,6,8,10], ARRAY[1,2,3,4,5,6,7,8,9,10]);
 array_intersect
-----------------
 {6,2,4,10,8}
(1 row)

Note that this doesn't guarantee any particular order in the returned array but you can fix that if you care about it. Then you could create your own aggregate function:
-- Pre-9.1
create aggregate array_intersect_agg(
    sfunc    = array_intersect,
    basetype = int[],
    stype    = int[],
    initcond = NULL
);

-- 9.1+ (AFAIK, I don't have 9.1 handy at the moment
-- see the comments below.
create aggregate array_intersect_agg(int[]) (
    sfunc = array_intersect,
    stype = int[]
);

And now we see why array_intersect does funny and somewhat kludgey things with NULLs. We need an initial value for the aggregation that behaves like the universal set and we can use NULL for that (yes, this smells a bit off but I can't think of anything better off the top of my head).
Once all this is in place, you can do things like this:
> select * from stuff;
    a
---------
 {1,2,3}
 {1,2,3}
 {3,4,5}
(3 rows)

> select array_intersect_agg(a) from stuff;
 array_intersect_agg
---------------------
 {3}
(1 row)

Not exactly simple or efficient but maybe a reasonable starting point and better than nothing at all.
Useful references:

*

*array_agg

*create aggregate

*create function

*PL/pgSQL

*unnest

A: The accepted answer did not work for me.  This is how I fixed it.
create or replace function array_intersect(a1 int[], a2 int[]) returns int[] as $$
declare
  ret int[];
begin
  -- RAISE NOTICE 'a1 = %', a1;
  -- RAISE NOTICE 'a2 = %', a2;
  if a1 is null then
    -- RAISE NOTICE 'a1 is null';
    return a2;
  -- elseif a2 is null then
  --    RAISE NOTICE 'a2 is null';
  --    return a1;
  end if;
  if array_length(a1,1) = 0 then
    return '{}'::integer[];
  end if;
  select array_agg(e) into ret
  from (
    select unnest(a1)
    intersect
    select unnest(a2)
  ) as dt(e);
  if ret is null then
    return '{}'::integer[];
  end if;
  return ret;
end;
$$ language plpgsql;

A: It is bit late to answer this question but maybe somebody will need it so I decided to share something I wrote cause did not found any ready solution for intersection of any number of arrays. So here it is. This function receives array of arrays, if it is only single array, function returns first array, if there are 2 arrays function intersects 2 arrays and returns result, if it is more that 2 arrays, function takes intersection of 2 first arrays, stores it in some  variable and loops through all other arrays, intersect each next array with stored result and stores result in variable. if result is null it exists with null. In the and the variable that stores array with interacted data returned from the function.
CREATE OR REPLACE FUNCTION array_intersected(iarray bigint[][])
  RETURNS bigint[] AS
$BODY$
    declare out_arr bigint[]; set1 bigint[]; set2 bigint[];
    BEGIN
        --RAISE NOTICE '%', array_length(iarray, 1);
        if array_length(iarray, 1) = 1 then
            SELECT ARRAY(SELECT unnest(iarray[1:1])) into out_arr;
        elseif array_length( iarray, 1) = 2 then
            set1 := iarray[1:1];
            set2 := iarray[2:2];
            SELECT ARRAY(SELECT unnest(set1) INTERSECT SELECT unnest(set2))into out_arr;
        elseif array_length(iarray, 1) > 2 then
            set1 := iarray[1:1];
            set2 := iarray[2:2];
            --exit if no common numbers exists int 2 first arrays
            SELECT ARRAY(SELECT unnest(set1) INTERSECT SELECT unnest(set2))into out_arr;
            if out_arr = NULL then
                EXIT;
                END IF;
            FOR i IN 3 .. array_upper(iarray, 1)
            LOOP
               set1 := iarray[i:i];
               SELECT ARRAY(SELECT unnest(set1) INTERSECT SELECT unnest(out_arr))into out_arr;
               if out_arr = NULL then
                EXIT;
                   END IF;
            END LOOP;
        end if;

    return out_arr;

    END;
    $BODY$
  LANGUAGE plpgsql VOLATILE;

Here is the code to validate it works.
select array_intersected(array[[1, 2]]::bigint[][]);

select array_intersected(array[[1, 2],[2, 3]]::bigint[][]);

select array_intersected(array[[1, 2],[2, 3], [2, 4]]::bigint[][]);

select array_intersected(array[[1, 2, 3, 4],[null, null, 4, 3], [3, 1, 4, null]]::bigint[][]);


text:
Q: java.lang.ClassNotFoundException after changed envinroment I got this exception after I change my environment from Eclipse on Ubuntu to Eclipse on Win10. I think this should not be a problem since I imported the project without any change.
SEVERE: Servlet [Jersey Web Application] in web application [/myProject-rest] threw load() exception
java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1305)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1139)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:518)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:499)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1102)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1038)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4996)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

The subsequent error when I try to request the index.jsp at localhost:8080/myProject-rest/
SEVERE: Servlet.service() for servlet [jsp] in context with path [/myProject-rest] threw exception [The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application] with root cause
    org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application
        at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:55)
        at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:277)
        at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:75)
        at org.apache.jasper.compiler.TagLibraryInfoImpl.generateTldResourcePath(TagLibraryInfoImpl.java:243)
        at org.apache.jasper.compiler.TagLibraryInfoImpl.<init>(TagLibraryInfoImpl.java:124)
        at org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:421)
        at org.apache.jasper.compiler.Parser.parseDirective(Parser.java:479)
        at org.apache.jasper.compiler.Parser.parseElements(Parser.java:1435)
        at org.apache.jasper.compiler.Parser.parse(Parser.java:139)
        at org.apache.jasper.compiler.ParserController.doParse(ParserController.java:227)
        at org.apache.jasper.compiler.ParserController.parse(ParserController.java:100)
        at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:199)
        at org.apache.jasper.compiler.Compiler.compile(Compiler.java:356)
        at org.apache.jasper.compiler.Compiler.compile(Compiler.java:336)
        at org.apache.jasper.compiler.Compiler.compile(Compiler.java:323)
        at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:585)
        at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:363)
        at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
        at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Unknown Source)

I report my configuration:
The pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>myProject-rest</groupId>
  <artifactId>myProject-rest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-bundle</artifactId>
        <version>1.19</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-server</artifactId>
        <version>1.19</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-core</artifactId>
        <version>1.19</version>
    </dependency>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20141113</version>
    </dependency>
    <dependency>
        <groupId>asm</groupId>
        <artifactId>asm</artifactId>
        <version>3.3.1</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.15</version>
        <exclusions>
            <exclusion>
                <groupId>com.sun.jdmk</groupId>
                <artifactId>jmxtools</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.jmx</groupId>
                <artifactId>jmxri</artifactId>
            </exclusion>
            <exclusion>
                <groupId>javax.jms</groupId>
                <artifactId>jms</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.3.10.Final</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.5.4</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.5.4</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.5.4</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-json-provider</artifactId>
        <version>2.5.4</version>
    </dependency>
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
        <dependency>
        <groupId>org.mindrot</groupId>
        <artifactId>jbcrypt</artifactId>
        <version>0.3m</version>
    </dependency>
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.10</version>
    </dependency>
</dependencies>
</project>

web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>myProject-web</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
             <param-name>com.sun.jersey.config.property.packages</param-name>
             <param-value>it.myProject.service;org.codehaus.jackson.jaxrs</param-value>
        </init-param>
     </servlet>
</web-app>

Index.jsp file:
<%@ page pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

Any idea?


text:
Q: FLAG_ACTIVITY_NEW_TASK doesn't open previous activity but only on fresh apk install I am developing an android library which uses FCM to receive a notification in the background. Upon tapping the notification, the user should be redirected to the last open activity - not the launch activity. I use the flag FLAG_ACTIVITY_NEW_TASK to accomplish this, and the app works as expected in two cases: 1. if I build the app directly over USB in android studio, and 2. If I download and install an .apk of the app, kill the app, and then restart it.
However, if I install the application as an .apk, I get the following behavior:
1. The app opens on the launch activity A.
2. I navigate to activity B and put the app in the background
3. I receive a notification and tap on it. The app opens on activity A instead of activity B as expected.
I don't understand the difference between installing the application as an apk and installing it over usb. Is there some difference in the activity that makes FLAG_ACTIVITY_NEW_TASK treat it like a separate activity? Here's my code:
    Intent packageIntent = applicationContext.getPackageManager().getLaunchIntentForPackage(packageName);
    String mainClassName = packageIntent.getComponent().getClassName();
    Intent intent = new Intent(applicationContext, NotificationTapService.class);

(Note that the reason I'm setting up an intermediate intent that launches a service to reopen the last activity is because the service also calls some unrelated analytics functionality)
    PendingIntent pendingIntent = PendingIntent.getService(applicationContext, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
    NotificationCompat.Builder notificationBuilder =
    new NotificationCompat.Builder(applicationContext, applicationContext.getString(R.string.channel_id))
        .setSmallIcon(notificationResourceId)
        .setContentTitle(messageTitle)
        .setContentText(messageBody)
        .setStyle(new NotificationCompat.BigTextStyle()
            .bigText(messageBody))
        .setSound(defaultSoundUri)
        .setVibrate(new long[] {1000, 1000, 1000, 1000, 1000})
        .setLights(Color.BLUE, 3000, 3000)
        .setContentIntent(pendingIntent)
        .setAutoCancel(true)
        .setPriority(NotificationCompat.PRIORITY_MAX);
    NotificationManager notificationManager = (NotificationManager) applicationContext.getSystemService(applicationContext.NOTIFICATION_SERVICE);
    notificationManager.notify(messageId, notificationBuilder.build());

(setting up the intent to reopen the activity at the top of the back stack) (from NotificationTapService)
    Intent activityIntent = new Intent(applicationContext, Class.forName(intent.getExtras().getString(CLASS_NAME)));
    activityIntent.setAction(Intent.ACTION_MAIN);
    activityIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(activityIntent);


text:
Q: waiting until recover value I am trying to develop an offline mobile application using the PhoneGap framework. I am using the sqlite PhoneGap to access my local database.
My application uses 2 table, Table 1 contains values and contains an identifier of the value in Table 2, to display the data I have to wait recuperation values of table 2 with the function recover_type_client passing the value of  IdClient
how can I wait until I retrieve value TXT to display
function successDB(tx, results)
{
    for( var i=0; i<results.rows.length; i++  )
    {
        TXT = recover_type_client(results.rows.item(i).IdClient )//Function
        $("#tbod").append('
<input type="checkbox" name="vehicle" value="'+results.rows.item(value).IdPrestation+'">	'
                        +' '+results.rows.item(value).RefPrestation                                               +' 	'
                        +' '+TXT                                                                      +' 	'
                        +' '+results.rows.item(value).CoordonneesAdressePrestation                                +' 	'
                        +' '+tab_client[i]
                        +'
');
    }
}

A: you have use
   results.rows.item(value).IdPrestation

But value is not defined


text:
Q: Python открыть независимый сопроцесс (cmd) Мне нужно, чтобы я смог запустить новое окно CMD(terminal или xterm), где смог бы запуститься другой python модуль, причем, чтобы главная программа продолжила работу. Решение нужно универсальное для Windows и Linux. (скрипт для выполнения второй CMD лежит в той же директории. Parent.py - основная программа, Child.py - вторая программа).

A:
причем что бы главная программа продолжила работу.

Чтобы запустить внешнюю команду, не дожидаясь её окончания:
import subprocess

command = ['программа', 'первый аргумент', 'второй']
p = subprocess.Popen(command)
# ... основная программа

обратите внимание функции в subprocess модуле (в отличии от os.system()) не запускают shell, если вы явно не попросите, поэтому к примеру, для внутренних команд CMD таких как START необходимо явно CMD запускать.
Этот вызов работает как на *nix так и на Windows.
Существует несколько градаций (спектр) "независимости" процесса (вплоть до демона/системного сервиса). См. Запустить независимый скрипт Python из другого скрипта.

Если вы хотите графическое окно открыть и в нём запустить команду:
import platform
import subprocess

# define a command that starts new terminal
if platform.system() == "Windows":
    new_window_command = "cmd.exe /c start".split()
else:
    new_window_command = "x-terminal-emulator -e".split()

subprocess.check_call(new_window_command + command)

*

*How can I open two consoles from a single script

*keep multiple console windows open from batch

Если вы хотите Питон-код в отдельном процессе выполнить, то можно использовать sys.executable, чтобы тот же исполняемый файл, что и текущий Питон-интерпретатор, запустить.
Чтобы найти путь к файлу относительно текущего скрипта, есть функции (такие как get_script_dir()), которые могут помочь:
import os
import sys

command = [sys.executable, os.path.join(get_script_dir(), 'do_something.py'),
           'other', 'args']

Если модуль, который вы хотите запустить, находится в sys.path, то можно -m ключ  использовать:
command = [sys.executable, '-m', 'do_something', 'other', 'args']

Вместо запуска как независимого скрипта, вы можете импортировать соответствующий модуль и вызвать функции из него, используя multiprocessing модуль:
#!/usr/bin/env python
import multiprocessing as mp
import do_something

if __name__ == '__main__':
   mp.Process(target=do_something.main, args=['other', 'args']).start()
   # ... основная программа

См. Calling a python script with input within a python script using subprocess.

A: Можете попробовать стандартным методом.
import os

os.system('x-terminal-emulator -e python test.py')

subprocess.Popen лучше, но не на всех системах работает почему-то


text:
Q: Step function exceeding the maximum number of characters service limit My state in a step function flow returns an error of state/task returned a result with a size exceeding the maximum number of characters service limit.. In the step function documentation, the limit for characters for input/output is 32,768 characters. Upon checking the total characters of my result data if falls below the limit. Are there any other scenarios that it will throw that error? Thanks!

A: 2020-09-29 Edit: Step Functions now supports 256KB payloads!
256KB is the maximum size of the payload that can be passed between states. You could also exceed this limit from a Map or Parallel state, whose final output is an array with the output of each iteration or branch.
https://aws.amazon.com/about-aws/whats-new/2020/09/aws-step-functions-increases-payload-size-to-256kb
The recommended solution from the Step Functions documentation is to store the data somewhere else (e.g. S3) and pass around the ARN instead of raw JSON.
https://docs.aws.amazon.com/step-functions/latest/dg/avoid-exec-failures.html
You can also use OutputPath to reduce the  output to the fields you want to pass to the next state.
https://docs.aws.amazon.com/step-functions/latest/dg/input-output-outputpath.html


text:
Q: The intersection complex and the Cohen-Macaulay property Let $\Delta:Y\rightarrow X$ a closed immersion of $k$-schemes of finite type and equidimensionnal.
We assume that $\Delta^{*}[-d]IC_{X}=IC_{Y}$, if $X$ is Cohen-Macaulay, does it imply that $Y$ is Cohen-Macaulay?


text:
Q: when i run the code i get this error UnboundLocalError: local variable 'cursor' referenced before assignment So I am a newbie but working on flask/MYSQL
I am receiving this error (UnboundLocalError: local variable 'cursor' referenced before assignment)
After hours of playing with the code and research I need your help.
how can i solve this error
This is my file, please let me know if there's anything else I need to share. thank you
import pymysql
from app import app
from db_config import mysql
from flask import flash, session, render_template, request, redirect, url_for
#from werkzeug import generate_password_hash, check_password_hash
from werkzeug.security import generate_password_hash, check_password_hash

@app.route('/add', methods=['POST'])
def add_product_to_cart():
    cursor = None
    try:
        _quantity = int(request.form['quantity'])
        _code = request.form['code']
        # validate the received values
        if _quantity and _code and request.method == 'POST':
            conn = mysql.connect()
            cursor = conn.cursor(pymysql.cursors.DictCursor)
            cursor.execute("SELECT * FROM product WHERE code=%s", _code)
            row = cursor.fetchone()

            itemArray = { row['code'] : {'name' : row['name'], 'code' : row['code'], 'quantity' : _quantity, 'price' : row['price'], 'image' : row['image'], 'total_price': _quantity * row['price']}}

            all_total_price = 0
            all_total_quantity = 0

            session.modified = True
            if 'cart_item' in session:
                if row['code'] in session['cart_item']:
                    for key, value in session['cart_item'].items():
                        if row['code'] == key:
                            #session.modified = True
                            #if session['cart_item'][key]['quantity'] is not None:
                            #   session['cart_item'][key]['quantity'] = 0
                            old_quantity = session['cart_item'][key]['quantity']
                            total_quantity = old_quantity + _quantity
                            session['cart_item'][key]['quantity'] = total_quantity
                            session['cart_item'][key]['total_price'] = total_quantity * row['price']
                else:
                    session['cart_item'] = array_merge(session['cart_item'], itemArray)

                for key, value in session['cart_item'].items():
                    individual_quantity = int(session['cart_item'][key]['quantity'])
                    individual_price = float(session['cart_item'][key]['total_price'])
                    all_total_quantity = all_total_quantity + individual_quantity
                    all_total_price = all_total_price + individual_price
            else:
                session['cart_item'] = itemArray
                all_total_quantity = all_total_quantity + _quantity
                all_total_price = all_total_price + _quantity * row['price']

            session['all_total_quantity'] = all_total_quantity
            session['all_total_price'] = all_total_price

            return redirect(url_for('.products'))
        else:
            return 'Error while adding item to cart'
    except Exception as e:
        print(e)
    finally:
        cursor.close()
        conn.close()

@app.route('/')
def products():
    try:
        conn = mysql.connect()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        cursor.execute("SELECT * FROM product")
        rows = cursor.fetchall()
        return render_template('products.html', products=rows)
    except Exception as e:
        print(e)
    finally:
        cursor.close()
        conn.close()

@app.route('/empty')
def empty_cart():
    try:
        session.clear()
        return redirect(url_for('.products'))
    except Exception as e:
        print(e)

@app.route('/delete/<string:code>')
def delete_product(code):
    try:
        all_total_price = 0
        all_total_quantity = 0
        session.modified = True

        for item in session['cart_item'].items():
            if item[0] == code:
                session['cart_item'].pop(item[0], None)
                if 'cart_item' in session:
                    for key, value in session['cart_item'].items():
                        individual_quantity = int(session['cart_item'][key]['quantity'])
                        individual_price = float(session['cart_item'][key]['total_price'])
                        all_total_quantity = all_total_quantity + individual_quantity
                        all_total_price = all_total_price + individual_price
                break

        if all_total_quantity == 0:
            session.clear()
        else:
            session['all_total_quantity'] = all_total_quantity
            session['all_total_price'] = all_total_price

        #return redirect('/')
        return redirect(url_for('.products'))
    except Exception as e:
        print(e)

def array_merge( first_array , second_array ):
    if isinstance( first_array , list ) and isinstance( second_array , list ):
        return first_array + second_array
    elif isinstance( first_array , dict ) and isinstance( second_array , dict ):
        return dict( list( first_array.items() ) + list( second_array.items() ) )
    elif isinstance( first_array , set ) and isinstance( second_array , set ):
        return first_array.union( second_array )
    return False

if __name__ == "__main__":
    app.run(debug=True)

A: In the products function, if there is an exception creating the connection, then execution jumps to the finally: block, so cursor = ... is never executed, thus cursor.close() fails.
One possible solution: add  cursor = None above, and then in the finally: block: if cursor is not None: cursor.close()