text:
Q: Avoid Telegram's file size limit Telegram bots have a 20MB size limit for files, i was wondering if it was possible to avoid it in python, especially with the pyTelegramBotAPI module.
I found a similar question here on stackoverflow but it wasn't using python.

A: These file size limits are set for the Telegram Bot API. So I wouldn't recommend using the pyTelegramBotAPI module for your purpose. Rather use the Telegram API, which uses the MTProto protocol rather than Bot API endpoints. This allows for maximum file sizes of 2GB.
Modules such as telethon or pyrogram allow to create bots that use MTProto.


text:
Q: making a loop to display buttons I am trying to make a loop that will display some images and add an event listener to each image which, when clicked will assign the appropriate value to humanGoal. I have:
var humanGoal;

function displayPicker(round){
    for(var i = 0; i <= round; i++){
        document.write('');
        document.getElementById('picker'+i).addEventListener("click", function () {
            humanGoal = i;
            document.write('you picked ' + humanGoal );
        });
    }
}

why does humanGoal always === round+1, instead of the variable i from the for loop?

A: The humanGoal variable is being overwrited with every for loop iteration and holds the round + 1 value at the end. Different words speaking - it will always display a wrong index.
Solution: apply same class to the each img element, bind a click event listener and display the actual index by passing i variable inside the Array#forEach function.

function displayPicker(round){
    for (var i = 0; i <= round; i++){
      document.write('');
    }
    var elems = document.getElementsByClassName('img');
        Array.from(elems).forEach((v,i) => v.addEventListener('click', function() {
          console.log(`You picked ${i}`);
        }));
}

displayPicker(5);

A: See answer to your question is simple, when you were trying to assign human goal with value of i, the loop is already been iterated over "rounds" value that why you always getting i === round inside click function.
See the below code snippet,

for getting the correct result you can follow the approach provided by @Kind user

redpajama_set_name: RedPajamaStackExchange


text:
Q: Custom Error Page for SharePoint We've created an Application Page which configure database for custom modules. We've designed this Application Page with SharePoint custom control.
There are some errors which can be occurred when user configure database, for example, database server not found etc. How should we design an Application which should be similar to SharePoint Error Pages.
Or Is there any better way of doing this?
Thanks.

A: It's not clear the purpose of "similar to SharePoint Error Page". If you can/want you can reusre SharePoint error page by using SPUtility.TransferToErrorPage(). If you need some customisations - then I beleave you must create something yorself ..

A: I believe if the exception caught by the page inherits from SPException, the message in the exception will be displayed on the normal error page.


text:
Q: Setting permissions for custom shell scripts and directory My question is about permissions and ownership settings for my custom shell scripts and the custom shell script directory itself. This is only for security on my personal machine, but I'd like to know best practices for any situation.
My script directory is /usr/local/scripts/

*

*Should I give myself write privileges to my own scripts? Or should root be the only one?

*Should everyone else have read-only permission?

*Should root have ownership over any of my scripts/directory?
I'm still learning UNIX permissions, so trying to wrap my head around the implications of certain files having certain permissions still eludes me to an extent. Thanks in advance.

A: First, I recommend you to put your unprivileged scripts (scripts that do not need to be executed as root) inside your home folder (it is a common practice to put them in ~/bin, some distributions even add this directory to your $PATH, so you can execute them from any directory). That way you do not have to write to a root-owned directory, avoiding the need of becoming root to edit them.
About execute permissions, almost always, if you have read permissions you will be able to execute it, either by copying to another location and giving it execute permissions, or by launching the interpreter with the script as first argument (eg. bash my_script.sh).
I see no problem in giving others read and execute permissions to my scripts, remember that they will be executed with the executing user's permissions, not yours. Anyway, if they have the knowledge, they will be able to write and execute them.
If you put scripts outside your home directory, they should be owned and only editable by root (they can be readable and executable by everyone). That way, if root executes it, it knows that no one else can have changed the file, so it is secure.

A:
Should I give myself write privileges to my own scripts? Or should root be the only one?

I don't see a security reason not to give yourself write privileges - it is just inconvenient to manually maintain scripts in system directories. If these scripts are for personal use, it is best to keep your scripts somewhere in your home directory, probably ~/bin and then add that directory to the beginning of your PATH variable through your shell's startup script in your home directory. That way, you don't need any special permissions to test your scripts.

Should everyone else have read-only permission?

Unless you want to keep the contents of your script a secret, it should not be a problem to give others both read and execute permissions.

Should root have ownership over any of my scripts/directory?

The important thing is that other users must not have write access to the scripts. As long as the owner is you and you are the sole member of the group assigned to the file, you don't need to worry about security. It is just not convenient to have your scripts outside your home directory, but otherwise things should be fine.


text:
Q: The appendTo() function in js didn't work I met a problem with js. The js function appendTo() is not work!
my js code is like this:

my browser console shows that everythings is as planed:

here is the problem , my html element tbody doesn't contain any things as followed:

why? how can i fix this?

A: Although HTML id is allowed to contain dot and colon characters, the fact that you are using jQuery makes it doesn't work because dot and colon have special meaning in a a selector context.
The following native JS will work:
document.getElementById('tb_10.3.3.186:32222').innerHTML += html;

But if you still want to use jQuery, you need to remove the dot (.) and colon (:) from your id.


text:
Q: How could I optimize this formular I have a range of values between 2 columns: I need to check every row in colum A and in column B respectively and return the number of time if the condition is True
=SUM(IF(AND(I28=B8;J28=G15);1;0) + IF(AND(I29=B8;J29=G15);1;0)+ IF(AND(I30=B8;J30=G15);1;0) + IF(AND(I31=B8;J31=G15);1;0))

I used This function it's working. But I didn't find how to optimized if I am going to work for a lot of rows.
I tried this but it's not workig:
=SUM(IF(AND((I28:I31)=B8;(J28:J31)=G15);1;0))

A: Use COUNTIFS()
=COUNTIFS(I28:I31;B8;J28:J31;G15)


text:
Q: Window.open makes the page into a popup block Below is my code for opening the button into a new page, but there are more complexity on the on click function. Here the post process also happens, which makes the window.open in as popup block.
I have tried to remove the post function and tried and the new page works perfectly. could anybody help out in this issue.
$('#catalog_demo_button a').click(function(e) {
        var curEmailId = $('#field-email').val();
        var validemail = validateEmail(curEmailId);
        if (validemail)
        {
        RSUI.util.setCookie("curEmailIdsc", curEmailId);
        $.post($("#targetform").val(),
        {
            email : $('#field-email').val(),
            demo_lang : $('#selectedLang').val(),
            cis_name : $("#cis_name").val(),
            website : $("#website").val(),
            form_type : "demo",
            demo_type : $("#form_type").val(),
            form_url : $("#form_url").val(),
            cid : $.trim(RSUI.util.getCookie('affiliate'))
        },function(data)
        {
            if (data != "")
            {
                data = eval("("+data+")");
                if (data[0].cisFlag == "true")
                {
                    s.events="event19";
                    s.t();
                    delete s.events;
                    s.sendFormEvent('s', s.pageName, "Demo Email Form");
                    adconionConversionCall();

                    var demolangid = $("[name=language_code]").val();
                    URL= 'url'+demolangid;
                        if(demolangid == 'ENG' || demolangid == 'ESC' || demolangid == 'ESP' || demolangid == 'DEU' || demolangid == 'FRA' || demolangid == 'ITA' || demolangid == 'SVE')
                            $('#demo').overlay().load();
                        else
                            window.open(URL,'_blank')
                            $("#demoform a.close").click();
                    }
                else {
                    s.sendFormEvent('e', s.pageName, "Demo Email Form", "Email Submission Failed");
                }
            }
        }, "");
    }
        else
        {
            $("#field-email").val(errorEmailText);
            $('#field-email').css('border', '1px solid red');
            s.sendFormEvent('e', s.pageName, "Demo Email Form", "field-email");
        }
    });

A: Popups are blocked when not invoked by a user action. Your window.open is not in the user action but in the POST success callback.
You should either make the post synchronous and do the window.open from outside the POST success(untested, but sounds logical) or first open the popup and fill it in later.


text:
Q: Topological features (and / or definition) of homology I am coming to grips with basic homological algebra as of late, in order to better understand my own subject, that of the study of language. The thing is, I have recently read in some handbook that Aleksandrov provided topological definitions for some (no idea if all) concepts from homological algebra. Specifically, I would like to know if (and how) he defines homology, (bounded) chain complex, tensor product and, eventually, quiver, from a topological point of view.
Thanks in advance


text:
Q: Is it possible to override the SD Card write protection setting in software? I'm using the built-in SD card reader on a Macbook Pro (15", late 2011) running Yosemite, and it treats every SD card as write-protected regardless of the position of the physical switch on the card.
Apparently this is a fairly common problem. I've already tried all the solutions given in this question, with no success. The only thing left that I can think of to try is making physical repairs to the drive. Since this problem is likely caused by a malfunctioning sensor for a setting I don't care about, that seems like overkill if there is a way to do it in software.
Is there any known way to tell the drive or the OS to ignore the write-protection setting and treat a protected SD card as writeable?

A: No.  You cannot override the write protection status of an SD Card via software.
The read/write status is handled by the firmware of the SD card host controller not by the driver.  From Toshiba (manufacturer of these chips):

Content protection can be realized by using the [controller] with
  firmware.

Inside the SD card reader are a series of pins that get connected if the write protection is enabled.  This tells the controller that write protection is enabled (Picture is not of the MacBook connectors, but the best one to illustrate how it works I could find online).

It is most likely that these pins are "stuck" together causing the controller to "see" the card as protected.  You can attempt to clean it out or as a better alternative, just purchase an inexpensive USB SD Card Reader.

A: I have sacrificed a micro SD to SD adapter in order to see that there is no wire or lever going from the slider to the micro SD card, hence the protection it NOT in the card but in the reader.

