text:
Q: In-app purchase confusion in iPhone: is it possible to use both type of in-app purchases in a single application? I have an application which is using a consumable in app purchase for the products. Now I want to add some more portions to the existing application which can be used only if the user is subscribed for that option. So is it possible to use both type of inapp purchases in a single application. And can anybody provide an idea about how I can achieve this.

A: So you want to hide some in apps unless they have purchased a special in app?
Can't you just check in your code if the first one has been bought? Then display the rest.

A: You just go to iTunes Connect, to your app, and then to manage in-app purchase section.
You can add any amount of purchases there. Then your new in-app will be reviewd by Apple and you would be able to update your app with new code for retrieving that new in-app.


text:
Q: sed with regular expression of positive look behind I want to search and replace the specified string with "module" in this line
ex. "apple" string in the line:

"happy applegg module banana tree" => "happy berrygg module banana
  tree"

sed 's/^((?=module).)*.*apple.*$/berry/g' filename >> newfile

^((?=module).)*$ => the positive look behind can fit the module, and .*apple.*$ can fit the apple
but it failed, how can I modify the sed command with regular expressions to do what I want?

A: Sed does not support full regexps. It does not even support grouping with simple (...) -- you need backslash escapes. You can use Perl's "-p" option for sed-like pass through and s/.../.../ syntax and perl's full regex support.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Open webpage on default system browser using specific credentials As the title says, I want on my C# application, to click a button(for example), and in the default browser of the computer, this site will open, and sign in to it using specific credentials.
For example open Facebook, and sign in using the credentials that I saved in my form. Is this possible?

A: There are usually 2 ways to go about this.

*

*Write a plugin that can get information from your application and use it on the website. It would be something similar to what KeePass (among others) uses.

*Write your application to act like a web UI test automation tool.
Both of these options are beyond my realm of experience since I have not needed to do either one. If I need to interact with a website, I usually do it within a hosted WebBrowser control where I can get access to the DOM.


text:
Q: d3.js pie chart legends slice toggle I'm working on a d3.js pie chart application. I am trying to develop the functionality that when you click on the legend rectangles, it toggles the slice on/off as well as the fill inside the legend rectangle.
http://jsfiddle.net/Qh9X5/3136/
legend
Rects
                        .enter()
                        .append("rect")
                        .attr("x", w - 65)
                        .attr("y", function(d, i){ return i *  20;})
                        .attr("width", 10)
                        .attr("height", 10)
                        .style("fill", function(d, i) {
                            return methods.color(i);
                        })
                        .style("stroke", function(d, i) {
                            return methods.color(i);
                        })
                        .on('click', function(d, i){
                            onLegendClick(d, i);
                        })

A: Here's one way to solve your problem:
One change required in your code is to use key functions, so that d3 matches the filtered data to the corresponding DOM node. Labels seem to be a proper key in your dataset.
Simply use:
.data(this.piedata, function(d) { return d.data.label});

instead of
.data(this.piedata);

Then, in your OnLegendClick function, you want to select all the legend's rect and all the svg arcs matching with the clicked element.
Workflow is :

*

*select the DOM elements

*match with the selected data

*apply changes

Here's how to do it:
function onLegendClick(dt){
    d3.selectAll('rect').data([dt], function(d) { return d.data.label}).style("opacity", function(d) {return Math.abs(1-d3.select(this).style("opacity"))})
    d3.selectAll('.pie').data([dt], function(d) { return d.data.label}).style("opacity", function(d) {return Math.abs(1-d3.select(this).style("opacity"))})
}

I let you adjust the "toggle" feature. You might also want to change the texts in addition to the arcs, for this use another selection.
Updated jsfiddle: http://jsfiddle.net/Qh9X5/3138/


text:
Q: Return set of numbers in recursion following code searches for one zero point of a polynomial function. It uses recursion technique:
    private static double funktion(int[] koef, double x){
        return koef[0] * Math.pow(x,4) + koef[1] * Math.pow(x,3) +
               koef[2] * Math.pow(x,2) + koef[3]*x + koef[4];
    }

    private static double nullstelle(double a, double b, int[] koef){
        double middle = (a + b)/2;
        double result = middle;
        if(Math.abs(a-b) > 0.00001){
            double sin = funktion(koef, middle);
            if(sin == 0){
                result = middle;
            }else if(Math.signum(funktion(koef, a)) ==
                             Math.signum(funktion(koef, middle))){
                result = nullstelle(middle, b, koef);
            }else{
                result = nullstelle(a, middle, koef);
            }
        }
        return result;
    }

I am wondering how to return all zero points. My ideas is to use an array but I am not sure how to do that. Any ideas?
I am not allowed to use anything else than arrays (e.g. hash tables or sets are not allowed)

A: I would pass in a Collection such as a HashSet to your functions and put all the numbers you discover into it.
As you say you can only use arrays, then you know the maximum number of zero-points that can be found, presumably, so create an array of that size, assigned NaN to every element, then pass in that array and the maximum current index of it to every function call.  You will need to return the new size of the array as the result so that you always know how many numbers have been found.

A: Here is some explanation as this is homework:
1) We need to create an array of the data type you will be using to store zero points.  My guess is double.
2) The array will need some type of starting size, lets say 10 for the sake of discussion
3) In the nullstelle method we will add an element to the array created in step 1
4) If the array has size LIMIT -1 we copy the array to a new array with size equal to LIMIT * 2
5) We now return this array.
If it needs to be sorted we can walk over the list utilizing whatever sort technique is to be decided on.

A: First of all your solution as it stands suffers from one of the same problems as your previous question in that you can't guarantee that you'll get the zero calculation exactly correct.  Unfortunately, this time you can't use the simple solution of checking that a and b have opposite signs because, for an arbitrary polynomial, a zero need not imply the function crosses the y = 0 line e.g. y = x^4.
Anyway, to answer your question:

*

*create an array of size 4 of type Double.  Use null to denote that an array slot is empty.  As your function is a quartic, there is a maximum of four zeroes.

*pass the array as a parameter in your function.

*when you have detected a zero, fill in the first free slot left in the array with the value of the zero.

No actual Java provided because this is homework.

A: Math.pow is a very expensive function. You can avoid it entirely using nested expressions. (And its shorter)
private static double funktion(int[] koef, double x){
     return (((koef[0] * x + koef[1]) * x +
           koef[2]) * x + koef[3]) * x + koef[4];
}

A:  public double[] returnOnlyZeros(int[] whatever1, double whatever2) {
  double[] result = new double[/*put the size here*/];

  // your math here

  // put the values into the result array

  return result;
 }


text:
Q: How to store a dictionary of string keys and numpy array values in a tsv file? I have a dictionary like following in python.
a = {'D1' : array([1, 2, 3]),
     'D2' : array([5,2,3]),
     ...
    }

I want to store this dictionary in a tsv file. I am aware about the pickle library, but currently I am not able to use it, because even before I start building this dictionary, my memory allocation is roughly 3 GB. After I create this dictionary, memory occupancy is 6.5-7 GB out of 8 GB of ram on my device. When I try to save this dictionary using pickle.dump, my memory gets overflowed and kernel dies.
I am not aware about any tool which can store the key value pairs dynamically in the file on secondary memory. Following code is my original code, it will give more insights.
import pickle
f = open('wordvecs.pickle', 'rb')
a = pickle.load(f)

Now when I load this file, memory of 3 GB gets occupied out of 8 GB.
Now using this dictionary a, I build another dictionary called doc_vecs as follows :
from nltk.corpus import stopwords
from tqdm import tqdm
import math

stop_words = set(stopwords.words('english'))

doc_vecs = {}
f1 = open("preprocessed_corpus.tsv", "rt")
f2 = open('doc_vecs.tsv', 'wt')
for i in tqdm(list(range(3213833))):
    docid, url, title, content = f1.readline().split('\t')
    line = title + " " + content
    v = np.mean(np.array([a[key] for key in line.split() if key in a and key not in stop_words]), axis=0)
    if(type(v) == np.float64 and math.isnan(v)):
        continue
    doc_vecs[docid] = v

seek_posn = f1.tell()

At the end, store the dictionary in the file f2.
pickle.dump(doc_vecs, f2)

After this portion is run, my memory is almost full, and when I try to save the dictionary doc_vecs using pickle, my kernel dies. Is there any option here? I'd like to know if I can store the dictionary of string keys and numpy array values to a txt or tsv or pickle file.
I also tried to free the more memory by deleting a after doc_vecs is built using del a, bu t I do not know why it does not free any memory. I also used gc.collect() to be sure that any non referenced variable is not occupying any memory.


text:
Q: Hardrive test using Gsmartcontrol Few weeks ago, my laptop hanged all of a sudden while transferring files from an external harddisk. After i restarted, there was a black screen which showed insert boot device. I checked the boot order and it was fine with my internal harddisk as my primary boot device. I booted from a live linux usb stick and it is working fine and i am able to access my harddrive and all files on it. Previously i had windows 7 running on it but now i did a complete install of linux ubuntu into the harddisk but still the laptop is not booting from it. It only works with the live usb stick. I did a harddrive test using gsmartcontrol software and i have attached a screen shot of the results. Can anyone tell me what is the problem with my harddrive?

A: The hard drive is damaged. Backup as much data as possible and replace it.
Reallocated Sectors Count:

Count of reallocated sectors. When the hard drive finds a read/write/verification error, it
  marks that sector as "reallocated" and transfers data to a special
  reserved area (spare area). This process is also known as remapping,
  and reallocated sectors are called "remaps". The raw value normally
  represents a count of the bad sectors that have been found and
  remapped. Thus, the higher the attribute value, the more sectors the
  drive has had to reallocate. This allows a drive with bad sectors to
  continue operation; however, a drive which has had any reallocations
  at all is significantly more likely to fail in the near future.
  While primarily used as a metric of the life expectancy of the drive,
  this number also affects performance. As the count of reallocated
  sectors increases, the read/write speed tends to become worse because
  the drive head is forced to seek to the reserved area whenever a remap
  is accessed. If sequential access speed is critical, the remapped
  sectors can be manually marked as bad blocks in the file system in
  order to prevent their use.


text:
Q: android facebook: Not showing info in dialog I'm trying to open a facebook post dialog when I click on some element. Dialog itself is working well. I could write some comments in the text field and the post could be seen on the website. However I want to add some info the area below the comment, which contains caption, link, picture and so on. I referred to several tutorials to implement this but they didn't work for me. Say, the caption I entered would not be shown in the dialog. The code is like:
mFacebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);

dFbPostButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {

      Bundle b = new Bundle();
      b.putString("caption","Check This Hotel");

      //Result is the class name
      //Nothing too much in SampleDialogListener
      mFacebook.dialog(Result.this, "feed", b,new SampleDialogListener());
    }
}

Any help would be really appreciated!!

A: Follow the below code
 Bundle params = new Bundle();
    params.putString("caption", "Mona Lisa");
    params.putString("description","The Mona Lisa...");
    params.putString("picture","http://tineye.com/images/widgets/mona.jpg");
    params.putString("name", "Mona Lisa");

        mFacebook.dialog(this, "feed", params, new DialogListener() {
            @Override
            public void onComplete(Bundle values) {}

            @Override
            public void onCancel() {}

            @Override
            public void onError(DialogError de) {}

            @Override
            public void onFacebookError(FacebookError fbe) {}
        });

it ll help