Yet it could be possible to overcome the lock with proper software (kind of spoofing or masquerading).
I happen to have a true full size no adapter Sandisk Extreme SD card that cost me more than 60 euros (I won't open it for curiosity).  It is almost always read only on my Macs (with either Mac OS or Linux).
Just like it used to be with floppies: cover the hole!
Let me do it.  Cover the hole with brown postal packaging tape (opaque and thin), being careful not to cover any electrical pin.

Now my SD card is almost always writable, even if the slider is in lock position, which proves that it does not know the slider position and does not have built-in lock.
After many years and many cards thrown to the bin for nothing...


text:
Q: WordPress - Show no articles if author is not logged in On my site I have successfully been able to show authors the links to their specific articles and no other articles. However, if not logged in, they see a list of all articles in the site of that post-type. I want to leave that space blank if the user is not logged in. I don't want to lock down the page because instead of the article link there will be a link to generate an article. Here is what I have so far...how can I return nothing if the author is not logged in?
$user_id = get_current_user_id();

$args=array(
    'post_type' => 'team_fundraiser',
    'post_status' => 'published',
    'posts_per_page' => -1,
    'author' => $user_id
);

$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post();
$team_link .= ''. esc_html( get_the_title() ) . '';

endwhile;

echo $team_link;

A: Can you not just check if the user is logged in?
if ( is_user_logged_in() ) {
    echo $team_link; //can place around this or the query itself
}

You can go one step further and check if the user that is logged in had the correct privileges
if ( is_user_logged_in() && current_user_can('manage_options')  ) {
    echo $team_link;
}


text:
Q: How to play the song by ordered , random , and replay? I want to make three models of play that can adjust the song .
You can see the on_finish() method , which is what I wrote about the play mode .
These three modes are ordered , random and replay .
But I got some errors that the song can't following these models of play .
For example,
song list :ABCDEFG , and now is playing A
When I click the ordered , it will play the next song(B) at first,then play the next third song(E).
But it should plays song B at first ,then plays song C , not song E.
And also the same happens in random .
Then I tried to print(path) , I found the code will be executed at once ,then three times ,and finally night times .......
I do not know where is the problem .
Here is my code of music_1.py.
#!/usr/bin/python
# -*- coding: utf-8 -*-

# music_1.py

import sys
import random
from PyQt4 import QtGui, QtCore
from PyQt4 import phonon
from music_ui import Ui_Form

warmpath_list=[r"C:\Users\Jacky\Desktop\music_list\warm\song1.mp3",
               r"C:\Users\Jacky\Desktop\music_list\warm\song2.mp3",
               r"C:\Users\Jacky\Desktop\music_list\warm\song3.wma",
               r"C:\Users\Jacky\Desktop\music_list\warm\song4.mp3",
               r"C:\Users\Jacky\Desktop\music_list\warm\song5.mp3",
               r"C:\Users\Jacky\Desktop\music_list\warm\song6.wma",

funnypath_list=[r"C:\Users\Jacky\Desktop\music_list\funny\songa.wma",
                r"C:\Users\Jacky\Desktop\music_list\funny\songb.wma",
                r"C:\Users\Jacky\Desktop\music_list\funny\songc.wma ",
                r"C:\Users\Jacky\Desktop\music_list\funny\songd.wma"]

class Music(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QDialog.__init__(self, parent)
        self.setWindowTitle('Player')
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.mediaObject = phonon.Phonon.MediaObject(self)
        self.audioOutput = phonon.Phonon.AudioOutput(phonon.Phonon.MusicCategory, self)
        phonon.Phonon.createPath(self.mediaObject, self.audioOutput)
        self.ui.volumeSlider.setAudioOutput(self.audioOutput)
        self.ui.seekSlider.setMediaObject(self.mediaObject)
        self.mediaObject.tick.connect(self.tick)

        self.timeLcd = QtGui.QLCDNumber(self)
        self.timeLcd.display('00:00')
        self.timeLcd.setGeometry(480, 330, 100, 50)

        self.ui.listWidget.insertItem(0,"warm")
        self.ui.listWidget.insertItem(1,"funny")

        self.ui.listWidget_3.insertItem(0,"song1")
        self.ui.listWidget_3.insertItem(1,"song2")
        self.ui.listWidget_3.insertItem(2,"song3")
        self.ui.listWidget_3.insertItem(3,"song4")
        self.ui.listWidget_3.insertItem(4,"song5")
        self.ui.listWidget_3.insertItem(5,"song6")

        self.ui.listWidget_2.insertItem(0,"songa")
        self.ui.listWidget_2.insertItem(1,"songb")
        self.ui.listWidget_2.insertItem(2,"songc")
        self.ui.listWidget_2.insertItem(3,"songd")

        self.connect(self.ui.listWidget,QtCore.SIGNAL("currentRowChanged(int)"),self.ui.stackedWidget,QtCore.SLOT("setCurrentIndex(int)"))
        self.connect(self.ui.listWidget_2,QtCore.SIGNAL("currentRowChanged(int)"),self.openaudio)
        self.connect(self.ui.listWidget_3,QtCore.SIGNAL("currentRowChanged(int)"),self.openaudio)

        self.connect(self.ui.pushButton, QtCore.SIGNAL('clicked()'),self.mediaObject.pause)
        self.connect(self.ui.pushButton_4, QtCore.SIGNAL('clicked()'),self.mediaObject.play)
        self.connect(self.ui.pushButton_5, QtCore.SIGNAL('clicked()'),self.mediaObject.stop)
        self.connect(self.ui.pushButton_2, QtCore.SIGNAL('clicked()'),self.m_previous)
        self.connect(self.ui.pushButton_3, QtCore.SIGNAL('clicked()'),self.m_next)

        popmenu = QtGui.QMenu(self.ui.pushButton_6)
        group = QtGui.QActionGroup(self.ui.pushButton_6)
        group.setExclusive(True)

        for i in range(1, 4):
            if i==1:
                action = group.addAction('oordered')
                action.setCheckable(True)
                #action.setChecked(True)

            if i==2:
                action = group.addAction('replay')
                action.setCheckable(True)

            if i==3:
                action = group.addAction('random')
                action.setCheckable(True)

            popmenu.addAction(action)
        self.ui.pushButton_6.setMenu(popmenu)

        group.triggered.connect(self.sortedEvent) # sortedEvent()

    def tick(self, time):
        displayTime = QtCore.QTime(0, (time / 60000) % 60, (time / 1000) % 60)
        self.timeLcd.display(displayTime.toString('mm:ss'))

    def openaudio(self,path):
        self.connect(self.ui.listWidget_2,QtCore.SIGNAL('currentTextChanged(QString)'),self.ui.label_4,QtCore.SLOT('setText(QString)'))
        self.connect(self.ui.listWidget_3,QtCore.SIGNAL('currentTextChanged(QString)'),self.ui.label_4,QtCore.SLOT('setText(QString)'))

        if self.ui.stackedWidget.currentIndex()==0:
            index1=self.ui.listWidget_3.currentRow()
            path=warmpath_list[index1]

        if self.ui.stackedWidget.currentIndex()==1:
            index2=self.ui.listWidget_2.currentRow()
            path=funnypath_list[index2]

        self.mediaObject.setCurrentSource(phonon.Phonon.MediaSource(path))
        self.mediaObject.play()
        self.mediaObject.finished.connect(self.on_finish)

    def m_next(self): # to play the next song
        if self.ui.stackedWidget.currentIndex()==0:
            index1=self.ui.listWidget_3.currentRow()
            if index1==len(warmpath_list)-1:
                path=warmpath_list[0]
                self.ui.listWidget_3.setCurrentRow(0)
            else:
                 path=warmpath_list[index1+1]
                 self.ui.listWidget_3.setCurrentRow(index1+1)
            print(path)
            self.openaudio(path)

        if self.ui.stackedWidget.currentIndex()==1:
            index2=self.ui.listWidget_2.currentRow()
            if index2==len(funnypath_list)-1:
                path=funnypath_list[0]
                self.ui.listWidget_2.setCurrentRow(0)
            else:
                path=funnypath_list[index2+1]
                self.ui.listWidget_2.setCurrentRow(index2+1)
            self.openaudio(path)

    def m_previous(self): # to play the previous song
        if self.ui.stackedWidget.currentIndex()==0:
            index1=self.ui.listWidget_3.currentRow()
            if index1==len(warmpath_list)-len(warmpath_list):
                path=warmpath_list[len(warmpath_list)-1]
                self.ui.listWidget_3.setCurrentRow(len(warmpath_list)-1)
            else:
                 path=warmpath_list[index1-1]
                 self.ui.listWidget_3.setCurrentRow(index1-1)
            print(path)
            self.openaudio(path)

        if self.ui.stackedWidget.currentIndex()==1:
            index2=self.ui.listWidget_2.currentRow()
            if index2==len(funnypath_list)-len(funnypath_list):
                path=funnypath_list[len(funnypath_list)-1]
                self.ui.listWidget_2.setCurrentRow(len(funnypath_list)-1)
            else:
                 path=funnypath_list[index2-1]
                 self.ui.listWidget_2.setCurrentRow(index2-1)
            print(path)
            self.openaudio(path)

    def sortedEvent(self,action):
        self.whatToDoNext=action.text()

    def on_finish(self):
        if self.whatToDoNext=="ordered":     # Order of play
            if self.ui.stackedWidget.currentIndex()==0:
                index1=self.ui.listWidget_3.currentRow()
                if index1==len(warmpath_list)-1:
                    path=warmpath_list[0]
                    self.ui.listWidget_3.setCurrentRow(0)
                else:
                    path=warmpath_list[index1+1]
                    self.ui.listWidget_3.setCurrentRow(index1+1)
                print(path)
                self.openaudio(path)
            if self.ui.stackedWidget.currentIndex()==1:
                index2=self.ui.listWidget_2.currentRow()
                if index2==len(funnypath_list)-1:
                    path=funnypath_list[0]
                    self.ui.listWidget_2.setCurrentRow(0)
                else:
                    path=funnypath_list[index2+1]
                    self.ui.listWidget_2.setCurrentRow(index2+1)
                self.openaudio(path)

        elif self.whatToDoNext=="random": # random of play
            if self.ui.stackedWidget.currentIndex()==0:
                path = random.choice(warmpath_list)
                self.ui.listWidget_3.setCurrentRow(warmpath_list.index(path))
                print(path)
                self.openaudio(path)

            if self.ui.stackedWidget.currentIndex()==1:
                path = random.choice(funnypath_list)
                self.ui.listWidget_2.setCurrentRow(funnypath_list.index(path))
                self.openaudio(path)

        else: # replay
            self.mediaObject.stop()
            self.mediaObject.play()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = Music()
    myapp.show()
    sys.exit(app.exec_())

Here is my code of music_ui .py
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_Form(object):
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(600, 400)
        self.seekSlider = phonon.Phonon.SeekSlider(Form)
        self.seekSlider.setGeometry(QtCore.QRect(230, 250, 361, 20))
        self.seekSlider.setObjectName(_fromUtf8("seekSlider"))
        self.volumeSlider = phonon.Phonon.VolumeSlider(Form)
        self.volumeSlider.setGeometry(QtCore.QRect(20, 360, 151, 22))
        self.volumeSlider.setObjectName(_fromUtf8("volumeSlider"))
        self.pushButton = QtGui.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(420, 280, 40, 40))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Agency FB"))
        font.setBold(True)
        font.setWeight(75)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.pushButton_2 = QtGui.QPushButton(Form)
        self.pushButton_2.setGeometry(QtCore.QRect(300, 280, 40, 40))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Agency FB"))
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
        self.pushButton_3 = QtGui.QPushButton(Form)
        self.pushButton_3.setGeometry(QtCore.QRect(540, 280, 40, 40))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Agency FB"))
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_3.setFont(font)
        self.pushButton_3.setObjectName(_fromUtf8("pushButton_3"))
        self.pushButton_4 = QtGui.QPushButton(Form)
        self.pushButton_4.setGeometry(QtCore.QRect(480, 280, 40, 40))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Agency FB"))
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_4.setFont(font)
        self.pushButton_4.setObjectName(_fromUtf8("pushButton_4"))
        self.pushButton_5 = QtGui.QPushButton(Form)
        self.pushButton_5.setGeometry(QtCore.QRect(360, 280, 40, 40))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Agency FB"))
        font.setPointSize(9)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_5.setFont(font)
        self.pushButton_5.setObjectName(_fromUtf8("pushButton_5"))
        self.label_3 = QtGui.QLabel(Form)
        self.label_3.setGeometry(QtCore.QRect(490, 30, 81, 71))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Agency FB"))
        font.setPointSize(16)
        self.label_3.setFont(font)
        self.label_3.setFrameShape(QtGui.QFrame.StyledPanel)
        self.label_3.setTextFormat(QtCore.Qt.AutoText)
        self.label_3.setAlignment(QtCore.Qt.AlignCenter)
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.label_2 = QtGui.QLabel(Form)
        self.label_2.setGeometry(QtCore.QRect(230, 60, 161, 61))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.label_2.setFont(font)
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.label_4 = QtGui.QLabel(Form)
        self.label_4.setGeometry(QtCore.QRect(230, 130, 341, 31))
        font = QtGui.QFont()
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.label_4.setFont(font)
        self.label_4.setObjectName(_fromUtf8("label_4"))
        self.groupBox = QtGui.QGroupBox(Form)
        self.groupBox.setGeometry(QtCore.QRect(10, 30, 201, 321))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.groupBox.setFont(font)
        self.groupBox.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
        self.groupBox.setFlat(False)
        self.groupBox.setCheckable(False)
        self.groupBox.setObjectName(_fromUtf8("groupBox"))
        self.listWidget = QtGui.QListWidget(self.groupBox)
        self.listWidget.setGeometry(QtCore.QRect(10, 30, 171, 51))
        self.listWidget.setFrameShape(QtGui.QFrame.NoFrame)
        self.listWidget.setFrameShadow(QtGui.QFrame.Plain)
        self.listWidget.setViewMode(QtGui.QListView.ListMode)
        self.listWidget.setObjectName(_fromUtf8("listWidget"))
        self.stackedWidget = QtGui.QStackedWidget(self.groupBox)
        self.stackedWidget.setGeometry(QtCore.QRect(10, 90, 181, 221))
        self.stackedWidget.setFrameShape(QtGui.QFrame.StyledPanel)
        self.stackedWidget.setObjectName(_fromUtf8("stackedWidget"))
        self.page = QtGui.QWidget()
        self.page.setObjectName(_fromUtf8("page"))
        self.listWidget_3 = QtGui.QListWidget(self.page)
        self.listWidget_3.setGeometry(QtCore.QRect(0, 0, 181, 221))
        self.listWidget_3.setFrameShape(QtGui.QFrame.NoFrame)
        self.listWidget_3.setObjectName(_fromUtf8("listWidget_3"))
        self.stackedWidget.addWidget(self.page)
        self.page_2 = QtGui.QWidget()
        self.page_2.setObjectName(_fromUtf8("page_2"))
        self.listWidget_2 = QtGui.QListWidget(self.page_2)
        self.listWidget_2.setGeometry(QtCore.QRect(0, 0, 181, 221))
        self.listWidget_2.setFrameShape(QtGui.QFrame.NoFrame)
        self.listWidget_2.setObjectName(_fromUtf8("listWidget_2"))
        self.stackedWidget.addWidget(self.page_2)
        self.pushButton_6 = QtGui.QPushButton(Form)
        self.pushButton_6.setGeometry(QtCore.QRect(240, 280, 40, 40))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Agency FB"))
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_6.setFont(font)
        self.pushButton_6.setObjectName(_fromUtf8("pushButton_6"))

        self.retranslateUi(Form)
        self.stackedWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(_translate("Form", "Form", None))
        self.pushButton.setText(_translate("Form", "|  |", None))
        self.pushButton_2.setText(_translate("Form", "<", None))
        self.pushButton_3.setText(_translate("Form", ">", None))
        self.pushButton_4.setText(_translate("Form", "►", None))
        self.pushButton_5.setText(_translate("Form", "■", None))
        self.label_2.setText(_translate("Form", "Now is playing........", None))
        self.label_4.setText(_translate("Form", "m u s i c", None))
        self.groupBox.setTitle(_translate("Form", "  music list  ", None))
        self.pushButton_6.setText(_translate("Form", "▦", None))

from PyQt4 import phonon

A: There's at least two issues in your code:

*

*In m_next(), you're calling self.ui.listWidget_3.setCurrentRow(0)
and then play the next song with self.openaudio(path)
The problem is, you previously connect the row changed signal of
listWidget to a function that play a song:
self.connect(self.ui.listWidget_3,QtCore.SIGNAL("currentRowChanged(int)"),self.openaudio)
You're calling self.openaudio(path) twice, so you get some
unexpected behaviour.

*You connect the same slots and signals multiple time
In the function openaudio(self,path), you're connecting mediaObject.finished to self.on_finish. Each time the function is called, you're adding a connection.
If you try the example below, you'll see that the slot is called twice with one click on the button:
button=QtGui.QPushButton("my button")
button.clicked.connect(on_click)
button.clicked.connect(on_click)

def on_click():
    print("slot called")

Usually, you only connect signal and slots in the __init__ function, because this function is called only once.


text:
Q: Ipod Classic 160GB shuffle issue I just bought one of the last Ipod classics and for some reason when its in shuffle mode (songs - artists or playlists), it shuffles to the next track in the middle of the current song. odd? is there a solution?
thanks!

A: Could be drive or file damage.
I had something similar happen on my old classic. The 'fix' was to wipe & restore - which took a long time [24h maybe], but worked.
One thing I've noticed about the classic with the slide-lock switch, don't attempt to sync with it locked.


text:
Q: In Silverlight 4 pass multi sellections from one combobox to stored procedure I am new on developing an application using Silverlight 4 and VS 2010. I need to select one or multi users from a combobox and pass it(them) as parameter to stored proc. My question is how to send the user IDs collection as parameter to stored proc?
Thanks.

A: Passing the data to the back-end shouldn't be terribly problematic: RIA Services and WCF know how to take a list (usually an ObservableCollection) and pass it back and forth between the client and middle tiers. If you've been able to pass other sorts of data back and forth between your client and the middle tier, you shouldn't have any difficulty getting this part to work.
The complexity (such as it is) comes when you need to pass the list from the middle tier to the stored procedure. And unfortunately, there isn't any straightforward way to do this. It's one of the great deficiencies in TSQL, in my opinion.
That said, there are a whole bunch of non-straightforward ways to do it. See http://vyaskn.tripod.com/passing_arrays_to_stored_procedures.htm for some suggestions. All of these require some sort of special handling of the data before you ever get around to calling the sproc, but with some clever LINQ, that can usually be reduced to just a couple lines of code.


text:
Q: Is checking if algorithm that solves NP problem running in polynomial time NP problem itself? input - correct algorithm A that solves NP class problem, algorithm runs in O(f), is O(f) polynomial?
Let's check with new algorithm B if A runs in polynomial time
what can we say about complexity of this problem?


text:
Q: Matrices with large diagonals and their inverses I am looking at a sequence of matrices $M_n \in \mathbb{R}^{p\times p}$ that satisfy the following properties:

*

*$M_n = A_n^T B_n A_n$, where $A_n \in \mathbb{R}^{n\times p}$ is full rank and $B_n \in \mathbb{R}^{n\times n}$ is symmetric positive definite for all $n$

*All $p$ diagonal elements of $M_n$ diverge as $n \rightarrow \infty$
Through simulations, it appears that $M_n^{-1}$ approaches the zero $p \times p$ matrix. Can I deduce this from these two properties alone?  Property 2 only implies that the largest eigenvalue of $M_n$ diverges, not necessarily the smallest (which is what we need).

A: Suppose the top $p$ rows of $A_n$ form the identity matrix, the rest being $0$.
$B_n$ is any positive definite $n \times n$ matrix.  Then $M_n$ is the top left $p \times p$
block of $B_n$, which can be any $p \times p$ positive definite matrix.  So you seem to be asserting that if $M_n$ is a sequence of positive definite $n \times n$ matrices
whose diagonal elements go to $\infty$ as $n \to \infty$, $M_n^{-1} \to 0$.
This is certainly false.  Try the case $p=2$ with $$M_n = \pmatrix{n & n-1\cr n-1 & n\cr},\ M_n^{-1} = \pmatrix{\frac{n}{2n-1} & \frac{1-n}{2n-1}\cr \frac{1-n}{2n-1} & \frac{n}{2n-1}\cr} $$


text:
Q: Force a Class Method Parameter to be a Constant From an Abstract Class Integration Trait
trait Integration {
    public function executeRequest($url, $method, $data, $acceptType) {
        //Do Something
    }
}

Rest Accept Type Abstract Class
abstract class RestAcceptType {
    const xml= "text/xml";
    const html = "text/html";
    const json = "application/json";
    const text = "text/plain";
}

I am trying to find a way to require the $acceptType method parameter to be a constant from the Rest Accept Type abstract class.
ie:
$a = new Integration;
$a->executeRequest("http://example.com/endpoint", "POST", $dataArray, RestAcceptType::json);

works but...
$a = new Integration;
$a->executeRequest("http://example.com/endpoint", "POST", $dataArray, "json");

should fail and throw a fatal exception. Would like to ideally do this through type hinting but can do it as a separate data type validation stage within the method itself.

A: You can use a library like php-enum. Then you can type hint enum type:
final class RestAcceptType extends Enum {
    public const XML = "text/xml";
    public const HTML = "text/html";
    public const JSON = "application/json";
    public const TEXT = "text/plain";
}

trait Integration {
    public function executeRequest($url, $method, $data, RestAcceptType $acceptType) {
        //Do Something
    }
}

$a = new class {
    use Integration;
};

$a->executeRequest("http://example.com/endpoint", "POST", $dataArray, RestAcceptType::JSON());

Pay attention that you are not accessing a constant here, but instead calling a static method that returns singleton.

A: You could always use SplEnum, which is as close to "standard" as you are going to get.
class RestAcceptType extends SplEnum {

    const __default = self::xml;

    const xml= "text/xml";
    const html = "text/html";
    const json = "application/json";
    const text = "text/plain";
}

trait Integration {
  public function executeRequest($url, $method, $data, RestAcceptType $acceptType) {
    //Do Something
  }
}

$acceptType = new RestAcceptType(RestAcceptType::xml);

A: It's not possible to do this with type-hinting, unfortunately. Type hints can only operate at the level of class, interface or scalar-type level.
Commonly, this pattern is achieved by giving your class a list of "known" constants, which you can then check either via a method on the same class, or a simple in_array check if you make the list public. So you might add the following to the RestAcceptType class:
public static function isValidAcceptType($type)
{
    return in_array($type, [
        self::xml,
        self::html,
        self::json,
        self::text,
    ]);
}

You could then use this at the top of your executeRequest method using something like:
if (!RestAcceptType::isValidAcceptType($acceptType)) {
  throw new InvalidArgumentException;
}

I appreciate this isn't the cleanest pattern (particularly since it means making two changes when you add a new constant), but short of using something like ReflectionClass::getConstants, it isn't possible to iterate over a class's constants. In my opinion at least, that wouldn't be particularly clean either (although that's exactly how the library in the other answer works, so it is definitely an option).


text:
Q: Jena TDB insert statement resulting in empty fields I am using Jena APIs to insert and update triples in Jena TDB. My design is such that each of the insert operation is within the transaction control. For example:
dataset.begin (ReadWrite.WRITE)
try
{
    // 1st insert operation
    dataset.commit()
} finally {
    dataset.end();
}

dataset.begin (ReadWrite.WRITE)
try
{
    // 2nd insert operation
    dataset.commit()
} finally {
    dataset.end();
}

After this, when I query the TDB using the READ transaction , I notice that some of the entries (either subject, predicate, or object) are empty.  Why does it behaves this way, even though I am not using nested transactions?
Insert Code
    public class UpdateTDB2 {

    String directory = "C://myTDB//";
    Dataset dataset = TDBFactory.createDataset(directory);
    public static final String RDFPrefix = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>";
    public static final String XSDPrefix = "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>";
    public static final String MYPrefix = "PREFIX myprefix: <http://www.myexample.com/mySchema#>";

    public static void main(String[] args) {
        UpdateTDB2 obj = new UpdateTDB2();
        obj.createActionInstance();
        obj.createStateInstance();

    }

    public static void execUpdate(String sparqlUpdateString,
            GraphStore graphStore) {
        UpdateRequest request = UpdateFactory.create(sparqlUpdateString);
        UpdateProcessor proc = UpdateExecutionFactory.create(request,
                graphStore);
        proc.execute();
    }

    private void updateTriple(String sparqlUpdateString) {

        dataset.begin(ReadWrite.WRITE);
        try {
            GraphStore graphStore = GraphStoreFactory.create(dataset);
            execUpdate(sparqlUpdateString, graphStore);
            dataset.commit();

        } finally {
            dataset.end();
        }
    }

    private void createActionInstance() {

        String subject = new StringBuffer("myprefix:").append("LS_1_user")
                .toString();
        String predicate = "rdf:type";
        String object = "myprefix:Action";

        String insertString = createInsertString(subject, predicate, object);
        String sparqlInsertString = createSparqlString(insertString);
        updateTriple(sparqlInsertString);
    }

    private void createStateInstance() {

        String subject = new StringBuffer("myprefix:").append("LS_1_user_LicState")
                .toString();
        String predicate = "rdf:type";
        String object = "myprefix:State";

        String insertString = createInsertString(subject, predicate, object);
        String sparqlInsertString = createSparqlString(insertString);
        updateTriple(sparqlInsertString);
    }

    private String createInsertString(String subject, String predicate,
            String object) {
        String insertString = new StringBuffer("INSERT DATA { ")
                .append(subject).append(" ").append(predicate).append(" ")
                .append(object).append(" }").toString();

        return insertString;
    }

    private String createSparqlString(String str) {
        String sparqlString = StrUtils.strjoinNL(UpdateTDB2.XSDPrefix,
                UpdateTDB2.RDFPrefix, UpdateTDB2.MYPrefix, str);

        System.out.println(sparqlString);
        return sparqlString;
    }

}

Query Code
public class QueryTDB3 {

    public static void main(String[] args) {
        String directory = "C://myTDB//" ;
        Dataset dataset = TDBFactory.createDataset(directory) ;

        dataset.begin(ReadWrite.READ) ;
        try
        {
            // Do some queries
            String sparqlQueryString1 = "SELECT (count(*) AS ?count) { ?s ?p ?o }" ;

            String sparqlQueryString2 = "SELECT * { ?s ?p ?o }" ;
            execQuery(sparqlQueryString2, dataset) ;
            execQuery(sparqlQueryString1, dataset) ;
        } finally
        {
            dataset.end() ;
        }
    }

    public static void execQuery(String sparqlQueryString, Dataset dataset)
    {
        Query query = QueryFactory.create(sparqlQueryString) ;
        QueryExecution qexec = QueryExecutionFactory.create(query, dataset) ;
        try {
            ResultSet results = qexec.execSelect() ;

            ResultSetFormatter.out(results) ;

          } finally { qexec.close() ; }
    }

}

A: Which version of the code are you running?
If the code you show (first part) is really being run in two separate runs (hence two JVMs), then this might be due to a known-and-fixed bug in TDB.  It was only present in relative recent versions.
Please try the development version of Jena 2.7.4-SNAPSHOT.


text:
Q: Unable to get Second Spinner value based on first Spinner Value I'm using Two Spinners where Second Spinner Value is based on First Spinner Value.
For Example If user Select Option A in First Spinner Then Second Spinner drop down list must contain value ( ox, cow, goat ) and if user select option B, then second Spinner value must contain ( Lion, Tiger and Cheetha ).
But I'm unable to do so. On selecting any value in first spinner  value, Second Spinner always loads same value. Below is the screenshot

As you can see, In selecting any option in first spinner master or diploma...In second spinner value is same.it does not change.
Below is my Activity Code
 public class UploadBook extends AppCompatActivity
        Spinner spinnerCountry,spinnerDivision,spinner_condition;
        ArrayAdapter<String> countryArray,divisionArray;

        String item = "start";

        int count = 0;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_upload_book);
            getSupportActionBar().setTitle("Upload book");

            spinnerCountry = (Spinner) findViewById(R.id.spinnerCountry);
            //implementing OnItemSelectedListener (need to override the method)
            spinnerCountry.setOnItemSelectedListener(this);

            countryArray = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
            countryArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            spinnerCountry.setAdapter(countryArray);

            countryArray.add("Master");

            countryArray.add("Diploma");

            countryArray.setNotifyOnChange(true);

            spinnerCountry.setSelection(0);

            spinnerDivision = (Spinner) findViewById(R.id.spinnerDivision);
            //implementing OnItemSelectedListener (need to override the method)
            spinnerDivision.setOnItemSelectedListener(this);

            divisionArray = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
            divisionArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            spinnerDivision.setAdapter(divisionArray);

        }

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            item = parent.getItemAtPosition(position).toString();
            count = position;
            //first spinner item position
            int countrySpinnerPosition = spinnerCountry.getSelectedItemPosition();
            switch (countrySpinnerPosition){
                case 1:
                    //fill data for second spinner
                    fillMasterDivision();
                    break;
                case 2:
                    //fill data for second spinner
                    fillDiplomaDivision();
                    break;

            }

        }

        private void fillMasterDivision() {
            divisionArray.clear();
            divisionArray.add("Select Subject:-");
            divisionArray.add("MSC Physics");
            divisionArray.add("MSC Chemistry");

            divisionArray.notifyDataSetChanged();
        }

        private void fillDiplomaDivision() {
            divisionArray.add("Select Subject:-");
            divisionArray.add("Science");
            divisionArray.add("CTEVT");
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }

Please Help.

A: There is two mistake in your code.

*

*CountrySpinnerPosition will be 0 and 1 for your case so the case should be "case 0" and "case 1".

*In fillDiplomaDivision method, you have to first clear the list and after adding into the list you have to call notifyDataSetChanged().

A: try to clear the arraylist and notifydatasetchanged in second method too
    private void fillDiplomaDivision() {
    divisionArray.clear();
    divisionArray.add("Select Subject:-");
    divisionArray.add("Science");
    divisionArray.add("CTEVT");

    divisionArray.notifyDataSetChanged();
}

A: First of all ,you are using same onItemSelected for both the spinner . so remove spinnerCountry.setOnItemSelectedListener(this); and  spinnerDivision.setOnItemSelectedListener(this);
After setting data to spinnerCountry use this .
spinnerCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
              if(i == 0){
                fillMasterDivision();
              }else{
                fillBachelorDivision();
              }

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

and clear your Division array in fillBachelorDivision()

A: See my example:
I have 2 spinners, firstSpinner and secndSpinner, Second depends of First.
First you have to initialize the spinners in onCreate method, and follow steps:

1 - You'll insert in first spinner your data ("Master", "Diploma");
2 - You'll create a function that will update the second spinner with associated values.

firstSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
        createSecondSpinnerByFirst(position);
     }

    @Override
    public void onNothingSelected(AdapterView<?> adapter) {
    }
});