text:
Q: Android - Reading HTML5 localStorage data direct from Java I've got a simple Android app that has a WebView. The WebView is set to browse to a site which uses JavaScript's localStorage feature.
I've already got my WebSettings set to allow DomStorage:
webSettings.setJavaScriptEnabled(true);
ebSettings.setDomStorageEnabled(true);

String dbPath = this.getApplicationContext().getDir("database", MODE_PRIVATE).getPath();
webSettings.setDatabasePath(dbPath);

What I need is a way that my Java code can read a variable stored using the localStorage mechanism, ie.:
The JavaScript does this:
    var storage = window.localStorage;
    storage.setItem("name", "Hello World!");

How can I read the value of "name" from localStorage from Java code?

A: yes possible to read localStorage value in java (Android).
use this plugin https://www.npmjs.com/package/cordova-plugin-nativestorage
that use native storage .
-for that we have to set value in cordova
    NativeStorage.setItem("reference", obj, setSuccess, setError);
    function setSuccess(obj){
    }
    function setError(obj){
    }

And In Anroid Java File to get this value :
    SharedPreferences sharedPreferences = getSharedPreferences("MainActivity", MODE_PRIVATE);
    System.out.println("********---------    shared pref values...   " +  sharedPreferences.getString("myid", "no value"));

A: yourWebView.setWebChromeClient(new WebChromeClient(){
      public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        Log.d(tag, "That's my local storage value =" + message);
        return false;
      };
    });
(...)
    yourWebView.loadURL("javascript:alert(localStorage.getItem(\"name\"))");

A: in your activity
webView.addJavascriptInterface(myInterface, "JSInterface");

Javascript interface class
class myInterface
{

    @JavascriptInterface
    public void getVariable(string fromLocalStorage)
    {
    //your code
    }

}

in javascript
window.JSInterface.getVariable(localStorage.getItem("variableName"))

A: To write data :
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
     webView.evaluateJavascript("localStorage.setItem('"+ key +"','"+ val +"');", null);
} else {
     webView.loadUrl("javascript:localStorage.setItem('"+ key +"','"+ val +"');");
}

To read and alert data :
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
     webView.evaluateJavascript("window.alert(localStorage.getItem('"+ key +"'));", null);
} else {
     webView.loadUrl("javascript:window.alert(localStorage.getItem('"+ key +"'));");
}

And remember to enable JavaScript of Android WebvView
webView.getSettings().setJavaScriptEnabled(true);


text:
Q: pyqt non-modal dialog always modal I have a dialog designed in Qt Designer and set as non-modal that when launched is always modal. I am using OS X El Capitan, Python 3.5.1, Qt 5.4.2, pyqt4.
These code snippets show what I am doing:

Designer .ui code converted to python using pyuic.
from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_purchaseInfoDialog(object):
    def setupUi(self, purchaseInfoDialog):
        purchaseInfoDialog.setObjectName(_fromUtf8("purchaseInfoDialog"))
        purchaseInfoDialog.setWindowModality(QtCore.Qt.NonModal)
        purchaseInfoDialog.resize(837, 377)
        purchaseInfoDialog.setSizeGripEnabled(True)
        purchaseInfoDialog.setModal(False)
        self.purchaseInfoButtonBox = QtGui.QDialogButtonBox(purchaseInfoDialog)
        self.purchaseInfoButtonBox.setGeometry(QtCore.QRect(710, 330, 101, 32))
        self.purchaseInfoButtonBox.setOrientation(QtCore.Qt.Horizontal)
        self.purchaseInfoButtonBox.setStandardButtons(QtGui.QDialogButtonBox.Close)
        self.purchaseInfoButtonBox.setObjectName(_fromUtf8("purchaseInfoButtonBox"))
        self.purchaseInfoTable = QtGui.QTableWidget(purchaseInfoDialog)
        self.purchaseInfoTable.setGeometry(QtCore.QRect(10, 50, 911, 271))
        self.purchaseInfoTable.setObjectName(_fromUtf8("purchaseInfoTable"))
        self.purchaseInfoTable.setColumnCount(9)
        self.purchaseInfoTable.setRowCount(0)
        item = QtGui.QTableWidgetItem()
        self.purchaseInfoTable.setHorizontalHeaderItem(0, item)
        item = QtGui.QTableWidgetItem()
        self.purchaseInfoTable.setHorizontalHeaderItem(1, item)
        item = QtGui.QTableWidgetItem()
        self.purchaseInfoTable.setHorizontalHeaderItem(2, item)
        item = QtGui.QTableWidgetItem()
        self.purchaseInfoTable.setHorizontalHeaderItem(3, item)
        item = QtGui.QTableWidgetItem()
        self.purchaseInfoTable.setHorizontalHeaderItem(4, item)
        item = QtGui.QTableWidgetItem()
        self.purchaseInfoTable.setHorizontalHeaderItem(5, item)
        item = QtGui.QTableWidgetItem()
        self.purchaseInfoTable.setHorizontalHeaderItem(6, item)
        item = QtGui.QTableWidgetItem()
        self.purchaseInfoTable.setHorizontalHeaderItem(7, item)
        item = QtGui.QTableWidgetItem()
        self.purchaseInfoTable.setHorizontalHeaderItem(8, item)
        self.piPartLabel = QtGui.QLabel(purchaseInfoDialog)
        self.piPartLabel.setGeometry(QtCore.QRect(20, 20, 71, 16))
        self.piPartLabel.setObjectName(_fromUtf8("piPartLabel"))
        self.piPartdescriptionLabel = QtGui.QLabel(purchaseInfoDialog)
        self.piPartdescriptionLabel.setGeometry(QtCore.QRect(120, 20, 191, 16))
        self.piPartdescriptionLabel.setObjectName(_fromUtf8("piPartdescriptionLabel"))
        self.poFromSelectionPushButton = QtGui.QPushButton(purchaseInfoDialog)
        self.poFromSelectionPushButton.setGeometry(QtCore.QRect(540, 330, 171, 32))
        self.poFromSelectionPushButton.setObjectName(_fromUtf8("poFromSelectionPushButton"))

        self.retranslateUi(purchaseInfoDialog)
        QtCore.QObject.connect(self.purchaseInfoButtonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), purchaseInfoDialog.accept)
        QtCore.QObject.connect(self.purchaseInfoButtonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), purchaseInfoDialog.reject)
        #QtCore.QObject.connect(self.poFromSelectionPushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), purchaseInfoDialog.poFromSelection)
        QtCore.QMetaObject.connectSlotsByName(purchaseInfoDialog)

    def retranslateUi(self, purchaseInfoDialog):
        purchaseInfoDialog.setWindowTitle(_translate("purchaseInfoDialog", "Purchase History", None))
        item = self.purchaseInfoTable.horizontalHeaderItem(0)
        item.setText(_translate("purchaseInfoDialog", "#", None))
        item = self.purchaseInfoTable.horizontalHeaderItem(1)
        item.setText(_translate("purchaseInfoDialog", "P.O. #", None))
        item = self.purchaseInfoTable.horizontalHeaderItem(2)
        item.setText(_translate("purchaseInfoDialog", "Vendor", None))
        item = self.purchaseInfoTable.horizontalHeaderItem(3)
        item.setText(_translate("purchaseInfoDialog", "P.O. Date", None))
        item = self.purchaseInfoTable.horizontalHeaderItem(4)
        item.setText(_translate("purchaseInfoDialog", "Mfg", None))
        item = self.purchaseInfoTable.horizontalHeaderItem(5)
        item.setText(_translate("purchaseInfoDialog", "Mpn", None))
        item = self.purchaseInfoTable.horizontalHeaderItem(6)
        item.setText(_translate("purchaseInfoDialog", "Qty", None))
        item = self.purchaseInfoTable.horizontalHeaderItem(7)
        item.setText(_translate("purchaseInfoDialog", "Price", None))
        item = self.purchaseInfoTable.horizontalHeaderItem(8)
        item.setText(_translate("purchaseInfoDialog", "Dock", None))
        self.piPartLabel.setText(_translate("purchaseInfoDialog", "Part", None))
        self.piPartdescriptionLabel.setText(_translate("purchaseInfoDialog", "Description", None))
        self.poFromSelectionPushButton.setText(_translate("purchaseInfoDialog", "P.O. From Selection", None))

I sub-class the designer class
#
# PURCHASE INFO (HISTORY) Dialog
#
# Sub-class Ui_purchaseInfoDialog
class PurchaseInfoDialog(QDialog, Ui_purchaseInfoDialog):
    def __init__(self):
        QDialog.__init__((self))
        self.setModal(False)

Commented code below shows attempts to make it non-modal even though it should be. Nothing works.
   self.ui.orderPartButton.clicked.connect(lambda: self.orderPartButtonClicked())

#
# Parts Slots
#
#

@pyqtSlot()
def orderPartButtonClicked(self):
    selectedPart = MainWindow.ui.partShortagesTable.selectedItems()
    if (selectedPart):
        part = selectedPart[0].text()
        aPurchaseInfoDialog = PurchaseInfoDialog()
        pidUi = Ui_purchaseInfoDialog()
        pidUi.setupUi(aPurchaseInfoDialog)

    refreshPurchaseInfoTable(self, pidUi.purchaseInfoTable, pidUi.piPartLabel, pidUi.piPartdescriptionLabel, part, pathToArchive)

    #aPurchaseInfoDialog.setWindowModality(QtCore.Qt.NonModal)
    result = aPurchaseInfoDialog.exec_()  # Launch the Purchase Info Dialog. result = 0 for Close
    #aPurchaseInfoDialog.show()

Is there a problem with pyqt4 in my environment (I tried this under Linux with the same result) or am I missing some setting somewhere?
Demo:
import sys
from PyQt4 import QtCore
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Dialog1(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.setModal(True)

class Dialog2(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.setModal(False)

def window():
    app = QApplication(sys.argv)
    w = QWidget()
    b = QPushButton(w)
    b.setText("Modal Dialog")
    b.move(15, 25)
    b.clicked.connect(showdialog1)

    c = QPushButton(w)
    c.setText("Modless Dialog")
    c.move(15, 75)
    c.clicked.connect(showdialog2)

    w.setWindowTitle("PyQt Dialog demo")
    w.resize(200, 150)
    w.show()
    sys.exit(app.exec_())

def showdialog1():
    # d = QDialog()
    d = Dialog1()
    #d.setWindowModality(QtCore.Qt.Modal)
    b1 = QPushButton("Modal Dialog", d)
    b1.move(50, 50)
    d.setWindowTitle("Modal Dialog")
    d.setWindowModality(Qt.ApplicationModal)
    d.exec_()

def showdialog2():
    # d = QDialog()
    d = Dialog2()
    d.setWindowModality(QtCore.Qt.NonModal)
    b1 = QPushButton("ok", d)
    b1.move(50, 50)
    d.setWindowTitle("Modeless Dialog")
    d.setWindowModality(Qt.ApplicationModal)
    d.exec_()

if __name__ == '__main__':
    window()

A: I rearranged some of your code because of personal preference (I'm sure you can put it back no problem), and now one is modal, and the other is nonmodal.
When you create a nonmodal window, you must provide a parent QWidget in the instantiation of the QDialog class. Then, instead of using QDialog.exec_(), use QDialog.show(). This shows the nonmodal window but allows the original parent to keep running, in a sense. Using exec_() will always result in a modal window, even if you set it to nonmodal. Here's the documentation: http://pyqt.sourceforge.net/Docs/PyQt4/qdialog.html
Here is the code:
class Dialog1(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.setModal(True)

class Dialog2(QDialog):
    def __init__(self, parent):
    QDialog.__init__(self, parent)
    self.setModal(0)
    b1 = QPushButton("ok", self)
    b1.move(50, 50)
    b1.clicked.connect(self.exit)
    self.setWindowTitle("Nonmodal Dialog")

    self.show()

def exit(self):
    self.close()

def window():
    app = QApplication(sys.argv)
    w = QWidget()
    b = QPushButton(w)
    b.setText("Modal Dialog")
    b.move(15, 25)
    b.clicked.connect(showdialog1)

    c = QPushButton(w)
    c.setText("Nonmodal Dialog")
    c.move(15, 75)
    c.clicked.connect(lambda: showdialog2(w))

    w.setWindowTitle("PyQt Dialog demo")
    w.resize(200, 150)
    w.show()
    sys.exit(app.exec_())

def showdialog1():
    # d = QDialog()
    d = Dialog1()
    #d.setWindowModality(QtCore.Qt.Modal)
    b1 = QPushButton("Modal Dialog", d)
    b1.move(50, 50)
    d.setWindowTitle("Modal Dialog")
    d.setWindowModality(Qt.ApplicationModal)
    d.exec_()

def showdialog2(w):
    # d = QDialog()
    Dialog2(w)

if __name__ == '__main__':
    window()


text:
Q: Stored Procedure taking too much time i'm facing a problem. i'm using a stored procedure to retrieve some set of data. this procedure is optimized by all DB expect and retrieving result in 0 sec. but after some days it takes too much time and i have to re-compile it after 3,4 days by using autojob. after re-compiling it again retrieving result in 0 sec.
can any one help me out is there any permanent solution for this issue.?
code:
DECLARE @account BIGINT = 2210124537100405
        WITH RECOMPILE

BEGIN
    -- declare @account bigint =101125953510789

    SELECT CONVERT(VARCHAR, table2.number) AS Claim_No,
           Table2.account,
           CONVERT(VARCHAR(10), B_DATE, 101) AS BILLDATE,
           table2.Location_Code,
           DOS,
           CONVERT(VARCHAR, DOS, 101)     AS DOS_SERVICE,
           (
               SELECT ISNULL(p_name, '') + ' ' + ISNULL(p_2name, '') + '. ' +
                      ISNULL(p_3name, '')
               FROM   table3 p
               WHERE  p.p_code = a_p
           )                              AS A_Pn,
           B_Phn,
           S_Phn,
           ISNULL(C_Total, 0.00)             C_Total,
           ISNULL(Amt_P, 0.00)               Amt_P,
           PA_NUMBER,
           Re_Number,
           Facility_Code,
           ho_to = CASE ISNULL(Ho_To, '')
                        WHEN '' THEN dot
                        ELSE Hos_To
                   END,
           Hos_Fr = CASE ISNULL(Hos_From, '')
                         WHEN '' THEN dost
                         ELSE Hos_From
                    END,
           PRI_STATUS,
           SEC_STATUS,
           OTH_STATUS,
           PAT_STATUS,
           Employment,
           Claim_Status,
           Claim_Status_Date,
           Accident_State,
           Phy_Exam_Code,
           Phy_Exam_Desc,
           Ordering_Physician,
           ICN_Number,
           Block1213,
           ISNULL(Pri_Ins_Payment, 0.00)  AS Pri_Ins_Payment,
           ISNULL(Sec_Ins_Payment, 0.00)  AS Sec_Ins_Payment,
           ISNULL(Oth_Ins_Payment, 0.00)  AS Oth_Ins_Payment,
           ISNULL(Patient_Payment, 0.00)  AS Patient_Payment,
           ISNULL(Adjustment, 0.00)       AS Adjustment,
           ISNULL(Amt_Due, 0.00)          AS Amt_Due,
           DX_Code1,
           DX_Code2,
           DX_Code3,
           DX_Code4,
           DX_Code5,
           DX_Code6,
           DX_Code7,
           DX_Code8,
           POS,
           table2.PTL_Status,
           ISNULL(table2.resolve, 0)         resolve,
           table2.Patient_Payment_Plan,
           Is_Self_Pay,
           table2.Deleted,
           UPPER(table2.Created_By)       AS Created_By,
           CONVERT(DATETIME, CONVERT(VARCHAR, table2.Created_Date, 101)) AS
           Created_Date,
           table2.Modified_By,
           table2.Modified_Date,
           IS_DRAFT                       AS Is_draft,
           ISNULL(ClaimTemp_Category.Temp_Name, '') AS Temp_Name,
           (
               SELECT COUNT(claim_no) AS table2_Submitted
               FROM   table2_Submitted
               WHERE  Claim_No        = table2.Claim_No
                      AND DELETED     = 0
           )                              AS table2_Submitted,
           (
               SELECT COUNT(claim_payments_id) AS CLAIMS_PAYMENT FROMtable4
               WHERE  Claim_No        = table2.Claim_No
                      AND DELETED     = 0
           )                              AS CLAIMS_PAYMENT
    FROM   table2
           JOIN table3
                ON  table2.attending_physician = table3.provider_code
           LEFT OUTER JOIN ClaimTemp_Category
                ON  table2.no = ClaimTemp_Category.Claim_No
    WHERE  (
               table2.account = @account
               OR table2.DRAFT_account = @account
           )
           AND ISNULL(table2.DELETED, 0) = 0
    ORDER BY
           DOS DESC
END


text:
Q: R: Regular Expressions in R - Multi string extraction Say I have a string like this:
[1] "Degradation: AGL, PGM1, PGM2, PGM3, PYGL, PYGM.
\n"

I want to extract each of these gene IDs into a vector. I could probably use strsplit in this case, but I want to do this with regex as I will later have more complex cases. Say I want to extract all strings that contain '[A-Z0-9]{2,} (if it contains any combinations of at least two capital letters and numbers then I want it).
Thoughts?

A: The stringr package makes this kind of thing pretty easy.
> library(stringr)
> x <- "Degradation: AGL, PGM1, PGM2, PGM3, PYGL, PYGM.
\n"
> str_extract_all(x, '[A-Z0-9]{2,}')
[[1]]
[1] "AGL"  "PGM1" "PGM2" "PGM3" "PYGL" "PYGM"

A: 1) strapply
strapply in the gsubfn package can do that:
library(gsubfn)
x <- "Degradation: AGL, PGM1, PGM2, PGM3, PYGL, PYGM.
\n"
strapply(x, "[A-Z0-9]{2,}", c)

2) strapplyc
Also there is a high speed version specialized to use c in the development repo.
library(gsubfn)
# download and read in strapplyc
source("http://gsubfn.googlecode.com/svn/trunk/R/strapplyc.R")
strapplyc(x, "[A-Z0-9]{2,}")

Also see this example of extracting all the words from James Joyce's Ulysses here .
Choosing
strapply has a lot of variations to it so if flexibility is most important then it might be a good choice.  On the other hand, strapplyc might be particularly useful if your strings are very long so that speed is important and you only need to extract strings.


text:
Q: Is there Widow Orphan protection using Prawn for Ruby on Rails? I have a question about using Prawn for Ruby on Rails.
I'm using a bounding_box for variable length content.  When the
content overflows to the next page I would like to have some sort of
widow/orphan protection in place.  Is there a recommended solution for
this?
Is there a way to break the content from the previous page at the last
paragraph break, then carry that paragraph to the next page?
Or perhaps take the last x lines from the previous page so that there
are at least x+1 number of lines in the new page?
Thoughts?
Suggestions?


text:
Q: X Toolkit: heap is growing when recreating widgets I'm trying to understand why the following program is leaking memory. When I look at the heap size by using the command more /proc/<pid>/smaps, I can see that the heap is only growing. It seems that the XtDestroyWidget is not really freeing up the memory. I would be very grateful if somebody can tell me why this is happening and show me the right way of recreating widgets.
Thanks in advance!
/* Compile on Solaris: cc widgets_mem.c -lXm -lXt -lX11 */
/* Compile on Linux: gcc -m32 widgets_mem.c -lXm -lXt -lX11 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysymdef.h>

#include <Xm/MainW.h>
#include <Xm/PushB.h>
#include <Xm/Form.h>

Widget      toplevel;
Widget      w_main;
Widget      w_bb;
Widget      w_button = NULL;

Window      root_win;
XtAppContext    app;
int     screen_number;
Display        *display = NULL;

void recreateWidgets ()
{
    printf ("recreating widgets\n");
    XtDestroyWidget (w_button);

    w_button = XtVaCreateManagedWidget (
    "button",
    xmPushButtonWidgetClass, w_bb,
    XmNfillOnArm, False,
    XmNhighlightThickness, 0,
    XmNborderWidth, 1,
    XmNmarginTop, 1,
    XmNmarginWidth, 2,
    XmNmarginHeight, 0,
    XmNwidth, 20,
    XmNheight, 10,
    XmNrecomputeSize, False,
    XmNalignment, XmALIGNMENT_CENTER,
    NULL);
}

void main (int argc, char **argv)
{
    XEvent  event;

    toplevel = XtVaAppInitialize (&app, "Mem leak test",
                  NULL, 0, &argc, argv, NULL, NULL);
    display = XtDisplay (toplevel);
    screen_number = DefaultScreen (display);
    root_win = RootWindow (display, screen_number);

    w_main = XtVaCreatePopupShell (
    "main",
    topLevelShellWidgetClass, toplevel,
    XmNgeometry, "-0+0",
    XmNborderWidth, 0,
    XmNshadowThickness, 0,
    XmNminWidth, 1,
    XmNmwmDecorations, 0,
    XmNmwmFunctions, 0,
    XmNwidth, 600,
    XmNheight, 200,
    NULL);

    w_bb = XtVaCreateManagedWidget (
    "",
    xmBulletinBoardWidgetClass, w_main,
    XmNborderWidth, 4,
    XmNshadowThickness, 0,
    XmNmarginWidth, 0,
    XmNmarginHeight, 0,
    XmNx, 0,
    XmNy, 0,
    XmNwidth, 500,
    XmNheight, 100,
    NULL);

    w_button = XtVaCreateManagedWidget (
    "button",
    xmPushButtonWidgetClass, w_bb,
    XmNfillOnArm, False,
    XmNhighlightThickness, 0,
    XmNborderWidth, 1,
    XmNmarginTop, 1,
    XmNmarginWidth, 2,
    XmNmarginHeight, 0,
    XmNwidth, 20,
    XmNheight, 10,
    XmNrecomputeSize, False,
    XmNalignment, XmALIGNMENT_CENTER,
    NULL);

    XtPopup (w_main, XtGrabNone);

    while (1)
    {
        XtAppNextEvent (app, &event);
        if (event.type == ButtonPress)
        {
            printf ("Button pressed, recreating widgets\n");
            recreateWidgets();
        }
    }
}

A: I found the bug in my code: I had to add a XtDispatchEvent(&event), which handles the deallocating of the widgets which are on the destory list, an internal list in Xt.


text:
Q: How to enable audio output with pulseaudio when it is running? Here I described trouble installing pulseaudio due to mismatching dependencies when using packages of Kodi19 on Debian10. This is now resolved insofar that after a recent upgrade I was able to install pulseaudio and get it running via this command: sudo apt-get install pulseaudio/buster-backports libpulse0/buster-backports libasound2-plugins.
My problem now is that the audio output still isn't working even though pulseaudio is running. I tried some changes to client.conf, daemon.conf and default.pa as described here and here. It still doesn't work. I didn't have this problem before the audio stops working. I recently noticed the sound output actually still does work (for local audio files) but only over headphones (and then there's still no volume icon in the tray bar etc).
How to get audio output working again? If changes to the config files are needed how to find out which changes are required? Any ideas about why this problem occurred?

Running pulseaudio -k didn't restart pulseaudio.
The audio output still worked for online streaming even before pulseaudio was installed.
Another Debian10/KDE machine with almost the same setup including Kodi19 doesn't have this problem.
Once pulseaudio works there should be a volume-icon in the tray bar and the volume-buttons should work again.
There shouldn't be any need to change configs to get audio working after installing pulseaudio (which should never have been removed anyway as I didn't deliberately remove it).
I also have e.g. gstreamer1.0-pulseaudio installed. When I search for "pulse" "Audio Volume" is not showing upl in the search results like on another machine so maybe I need to install some additional package. Or maybe I need to clear some configs.
When I run pulseaudio in the console because it doesn't get restarted after running pulseaudio -k I get Failed to load module "module-native-protocol-unix" (argument: ""): initialization failed. (it does start it nevertheless).
One other thing that might have to do with it, is that running an upgrade with apper or sudo apt-get upgrade asks me to downgrade libwayland-client++0 libwayland-cursor++0 which appears to work but even after rebooting it still asks for the same two downgrades. This was solved by rerunning the setup steps for Basil Gello's repo.

A: It worked once new packages were available and could be upgraded. Maybe it was a problem with mismatching packages of Basil Gello's repo which isn't needed anymore as those Kodi things moved into backports.


text:
Q: How to draw curved arrows linking two nodes and how to put an icon in the corner of a node? I'm trying to make a diagram but I'm having some issues:

*

*I'd like to have a curver arrow linking node 5 to node 1.

*I'd like the icons on image nodes to be on the upper right corner.

*I wanted to put more information under the arrow linking nodes 1 and 2.

This is what I have so far:

To generate this diagram, I used the following source code:
\documentclass[tikz]{standalone}

\usepackage{tikz}
\usepackage{fontawesome}

\usetikzlibrary{positioning, arrows}

\tikzstyle{smallerblock} = [rectangle, draw,
text width=2.0cm, text centered, rounded corners, minimum height=4em]
\tikzstyle{largerblock} = [rectangle, draw,
text width=3.8cm, text centered, rounded corners, minimum height=4em]
\tikzstyle{line} = [draw, -latex']

\begin{document}

\begin{tikzpicture}[node distance = 0.75cm and 2.5cm, auto]
    % Place nodes
    \node [largerblock] (1) {\small 1};
    \node [largerblock, right=of 1] (2) {2};
    \node [smallerblock, right=of 2] (image) {\small Image \\ (binary) \faFileO};
    \node [largerblock, below=of 2] (4) {4};
    \node [smallerblock, right=of 4] (png) {\small Image \\(png) \faFilePhotoO};
    \node [largerblock, below=of 4] (5) {5};

    % Draw edges
    \path [line] (1) -- node [near start] {1.} (2);
    \path [line] (2) -- (image);
    \path [line] (1) |- node [pos=0.56] {2.} (4);
    \path [line] (image) -- (4);
    \path [line] (4) -- (png);
    \path [line] (png) -- (5);
    \path [line] (1) |- node [pos=0.56] {3.} (5);
\end{tikzpicture}

\end{document}

This is what I'd like to have:

If anybody has any idea how to solve one of these issues, or all of them, I'd be truly grateful :)

A: Note the use of \tikzset in the code below instead of \tikzstyle. The \tikzstyle command works for now, but has been deprecated and may (theoretically) not work in the future. You can set optional arguments and default values in the same tikzset as I did below with noteblock.
For the curved arrow, you can set out= and in= angles as options for to. Adjusting the looseness can change the amount of curve.
For the boxed descriptions you can define an additional style (I used noteblock) and treat those labels as additional nodes.
To place the icons, make them additional nodes and position them below left of the north east corner of the other node.
Note that \draw can be used if you wish instead of \path[draw] to shorten the code.

\documentclass{article}

\usepackage{tikz}
\usepackage{fontawesome}

\usetikzlibrary{positioning, arrows}

\tikzset{smallerblock/.style={rectangle, draw, text width=2.0cm, text centered, rounded corners, minimum height=4em},
    largerblock/.style={rectangle, draw, text width=3.8cm, text centered, rounded corners, minimum height=4em},
    line/.style={draw, -latex'},
    noteblock/.style={draw, align=#1, outer sep=2pt, font=\scriptsize},
    noteblock/.default={center}
}

\begin{document}

\begin{tikzpicture}[node distance = 0.75cm and 2.5cm, auto]
    % Place nodes
    \node [largerblock] (1) {\small 1};
    \node [largerblock, right=of 1] (2) {2};
    \node [smallerblock, right=of 2] (image) {\small Image \\ (binary)};
    \node [below left=2pt of image.north east]{\small \faFileO};
    \node [largerblock, below=of 2] (4) {4};
    \node [smallerblock, right=of 4] (png) {\small Image \\(png)};
    \node [below left=2pt of png.north east]{\small \faFilePhotoO};
    \node [largerblock, below=of 4] (5) {5};

    % Draw edges
    \path [line] (1) -- node [near start] {1.} node[below, noteblock=left]{- variable\\- integer bits\\- fractional bits} (2);
    \path [line] (2) -- (image);
    \path [line] (1) |- node [pos=0.56] {2.} (4);
    \path [line] (image) -- (4);
    \path [line] (4) -- (png);
    \path [line] (png) -- (5);
    \path [line] (1) |- node [pos=0.56] {3.} (5);
    \path [line, looseness=1.6] (5) to[out=210, in=-120]node[noteblock]{repeat for\\all variables} (1);

\end{tikzpicture}

\end{document}


text:
Q: AppCenter Crashes and Firebase Crashlytics - Both Together Not Working - Xamarin.Forms iOS Trying to integrated both Firebase Crashlytics and AppCenter Crashes in single application. I see, none of this is able to log any crashes.
   public override bool FinishedLaunching(UIApplication app, NSDictionary options)

  {

        global::Xamarin.Forms.Forms.Init();

        Firebase.Core.App.Configure();
        Crashlytics.SharedInstance.Init();

        AppCenter.Start("xxxxxxxxxxxxxxxxxxxx", typeof(Analytics), typeof(Crashes));

        LoadApplication(new App());
        return base.FinishedLaunching(app, options);
    }

Also, I am using latest SDKs.
<ItemGroup>
    <PackageReference Include="Xamarin.Forms" Version="4.8.0.1451" />
    <PackageReference Include="Xamarin.Essentials" Version="1.5.3.2" />
    <PackageReference Include="Microsoft.AppCenter.Analytics">
      <Version>4.1.0</Version>
    </PackageReference>
   <PackageReference Include="Microsoft.AppCenter.Crashes">
      <Version>4.1.0</Version>
   </PackageReference>
   <PackageReference Include="Xamarin.Firebase.iOS.Core">
     <Version>6.10.4</Version>
   </PackageReference>
   <PackageReference Include="Xamarin.Firebase.iOS.Crashlytics">
     <Version>4.6.2</Version>
   </PackageReference>
</ItemGroup>

Also, from the Visual Studio Console Log, i am receiving below error logs.
 [Crashlytics] The signal SIGABRT has a non-Crashlytics handler (sigabrt_signal_handler).  This will interfere with reporting. 2021-02-24 12:26:30.173858+0530 DemoApp.iOS[12308:580294] 6.34.0 -
 [Firebase/Crashlytics][I-CLS000000] Warning: NSUncaughtExceptionHandler is '_ZL17exception_handlerP11NSException' in '/Users/sakeridilipkumar/Library/Developer/CoreSimulator/Devices/CC5157E9-F6A5-46D8-BA9E-B2D67936538D/data/Containers/Bundle/Application/41E5D8C0-19FC-474C-84B9-EDFC5C9B024A/DemoApp.iOS.app/DemoApp.iOS'
 [Crashlytics] The signal SIGBUS has a non-Crashlytics handler (mono_sigsegv_signal_handler).  This will interfere with reporting.
 [Crashlytics] The signal SIGFPE has a non-Crashlytics handler (mono_sigfpe_signal_handler).  This will interfere with reporting.
 [Crashlytics] The signal SIGILL has a non-Crashlytics handler (mono_crashing_signal_handler).  This will interfere with reporting.
 [Crashlytics] The signal SIGSEGV has a non-Crashlytics handler (mono_sigsegv_signal_handler).  This will interfere with reporting.
 [Crashlytics] The signal SIGSYS has a non-Crashlytics handler (mono_crashing_signal_handler).  This will interfere with reporting.
 [Crashlytics] The signal SIGTRAP has a non-Crashlytics handler (MSplcrash_signal_handler).  This will interfere with reporting.

Any suggestion to find rootcause is appreciable.

A: It's resolved.
I have kept below packages only and it started working. I have also needed to upload dSYM file to upload. Please upload same dSYM which was generated while archived.
<ItemGroup>
 <PackageReference Include="Xamarin.Forms" Version="4.8.0.1451" />
 <PackageReference Include="Xamarin.Essentials" Version="1.5.3.2" />
 <PackageReference Include="Microsoft.AppCenter.Analytics">
  <Version>4.1.0</Version>
 </PackageReference>
 <PackageReference Include="Xamarin.Firebase.iOS.Core">
  <Version>6.10.4</Version>
 </PackageReference>
 <PackageReference Include="Xamarin.Firebase.iOS.Crashlytics">
  <Version>4.6.2</Version>
 </PackageReference>
</ItemGroup>


text:
Q: Anime where half American half Japanese guy comes to Japan to fight First episode has a group of school girls in mechas fighting massive bugs/aliens, and all but one are slaughtered. Then it transitions to a young half-American and half-Japanese boy, who's an ace pilot being sent to Japan. There are two sisters that fight in a black mecha and are crazy scary and strong, the older one at some point in the show goes on a raft and falls ill with the MC and another girl getting her and being washed ashore an island for an episode. One episode has different countries competing against each other in their mechas in a competition/tournament

A: Still researching, but this may be Muv-Luv Alternative: Total Eclipse.

Since 1973, an invasion of aliens upon Earth known as BETA has driven human civilization to destruction. In order to defend themselves from this enormous mass of enemy force, mankind has developed large humanoid arms called Tactical Surface Fighters and deployed them to its defense lines through out the world. However, its efforts could only slow down the impending defeat, and mankind has been forced to abandon the major areas of the Eurasian Continent. For 30 years, they have been caught in an endless war against BETA without any hopes of victory.
Now in 2001, Imperial Japan faces difficulties in the development of the next-generation of Tactical Surface Fighters (TSF) as it defends the front lines of the Far East. The UN has proposed a joint development program between Imperial Japan and the United States as a part of its TSF international mutual development unit, the Prominence Project.
Yui Takamura (a surface pilot of the Imperial Royal Guards of Japan) is given the responsibility of the project and sets off to Alaska. Meanwhile, Yuya Bridges, also a surface pilot of the US Army, heads to the same destination.

Yuya is half Japanese and half American.
Trailer.

Found with a search for anime "giant robot" "half american"


text:
Q: Cloudant incremental backup supported? I was working on an incremental backup solution for my Cloudant databases.
I was using the documentation at https://docs.cloudant.com/backup-guide.html  and today I tried to go back to that link to look something up and the page is gone.
Is this an error in the documentation, or has support for this been removed?
Thanks

A: The documentation on the page you were reading was for features that have not yet been released. Once the features are officially released, we will make that page available again. In the meantime, this page may be helpful: https://docs.cloudant.com/backup.html


text:
Q: OpenID Connect scope/role discovery I recently learned how OIDC provides user identity on top of OAuth 2, and also managed to create an OIDC login to my webapp. However, when it comes to the authorization part, it is unclear how the application should know what scopes to request for the API?
For example, certain endpoints should be protected with the 'admin' scope, as well as respective UI elements should be hidden from non-admin users. The enforcement part I can implement easily, but when the user logs in, the app needs to know if the user is an admin or not - i.e whether or not to request the 'admin' scope / show the admin-related UI parts.
Is there any standard way of representing app-specific details in the user profile that comes from the IDP? What disturbs me most is that such information - to my knowledge - cannot be added to user profiles that come from e.g Google/Twitter/Facebook, so one needs either a) an extra layer (IdentityServer/OpenAM/etc), or b) extra user profile data in the webapp's DB.
My first thought was to add custom claims by doing a) - but when it comes to integrating with existing IDPs, it might not be possible to adjust all the user profiles (e.g large corporate databases), so I am assuming the app itself should be flexible enough to translate existing user profile data to 'admin/not-admin'.
Is there a better solution?

A: In my opinion it's not a good practice to base your authorization on the claims returned by your identity providers.
This responsibility should be delegated to the UMA server. It's up to him to decide or not to grant a request access to a protected resource.
For example, image that we have the following scenario :
Context : An e-commerce enterprise has internally developed a tool used by his marketing team, to retrieve information about his most loyal clients.
The application has been developed in WPF and interact with a RESTFUL API to retrieve the clients.
Only this application and users that belong to the marketing group are authorized to retrieve the list.
Problem : How the application can access to the protected operation ?

workflow
Solution : the workflow is made of three big steps :

*

*Identity token : retrieve an identity token with implicit grant-type. The token is returned to the client in a callback parameter

*RPT token : the identity and access token (valid for the scopes uma_authorization & uma_protection) are passed in the request to retrieve the RPT one.
When it is received by the WPF application, the token is passed in the Authorization header to retrieve the loyal clients. Both parameters are required by the authorization policy.

*Check RPT token : the token is checked against the introspection endpoint, this endpoint is offered by the UMA server.

As you can see internal policies are used by the UMA server to grant / or not access to the resource.
Authorization policy is out of scope of the UMA specification, you have to define it yourself :'(.
I have developed a product (open-source) to easily manage authorization policies. If you are interested you can test the demo here  :
http://lokit.westus.cloudapp.azure.com/Demo
Note : If you are not satisfied about claims returned by external identity providers, you can always enrich them (read the use case : "assign role to resource owner" in the documentation)


text:
Q: Monitor/Java synchronized methods, how to schedule an activity in a non-blocking way? So, basically the whole idea is that I have to simulate the entrance of a school. N students queue at four turnstiles and then they join a random classroom. When the first student joins that classroom a lecture starts and lasts for a time T, after which the lecture ends and students go home.
I'm specifically struggling at the "lasts for a time T" part. Here is what I tried:
StudentThread:
@Override
public void run() {
    try {
        /** Some uninteresting code**/
        classroom.joinClass(studentID);

    }catch(InterruptedException e) {

    }
}