private void createSecondSpinnerByFirst(Integer position) {
    List<String> secValues = new ArrayList<>();
    switch (position) {
        case 1:
            // insert in secValues array the strings of this condition
            break;
        case 2:
            // insert in secValues array the strings of this condition
            break;
    }

    // usually I use Adapter
    final SpinnerAdapter adapter = new SpinnerAdapter(this, secValues);
    secndSpinner.setAdapter(adapter);
}

//Code of myAdapter
public class SpinnerAdapter extends ArrayAdapter<String> {

    private Context context;
    private List<String> mValues;

    public SpinnerAdapter(Context ctx, List<String> values) {
        super(ctx, 0, values);
        context = ctx;
        mValues = values;
    }

    @Override
    public int getCount() {
        return mValues.size();
    }

    @Override
    public Process getItem(int position) {
        return mValues.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return returnLayoutSpinner(context, convertView, mValues.get(position));
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return returnLayoutSpinner(context, convertView, mValues.get(position));
    }
}

//My function to return the adapter view
private View returnLayoutSpinner(Context context, View convertView, String value) {
    if (convertView == null) {
        convertView = LayoutInflater.from(context).inflate(
                R.layout.spinner_items_view, null);
    }
    TextView txt = convertView.findViewById(R.id.txtSpinnerItem);
    txt.setText(value, 25);
    return convertView;
}

//spinner_items_view.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/txtSpinnerItem"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center|left"
    android:padding="13dp"
    android:textColor="@android:color/black"
    android:textSize="16sp">
</TextView>

A: private void fillDiplomaDivision() {
        //add this line in your code and it solve
        divisionArray.clear();
        divisionArray.add("Select Subject:-");
        divisionArray.add("Science");
        divisionArray.add("CTEVT");
    }


text:
Q: How to save changes to app.config file from runtime for a Visual Studio Add-In Thanks to Is there a config type file for Visual Studio Add-In?  I was able to create an app.config file for the Visual Studio add-in I am developing with the ability to read/write to it.
Now I am having trouble saving the changes made to it at runtime. I have been running the following test code, but when I look the app.config file after running in debug, nothing has changed.
Dim pluginAssemblyPath As String = Assembly.GetExecutingAssembly().Location
Dim configuration As Configuration = ConfigurationManager.OpenExeConfiguration(pluginAssemblyPath)
Dim test1 As String = configuration.AppSettings.Settings.Item("Key1").Value

configuration.AppSettings.Settings.Item("Key1").Value = "Is this thing on?"

Dim test3 As String = configuration.AppSettings.Settings.Item("Key1").Value
configuration.AppSettings.SectionInformation.ForceSave = True
configuration.Save(ConfigurationSaveMode.Modified)

A: Dim pluginAssemblyPath As String = Assembly.GetExecutingAssembly().Location
   'Dim configuration As Configuration = ConfigurationManager.OpenExeConfiguration(pluginAssemblyPath)
    Dim test1 As String = configuration.AppSettings.Settings.Item("Key1").Value

    configuration.AppSettings.Settings.Item("Key1").Value = "Is this thing on?"

    Dim test3 As String = configuration.AppSettings.Settings.Item("Key1").Value
    configuration.AppSettings.SectionInformation.ForceSave = True
    configuration.Save(ConfigurationSaveMode.Modified)
    ConfigurationManager.RefreshSection("appSettings")

The actual app.config will not change, but the config file inside of the bin folder does.


text:
Q: MYSQL prepare statements procedure which updates a variable number of columns of a table I need to create a stored procedure which uses prepared statements, whose purpose is to update a table. The thing is that I don't know beforehand which columns of the table will be updated. It can be one column, several or all of them. I created the procedure below but I ran into a problem I can't figure out:
CREATE DEFINER=`root`@`localhost`
PROCEDURE `updateEntries`(  IN setcols varchar(200),
                            IN column varchar(20),
                            IN relation varchar(10),
                            IN value varchar(15),
                            IN setvalue varchar(100)
                         )
BEGIN
SET @sql = CONCAT('UPDATE table SET ',setcols,' WHERE ', column,' ', relation,' ?');
SET @setvalue = setvalue;
SET @value = value;
PREPARE stmt FROM @sql;
EXECUTE stmt USING @setvalue, @value;
DEALLOCATE PREPARE stmt;
END