Classroom:
private static final int LECTURE_DURATION = 3000;

public synchronized void joinClass(UUID student) throws InterruptedException {
            this.students.add(student);

            if( students.size() == 1 ) {
                lecture = true;
                new ScheduledThreadPoolExecutor(1).schedule(new Runnable() {
                    @Override
                    public void run() {
                        while( !students.isEmpty() )
                            students.remove(0);

                        lecture = false;
                        notifyAll();
                    }
                }, LECTURE_DURATION, TimeUnit.MILLISECONDS);

            }

            while( lecture )
                wait();
        }

The apparent problem with this solution is that the first student joining a classroom will block the access to all the others, basically never leaving the joinClass method until the lecture ends. I assume it's because of that schedule call. I also can only use synchronized methods, no semaphores otherwise it would've been relatively easy. What should I do in this case?

A: You should not create a new ScheduledThreadPoolExecutor within the method. An executor is supposed to be reused. And you should call shutdown() on it once you really don't need it anymore.
But more important is that, since the scheduled action is performed by a different thread, it must use synchronized when accessing the mutable state.
This leads to the point you're missing about wait(). The only way for the condition you're waiting for to correctly become fulfilled, is by having another thread performing the necessary steps within a synchronized block and calling notify() or notifyAll(), both methods insisting on being called within that synchronized block.
This can only work, when wait() releases the lock, so the other thread can acquire it and do the duty. And that's precisely what wait does:

This method causes the current thread (referred to here as T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Note that only the locks on this object are relinquished; any other objects on which the current thread may be synchronized remain locked while the thread waits.
Thread T then becomes disabled for thread scheduling purposes and lies dormant until one of the following occurs:
…
The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It competes in the usual manner with other threads for the right to synchronize on the object; once it has regained control of the object, all its synchronization claims on the object are restored to the status quo ante - that is, to the situation as of the time that the wait method was invoked. Thread T then returns from the invocation of the wait method. Thus, on return from the wait method, the synchronization state of the object and of thread T is exactly as it was when the wait method was invoked.

Note that the documentation of the no-arg wait method redirects to the wait(long,int) documentation shown above
So the issue of your code is not that the initiating thread synchronizes but that the pool's thread does not.
static final ScheduledThreadPoolExecutor EXEC = new ScheduledThreadPoolExecutor(1);

public synchronized void joinClass(UUID student) throws InterruptedException {
    this.students.add(student);

    if(students.size() == 1) {
        lecture = true;
        EXEC.schedule(new Runnable() {
            @Override
            public void run() {
                synchronized(OuterClassName.this) {
                    students.clear();
                    lecture = false;
                    OuterClassName.this.notifyAll();
                }
            }
        }, LECTURE_DURATION, TimeUnit.MILLISECONDS);
    }
    while(lecture) wait();
}

As a side note, there is no reason to remove single elements in a loop to empty a list, clear() does the job. In case of an ArrayList, repeatedly calling remove(0) is the worst way to clear it.
It's also important to keep in mind that an inner class instance is a different object than the outer class instance. It's simpler when using a lambda expression:
public synchronized void joinClass(UUID student) throws InterruptedException {
    this.students.add(student);

    if(students.size() == 1) {
        lecture = true;
        EXEC.schedule(() -> {
            synchronized(this) {
                students.clear();
                lecture = false;
                notifyAll();
            }
        }, LECTURE_DURATION, TimeUnit.MILLISECONDS);
    }

    while(lecture) wait();
}

A: No idea if this going to solve your problem but it might give you an idea.
public class Main
{
    public static void main(String[] args) throws Exception
    {
        Classroom classroom = new Classroom();
        Student studentA = new Student("Student A", classroom);
        Student studentB = new Student("Student B", classroom);
        Student studentC = new Student("Student C", classroom);
        Student studentD = new Student("Student D", classroom);

        studentA.enterClass();
        Thread.sleep(1000L); //1000 m/s early.
        classroom.start();
        Thread.sleep(1000L); //1 second late.
        studentB.enterClass();
        Thread.sleep(500L); //Late for 1.5 seconds.
        studentC.enterClass();
        classroom.join();
        Thread.sleep(2000L); //Class has ended.
        studentD.enterClass();
        System.out.println("Main Thread");
    }
}

class Student implements Runnable
{
    public String name;
    private Classroom classroom;
    public Thread thread;

    Student(String name, Classroom classroom)
    {
        this.name = name;
        this.classroom = classroom;
        thread = new Thread(this);
    }
    public void enterClass()
    {
        thread.start();
    }
    public synchronized void exitClass()
    {
        this.notify();
    }
    @Override
    public void run()
    {
        try {
            System.out.println(name + " entering the class.");
            classroom.joinClass(this);
            synchronized(this) {
                while(!classroom.hasEnded) this.wait();
            }
            System.out.println(name + " existing the class.");
        } catch(Exception e) {}
    }
}

class Classroom implements Runnable
{
    private static final long LECTURE_DURATION = 3000L;
    private Thread thread;
    public volatile boolean hasEnded;
    private List<Student> students;

    Classroom()
    {
        students = new ArrayList<Student>();
        thread = new Thread(this);
    }
    public void start()
    {
        thread.start();
    }
    public void join() throws Exception
    {
        thread.join();
    }
    @Override
    public void run()
    {
        System.out.println("Class starting...");
        try {
            Thread.sleep(LECTURE_DURATION);
        } catch(Exception e) {}
        hasEnded = true;
        System.out.println("Class ended");
        for(Student s : students) s.exitClass();
    }
    public void joinClass(Student student) throws Exception
    {
        if(!hasEnded) {
            System.out.println(student.name + " joins the class.");
            students.add(student);
        }
    }
}

Here is the output. It may vary in your system.
Student A entering the class.
Student A joins the class.
Class starting...
Student B entering the class.
Student B joins the class.
Student C entering the class.
Student C joins the class.
Class ended
Student B existing the class.
Student A existing the class.
Student C existing the class.
Main Thread
Student D entering the class.
Student D existing the class.


text:
Q: HAProxy and LXD Containers - Route based on naked domain, specific sub-domain and all other sub-domains I have tried searching for a similar solution to the problem I am having, but could not find anything.
I have setup some LXD containers, one is HAProxy which is recieving port 80 traffic from the host's public IP address. HAProxy thens sends the traffic to the correct container depending on the domain.
The issue I am having is, even though I have set The domain_specific_subdomain ACL rule for subdomain.example.com, the other domain_root ACL rule takes precedant.
Containers:

*

*lxd-container-web1: Use if root domain, or any other subdomain, e.g. (www., dev.) 'example.com'

*lxd-container-web2: Use only if this specific subdomain 'subdomain.example.com'

Question: How can I have this so the naked domain example.com and all other subdomains (e.g. www., dev., etc) go to this backend backend_web1 except for subdomain.example.com which should go to the: backend_web2 backend.
This is my config file:
global
        log /dev/log    local0
        log /dev/log    local1 notice
        chroot /var/lib/haproxy
        stats socket /run/haproxy/admin.sock mode 660 level admin
        stats timeout 30s
        user haproxy
        group haproxy
        daemon

        # Default SSL material locations
        ca-base /etc/ssl/certs
        crt-base /etc/ssl/private

        # Default ciphers to use on SSL-enabled listening sockets.
        # For more information, see ciphers(1SSL). This list is from:
        #  https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
        ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS
        ssl-default-bind-options no-sslv3

defaults
        log     global
        mode    http
        option  httplog
        option  dontlognull
        option   forwardfor
        option   http-server-close
        timeout connect 5000
        timeout client  50000
        timeout server  50000
        errorfile 400 /etc/haproxy/errors/400.http
        errorfile 403 /etc/haproxy/errors/403.http
        errorfile 408 /etc/haproxy/errors/408.http
        errorfile 500 /etc/haproxy/errors/500.http
        errorfile 502 /etc/haproxy/errors/502.http
        errorfile 503 /etc/haproxy/errors/503.http
        errorfile 504 /etc/haproxy/errors/504.http

# Frontend
frontend www_frontend
        bind *:80     # Bind to port 80 (www) on the container

        # Covers naked domain and all subdomains
        acl domain_root hdr(host) -i example.com

        # Specific sub-domain
        acl domain_specific_subdomain hdr(host) -i subdomain.example.com

        # Redirect the connection to the proper server cluster, depending on the match.
        use_backend backend_web1 if domain_root
        use_backend backend_web2 if domain_specific_subdomain

# Domain dependent containers
backend backend_web1
        balance leastconn

        # We set the X-Client-IP HTTP header. This is useful if we want the web server to know the real client IP.
        http-request set-header X-Client-IP %[src]

        # This backend, named here "backend_web1", directs to container "lxd-container-web1.lxd" (hostname).
        server web1 lxd-container-web1:80 check

backend backend_web2
        balance leastconn
        http-request set-header X-Client-IP %[src]
        server web2 lxd-container-web2.lxd:80 check

A: From the haproxy docs:

There may be as many "use_backend" rules as desired. All of these rules are evaluated in their declaration order, and the first one which matches will assign the backend.

So if you switch the use_backend line ordering, it should work.
    # Redirect the connection to the proper server cluster, depending on the match.
    use_backend backend_web2 if domain_specific_subdomain
    use_backend backend_web1 if domain_root

Or better yet, maybe default_backend would be better here:
    # Use backend_web2 if ACL matches
    use_backend backend_web2 if domain_specific_subdomain

    # Otherwise, default to backend_web1
    default_backend backend_web1


text:
Q: How do you decouple getData with a private flag variable? I have a custom UITableViewController class that is shared among a few ViewControllers of my app.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ...
    // Check if we are almost at the end of the scroll. If so, start fetching.
    // Doing this here is better than overriding scrollViewDidEndDragging
    if (indexPath.row >= [self.tableView numberOfRowsInSection:0] - 3) {
        [self refill];
    }

    return cell;
}