I can easily call the procedure when I must update only one column, like this:
call updateEntries('column = ?','id', '>', 2, 'new_value')
because my @sql would then be: UPDATE table SET column = ? WHERE id > ?; new_value would be assigned to @setvalue and 2 would be assigned to value then everyting executed.
However, I can't figure out what should I do when there are multiple columns to update, since I need to store all these new values for each column into variables, which EXECUTE would use.
Is there a way to store all the new values into a single variable, maybe a string, and have my procedure pick the values from it?
Or what options do I have?


text:
Q: Cursor in Mysql not working in Mysql 5.57 Cursor in Mysql not working in Mysql 5.57
I converted SQL query into MySQL query, SQL query give me records, but in Mysql query is doesn't provide any records and neither give any error
//Following is my SQL query
USE [Trackdb]
GO
/****** Object:  StoredProcedure [dbo].[GetRecords]    Script Date: 06-11-2019 09:48:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetRecords]
AS
BEGIN
DECLARE @Date VARCHAR(15)

create table #TempHotel
(
    CatID Varchar(50),
    Cnt INT,
    Date Date
)

create table #TempRestaurant
(
    CatID Varchar(50),
    Cnt INT,
    Date Date
)

DECLARE Track_CURSOR CURSOR
LOCAL  FORWARD_ONLY  FOR
SELECT Distinct(Convert(date,ms_date)) FROM tbltrackingrtt WHERE ms_date > '2017-11-01' AND heirarchy LIKE '%*145*%' AND category <> 0 AND category <> 145
OPEN Track_CURSOR
    FETCH NEXT FROM Track_CURSOR INTO  @Date
WHILE @@FETCH_STATUS = 0
BEGIN
    --PRINT  'EMP_ID: ' + @Date --+  '  EMP_NAME '+@EMP_NAME +'  EMP_SALARY '  +CONVERT(NVARCHAR(MAX),@EMP_SALARY)  +  '  EMP_CITY ' +@EMP_CITY

    INSERT INTO #TempHotel
    SELECT TOP 100 Category AS CatID, Count(id) Cnt, convert(Date,ms_date) Date FROM tbltrackingrtt
    WHERE heirarchy LIKE '%*145*%' AND category <> 0 AND category <> 145 AND CONVERT(DATE,ms_date) = @Date
    GROUP BY Category, convert(Date,ms_date)
    ORDER BY convert(Date,ms_date) ASC, Count(id) DESC

    INSERT INTO #TempRestaurant
    SELECT TOP 100 Category AS CatID, Count(id) Cnt, convert(Date,ms_date) Date FROM tbltrackingrtt
    WHERE heirarchy LIKE '%*169*%' AND category <> 0 AND category <> 169 AND CONVERT(DATE,ms_date) = @Date
    GROUP BY Category, convert(Date,ms_date)
    ORDER BY convert(Date,ms_date) ASC, Count(id) DESC

    FETCH NEXT FROM Track_CURSOR INTO @Date

END
SELECT * FROM #TempHotel
SELECT * FROM #TempRestaurant

CLOSE Track_CURSOR
DEALLOCATE Track_CURSOR

DROP table #TempHotel
DROP table #TempRestaurant

END

// Following is my Mysql query
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetRecords`()
BEGIN
DECLARE NOT_FOUND INT DEFAULT 0;
DECLARE v_Date VARCHAR(15);

DECLARE Track_CURSOR
CURSOR FOR
SELECT Distinct CAST(ms_date as Date) FROM tbltrackingrtt WHERE ms_date > '2017-11-01' AND heirarchy LIKE '%*145*%' AND category <> 0 AND category <> 145;
create temporary table TempHotel
(
    CatID Varchar(50),
    Cnt INT,
    Date Date
);

create temporary table TempRestaurant
(
    CatID Varchar(50),
    Cnt INT,
    Date Date
);
OPEN Track_CURSOR;
   FETCH  Track_CURSOR INTO  v_Date;
WHILE NOT_FOUND = 0
DO
    -- PRINT  'EMP_ID: ' + @Date --+  '  EMP_NAME '+@EMP_NAME +'  EMP_SALARY '  +CONVERT(NVARCHAR(MAX),@EMP_SALARY)  +  '  EMP_CITY ' +@EMP_CITY

    INSERT INTO TempHotel
    SELECT Category AS CatID, Count(id) Cnt, CAST(ms_date as Date) as Date FROM tbltrackingrtt
    WHERE heirarchy LIKE '%*145*%' AND category <> 0 AND category <> 145 AND CAST(ms_date as Date) = v_Date
    GROUP BY Category, CAST(ms_date as Date)
    ORDER BY CAST(ms_date as Date) ASC, Count(id) DESC LIMIT 100;

    select TempHotel;

    INSERT INTO TempRestaurant
    SELECT  Category AS CatID, Count(id) Cnt, CAST(ms_date as Date) as Date  FROM tbltrackingrtt
    WHERE heirarchy LIKE '%*169*%' AND category <> 0 AND category <> 169 AND CAST(ms_date as Date) = v_Date
    GROUP BY Category, CAST(ms_date as Date)
    ORDER BY CAST(ms_date as Date) ASC, Count(id) DESC LIMIT 100;

    FETCH Track_CURSOR INTO v_Date;

END WHILE;
SELECT * FROM TempHotel;
SELECT * FROM TempRestaurant

CLOSE;
DROP table TempHotel;
DROP table TempRestaurant;

END

Anyone help me on this, I don't what I am doing wrong here, is there is any problem in MySQL cursor

A: Apart from the syntax error pointed out by @solarflare the only thing that appears to be wrong with this code is the lack of a handler you should review https://dev.mysql.com/doc/refman/8.0/en/cursors.html and https://dev.mysql.com/doc/refman/5.7/en/handler.html (which you should know about for error handling in mysql)
drop procedure if exists p;
drop temporary table if exists temphotel,temprestaurant;

drop table if exists tbltrackingrtt;
create table tbltrackingrtt
(id int auto_increment primary key,ms_date date,heirarchy varchar(20),category int);

insert into tbltrackingrtt (ms_date,heirarchy,category) values
('2017-11-02','*145*',10), ('2017-11-02','*145*',10),
('2017-11-02','*169*',10), ('2017-11-02','*145*',10);

delimiter $$

CREATE  PROCEDURE p()
BEGIN
DECLARE NOT_FOUND INT DEFAULT 0;
DECLARE v_Date VARCHAR(15);

DECLARE Track_CURSOR
CURSOR FOR
    SELECT Distinct CAST(ms_date as Date)
    FROM tbltrackingrtt
    WHERE ms_date > '2017-11-01' AND heirarchy LIKE '%*145*%' AND category <> 0 AND category <> 145;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET not_found = TRUE;

create temporary table TempHotel
(
    CatID Varchar(50),
    Cnt INT,
    Date Date
);

create temporary table TempRestaurant
(
    CatID Varchar(50),
    Cnt INT,
    Date Date
);
OPEN Track_CURSOR;
   FETCH  Track_CURSOR INTO  v_Date;
WHILE NOT_FOUND = 0  DO
    -- PRINT  'EMP_ID: ' + @Date --+  '  EMP_NAME '+@EMP_NAME +'  EMP_SALARY '  +CONVERT(NVARCHAR(MAX),@EMP_SALARY)  +  '  EMP_CITY ' +@EMP_CITY

    INSERT INTO TempHotel
    SELECT Category AS CatID, Count(id) Cnt, CAST(ms_date as Date) as Date
     FROM tbltrackingrtt
    WHERE heirarchy LIKE '%*145*%' AND category <> 0 AND category <> 145 AND CAST(ms_date as Date) = v_Date
    GROUP BY Category, CAST(ms_date as Date)
    ORDER BY CAST(ms_date as Date) ASC, Count(id) DESC LIMIT 100;

    select * from TempHotel;

    INSERT INTO TempRestaurant
    SELECT  Category AS CatID, Count(id) Cnt, CAST(ms_date as Date) as Date
     FROM tbltrackingrtt
    WHERE heirarchy LIKE '%*169*%' AND category <> 0 AND category <> 169 AND CAST(ms_date as Date) = v_Date
    GROUP BY Category, CAST(ms_date as Date)
    ORDER BY CAST(ms_date as Date) ASC, Count(id) DESC LIMIT 100;

    FETCH Track_CURSOR INTO v_Date;

END WHILE;
SELECT * FROM TempHotel;
SELECT * FROM TempRestaurant

CLOSE;
DROP table TempHotel;
DROP table TempRestaurant;

END $$

delimiter ;

call p();

+-------+------+------------+
| CatID | Cnt  | Date       |
+-------+------+------------+
| 10    |    3 | 2017-11-02 |
+-------+------+------------+
1 row in set (0.27 sec)

+-------+------+------------+
| CatID | Cnt  | Date       |
+-------+------+------------+
| 10    |    3 | 2017-11-02 |
+-------+------+------------+
1 row in set (0.29 sec)

+-------+------+------------+
| CatID | Cnt  | Date       |
+-------+------+------------+
| 10    |    1 | 2017-11-02 |
+-------+------+------------+
1 row in set (0.30 sec)


text:
Q: GLSL vertex shader for texture display not compiling I've got a vertex shader that doesn't want to compile, but I see absolutely no reason for the error it is giving.  It's failing with the following error:
ERROR: D:\local\Temp\f46179fe-8934-4135-820a-bed1e54b98bf.tmp:22: 'texture2D' : no matching overloaded function found
ERROR: D:\local\Temp\f46179fe-8934-4135-820a-bed1e54b98bf.tmp:22: 'assign' :  cannot convert from ' const float' to ' smooth out 4-component vector of float'
ERROR: D:\local\Temp\f46179fe-8934-4135-820a-bed1e54b98bf.tmp:22: '' : compilation terminated
ERROR: 3 compilation errors.  No code generated.

SPIR-V is not generated for failed compile or link

Here is the code:
#version 460
//Passes variables from uniforms to frag_hud shader

layout(location = 0) in vec3 pos;
layout(location = 1) in vec2 vert_tex_coord;

uniform float vert_col_dist;
uniform sampler2D vert_hud01;
uniform sampler2D vert_hud02;
uniform sampler2D vert_hud03;

out vec2 tex_coord;
out float col_dist;
out vec4 hud01;
out vec4 hud02;
out vec4 hud03;

void main() {
    gl_Position = vec4(pos, 1.0);
    tex_coord = vec2(vert_tex_coord.x, vert_tex_coord.y);
    col_dist = vert_col_dist;
    hud01 = texture2D(vert_hud01, vert_tex_coord);
    hud02 = texture2D(vert_hud02, vert_tex_coord);
    hud03 = texture2D(vert_hud03, vert_tex_coord);
}

A: Figured it out.  Needed to use texture() instead of texture2D().


text:
Q: Delete existing Records if they are not in sent array Rails 5 API I need help on how to delete records that exist in the DB but not in array sent in a request;
My Array:

[
    {   "id": "509",
        "name": "Motions move great",
        "body": "",
        "subtopics": [
            {
                "title": "Tywan",
                "url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
            },
            {

                "title": "Transportations Gracious",
                "url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
            },
            {
                "title": "Transportation part",
                "url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
            }
        ]
    },
    {
        "name": "Motions kkk",
        "body": "",
        "subtopics": [
            {
                "title": "Transportations",
                "url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
            }
        ]
    }
]

Below is my implementation: where am going wrong?
@topics = @course.topics.map{|m| m.id()}
                     @delete= @topics
                    puts @delete
                  if Topic.where.not('id IN(?)', @topics).any?
                      @topics.each do |topic|
                        topic.destroy
                    end
                  end

A: it's not clear to me where, in your code, you pick the ids sent in the array you showed before... so I'm assuming like this:
   objects_sent = [
    {   "id": "509",
        "name": "Motions move great",
        "body": "",
        "subtopics": [
            {
                "title": "Tywan",
                "url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
            },
            {

                "title": "Transportations Gracious",
                "url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
            },
            {
                "title": "Transportation part",
                "url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
            }
        ]
    },
    {
        "name": "Motions kkk",
        "body": "",
        "subtopics": [
            {
                "title": "Transportations",
                "url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
            }
        ]
    }
]

since you have your array like this, the only information you need to query on database is the ids (also, assuming the id's in the array are the id's on database, otherwise it wouldn't make sense). You can get them like this:
sent_ids = objects_sent.map{|o| o['id'].to_i}

Also, it seems to me that, for the code you showed, you want to destroy them based on a specific course. There would be 2 ways to do that. First, using the relationship (I prefer like this one):
@course.topics.where.not(id: sent_ids).destroy_all

Or you can do the query directly on the Topic model, but passing the course_id param:
Topic.where(course_id: @course.id).where.not(id: sent_ids).destroy_all

ActiveRecord is smart enough to mount that query correctly in both ways. Give it a test and see which works better for you


text:
Q: Mutex Across Threads? So, I am getting an exception with the code below. I have put the exception details with it, but I believe it is caused by the fact that a different thread releases the lock then the one that starts the lock. I want to do this to potentially allow my main thread to continue while the writes queue up and occur.
First and foremost, I want to know if there IS a way this can be done? Secondly, should this be done or is it a bad plan?  have looked at ManualResetEvent, Monitor and Mutex all of which seem to do this. Note, this is for a network server and it is my first time writing a multithreaded, potentially high traffic one.
Exception: Thrown the first time a send (and its callback) is called.

System.ApplicationException on mutex.ReleaseMutex(). "Object synchronization method was called from an unsynchronized block of code."

public void SendAsync(byte[] packet)
{
    mutex.WaitOne();
    client.GetStream().BeginWrite(packet, 0, packet.Length, WriteCallback, null);
}

private void WriteCallback(IAsyncResult ar)
{
    client.GetStream().EndWrite(ar);
    mutex.ReleaseMutex();

    Console.WriteLine("Sent Data to " + RemoteEndPoint);
}

A: Assuming you're using Mutex class, according to Microsoft

The Mutex class enforces thread identity, so a mutex can be released only by the thread that acquired it. By contrast, the Semaphore class does not enforce thread identity. A mutex can also be passed across application domain boundaries.

I think, your callback method is called from another thread, it causes the Exception.
As suggested by Microsoft, you can use Semaphore for this situation.
For example:
static volatile Semaphore sem = new Semaphore(1,1);
    static void Main(string[] args)
    {
        Thread oThread = new Thread(new ThreadStart(fn2));
        oThread.Start();
        Thread.Sleep(200);
        sem.WaitOne();
        Console.WriteLine("Main is Doing");
        Thread.Sleep(2000);

        sem.Release();
    }
    static void fn2()
    {
        sem.WaitOne();
        Console.WriteLine("Thread is Doing");
        Thread.Sleep(2000);

        sem.Release();
    }

A: Considering this -

I want to do this to potentially allow my main thread to continue while the writes queue up and occur.
First and foremost, I want to know if there IS a way this can be done?

I don't think you need a mutex for that. Are you looking for something like this -
static object _lock = new object(); //somewhere based on your context
public void SendAsync(byte[] packet)
{
    Task.Run(() =>
        {
            ..... other codes
            lock (_lock)
            {
                client.GetStream().BeginWrite(packet, 0, packet.Length,
                ar => // the write callback (lambda)
                {
                    client.GetStream().EndWrite(ar);
                    Console.WriteLine("Sent Data to " + RemoteEndPoint);
                }, null);
            }
        });
}

Explanation:

*

*Task.Run runs asynchronously in a threadpool, which keeps your main thread free all the time.

*lock(_lock)  ensures only one thread is writing to the stream at any single moment, (threads are spawned by the threadpool from Task.Run)

*You don't need a separate writecallback, you could use inline lambda callback methods. Makes life much easier.

Let me know if this solves your problem.


text:
Q: Android listview selector not working in 2.2 The list selection is not working in 2.2. I found many of them having this issue but i did not find a solution which is working.
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_activated="false">
            <shape android:shape="rectangle">
              <solid android:color="@android:color/transparent" />
            </shape>
        </item>
        <item android:state_activated="false" android:state_pressed="false">
             <shape android:shape="rectangle">
                <solid android:color="@android:color/transparent" />
            </shape>
        </item>
        <item android:state_pressed="true">
            <shape android:shape="rectangle">
                 <solid android:color="@color/list_selector" />
            </shape>
        </item>
         <item android:state_selected="true">
            <shape android:shape="rectangle">
                 <solid android:color="@color/list_selector" />
            </shape>
        </item>
        <item android:state_activated="true">
             <shape android:shape="rectangle">
                 <solid android:color="@color/list_selector" />
            </shape>
        </item>
 </selector>

The above selector is my listselector. Its working fine in other devices 3.1, 4.1 etc..But its not working in 2.2
Any Help is appreciated.

A: I think the problem lies in android:state_activated
It was added in API 11(3.0), so it wont work in prior versions. More info in doc.
I believe you can accomplish the same behavior using state_checked property (available since API 1).
Also check this post.
Hope it helps.


text:
Q: Bessel function recursion relation I'm reading a paper and the following set of radial equations is derived:
$
-i \lbrack \partial_r + \frac{1}{r} \left( \frac{1}{2} - \nu \right) \rbrack u(r) = \pm k v(r)
$
$
-i \lbrack \partial_r + \frac{1}{r} \left( \frac{1}{2} + \nu \right) \rbrack v(r) = \pm k u(r)
$
Where $\nu$ is some constant whose meaning doesn't really matter here. The authors state that the left-hand sides of these equations are a version of the recursion relations for Bessel functions, so the solutions have the form:
$
\left( \begin{array} &u(r) \\ v(r) \end{array} \right) = \left( \begin{array} &(i \epsilon)^{-1/2} J_{\epsilon (\nu - 1/2)}(kr) \\ \pm (i \epsilon)^{-1/2} J_{\epsilon (\nu + 1/2)}(kr) \end{array} \right)$
and $\epsilon = \pm 1$.
No derivation is provided and I don't understand this step. Could someone briefly outline the method used here or provide some helpful reading material? I haven't had any luck so far.

A: You can verify the correctness of the solutions by using the two recursion relations
$$
J_n(z) = \frac{z}{2n}(J_{n-1}(z)+J_{n+1}(z))
$$
 and
$$
\frac{\mathrm d}{\mathrm dz}J_n(z) = \frac{J_{n-1}(z)-J_{n+1}(z)}{2}
$$
which you can find e.g. on Wikipedia.

A: It is in fact just a systems of linear first-order ODEs.
$\begin{cases}-i\left[\partial_r+\dfrac{1}{r}\left(\dfrac{1}{2}-\nu\right)\right]u(r)=\pm kv(r)\\-i\left[\partial_r+\dfrac{1}{r}\left(\dfrac{1}{2}+\nu\right)\right]v(r)=\pm ku(r)\end{cases}$
$\begin{cases}\partial_ru(r)+\dfrac{1}{r}\left(\dfrac{1}{2}-\nu\right)u(r)=\pm kiv(r)\\\partial_rv(r)+\dfrac{1}{r}\left(\dfrac{1}{2}+\nu\right)v(r)=\pm kiu(r)\end{cases}$
$\therefore\partial_{rr}u(r)+\dfrac{1}{r}\left(\dfrac{1}{2}-\nu\right)\partial_ru(r)-\dfrac{1}{r^2}\left(\dfrac{1}{2}-\nu\right)u(r)=\pm ki\partial_rv(r)$
$\partial_{rr}u(r)+\dfrac{1}{r}\left(\dfrac{1}{2}-\nu\right)\partial_ru(r)-\dfrac{1}{r^2}\left(\dfrac{1}{2}-\nu\right)u(r)=\pm ki\left(-\dfrac{1}{r}\left(\dfrac{1}{2}+\nu\right)v(r)\pm kiu(r)\right)$
$\partial_{rr}u(r)+\dfrac{1}{r}\left(\dfrac{1}{2}-\nu\right)\partial_ru(r)-\dfrac{1}{r^2}\left(\dfrac{1}{2}-\nu\right)u(r)=\mp\dfrac{ki}{r}\left(\dfrac{1}{2}+\nu\right)v(r)-k^2u(r)$
$\partial_{rr}u(r)+\dfrac{1}{r}\left(\dfrac{1}{2}-\nu\right)\partial_ru(r)-\dfrac{1}{r^2}\left(\dfrac{1}{2}-\nu\right)u(r)=-\dfrac{1}{r}\left(\dfrac{1}{2}+\nu\right)\left(\partial_ru(r)+\dfrac{1}{r}\left(\dfrac{1}{2}-\nu\right)u(r)\right)-k^2u(r)$
$\partial_{rr}u(r)+\dfrac{1}{r}\left(\dfrac{1}{2}-\nu\right)\partial_ru(r)-\dfrac{1}{r^2}\left(\dfrac{1}{2}-\nu\right)u(r)=-\dfrac{1}{r}\left(\dfrac{1}{2}+\nu\right)\partial_ru(r)-\dfrac{1}{r^2}\left(\dfrac{1}{4}-\nu^2\right)u(r)-k^2u(r)$
$\partial_{rr}u(r)+\dfrac{1}{r}\partial_ru(r)+\left(k^2-\dfrac{1}{r^2}\left(\nu^2-\nu+\dfrac{1}{4}\right)\right)u(r)=0$
$r^2\partial_{rr}u(r)+r\partial_ru(r)+\biggl(k^2r^2-\left(\nu-\dfrac{1}{2}\right)^2\biggr)u(r)=0$
$u(r)=\begin{cases}C_1J_{\nu-\frac{1}{2}}(kr)+C_2Y_{\nu-\frac{1}{2}}(kr)&\text{when}~\nu-\dfrac{1}{2}\text{is an integer}\\C_1J_{\nu-\frac{1}{2}}(kr)+C_2J_{\frac{1}{2}-\nu}(kr)&\text{when}~\nu-\dfrac{1}{2}\text{is not an integer}\end{cases}$
According to http://people.math.sfu.ca/~cbm/aands/page_361.htm,
$\partial_ru(r)=\begin{cases}-C_1\left(J_{\nu+\frac{1}{2}}(kr)-\dfrac{1}{r}\left(\nu-\dfrac{1}{2}\right)J_{\nu-\frac{1}{2}}(kr)\right)-C_2\left(Y_{\nu+\frac{1}{2}}(kr)-\dfrac{1}{r}\left(\nu-\dfrac{1}{2}\right)Y_{\nu-\frac{1}{2}}(kr)\right)&\text{when}~\nu-\dfrac{1}{2}\text{is an integer}\\-C_1\left(J_{\nu+\frac{1}{2}}(kr)-\dfrac{1}{r}\left(\nu-\dfrac{1}{2}\right)J_{\nu-\frac{1}{2}}(kr)\right)+C_2\left(J_{-\nu-\frac{1}{2}}(kr)-\dfrac{1}{r}\left(\dfrac{1}{2}-\nu\right)J_{\frac{1}{2}-\nu}(kr)\right)&\text{when}~\nu-\dfrac{1}{2}\text{is not an integer}\end{cases}$
$\therefore v(r)=\begin{cases}\mp\dfrac{i}{k}\left(-C_1\left(J_{\nu+\frac{1}{2}}(kr)-\dfrac{1}{r}\left(\nu-\dfrac{1}{2}\right)J_{\nu-\frac{1}{2}}(kr)\right)-C_2\left(Y_{\nu+\frac{1}{2}}(kr)-\dfrac{1}{r}\left(\nu-\dfrac{1}{2}\right)Y_{\nu-\frac{1}{2}}(kr)\right)+\dfrac{1}{r}\left(\dfrac{1}{2}-\nu\right)(C_1J_{\nu-\frac{1}{2}}(kr)+C_2Y_{\nu-\frac{1}{2}}(kr))\right)&\text{when}~\nu-\dfrac{1}{2}\text{is an integer}\\\mp\dfrac{i}{k}\left(-C_1\left(J_{\nu+\frac{1}{2}}(kr)-\dfrac{1}{r}\left(\nu-\dfrac{1}{2}\right)J_{\nu-\frac{1}{2}}(kr)\right)+C_2\left(J_{-\nu-\frac{1}{2}}(kr)-\dfrac{1}{r}\left(\dfrac{1}{2}-\nu\right)J_{\frac{1}{2}-\nu}(kr)\right)+\dfrac{1}{r}\left(\dfrac{1}{2}-\nu\right)(C_1J_{\nu-\frac{1}{2}}(kr)+C_2J_{\frac{1}{2}-\nu}(kr))\right)&\text{when}~\nu-\dfrac{1}{2}\text{is not an integer}\end{cases}$
$v(r)=\begin{cases}\pm\dfrac{i}{k}\left(C_1J_{\nu+\frac{1}{2}}(kr)+C_2Y_{\nu+\frac{1}{2}}(kr)\right)&\text{when}~\nu-\dfrac{1}{2}\text{is an integer}\\\pm\dfrac{i}{k}\left(C_1J_{\nu+\frac{1}{2}}(kr)-C_2J_{-\nu-\frac{1}{2}}(kr)\right)&\text{when}~\nu-\dfrac{1}{2}\text{is not an integer}\end{cases}$


text:
Q: python issue with projectile.py I am trying to get this code to work but I keep getting the error:

angle, vel, h0, time = getInputs()
NameError: name 'getInputs' is not defined" is not defined.

Can someone help me figure out why this is happening?
from math import sin, cos, radians

class Projectile:

     def __init__(self, angle, velocity, height):
         """Create a projectile with given launch angle, initial
          velocity and height."""
          self.xpos = 0.0
          self.ypos = height
          theta = radians(angle)
          self.xvel = velocity * cos(theta)
          self.yvel = velocity * sin(theta)
          self.maxypos = max(self.maxypos, self.ypos)
     def update(self, time):
          """Update the state of this projectile to move it time seconds
          farther into its flight"""
          self.xpos = self.xpos + time * self.xvel
          yvel1 = self.yvel - 9.8 * time
          self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0
          self.yvel = yvel1

     def getY(self):
          "Returns the y position (height) of this projectile."
          return self.ypos

     def getX(self):
          "Returns the x position (distance) of this projectile."
           return self.xpos

     def getInputs():
          a = eval(input("Enter the launch angle (in degrees): "))
          v = eval(input("Enter the initial velocity (in meters/sec): "))
          h = eval(input("Enter the initial height (in meters): "))
          t = eval(input("Enter the time interval between position calculations: "))
          return a,v,h,t

def main():
    angle, vel, h0, time = getInputs()
    cball = Projectile(angle, vel, h0)
    while cball.getY() >= 0:
        cball.update(time)
    print("\nDistance traveled: {0:0.1f} meters.".format(cball.getX()))

if __name__ == "__main__":
main()

A: The indentation of getInputs is off (it is placed in the class):
(note that using eval on user inputs is a very bad idea)
from math import sin, cos, radians

class Projectile:

    def __init__(self, angle, velocity, height):
        """Create a projectile with given launch angle, initial
        velocity and height."""
        self.xpos = 0.0
        self.maxypos = self.ypos = height   # defining self.maxypos
        theta = radians(angle)
        self.xvel = velocity * cos(theta)
        self.yvel = velocity * sin(theta)
        self.maxypos = max(self.maxypos, self.ypos)

    def update(self, time):
        """Update the state of this projectile to move it time seconds
        farther into its flight"""
        self.xpos = self.xpos + time * self.xvel
        yvel1 = self.yvel - 9.8 * time
        self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0
        self.yvel = yvel1

    def getY(self):
        "Returns the y position (height) of this projectile."
        return self.ypos

    def getX(self):
        "Returns the x position (distance) of this projectile."
        return self.xpos

def getInputs():
    a = eval(input("Enter the launch angle (in degrees): "))
    v = eval(input("Enter the initial velocity (in meters/sec): "))
    h = eval(input("Enter the initial height (in meters): "))
    t = eval(input("Enter the time interval between position calculations: "))
    return a,v,h,t

def main():
    angle, vel, h0, time = getInputs()
    cball = Projectile(angle, vel, h0)
    while cball.getY() >= 0:
        cball.update(time)
    print("\nDistance traveled: {0:0.1f} meters.".format(cball.getX()))

if __name__ == "__main__":
    main()

Corrected the declaration of self.maxypos as pointed out by @PM2Ring


text:
Q: Plone 4 Navigation Portlet, show only in non-folderish children Starter Info: Working with Plone 4.0.7 on CentOS 5.5 with Python 2.6.6.
I've got a folder that contains a few pages and I want to have a navigation portlet on all of the child pages but not the parent folder. My first thought of how to do this was to add the navigation portlet to the parent folder, pointing to itself, and setting the start level to 1. This works for not showing the portlet on the parent, but none of the child Pages are showing the portlet. I assume this is because the Pages aren't a folderish content type so the start level doesn't apply to them. Does anyone know where I would start to look to create a work around for this?
Thanks

A: I can confirm the issue.
The problem seems to be, that pages/documents are not recognized as subsections but as an item of the containing folder.
You can counterproof that, if you add folders to your folder, with them the navigation will work as you expect.
As a workaround you could use CSS to hide the navi on the folder with sth like:
.portaltype-folder .portletNavigation { display: none; }

A: Actually your method is the right method:

*

*add the navigation portlet in the parent folder

*set the initial level to 1. If child pages don't diplay the portlet check if they block the parent portlet acquisition.

*go to every child folder and block the portlet acquisition. If the number of child folder is hight, you can programmatically block the acquisition


text:
Q: how to pass selected drop-down list value to a variable or data block to execute a query I have a form and  I  a dropdown pop-list with year values in it(year field is not a primary key).
I have to fill all other field values when i select a year from dropdown(need to execute query of data block).
how can i achieve this.

A: If that dropdown list is part of the data block (it doesn't matter whether it is or is not a primary key), then

*

*navigate to that block

*enter query mode

*select year

*execute query

If dropdown belongs to another (control?) block, then

*

*in Forms Builder, open data block year field's property palette and set "Copy value from item" property to CTRL_BLOCK.YEAR

*

*alternatively, create a data block-level pre-query trigger:
:data_block_name.year := :control_block.year;

*create a button (in control block)

*create a when-button-pressed trigger which will
go_block('data_block_name');
execute query;

*run the form

*select year

*push the button


text:
Q: Show that $\sum_{k=1}^n a_k=3/4$. I am only looking for a hint on how to start this problem, not a full proof.
If $\sum_{k=1}^n ka_k=(n+1)/(n+2)$ for $n\in \mathbb{N}$, prove that
$$\sum_{k=1}^\infty a_k=\frac{3}{4}$$
So far all that I can come up with is that $\sum_{k=1}^\infty ka_k=\lim_{n\rightarrow \infty}(n+1)/(n+2)=1$. I have no idea how to come to any conclusion about $a_k$ given this information. I have written out the terms of $\sum_{k=1}^n ka_k$ and could not draw any conclusion about $a_k$ from that.

A: What you want to do is find an explicit formula for $a_k$ using the given condition. This is pretty easy to do by taking differences of consecutive partial sums.

 It is clear that $na_n = S_n - S_{n-1},$ where $S_k$ denotes the $k^{th}$ partial sum, so $a_n = \frac{1}{n(n+1)(n+2)}.$ The classic way to sum is this is by noting $a_n = 1/2\left(\frac{1}{n(n+1)} - \frac{1}{(n+1)(n+2)}\right).$ You should realize though that $a_1$ does not follow this rule, so the sum will be slightly altered.


text:
Q: Wrong numbers or errors when reading rows of numbers from a data file I'm trying to read a data file and take the 3 rows of numbers and store them into an array. I'm so confused on how I should approach this. Im not even sure if my while loop is even correct. The format of the file is throwing me off. I create variables to hold the name, school, scores, and difficulty for the diver but when I put it in my diveScore method the numbers are wrong, or theres an error reading the file when i don't use the Double.parseDouble() way. The parameters for the method are the dive number (1 to 3), the array of 7 scores, and the difficulty of the dive (1 to 4). Do I also call the diveScore method 3 times for each dive? Each diver has 3 dives which is why there are 3 rows of numbers.
Diver Class:
    public class Diver {

    private String name;
    private String school;
    private double [] scoreArray = new double[3];
    private double totalScore;

    Diver() {

    }
    Diver(String name, String school) {
        this.name = name;
        this.school = school;
    }
    //loop through score array and calculate the total score for each dive attempt
    public double [] diveScore(int diveNum, double [] scores, double difficulty) {
        double min = min(scores);
        double max = max(scores);

        for (int i = 0; i < scores.length; i++) {
            totalScore += scores[i];
        }
        totalScore -= max;
        totalScore -= min;
        totalScore *= difficulty;

        for (int i = 0; i < scoreArray.length; i++) {
            scoreArray[i] = totalScore;
        }
        return scoreArray;
    }
    //finds smallest score in array of scores
    private double min(double [] scores) {
        java.util.Arrays.parallelSort(scores);

        double min = scores[0];
        return min;
    }
    //finds largest score in array of scores
    private double max(double [] scores) {
        java.util.Arrays.parallelSort(scores);

        double max = scores[scores.length - 1];
        return max;
    }
    //calculates total of the 3 dives
    public double totalScore() {
        for (int i = 0; i < scoreArray.length; i++) {
                totalScore += scoreArray[i];
        }
        return totalScore;
    }
    public String toString() {
        String str = name + ", " + school + ": " + totalScore + "\n" + "Dive 1: " + scoreArray[0] + "\n" + "Dive 2: " + scoreArray[1] + "\n" + "Dive 3: " + scoreArray[2] + "\n";
        return str;
    }
}

Main File:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {

public static void main(String[] args) throws FileNotFoundException {
    Diver [] divers = new Diver[25];
    int numDivers = readFile(divers);
    System.out.println(numDivers);

}
public static int readFile(Diver [] divers) throws FileNotFoundException {
    File f = new File("divers.dat");
    Scanner kb = new Scanner(f);
    Diver d;

    int count = 1;
    int diveNum = 1;
    while (kb.hasNextLine()) {
        String name = kb.nextLine();
        String school = kb.nextLine();
        String s1 = kb.next();
        String s2 = kb.next();
        String s3 = kb.next();
        String s4 = kb.next();
        String s5 = kb.next();
        String s6 = kb.next();
        String s7 = kb.next();
        String diff = kb.next();

        double score1 = Double.parseDouble(s1);
        double score2 = Double.parseDouble(s2);
        double score3 = Double.parseDouble(s3);
        double score4 = Double.parseDouble(s4);
        double score5 = Double.parseDouble(s5);
        double score6 = Double.parseDouble(s6);
        double score7 = Double.parseDouble(s7);
        double difficulty = Double.parseDouble(diff);

        double [] scores = new double [7];
        scores[0] = score1;
        scores[1] = score2;
        scores[2] = score3;
        scores[3] = score4;
        scores[4] = score5;
        scores[5] = score6;
        scores[6] = score7;

        count++;
        diveNum++;
    }
    kb.close();
    return count;
}
public static void printDivers(Diver [] divers, int numDivers) {
    System.out.println("All Divers\n");
    for (int i = 0; i < divers.length; i++) {
        if (divers[i] != null) {
            System.out.println(divers[i]);
        }
    }
}

}
Data File:
Lucieta Spinelli
Bryn Mawr College
8 9 8 7 8 8 8 2.5
7 8 7 6 7 7 6 3.7
8 7 6 7 7 6 8 3.2
LiPing Sun
Rutgers University
6.5 5 9.5 7.5 8 8.5 7 2.3
7 9 7.5 9 8.5 6.5 8 2.6
6 4 5 9 7 8 6 3.0
Greg McEntire
University of Southern California
9 8 8.5 9.5 9 9.5 7 2.3
9 7 8 8 7.5 8.5 7.5 2.6
8 8 8 8 8 8 8 3.4
Shiva Vadaparthy
Northwestern University
9 8 9.5 9.5 7.5 8 8.5 3.0
8 9 8.5 7.5 9 8.5 8 3.6
7.5 9 8 7 8.5 8 7 4.1
Elizabeth Bennet
Oxford University
7 8 9 8 7 7 8 2.4
8 8 6 7 9 7 8 2.7
8 7 8 6 9 8 9 3.0
Sofia Berrios
Universidad Simon Bolivar
8.5 7.5 9.5 9 7 8.5 8 2.4
8 7 8 9 8 6 7 3.0
7 5.5 6.5 7 5 6.5 7 3.6
Amir Majid
Reed College
4 5 6 5 3 5 7 2.8
7 6 7 8 7 9 8 2.9
8 9 7 9 8.5 8 9 3.4
James Pajuio
University of Pennsylvania
8 7 8 9 8 6 7 2.8
7.5 9 8 7 8.5 8 7 3.0
7.5 9 8 7 8.5 8 7 4.3
Sharon Lewis
Howard University
8 9 9.5 9 8.5 8 9 2.7
4 5 5.5 7 6.5 4.5 5 3.2
8 7 8 9 8 8 7 4.0
Divya Patel
Temple University
7 9 7.5 9 8.5 6.5 8 2.1
8 7 8 6 9 8 9 2.3
3.5 5.5 4 5 3 4 4.5 4.3
Guo Zhang
Portland State University
5 6 5.5 7 6.5 7 5.5 6 3.0
8 7 8.5 9 7.5 8.5 8 3.2
9 8 9.5 8.5 9 8.5 9.5 4.1
Tomasz Wojaczyk
Tufts University
8 8 7 8 7 8 7 2.6
5 4 5 6 7 5 5 2.9
8 6 6 7 8 7 6 3.6

A: There are a few problems here. The ones that are causing your exception are:
You read a number with the next() method of Scanner, which leaves the end-of-line character at the end of the line, and then you try to read the next name with the nextLine() method, which is going to return an empty string for the name since the scanner is looking at the end of the line.
This is compounded by the fact that the lines for the name and school are followed by three lines of eight numbers each, or twenty-four numbers total, but you only try to read eight numbers.
The result is that you get "Lucieta Spinelli" and "Bryn Mawr College" and then the numbers 8, 9, 8, 7, 8, 8, 8, 2.5 for the first entry, and then the name "" and the school "7 8 7 6 7 7 6 3.7" and then the numbers 8, 7, 6, 7, 7, 6, 8, 3.2 for the second entry, and finally you get the name "" and the school "LiPing Sun" and then the numbers "Rutgers" and "University" and...
Well, that's as far as you get, since "Rutgers" isn't a number and when you try to convert it into one with parseDouble your program crashes.
You also aren't using the Diver class at all; you never create a Diver. There's also no point in reading the numbers into s1 and so on just to parse them and stick them in an array; you might as well just parse them into the array directly and leave s1 out of it, but that's minor.
The call to kb.close() should be inside a finally block, or else you should use a try-with-resources block to ensure the file gets closed.
I would strongly suggest reading Eric Lippert's excellent article, How to debug small programs; with the skills it would provide you with, you would likely not have needed to ask this question at all.


text:
Q: Manytoone mapping for two tables to the single entity Class A{
private int campid;
private string name;
}

Class B {
Private int campid;
Private string name;
}`

Class combo{
private int id;
private string phonenumber;
}

I'm trying like this
Class A{
private int campid;
private string name;
@OneToMany(targetEntity = Combo.class,mappedBy ="a",fetch = FetchType.LAZY,cascade=CascadeType.ALL )
private Combo combo;
}

Class B {
Private int campid;
Private string name;
@OneToMany(targetEntity = Combo.class,mappedBy ="b",fetch = FetchType.LAZY,cascade=CascadeType.ALL )
private Combo combo;
}`

Class combo{
private int id;
private string phonenumber;
@ManyToOne
@JoinColumn(name = "Camp_Id_fk",insertable=true, updatable=true)
private  A a;

@ManyToOne
@JoinColumn(name = "Camp_Id_fk",insertable=true, updatable=true)
private B b;
}

want to store the campid of class A and campid class B as the foreign key in the combo table. One campid can have multiple phone numbers.
I want to do this in spring jpa..I'm not understanding how to do it

A: @Entity
@Table(name = "a")
public class A {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "camp_id")
    private Long campid;

    @Column(name = "name")
    private String name;

    @Column
    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
    @JoinTable(name = "a_combo",
            joinColumns = @JoinColumn(name = "camp _id"),
            inverseJoinColumns = @JoinColumn(name = "id"))
    private Set<Combo> comboSet = new HashSet<>();
}

And same for B class


text:
Q: Grant command syntax error I get a syntax error when I run this command:
GRANT ALL PRIVILEGES ON  *.* TO 'root'@'%' IDENTIFIED BY 'password';

A: You only need to declare your instruction as follows
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';

You don´t need to use IDENTIFIED BY instruction because that command corresponds to
CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';

A: Simply use the as below it should work for you :
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';


text:
Q: Javascript - setInterval remains executing when declaration is removed I've got a problem with setInterval function. I've got an HTML page that loads content dynamically. The content is loaded via AJAX Post Request against a PHP Script that contains the target HTML content that is being loaded into an HTML div. Also a Javascript script is loaded and executed when the content is loaded dynamically. That script calls setInterval function and it executes forever. The problem comes when I load new content dynamically, I want setInterval function to stop because content that was being affected by setInterval is removed, but It continues executing, and throws error due to elements don't exist. It's obvious because the function is loaded in memory and the page ins't reloaded, so memory isn't flushed.
I need to clear the interval when loading new content (this also happens if I reload the new content: old setInterval still executes and new also does).
This is a simple example of the script being dynamically loaded:
//Autoload Array for each Grid
var GRID_autoLoad = new Array();

function Grid_autoLoad(grid_id){

   //This doesn't work! A new instance of the variable is created everytime
   if(GRID_autoLoad[grid_id] !== undefined ) {
      clearInterval(GRID_autoLoad[grid_id]);
   }

   GRID_autoLoad[grid_id] = setInterval(function(){
       Grid_load(grid_id);
   }, 5000);
}

function Grid_init(grid_id){
    Grid_load(grid_id);
    Grid_autoLoad(grid_id);
}

I'm not able to check if the variable is already defined and clear the previous interval because a new instance of the variable is created when reloading the content! How can I unset setInterval function?


text:
Q: offline gps coordinate access - iPhone/Android I'm working on a little app, and one of our requirements is to check a users physical location when he did a particular activity (Example: A picture must be taken near Eiffel Tower only)
Now, a lot of our smartphone users might or might not have Data Access at that very instant.
Is it possible to fetch the users Latitude and Longitude when he's offline (No 3G/WiFi).???
I guess the Maps app on iPhone uses data connectivity just to render the underlying Google Maps and the iPhone OS still has access to device's GPS co-ordinates. Please let me know if i'm right or wrong..
I would like to learn the same about other OS'es, example: Android. Any links/references will be much appreciated.
UPDATE: I'm aware that GPS is a satellite based technology and hence i guess it should have no direct relation with internet connectivity.

A: You are right!
To get the latitude and longitude Informations the devices use the GPS hardware. This is done without internet connection. What you need is a GPS signal! However, if you are inside buildings where you often don't have good GPS signals the iPhone tries to also locate the device using surrounding 3G and WIFI nets.
If you want to display that coordinates for example with google maps you need internet connection to load the maps according to the coordinates you got. Also, to retrieve informations like address,street, etc. the devices needs access to the internet to search the databases for this kind of informations.
EXAMPLE for iOS:
Fist import #import<CoreLocation/CoreLocation.h> to you .h file.
Then basically you need the CLLocationManager.
- (IBAction)startSearchingLocation:(id)sender
{
    //locationManager is ivar of CLLocationManager
    self.locationManager = [[CLLocationManager alloc] init];
    //release it when you stop the location manager!

    // make self the delegate of the location manager
    [locationManager setDelegate:self];

    //Note that this settings will have a huge impact on battery life!
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];

    //And finally start the location manager.
    [locationManager startUpdatingLocation];
}

The location Manager will start sending location informations to a delegate method
called:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

It's recommended to throw the very first results away because they could be old cached data. Also check for accuracy to make sure you get good results here.
REFERENCES:
For more informations check out this and this documentation.
Also take a look at the apple example code named Locations.

A: thats code works with android
private double[] getGPS() {
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        List<String> providers = lm.getProviders(false);

        /* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
        Location l = null;

        for (int i=providers.size()-1; i>=0; i--) {
                l = lm.getLastKnownLocation(providers.get(i));
                if (l != null) break;
        }

        double[] gps = new double[2];
        if (l != null) {
                gps[0] = l.getLatitude();
                gps[1] = l.getLongitude();
        }
        return gps;
}


text:
Q: In Train Simulator 2015, is there a way to use SI units? In Train Simulator 2015 (TS2015), is there a way to use the International System of Units (SI) instead of the Imperial units? This option does not seem available from the menus and options.

A: The units used depend on the route you select -- based on what that country actually uses.
For example, routes in Germany should use SI (km) units while those in the UK or USA use Imperial measurements (miles).