I would like to do pre-emptive fetching before the user has hit the bottom of the page.
However, I noticed that if the user scrolls up and then down again, my VC will trigger another fetching.
So I came up with a flag isFetching which checks to prevent double fetching. Unfortunately I am running asynchronous code and I need a way to reset this flag after my fetching operation has completed.
FeedVC:
- (void)refill {
    if (self.continueFetching && !self.isFetching) {
        NSLog(@"Fetching started");
        self.isFetching = true;
        AFJSONRequestOperation *operation = [self.delegate refill:^{
            NSLog(@"Fetching completed");
            self.isFetching = false;
        }];
        [self.pendingOperations addObject:operation];
    }
}

Delegate:
- (AFJSONRequestOperation *)refill:(void (^)(void))finishCallback {
    return [[ItemStore sharedInstance] fetchItemsForFeed:^(int itemsFetched, int nextOffset, bool hasNextPage) {
        finishCallback();
    } withFailureBlock:^{
        finishCallback();
    }];
}

I find it very painful to pass around a finish bloc in order to flip a boolean. does anyone have a better recommendation?

A: Elaboration:
typedef void(^block_t)(void);
typedef void(^success_block_t)(int itemsFetched, int nextOffset, bool hasNextPage);

FeedCV:
/****************************************************************************/
/*!
 @note assume the declarations:
 @property (nonatomic,strong) NSOperation* fetchOp;
 @property (nonatomic,strong) NSOperationQueue* operationQueue;
 */
/****************************************************************************/
- (void) refill
{
    if (self.fetchOp) { //fetch is in progress
        return;
    }

    __block __weak id weakSelf = self;
    block_t completionBlock = ^{ //this will happen on a BG thread
        //Implement what ever logic seems to fit your FeedVC uppon completion
        //This will be called on the operation thread, so don't update UI here
        //Move to main thread UI updates
        [weakSelf setFetchOp:nil];
    };

    self.fetchOp = [self.delegate refill:completionBlock];
//                            successBlock:nil
//                               failBlock:nil];

    //If you can't change your delegate code then:
    //self.fetchOp = [self.delegate refill:nil];
    //[self.fetchOp setCompletionBlock:completionBlock];

    [self.operationQueue addOperation:self.fetchOp];
}
/****************************************************************************/

Delegate:
/****************************************************************************/
/*!
 @note If you can change this API add support for the blocks
 */
/****************************************************************************/
- (AFJSONRequestOperation*) refill:(block_t)completionBlock
//                      successBlock:(success_block_t)success
//                         failBlock:(block_t)fail
{
    AFJSONRequestOperation* op = [[ItemStore sharedInstance] fetchItemsForFeed:nil/*success*/
                                                              withFailureBlock:nil/*fail*/];
    [op setCompletionBlock:completionBlock];
    return op;
}
/****************************************************************************/


text:
Q: Retrieve Java string from Android drawable resource name I have an array of drawable png files like this :
int[] images = {R.drawable.alabama, R.drawable.alaska, R.drawable.arizona};

currentImage++;
currentImage = currentImage % images.length;
hImageViewPic.setImageResource(images[currentImage]);

How can I get something like this:
String imageName = "alabama"

I tried this, but it returns my Image View id instead of the src name.
String imageName = getResources().getResourceEntryName(R.id.idImageViewPic);

UPDATE
This is more of my code to get things in context. I have adapted an answer below, but i get an error: incompatible types: String cannot be converted to int.
public class GameFragment extends Fragment {

    private AlertDialog mDialog;
    private ImageView hImageViewPic;
    private Button iButton, gButton;

    private int currentImage = 0;
    int[] images = {R.drawable.alabama, R.drawable.alaska, R.drawable.arizona};

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_game, container, false);
        hImageViewPic = (ImageView) rootView.findViewById(R.id.idImageViewPic);
        iButton = (Button) rootView.findViewById(R.id.guess_button);

        final EditText responseField = (EditText) rootView.findViewById(R.id.ResponseText);

        // Handle buttons here...
        View guessButton = rootView.findViewById(R.id.guess_button);
        guessButton.setOnClickListener(new View.OnClickListener() {
            int score = 0;

            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder =
                        new AlertDialog.Builder(getActivity());
                String response = responseField.getText().toString();
                String wrongTextAnnouncement = getString(R.string.wrong_text, response);

                int resourceId = images[currentImage];
                String name = getResources().getResourceEntryName(resourceId);
                hImageViewPic.setImageResource(resourceId);
                hImageViewPic.setTag(name);
                String imageName = hImageViewPic.getTag(name);

                Log.d("UT3", response);
                Log.d("UT3", wrongTextAnnouncement);
                Log.d("UT3", imageName);
                if (imageName != response) {
                    builder.setTitle(R.string.wrong_title);
                    builder.setMessage(wrongTextAnnouncement);
                    builder.setCancelable(false);
                    builder.setPositiveButton(R.string.ok_label,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface,
                                                    int i) {
                                    // nothing
                                }
                            });
                    mDialog = builder.show();
                } else {
                    builder.setTitle(R.string.right_title);
                    builder.setMessage(R.string.right_text);
                    builder.setCancelable(false);
                    builder.setPositiveButton(R.string.ok_label,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface,
                                                    int i) {
                                    // nothing
                                }
                            });
                    score += 10;
                    String scoreString = String.valueOf(score);
                    Log.d("UT3", scoreString);
                }
                mDialog = builder.show();
                currentImage++;
                currentImage = currentImage % images.length;
                hImageViewPic.setImageResource(images[currentImage]);
            }
        });
        return rootView;
    }

A: You are receiving id of View because you are passing id of View to
getResourceEntryName(int resid)

If you want to get String imageName = "alabama" pass to method id of drawable, not ImageView
But there is no way to check what resource id was set to image view because under the hood Drawable was created from passed id.
Fortunately you can use hImageViewPic.setTag(Object object) to read it later.
So the code may look like:
int[] images = {R.drawable.alabama, R.drawable.alaska, R.drawable.arizona};

currentImage++;
currentImage = currentImage % images.length;
int resourceId = images[currentImage];
String name = getResources().getResourceEntryName(resourceId);
hImageViewPic.setImageResource(resourceId);
hImageViewPic.setTag(name);

Later you can get the name of image by using: hImageViewPic.getTag()

A: In my opnion this is better you use array of string images name like:
String[] imagesTitle = {alabama, alaska,arizona};

then get id of images like:
String imageName = imagesTitle[currentImage];
int drawableResourceId = this.getResources().getIdentifier(imageName,"drawable", this.getPackageName())

Where "this" is an Activity, written just to clarify.
then you can set tag for image and set id for your imageview like:
hImageViewPic.setImageResource(drawableResourceId);
hImageViewPic.setTag(imageName);

I hope this can help!


text:
Q: Unable to toggle div on top.document I have an iframe that returns data to the top.document window just fine by using:
$("#someDiv", top.document).html(data);

The above works fine. Now I want to be able to hide a div on the top document and I try:
$("#someDiv", top.document).toggle("slow");

It is not working... any ideas?

A: Try
top.$('#someDiv').toggle('slow');


text:
Q: converting a string to stringified JSON I'm getting a string which looks like following
"{option:{name:angshu,title:guha}}"

Now I have to make a valid JSON string from this. Is there any smart way to convert that. I tried with string handelling but that takes a lot of conditions still being case specific. Even i tried with eval() that doesn't work also.

A: This regex will do the trick for the provided example string:
/:([^{},]+)/g

Regex101 analysis of it:
: matches the character : literally
1st Capturing group ([^{},]+)
   [^{,}]+ match a single character not present in the list below
       Quantifier: + Between one and unlimited times, as many times as possible,   giving back as needed [greedy]
       {}, a single character in the list {}, literally
g modifier: global. All matches (don't return on first match)

Basically, it looks for all characters following a : that aren't {},. those "words" are saved in the 1st capturing group, which allows .replace to re-use them with $1.
You can use the regex like this:

var raw = "{option:{name:angshu,title:guha}}",
    regex = /:([^{,}]+)/g,
    replacement = ':"$1"';

var jsonString = raw.replace(regex, replacement);

alert(jsonString);

A: try this if you are looking for JSON object
 string inputString = '{option:{name:angshu,title:guha}}';
 var obj = JSON.parse(inputString);


text:
Q: Why isn't jQuery binding with click? Why isn't jQuery binding to the click event?  When I click the selects, they don't alert, except for the one that I put onClick on.
<html>
<head>
<title>Robo</title>

<script type="text/javascript" src="jquery-1.4.2.min.js"></script><script type="text/javascript">

$('.changer').click(function(){alert('test');});

</script>
</head>
<body>

<select class="changer" name="dept" id="dept_select">
    <option value="">Select a Department</option>
</select>

<select onclick="alert('ya');" class="changer" name="course" id="course_select">
    <option value="">Select a Course</option>
</select>
<select class="changer" name="section" id="section_select">
    <option value="">Select a Section</option>
</select>

</body>
</html>

A: Because the .changer elements are not available in the dom when you are binding the click handlers.
You can do two things:
Use jQuery ready event handler
 $.ready(function(){
      $('.changer').click(function(){
        alert('test');
      });
    });

or  Use live function.
$('.changer').live("click", (function(){
   alert('test');
 });

A: You need to wrap your code in ready handler:
$(function(){
  $('.changer').click(function(){alert('test');});
});

A: Wrap your jQuery in a ready event:
$(function() {
    $('.changer').click(function(){alert('test');});
});

A: you can also use delegate function...
$('.changer').delegate('click',function(){
   alert('test');
 });

A: You have to wrap syntax dg .ready handler.
<script type="text/javascript">
$(document).ready( function(){
   $('.changer').click(function(){alert('test');});
});
</script>

It's method used to specify a function to execute when the DOM is fully loaded.


text:
Q: Unable to Compile Applications No matter which project I choose, I am getting the same error when I go to run the app in the simulator (iPhone).  I am using the latest iPhone SDK and Titanium SDK (though I also had problems before that).
[INFO] Compiling JavaScript...one moment
[INFO] No JavaScript errors detected.
[INFO] One moment, building ...
[INFO] Titanium SDK version: 1.6.1
[INFO] iPhone Device family: iphone
[INFO] iPhone SDK version: 4.3
[INFO] iPhone simulated device: iphone
[INFO] Performing full rebuild. This will take a little bit. Hold tight...
[INFO] Skipping JS compile, running from simulator
[ERROR]
[ERROR] Error: Traceback (most recent call last):
File "/Library/Application Support/Titanium/mobilesdk/osx/1.6.1/iphone/builder.py", line 1091, in main
execute_xcode("iphonesimulator%s" % link_version,["GCC_PREPROCESSOR_DEFINITIONS=__LOG__ID__=%s DEPLOYTYPE=development TI_DEVELOPMENT=1 DEBUG=1 TI_VERSION=%s" % (log_id,sdk_version)],False)
File "/Library/Application Support/Titanium/mobilesdk/osx/1.6.1/iphone/builder.py", line 1012, in execute_xcode
output = run.run(args,False,False,o)
File "/Library/Application Support/Titanium/mobilesdk/osx/1.6.1/iphone/run.py", line 39, in run
sys.exit(rc)
SystemExit: 65

A: Things to try, if you haven't tried them yet:

*

*Create a new project.  Just using the default generated code and none of your own code or code imported from elsewhere, try to run it in the emulator.  Does it work?  If so, copy everything except the build directory from a project that doesn't work into your new project.  Does it work now?  This is what I (and, judging from Internet forums, a lot of other people) needed to do to get the Kitchen Sink app to run, for example.

*The error above is for the iPhone.  What happens if you install the Android SDK and try compiling as an Android app?  This is not really a solution, but it would be useful information for someone trying to help you.

Not exactly a slam-dunk here's-how-to-fix-it answer, but hopefully something that gets you on the right track (or if it's stuff you already tried, edit your post to mention that!).


text:
Q: How to compute the Monopole Floer Homology for Surface $\times S^1$ ? We know that Monopole Floer homology of a 3-manifold $M$ depends on a spin-c structure. My question is that if $M$ is $F\times S^1$ ($F$ is a surface of genus larger than 1) then how can we compute the Floer homology for it?
For the spin-c structures satisfying $\langle c_1(L),F\rangle>2g-2$ ($L$ is the determinant bundle of the spin-c structure,$g$ is the genus of $F$), Kronheimer and Mrowka prove that the Floer homology vanishes. They also proved that if $\langle c_1(L),F\rangle=2g-2$ then the Floer homology is $\mathbb{Z}$. But what about the other spin-c  structure (when $\langle c_1(L),F\rangle<2g-2$)?
Also, what is the answer for this question if we consider Heegaard Floer Homology instead of Monopole Floer Homology?

A: I would assume you are interested in $HM$-to as opposed to $HM$-bar ($HM$-bar is mostly computed in the book Monopoles and 3-manifolds by Kronheimer and Mrowka).  For the case of $HM$-to, you should use (as answered above) that monopole is isomorphic to Heegaard Floer (Kutluhan-Lee-Taubes or Taubes + Colin-Ghiggini-Honda).
If you want the trivial torsion Spin$^c$ structure, this is computed by Jabuka and Mark:
http://arxiv.org/pdf/math/0502328v4.pdf
This paper also has the references to the earlier computations for the other Spin$^c$ structures, done by Ozsvath and Szabo.


text:
Q: How can I configure the default transmission rate for 802.11 ("WiFi")? I need to lower the transmission rate of my IEEE 802.11g network interface controller to have acceptable an packet loss ratio (< 0.5 %), otherwise it becomes very high (> 50 % is typical, but it varies). I use NetworkManager to handle my network connection, however it doesn't has a option to lower the transmission rate, so I do it manually through the command line with sudo iwconfig wlan0 rate 1M every time I power on the computer.
After installation, how can I configure my GNU/Linux system so that the transmission rate is 1 Mbit/s by default (without having to set it manually every time I boot the computer)?. Equivalently, how can I persistently set the transmission rate of my IEEE 802.11g network interface controller to 1 Mb/s?.
Note: I connect only to a single wireless network, but it's not always available every time I power on the computer (this is because I'm not in that location, not a technical problem), and connecting isn't immediate anyway, so I can't work around the problem by making a script that is run when I log-in to the graphic environment and does iwconfig lwan0 rate 1M.
Regards and thanks.
Edit: My /etc/network/interfaces only has the following (Bear in mind the network is handled by NetworkManager):
auto lo
iface lo inet loopback

A: Please (after you created the backup copy) edit your /etc/network/interfaces file to the following state by adding the last three lines:
auto lo
iface lo inet loopback

auto wlan0
iface wlan0 inet dhcp
  pre-up iwconfig wlan0 rate 1M

I am not sure if this works as I can't try it out here. Maybe you will lose your wlan0 connection because I missed some necessary additional lines. If this happens, reset the file to the backup state and it should work again as before.


text:
Q: Reading an ADT from a ByteString Let's say we have a data type like
data Letter = A | B | C

and we get a ByteString input that contains "A".
How do we easily transform that ByteString into a Letter type?
P.S. I found the Readable library that does this, however it returns a MonadPlus (that I'm not very familiar with) instead of a Maybe Letter that I would expect.

Edit:
Here is the simple HTTP app I'm working on for context. I can't seem to be able to get a Maybe Letter with this.
import Network.Wai
import Network.HTTP.Types
import Network.Wai.Handler.Warp (run)

app :: Application
app request respond = let letter :: Maybe Letter
                          letter = fmap fromBS $ getParam request "letter"
                      respond $ responseLBS status200
                                            [("Content-Type", "text/plain")]
                                            "hello"

getParam request name = join (lookup name (queryString request))

The compiler complains about a type error and I can't figure out how to capture these two types m0 and a0, not even if I write something like let letter :: Maybe (Letter, ByteString) in line 7 instead.
• Couldn't match type 'm0 a0' with 'Letter'
  Expected type: Maybe Letter
  Actual type: Maybe (m0 a0)

A: Typed not tested:
{-# LANGUAGE OverloadedStrings #-}
import Data.ByteString.Char8 as BC
-- ^^ Replace if you want an encoding besides ASCii

data T = A | B | C deriving (Eq,Ord,Show)

f :: ByteString -> Maybe T
f x | x == "A" = Just A
    | x == "B" = Just B
    | x == "C" = Just C
    | otherwise = Nothing

A: The general approach is to derive a Read instance which provides deserialization from a String:
data Letter = A | B | C deriving (Read)

via read, reads, readMaybe and other variations defined in Text.Read, and then use a conversion function (such as Data.ByteString.Char8.unpack, if the byte string is ASCII or Latin-1) to convert from the bytestring to a string.
The details of what you're trying to do are a little fuzzy.  (For example, if the bytestring is "ABC", do you want to parse the "A" and save the "BC" for later, or should that yield Nothing.)  However, the following may get you started:
import Text.Read
import qualified Data.ByteString.Char8 as C

data Letter = A | B | C deriving (Show, Read)

readLetter :: C.ByteString -> Maybe Letter
readLetter = readMaybe . C.unpack

Testing it in GHCi:
> :set -XOverloadedStrings
> readLetter "A"
Just A
> readLetter "B"
Just B
> readLetter "X"
Nothing
> readLetter "ABC"
Nothing
>

A:
it returns a MonadPlus (that I'm not very familiar with)

Maybe has a MonadPlus instance, so you could just use that.


text:
Q: React-Redux - using a response from a fetch request in componentDidMount in another request in the component I have a component that fires off a fetch request (in redux) on componentDidMount.  In the same component I need to fire off another redux fetch request using the response data from the first one, preferably before the render.
Due to the fetch being executed in the redux action I havent been able to do this with a promise in componentDidMount as the promise resolves when the action starts and not finishes.
on research I thought it might be able to do it with componentWillRecieveProps however I don't fully understand how and also read that this hook is being depreciated soon.
any help would be greatly appreciated.
first action:
componentDidMount(){
 this.props.onGetSessionId(this.parseToken(this.props.location.search))
};

secondAction:
this.props.onFetchFavourites(this.props.sessionId)

A: In onGetSessionId you can return promise, like this:
function onGetSessionId(param) {
    return new Promise((resolve, reject) => {
        apiClient.call()
            .then(data => {
                resolve(data);
            })
            .catch(error => {
                reject(error)
            })
    })
}

and then in componentDidMount:
componentDidMount(){
    this.props.onGetSessionId(this.parseToken(this.props.location.search))
        .then(data => {
            // ... do stuff with returned data
        })
}

A: It's hard to help here without seeing the code for how onGetSessionId and onFetchFavourites are implemented but assuming that you're using redux-thunk, it's probably something like this:
function getSessionId(token) {
  return function (dispatch) {
    return fetchSessionId(token)
    .then(
      response => dispatch(getSessionIdSuccess(forPerson, response.id))
    )
    .catch(
      error => dispatch(getSessionIdFailure(error)
    )
  };
}

function getFavorites(sessionId) {
  return function (dispatch) {
    return fetchFavorites(sessionId)
    .then(
      response => dispatch(getFavoritesSuccess(sessionId, response.favorites))
    )
    .catch(
      error => dispatch(getFavoritesFailure(error)
    )
  };
}

fetch returns a promise so you can just keep chaining .then and using the return value from the previous then. this lets you do something like
function getSessionIdAndFavorites(token) {
  return function (dispatch) {
    return fetchSessionId()
    .then(
      response => {
        dispatch(getSessionIdSuccess(response.id))
        return response.id
      }
    )
    .then(id => {dispatch(getFavorites(id)}
    .catch(
      error => dispatch(getSessionAndFavoritesIdFailure(error)
    )
  };
}


text:
Q: Cookie working 50% I am using the query cookie plugin like this:
$(document).ready(function(){
    $('a.close').click(function(){
        var user = $('div.popup article.user').html();

        $.cookie('the_cookie', user, {path: "/", domain: "domain.com"});
        message = $.cookie('the_cookie');

        $('section#sidebar_right').html(message);
    });
});

So, when user clicks the "close-button", the cookie gets the username and puts it into a specific area, this scenario is created on this site:
domain.com/test.php#close
When i refresh to this site:
domain.com/test.php
The cookie disappear´s (I can see this because the displayed content disappear´s).
Anybody could tell me why?
Greetings
EDIT:
$(document).ready(function(){
$('a.close').click(function(){
    var user = $('div.popup article.user').html();

    $.cookie('the_cookie', user, {expires: "7",path: "/", domain: "domain.com"});
    message = $.cookie('the_cookie');

    $('section#sidebar_right').html(message);
});

});
=> still not working, any idea´s ?

A: You haven't set lifetime of the cookie, so it's getting deleted on session end.

https://github.com/carhartl/jquery-cookie
expires
expires: 365 Define lifetime of the cookie. Value can be a Number
  which will be interpreted as days from time of creation or a Date
  object. If omitted, the cookie becomes a session cookie.


text:
Q: The breakpoint will not currently be hit. No symbols have been loaded for this document I am dealing with a puzzling situation here,and need any help I can get . I am using Visual Studio 2008 and have a dev site running on IIS. When I  Attach to the process running in IIS, it attaches successfully(no errors). However when I attempt to debug, nothing happens. I have closed out my browser, done a restart on the application pool, and website, cleared cache, and even forced a rebuild in visual studio. Still I am unable to step into code. Any idea what I could have wrong here?
The breakpoint will not currently be hit. No symbols have been loaded for this document.

A: Your symbols might be wrong or missing. In extra rare circumstances you might need to step inside the function via assembly, only then VS picks up that you're actually calling your component.

A: Check if you have you set  compilation debug="true"  in you web.config file?

A: I believe you need to debug the website from within Visual Studio in order for breakpoints to be hit.  Use the green "play" button, or use F5, or just go to Debug > Start Debugging.


text:
Q: Connection between boundary value problems and eigenvalue problems In a recent course on Fourier Analysis and Approximation, the lecturer introduced the topic by attempting to solve a boundary value problem (BVP)  $y''+y=\sin^3 x$, where $y$ is a function with a single argument.
The lecturer first solved the equation $y''+y=\lambda y$, which eventually leads to the line $\sum_k c_ky_k''+\sum_kc_ky_k=\sum_kc_k\lambda_ky_k$, where $k$ is the eigenvalue(s).
To me, the question was originally a boundary value problem, and the equation lecturer considered is an eigenvalue problem. While I understand that eigenvalue problems are important in BVP, I was a bit confused why we need to consider $y''+y=\lambda y$ in the first place (or why the question can be transformed into the eigenvalue problem). The lecturer briefly mentioned a name "Fourier method", but I failed to catch the details.

A: At a very basic level you need to look at the $\lambda=0$ eigenvalue problem just to know whether solutions to the BVP, if they exist, are unique. This part is necessary, it is not just a method that you can swap out for another method.
You can further use eigenfunctions to solve the whole problem if the forcing can be written as a superposition of eigenfunctions with nonzero eigenvalue. Suppose you can; that is, suppose the problem is $Ly=f$, $f=\sum a_k e_k$, $Le_k=\lambda_k e_k$ with nonzero $\lambda_k$. Then with $y=\sum b_k e_k$ the equation reads $Ly=\sum \lambda_k b_k e_k=\sum a_k e_k$, so you get a solution with $b_k=\frac{a_k}{\lambda_k}$. Then you have to add the general solution to the homogeneous BVP (which might or might not be just the zero function) to that to get the general solution.


text:
Q: How to edit a nodejs package? I have a nodejs project. Within this project, I installed a package via npm install youtube-dl --save. So, I not got a ./SuperProject/node_modules/youtube-dl/ directory, whom content is something such as :
|-/bin
   +- youtube-dl       <--- what is that thing ?
|-/example
|-/lib
   +- youtube-dl.js    <--- core code and executable ... i guess
|-/scripts
|-/test
|-LICENSE
|-package.json
|-README.md

I inspect around, and I see that I could edit ./node_modules/youtube-dl/lib/youtube-dl.js, by adding one condition to this package's main file :
if (options.format) {
    args.push('--sub-format=' + options.format);
}

I instinctively and boldly add this lines to ./node_mudules/youtube-dl/lib/youtube-dl.js.
Back to root, I relaunch my script :
cd ../../SuperProject
node superproject.js

I see no change in my output. Was I right to edit ./node_modules/youtube-dl/lib/youtube-dl.js ? Or is ./node_modules/youtube-dl/bin/youtube-dl the real deal to edit ?

A: Yes, edit youtube-dl/lib/youtube-dl.js. A console.log('hello world') there can proves you that it is the right file to edit. I have no idea what is the youtube-dl/bin/youtube-dl about.


text:
Q: Unix join two files with regular expressions using awk I have one file (lookup.txt) which contains a lookup table consisting of a list of regular expressions, with corresponding data (categories, and periods). e.g.
INTERNODE|household/bills/broadband|monthly
ORIGIN ENERGY|household/bills/electricity|quarterly
TELSTRA.*BILL|household/bills/phone|quarterly
OPTUS|household/bills/mobile|quarterly
SKYPE|household/bills/skype|non-periodic

I have another file (data.txt) which contains a list of expenses, eg:
2009-10-31,cc,-39.9,INTERNODE BROADBAND
2009-10-31,cc,-50,ORIGIN ENERGY 543546
2009-10-31,cc,-68,INTERNODE BROADBAND EXCESS CHARGES
2009-10-31,cc,-90,TELSTRA MOBILE BILL
2009-11-02,cc,-320,TELSTRA HOME BILL
2009-11-03,cc,-22.96,DICK SMITH
2009-11-03,cc,-251.24,BUNNINGS
2009-11-04,cc,-4.2,7-ELEVEN

I want to join these two together, whereby the 4th column in data.txt file matches the regular expression from the first column of the lookup.txt file.
So the output would be:
2009-10-31,cc,-39.9,INTERNODE BROADBAND,household/bills/broadband,monthly
2009-10-31,cc,-50,ORIGIN ENERGY 543546,household/bills/electricity,quarterly
2009-10-31,cc,-68,INTERNODE BROADBAND EXCESS CHARGES,household/bills/broadband,monthly
2009-10-31,cc,-90,TELSTRA MOBILE BILL,household/bills/phone,quarterly
2009-11-02,cc,-320,TELSTRA HOME BILL,household/bills/phone,quarterly
2009-11-03,cc,-22.96,DICK SMITH
2009-11-03,cc,-251.24,BUNNINGS
2009-11-04,cc,-4.2,7-ELEVEN

I've acheived this using a bash loop, looping over the lookup, doing greps and adding extra columns on using sed, but it is very slow.  So was wondering if there was a faster method of doing this, saying using awk.
Any help would be appreciated.

A: $ awk -F'|' 'FNR==NR{a[$1]=$2","$3;next}{m=split($0,b,",");for(i in a){if(b[4]~i){print $0","a[i];next}}}1' lookup file
2009-10-31,cc,-39.9,INTERNODE BROADBAND,household/bills/broadband,monthly
2009-10-31,cc,-50,ORIGIN ENERGY 543546,household/bills/electricity,quarterly
2009-10-31,cc,-68,INTERNODE BROADBAND EXCESS CHARGES,household/bills/broadband,monthly
2009-10-31,cc,-90,TELSTRA MOBILE BILL,household/bills/phone,quarterly
2009-11-02,cc,-320,TELSTRA HOME BILL,household/bills/phone,quarterly
2009-11-03,cc,-22.96,DICK SMITH
2009-11-03,cc,-251.24,BUNNINGS
2009-11-04,cc,-4.2,7-ELEVEN

A: You can do it in Python:
#!/usr/bin/python
import csv, re
lookup = []
with open('lookup.txt') as f:
    for rec in csv.reader(f, delimiter='|'):
        lookup.append((re.compile(rec[0]), rec[1:]))
with open('data.txt') as f:
    for rec in csv.reader(f, delimiter=','):
        for rexp, fields in lookup:
            if rexp.match(rec[3]):
                rec.extend(fields)
                break
        print ','.join(rec)

For your files lookup.txt and data.txt it returns the following in less than 0.3s:
2009-10-31,cc,-39.9,INTERNODE BROADBAND,household/bills/broadband,monthly
2009-10-31,cc,-50,ORIGIN ENERGY 543546,household/bills/electricity,quarterly
2009-10-31,cc,-68,INTERNODE BROADBAND EXCESS CHARGES,household/bills/broadband,monthly
2009-10-31,cc,-90,TELSTRA MOBILE BILL,household/bills/phone,quarterly
2009-11-02,cc,-320,TELSTRA HOME BILL,household/bills/phone,quarterly
2009-11-03,cc,-22.96,DICK SMITH
2009-11-03,cc,-251.24,BUNNINGS
2009-11-04,cc,-4.2,7-ELEVEN

A: You can do it in Perl.  The advantage of Perl (or Python) is they have libraries for dealing with CSV files.  Your examples are simple enough, but what happens if you have a comma inside double quotes?  Or what about utf8?  etc.
The standard Perl library for this is Text:CSV_XS.  However, its a bit verbose and I prefer Parse::CSV which is a wrapper around Text::CSV_XS.
#!/usr/bin/perl

use strict;
use warnings;
use Parse::CSV;

my %lookup;
my $l = Parse::CSV->new(file => "lookup.txt", sep_char => '|');
while (my $row = $l->fetch) {
   my $key = qr/$row->[0]/;
   $lookup{$key} = [$row->[1,]];
}

my $d = Parse::CSV->new(file => "data.txt");
while (my $row = $d->fetch) {
   foreach my $regex (keys %lookup) {
      if ($row->[3] =~ $regex) {
         push @$row, @{$lookup{$regex}};
         last;
      }
   }
   print join(",", @$row), "\n";
}

A: If you didn't have the regexs, you could use join. How many regexps does lookup.txt have? If it's just that one, just expand it and drop that feature.

A: Awk is really designed to process a single stream of data one record at a time, so it isn't the right tool for this job.  It would be a ten-minute exercise in Perl or another language that's more oriented toward general-purpose programming.
If you're bent on doing it all in awk, write one script to generate a second awk script from your lookup file that processes the data, then run the second script.


text:
Q: getting the latest xx records with mongoose, How to order them? I'm trying to get the last 20 records of user collection with mongoose:
User.find({'owner': req.params.id}).
sort(date:'-1').
limit(20).
exec(.....)

This works well, show the last 20 items.
But the items inside the array are sorted from the most recent to the oldest, Is there any way to reverse this with mongoose?
Thanks

A: Find total and select only latest 20 , may be this is not effective way you found , but this will solve your problem.
 User.count({'owner': req.params.id},function(err,count){

  if(count){

    var skipItem=count-20;
    User.find({'owner': req.params.id}).
    .skip(skipItem)
    .limit(20)
    .sort(date:'1').
    exec(.....)

  }

});

A: You can certainly do this with an aggregation, such as this:
db.user.aggregate[(
  { $match : {"owner" : req.params.id}},
  { $sort : {"date" : -1}},
  { $limit : 20},
  { $sort : {"date" : 1}}
])

Notes on this aggregation:

*

*The first three parts do the same job as the Find in your question

*The fourth part applies a further sort, which re-orders the returned 20 records from oldest to most recent

*I have written it in native MongoDB aggregation syntax; you will need to adjust the code to generate the same aggregation from Mongoose.

Update: I think this is not possible with a find() with cursor methods, because you would need two different sort() operations. But, MongoDB does not treat them as a sequence of independent operations; the docs give an example of methods written in one order — sort().limit() — being equivalent to the opposite order — limit().sort(), showing that the order cannot be relied upon as meaningful.

A: db.users.aggregate([
    { $match: {
       'owner': req.params.id
    }},
    { $unwind: '[arrayFieldName]' },
    { $sort: {
        '[arrayFieldName]': -1/1,
         'date':-1
    }}
])