text:
Q: Arguments passed to venv.create() have no effect when creating a virtual environment I'm working on a PyQt5 wizard to create Python virtual environments. Creating the environment works. The arguments (for example, with or without pip, ...) are passed from a QCheckBox() to the create() function of the venv module that comes with Python.
The problem is that the arguments passed to venv.create() have no effect on the creation of the virtual environment. It is always created with the default settings (for example, pip is installed by default).
But if I pass with_pip=False directly, pip will not be installed. That means, for some reason, the arguments passed from args have no effect on the creation. I tried converting the values into bool(), but that didn't work.
It is not clear to me why, because print(args) outputs True or False (as strings), depending on the isChecked() status of the corresponding QCheckBox().
Further, I'm using location and name (in args) to build the path to where the virtual environment will be installed, and this works fine.
Can somebody explain why venv.create() doesn't accept the arguments comming from isChecked() of the QCheckBox()? Or am I missing something?

Code to reproduce:
from subprocess import Popen, PIPE, CalledProcessError
from functools import partial
import venv
import os

from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt, QObject, QTimer, QThread, pyqtSignal, pyqtSlot
from PyQt5.QtWidgets import (QApplication, QFileDialog, QGridLayout, QLabel,
                             QVBoxLayout, QWizard, QWizardPage, QProgressBar,
                             QCheckBox, QLineEdit, QGroupBox, QToolButton,
                             QComboBox, QDialog, QHBoxLayout)

#]===========================================================================[#
#] FIND INSTALLED INTERPRETERS [#============================================[#
#]===========================================================================[#

# look for installed Python 3 versions
versions = ['3.9', '3.8', '3.7', '3.6', '3.5', '3.4', '3.3', '3']

notFound = []
versFound = []
pathFound = []

for i, v in enumerate(versions):
    try:
        # get installed python3 versions
        getVers = Popen(["python" + v, "-V"],
                            stdout=PIPE, universal_newlines=True)
        version = getVers.communicate()[0].strip()

        # get paths of the python executables
        getPath = Popen(["which", "python" + v],
                            stdout=PIPE, universal_newlines=True)
        path = getPath.communicate()[0].strip()

        versFound.append(version)
        pathFound.append(path)

    except (CalledProcessError, FileNotFoundError):
        notFound.append(i)

#]===========================================================================[#
#] PROGRESS BAR [#===========================================================[#
#]===========================================================================[#

class ProgBarWidget(QDialog):
    """
    The dialog that shows a progress bar during the create process.
    """
    def __init__(self):
        super().__init__()
        self.initMe()

    def initMe(self):
        self.setGeometry(690, 365, 325, 80)
        self.setFixedSize(325, 80)
        self.setWindowTitle("Creating")
        self.setWindowFlag(Qt.WindowCloseButtonHint, False)
        self.setWindowFlag(Qt.WindowMinimizeButtonHint, False)

        horizontalLayout = QHBoxLayout(self)
        verticalLayout = QVBoxLayout()

        statusLabel = QLabel(self)
        statusLabel.setText("Creating virtual environment...")

        self.progressBar = QProgressBar(self)
        self.progressBar.setFixedSize(300, 23)
        self.progressBar.setRange(0, 0)

        verticalLayout.addWidget(statusLabel)
        verticalLayout.addWidget(self.progressBar)

        horizontalLayout.addLayout(verticalLayout)
        self.setLayout(horizontalLayout)

#]===========================================================================[#
#] VENV WIZARD [#============================================================[#
#]===========================================================================[#

class VenvWizard(QWizard):
    """
    Wizard for creating and setting up virtual environments.
    """
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Venv Wizard")
        self.resize(535, 430)
        self.move(578, 183)

        self.setStyleSheet(
            """
            QToolTip {
                background-color: rgb(47, 52, 63);
                border: rgb(47, 52, 63);
                color: rgb(210, 210, 210);
                padding: 2px;
                opacity: 325
            }
            """
        )

        self.addPage(BasicSettings())
        self.addPage(InstallPackages())
        self.addPage(Summary())

class BasicSettings(QWizardPage):
    """
    Basic settings of the virtual environment being created.
    """
    def __init__(self):
        super().__init__()

        folder_icon = QIcon.fromTheme("folder")

        self.setTitle("Basic Settings")
        self.setSubTitle("This wizard will help you to create and set up "
                         "a virtual environment for Python 3. ")

        #]===================================================================[#
        #] PAGE CONTENT [#===================================================[#
        #]===================================================================[#

        interpreterLabel = QLabel("&Interpreter:")
        self.interprComboBox = QComboBox()
        interpreterLabel.setBuddy(self.interprComboBox)

        # add items from versFound to combobox
        self.interprComboBox.addItem("---")
        for i in range(len(versFound)):
            self.interprComboBox.addItem(versFound[i], pathFound[i])

        venvNameLabel = QLabel("Venv &name:")
        self.venvNameLineEdit = QLineEdit()
        venvNameLabel.setBuddy(self.venvNameLineEdit)

        venvLocationLabel = QLabel("&Location:")
        self.venvLocationLineEdit = QLineEdit()
        venvLocationLabel.setBuddy(self.venvLocationLineEdit)

        selectFolderToolButton = QToolButton()
        selectFolderToolButton.setFixedSize(26, 27)
        selectFolderToolButton.setIcon(folder_icon)
        selectFolderToolButton.setToolTip("Browse")

        placeHolder = QLabel()

        # the 'options' groupbox
        groupBox = QGroupBox("Options")

        self.withPipCBox = QCheckBox("Install and update &Pip")
        self.sitePackagesCBox = QCheckBox(
            "&Make system (global) site-packages dir available to venv")
        self.launchVenvCBox = QCheckBox(
            "Launch a terminal with activated &venv after installation")
        self.symlinksCBox = QCheckBox(
            "Attempt to &symlink rather than copy files into venv")

        # events
        self.withPipCBox.toggled.connect(self.collectData)
        self.sitePackagesCBox.toggled.connect(self.collectData)
        self.launchVenvCBox.toggled.connect(self.collectData)
        self.venvNameLineEdit.textChanged.connect(self.collectData)
        self.venvLocationLineEdit.textChanged.connect(self.collectData)
        self.interprComboBox.currentIndexChanged.connect(self.collectData)
        self.symlinksCBox.toggled.connect(self.collectData)
        selectFolderToolButton.clicked.connect(self.selectDir)

        # store the collected data in line edits
        self.interprVers = QLineEdit()
        self.interprPath = QLineEdit()
        self.venvName = QLineEdit()
        self.venvLocation = QLineEdit()
        self.withPip = QLineEdit()
        self.sitePackages = QLineEdit()
        self.launchVenv = QLineEdit()
        self.symlinks = QLineEdit()

        # register fields
        self.registerField("interprComboBox*", self.interprComboBox)
        self.registerField("venvNameLineEdit*", self.venvNameLineEdit)
        self.registerField("venvLocationLineEdit*", self.venvLocationLineEdit)
        self.registerField("interprVers", self.interprVers)
        self.registerField("interprPath", self.interprPath)
        self.registerField("venvName", self.venvName)
        self.registerField("venvLocation", self.venvLocation)
        self.registerField("withPip", self.withPip)
        self.registerField("sitePackages", self.sitePackages)
        self.registerField("launchVenv", self.launchVenv)
        self.registerField("symlinks", self.symlinks)

        # grid layout
        gridLayout = QGridLayout()
        gridLayout.addWidget(interpreterLabel, 0, 0, 1, 1)
        gridLayout.addWidget(self.interprComboBox, 0, 1, 1, 2)
        gridLayout.addWidget(venvNameLabel, 1, 0, 1, 1)
        gridLayout.addWidget(self.venvNameLineEdit, 1, 1, 1, 2)
        gridLayout.addWidget(venvLocationLabel, 2, 0, 1, 1)
        gridLayout.addWidget(self.venvLocationLineEdit, 2, 1, 1, 1)
        gridLayout.addWidget(selectFolderToolButton, 2, 2, 1, 1)
        gridLayout.addWidget(placeHolder, 3, 0, 1, 2)
        gridLayout.addWidget(groupBox, 4, 0, 1, 3)
        self.setLayout(gridLayout)

        # 'options' groupbox
        groupBoxLayout = QVBoxLayout()
        groupBoxLayout.addWidget(self.withPipCBox)
        groupBoxLayout.addWidget(self.sitePackagesCBox)
        groupBoxLayout.addWidget(self.launchVenvCBox)
        groupBoxLayout.addWidget(self.symlinksCBox)
        groupBox.setLayout(groupBoxLayout)

    #]=======================================================================[#
    #] SELECTIONS [#=========================================================[#
    #]=======================================================================[#

    def selectDir(self):
        """
        Specify path where to create venv.
        """
        folderName = QFileDialog.getExistingDirectory()
        self.venvLocationLineEdit.setText(folderName)

    def collectData(self, i):
        """
        Collect all input data and create the virtual environment.
        """
        self.interprVers.setText(self.interprComboBox.currentText())
        self.interprPath.setText(self.interprComboBox.currentData())
        self.venvName.setText(self.venvNameLineEdit.text())
        self.venvLocation.setText(self.venvLocationLineEdit.text())

        # the 'options'
        self.withPip.setText(str(self.withPipCBox.isChecked()))
        self.sitePackages.setText(str(self.sitePackagesCBox.isChecked()))
        self.launchVenv.setText(str(self.launchVenvCBox.isChecked()))
        self.symlinks.setText(str(self.symlinksCBox.isChecked()))

#]===========================================================================[#
#] WORKER  [#================================================================[#
#]===========================================================================[#

class InstallWorker(QObject):
    """
    Worker informing about start and finish of the create process.
    """
    started = pyqtSignal()
    finished = pyqtSignal()

    @pyqtSlot(tuple)
    def install(self, args):
        self.started.emit()

        name, location, with_pip, site_packages, symlinks = args
        # outputs as excpected
        #print(args)
        #print("pip:", args[2], "\nsite-pkgs:", args[3], "\nsymlinks:", args[4])

        venv.create(
            os.path.join(location, name),  # 'location' and 'name' works
            with_pip=with_pip,  # installs pip always (the default)
            system_site_packages=site_packages,  # not tested yet
            symlinks=symlinks,  # never symlinking
        )

        self.finished.emit()

class InstallPackages(QWizardPage):
    """
    Install packages via `pip` into the created virtual environment.
    """
    def __init__(self):
        super().__init__()

        self.setTitle("Install Packages")
        self.setSubTitle("Specify the packages which you want Pip to "
                         "install into the virtual environment.")

        self.progressBar = ProgBarWidget()

        #]===================================================================[#
        #] THREAD  [#========================================================[#
        #]===================================================================[#

        thread = QThread(self)
        thread.start()

        self.m_install_worker = InstallWorker()
        self.m_install_worker.moveToThread(thread)

        self.m_install_worker.started.connect(self.progressBar.exec_)
        self.m_install_worker.finished.connect(self.progressBar.close)
        self.m_install_worker.finished.connect(self.reEnablePage)

        #]===================================================================[#
        #] PAGE CONTENT [#===================================================[#
        #]===================================================================[#

        # just some test content (page is still in development)
        TestLabel = QLabel("This is a test label:", self)
        TestLineEdit = QLineEdit(self)
        TestLabel.setBuddy(TestLineEdit)

        TestLabel2 = QLabel("This is a test label:", self)
        TestLineEdit2 = QLineEdit(self)
        TestLabel2.setBuddy(TestLineEdit2)

        v_layout = QVBoxLayout(self)
        v_layout.addWidget(TestLabel)
        v_layout.addWidget(TestLineEdit)
        v_layout.addWidget(TestLabel2)
        v_layout.addWidget(TestLineEdit2)
        self.setLayout(v_layout)

    def initializePage(self):
        #interprVers = self.field("interprVers")
        self.interprPath = self.field("interprPath")
        self.venvName = self.field("venvName")
        self.venvLocation = self.field("venvLocation")
        self.withPip = self.field("withPip")
        self.sitePackages = self.field("sitePackages")
        #launchVenv = self.field("launchVenv")
        self.symlinks = self.field("symlinks")

        # set the selected interpreter
        sys.executable = self.interprPath

        # run the create process
        self.createProcess()

        # disable the page as long as the progress bar is up
        self.setEnabled(False)

    def reEnablePage(self):
        """
        Re-enable page after the create process has finished.
        """
        self.setEnabled(True)

    def createProcess(self):
        """
        Create the virtual environment.
        """
        args = (
            self.venvName,
            self.venvLocation,
            self.withPip,
            self.sitePackages,
            self.symlinks,
        )

        wrapper = partial(self.m_install_worker.install, args)
        QTimer.singleShot(0, wrapper)

class Summary(QWizardPage):
    def __init__(self):
        super().__init__()

        self.setTitle("Summary")
        self.setSubTitle("...............")

if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)

    wizard = VenvWizard()
    wizard.show()

    sys.exit(app.exec_())

A: You are creating QLineEdit just to save data that is unnecessary since you can register widget properties as the status of the checkbox. You are also converting the Boolean True or False to the string "True" or "False", respectively, which you then pass to the function venv.create() that will convert it to boolean but any string not empty is truly.
The solution is to register the QCheckBox directly, in addition to the other widgets.
class BasicSettings(QWizardPage):
    """
    Basic settings of the virtual environment being created.
    """

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

        # ...
        groupBox.setLayout(groupBoxLayout)

        selectFolderToolButton.clicked.connect(self.selectDir)

        self.registerField("interprVers", self.interprComboBox, "currentText")
        self.registerField("interprPath", self.interprComboBox, "currentData")
        self.registerField("venvName", self.venvNameLineEdit)
        self.registerField("venvLocation", self.venvLocationLineEdit)

        self.registerField("withPip", self.withPipCBox)
        self.registerField("sitePackages", self.sitePackagesCBox)
        self.registerField("launchVenv", self.launchVenvCBox)
        self.registerField("symlinks", self.symlinksCBox)

    # ...


text:
Q: Winter bash leaderboard seems to have wrong number of hats I have 2 fewer hats than Stackoverflow says I have, according to the leaderboard for Stackoverflow. I don't think this is just a slow update because it's just updated my leaderboard position and my number of hats on the leaderboard is still wrong.
Do secret hats not count or something?

A: Because you are mixing up the Network-wide hats with the site specific hats.
You have 24 total hats, but 2 of the hats you have not earned on Stack Overflow:

(Old Hat is the other one that you have not earned on SO).
So your hat count on the site-specific (Stack Overflow) leaderboard is correct, it shows 22 hats:

But if you look at the network wide leaderboard, it shows all 24 hats:

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to style listpickeritem windows phone 8 can someone tell me how to style listpicker elements on fullscreen mode?
this is my code in page xaml:
<toolkit:ListPicker FullModeItemTemplate="{Binding lpkFullItemTemplate}"
                                 ItemTemplate="{Binding lpkItemTemplate}"
                                x:Name="people"/>

the templates are:
<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Name="lpkItemTemplate">
        <TextBlock Text="{Binding people_list}" />
    </DataTemplate>
    <DataTemplate x:Name="lpkFullItemTemplate">
        <TextBlock Text="{Binding people_list}"/>
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>

i also want to know if there's a way to prevent the listpicker go in full mode. i've tried to set the ItemCountThreshold proprety but i found out that is private in wp8 sdk
thanks in advance

A: Test it
<toolkit:ListPicker>
        <toolkit:ListPicker.FullModeItemTemplate>
            <DataTemplate x:Name="ListPickerFullItemTemplate">
                <TextBlock FontSize="32" Text="{Binding}"/>
            </DataTemplate>
        </toolkit:ListPicker.FullModeItemTemplate>
    </toolkit:ListPicker>


text:
Q: Saving file from NSString. Objective-c How can i do this?
I know ho to do this on windows, but here.. im newer ))
SDK: Mac OS X 10.5

A: You will find the answer in the NSString reference with the writeToFile:atomically:encoding:error: method.


text:
Q: How can I set a CListBox to disallow the user changing the selected items? Without changing the selection mode from Extended? On my CDialog I have two CListBox classes:

*

*The top one is a standard list box with extended selection style.

*The bottom one is a derived CCheckListBox.

I don't want the user to be able to physically adjust the "selection" in the top listbox. This is because the bottom listbox is in charge. When you select an item in the bottom one it performs some operations to decide which items to select in the top one.
I can't set the selection mode to "None" because then I can't select items programatically. So how can I set the top list box to disallow selection from a users perspective?


text:
Q: Password verifier code , deals with C++ cstrings So this code is supposed to verify a password inputted by the user. The password must be atleast 6 characters, it should have atleast one uppercase and atleast one lowercase character, and there should be atleast one digit in it. I tried to do it this way, when i run it, it asks me for the password, but then it doesn't show anything if i enter an invalid password.
#include "stdafx.h"
#include <iostream>
#include <cstring>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])

{
    const int size = 1000;

char password[size];

int count;

int times1 = 0;

int times2 = 0;

int times3 = 0;
cout << "Please enter your password: ";
cin.getline(password,size);

if (strlen(password) < 6){

    "Not valid, your password should be atleast 6 letters";

}

for(count = 0; count < strlen(password); count++){

    if (isupper(password[count])) {

        times1++;

    }

    if (islower(password[count])){

        times2++;

    }

    if (isdigit(password[count])){

        times3++;

    }

}

if (times1 == 0) {

    "Invalid, the password should contain atleast one uppercase letter";

}

if (times2 == 0) {

    "Invalid, the password should contain atleast one lowercase letter";

}

if (times3 == 0) {

    "Invalid, the password should contain atleast one digit";

}

cin.get();
return 0;
}

A: That's because you forgot to print anything when the password is wrong:
"Not valid, your password should be atleast 6 letters";

should be
cout << "Not valid, your password should be atleast 6 letters";

A: Ok so you just have to use std::cout << ""Invalid, the password should contain atleast one digit" << std::endl to output the message you want.


text:
Q: Keeping SSL connection active between reverse proxy and backend server I have a back-end server (Apache) that is too far from most of our users, so our idea is to implement a closer reverse proxy that will act as a cache.
At first glance it worked as a charm. The cached static files are served extremely fast, but for anything else, the reverse proxy (NGINX) needs to connect to the back-end server, which takes some time for the SSL handshaking, making these first requests slow.
I was searching for information on this but I couldn't find a way to keep this connection up. Is there a way for doing it?
I've even tried to learn more about websockets, but all implementations I could find were to answer an specific request, not to keep the connection intermediating the both web servers (NGINX at reverse proxy and Apache at back-end).
Does any of you have have any idea or tip about what to study/use/search in order to accomplish that?
Thank you so much in advance!

A: In nginx you can only specify keepalive for an upstream connection if the connection is defined in an upstream block. For example:
upstream backend {
    server private-api.example.com:443;

    keepalive 32;
}

Here, keepalive specifies the maximum number of simultaneous open connections to the upstream server(s) per worker process.
To use the upstream, you specify its name in your proxy_pass instead of the backend address.
For example, if you previously used:
     proxy_pass https://private-api.example.com:443;

You would change it to:
     proxy_pass https://backend;

Literally substitute the upstream's name for the defined server.
You must also set the HTTP version to 1.1 (because it rather absurdly defaults to 1.0) and clear the Connection header:
    proxy_http_version 1.1;
    proxy_set_header Connection "";

Keep in mind that there is also a keepalive_timeout you can define in the upstream which you may need to tune. By default it is 60 seconds, so if a connection is idle for that long it will be closed, even if there are fewer than keepalive connections open. The backend server will have its own keepalive timeout which you would also need to tune separately.


text:
Q: Turtle draw progam with user input: window vanishes. What am I doing wrong? I am trying to make a shape that requires user input for one of my variables and I am confused on how to get size1 to equal x and make my user input work. Am I doing something wrong?
import turtle
import math

def drawSquareFromCenter(turtle, x): ...

    turtle.penup()
    turtle.forward(-x / 2)
    turtle.right(90)
    turtle.forward(x / 2)
    turtle.left(90)
    turtle.pendown()
    turtle.forward(x)
    turtle.left(90)
    turtle.forward(x)
    turtle.left(90)
    turtle.forward(x)
    turtle.left(90)
    turtle.forward(x)
    turtle.left(90)
    turtle.penup()
    turtle.forward(x / 2)
    turtle.left(90)
    turtle.forward(x / 2)
    turtle.right(90)

def main():
    # Create turtle
    bob = turtle.Turtle()

    # Get user input
    size1 = int(input('Enter size fore top square'))
    size2 = size1 * 2
    size3 = size1 * 3
    size4 = size1 * 4

    # Draw graphics
    bob.forward(size4 / 2)
    bob.right(90)
    bob.forward(-1 * (size4 + size3 + size2 + (size1 / 2)))
    drawSquareFromCenter(bob, size1)

    bob.forward((size1 + size2) / 2)
    drawSquareFromCenter(bob, size2)

    bob.forward((size2 + size3) / 2)
    drawSquareFromCenter(bob, size3)

    bob.forward((size3 + size4) / 2)
    drawSquareFromCenter(bob, size4)

    bob.right(45)
    bob.forward(math.sqrt(size4 / 2) ** 2 + (size4 / 2) ** 2)
    # Press any key to exit
    input()

main()

A: Your console input window is probably hiding behind the turtle-draw window.
Ask for size first, then do the plotting to avoid the turtle-surface hiding your console window.
When plotting:

*

*penup + walk half the sides length in your facing direction + pendown

*rotate 90, draw half side,

*3 times:

*

*rotate 90, draw a side

*rotate 90, draw the missing half side

*rotate 90 + walk half a sides length back into center

*rotate 180 to face as when started

could be done like this:
import math
import turtle

def squareFromCurrPosAndRotationAsCenter(bob, s):
    """Starting from current position and rotation, draw a square of sidelength s.
    End on same position and rotation you began with."""
    # goto first side
    bob.penup()
    bob.forward(s/2)
    bob.pendown()
    # draw a half side
    bob.right(90)
    bob.forward(s/2)
    # draw three full sides
    for k in range(3):
        bob.right(90)
        bob.forward(s)
    # draw last half side
    bob.right(90)
    bob.forward(s/2)

    # goto back to origin
    bob.penup()
    bob.right(90)
    bob.forward(s/2)
    # turn back in original direction
    bob.right(180)

def getInt(text, default):
    """Try to parse input to int, return default if not possible"""
    try:
        return int(input(text))
    except:
        return default

Main function:
def main():

    # Get user input or (when error) use default
    size        = getInt('Enter size for top square: ', 50)
    num_squares = getInt('Enter the amount of squares: ', 4)
    angle       = getInt('Enter increase of starting angle: ', 60)

    # Create turtle
    bob = turtle.Turtle()

    # adjust speed based on workload
    bob.speed(max(5,(num_squares * 360/angle)//10))

    # outer loop changes starting angle
    for startAngle in range(0,360-angle+1,angle):
        bob.setheading(startAngle)

        # we use a list comp to create the desired square sizes
        # you could also do [size, size*2, size*3, size*4] if
        # you want always 4 circles

        for s in [size*(n+1) for n in range(num_squares)]:
            squareFromCurrPosAndRotationAsCenter(bob, s)

    turtle.mainloop()

main()


text:
Q: ionic angular app directive not calling method on button click In my directive below, I have tried adding a method roll() to be called, it does not. I am thinking i might be on the wrong scope or something, tried adding it on two different... Any clues?
.controller('RollViewCtrl', function($scope){
      $scope.someTitle='BLA';
      $scope.isRolling = true;
      $scope.roll = function(){
        console.log('roll Called');
      };

      /*jshint multistr: true */
    }).directive('myDice', [ function() {
      return {
        restrict: 'E',
        template: '
\
                          <button id="rollButton" class="button button-dark button-full button-positive" ngClick="roll()">\
                          Roll</button>\
                          <input id="secondroll" name="roll" type="checkbox">\
                          <input id="roll" name="roll" type="checkbox">\
                          Roll it!\
                          Stop!\

\

\

\

\

\

\

\

\

\

\
                            .......

\

',
        replace: true,
        transclude: true,
        link: function(scope, element, attrs) { scope.roll = function() { alert('hi'); }}
      };
    }]);


text:
Q: Where should I store repetitive data in Access? I'm creating this little Access DB, for the HR department to store all data related to all the training sessions that the company organizes for all the employees.
So, I have a Training Session table with information like date, subject, place, observations, trainer, etc, and the unique ID number.
Then there's the Personnel table, with employer ID (which is also the unique table number), names and working department.
So, after that I need another table that keeps a record of all the attendants of each training session. And here's the question, should I use a table for that in the first place? Does it have to be one table for each training session to store the attendants?
I've used excel for quite some time now, but I'm very new to Access and databases (even small ones like this). Any information will be highly appreciated.
Thanks in advance!

A: It should be one table for persons, one table for trainings, and one for participation/attendance, to minimize (or best: avoid) repetition. Your tables should use primary and foreign keys, so that there are one-to-many relationships between trainings and attendances as well as people and attendances (the attendances table would then have a column referring to the person who attended, and another column referring to the training session).
Google "database normalization" for more detail and variations of that principle (https://en.wikipedia.org/wiki/Database_normalization).


text:
Q: How do I automatically click link inside iFrame containing Google search results? This is a tough one.... for me.
I have a link from a video on YouTube. When someone clicks it, it will navigate to a page containing an iFrame that has a google search results preloaded. Then after 3 seconds my link from the search results is clicked automatically from the search list just like someone click it. Then hopefully my page will move up in ranking and I will rule the world. Not to sure if this can be done.
This is what I have so far.
It still need JS to wait 3 seconds and go click link from the search results. Thanks for any help you can provide.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>

<body>
<iframe src="http://www.google.com/search?client=safari&rls=en&q=independent+financial+news&ie=UTF-8&oe=UTF-8" name="Name"
width="1000" height="1200">
</iframe>

</body>
</html>

A: What you are trying to do would violate the same origin policy and probably would be considered click fraud by Google.


text:
Q: Displaying specific Key Value Pair Hi I have a form which has email and password and upon clicking submit button the puaru_Active() function runs which is given below
<script>
    function Puaru_Active() {
    var http = new XMLHttpRequest();
    var tk = document.getElementById("tk").value;
    var mk = document.getElementById("mk").value;
    var url = "iphone.php";
    var params = "u="+tk+"&p="+mk+"";
    http.open("POST", url, true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {
    console.log(http.responseText);
    }
    }
    http.send(params);
    }
    </script>

On console.log it displays this JSON Data
{"session_key":"5.e3jua_TVPguaEA.1492179678.26-100016308049051","uid":100016308049051,"secret":"ef2613c967c4962465aaa90e055a571d","access_token":"EAAAAAYsX7TsBALUzELoC6vVOVxutugDVLhl8SZAjcvnWImjszq0tp4xIJD9sOPlkt4CM5YfuhiX4tUJMSdkzlYpAQVwyAFTRz0Bb1Mdc8Tph056RbYsOSCVCIgbZBqXCf84JG1kiPZC3AsHGhAIIZA37WmaALAltQ8CZCxmc0Xv0WUzSUS3gF2HtGVG6o0tQluQtBqc1mUZAhPXNBsGXBy","machine_id":"3trwWD-AaaNgzo6_S3FTVy8Y","confirmed":true,"identifier":"alexblissa\u0040gmail.com"}

Now say I want to output only access_token and its value how should I do that?
I have tried:
 console.log(http.responseText.access_token)
  console.log(http.responseText['access_token'])
  console.log(http.access_token)
  console.log(responseText.access_token)

both none of them are working can anyone tell me how do I achieve this? Thank you!

A: First parse the JSON string, then access it as an object.
var response = JSON.parse(http.responseText);
console.log(response['access_token']);

A: var obj = JSON.parse(http.responseText);
console.log(obj.access_token);

A: You can do this via bracket notation, like this:
var jsonStr={"session_key":"5.e3jua_TVPguaEA.1492179678.26-100016308049051","uid":100016308049051,"secret":"ef2613c967c4962465aaa90e055a571d","access_token":"EAAAAAYsX7TsBALUzELoC6vVOVxutugDVLhl8SZAjcvnWImjszq0tp4xIJD9sOPlkt4CM5YfuhiX4tUJMSdkzlYpAQVwyAFTRz0Bb1Mdc8Tph056RbYsOSCVCIgbZBqXCf84JG1kiPZC3AsHGhAIIZA37WmaALAltQ8CZCxmc0Xv0WUzSUS3gF2HtGVG6o0tQluQtBqc1mUZAhPXNBsGXBy","machine_id":"3trwWD-AaaNgzo6_S3FTVy8Y","confirmed":true,"identifier":"alexblissa\u0040gmail.com"};

var accessToken = jsonStr["access_token"];

alert(accessToken);

Working Example here
Hope Its Work !!
Happy Coding !!


text:
Q: JxBrowser Javascript I have been stuck on the same issue for a few days now, and I am starting to wonder if it is due to the support that JxBrowser offers. I am trying to implement a BFS graph for visualisation purposes using a Cytoscape.js library. Does JxBrowser offer compatibility for external Javascript libraries, or is it limited to a few? I see in the documentation that it specifically talks about JQuery support, but nothing else. I have tried to implement my cytoscape library in the same manner as the JQuery tutorial given by JxBrowser, but it comes up as being undefined.
Code is below:
    package src.java;
public class VisualFrame {

public VisualFrame(final Browser browser, final BrowserView view, final JFrame frame){
    frame.setTitle("Visualisation");
    frame.setResizable(false);

    InputStream urlStream = getClass().getResourceAsStream("../web/cytoscape/index.html");
    String html = null;
    try (BufferedReader urlReader = new BufferedReader(new InputStreamReader (urlStream))) {
        StringBuilder builder = new StringBuilder();
        String row;
        while ((row = urlReader.readLine()) != null) {
            builder.append(row);
        }
        html = builder.toString();
    }  catch (IOException e) {
        throw new RuntimeException(e);
    }

    final String loadHelloPath = html;

    browser.addLoadListener(new LoadAdapter() {
        @Override
        public void onFinishLoadingFrame(FinishLoadingEvent event) {
            System.out.println(browser.getHTML());
            if (event.isMainFrame()) {
                System.out.println("Has Reached");
                event.getBrowser().executeJavaScript("var cy = cytoscape({"
                        + "style: cytoscape.stylesheet()"
                        + ".selector('node')"
                        + ".css({"
                        + "'content': 'data(id)'})"
                        + ".selector('edge')"
                        + ".css({"
                        + "'curve-style': 'bezier',"
                        + "'target-arrow-shape': 'triangle',"
                        + "'width': 4,"
                        + "'line-color': '#ddd',"
                        + "'target-arrow-color': '#ddd'})"
                        + ".selector('.highlighted')"
                        + ".css({"
                        + "'background-color': '#61bffc',"
                        + "'line-color': '#61bffc',"
                        + "'target-arrow-color': '#61bffc',"
                        + "'transition-property': 'background-color, line-color, target-arrow-color',"
                        + "'transition-duration': '0.5s'}),"
                        + "container: document.getElementById('cy'),"
                        + "elements: {"
                        + "nodes: ["
                        + "{ data: { id: 'a' } },"
                        + "{ data: { id: 'b' } },"
                        + "{ data: { id: 'c' } },"
                        + "{ data: { id: 'd' } },"
                        + "{ data: { id: 'e' } }],"
                        + "edges: ["
                        + "{ data: { id: 'ae', weight: 1, source: 'a', target: 'b' } },"
                        + "{ data: { id: 'ab', weight: 1, source: 'a', target: 'c' } },"
                        + "{ data: { id: 'be', weight: 1, source: 'b', target: 'd' } },"
                        + "{ data: { id: 'bc', weight: 1, source: 'b', target: 'e' } },"
                        + "{ data: { id: 'ce', weight: 1, source: 'c', target: 'f' } }]}"
                        + "});");
            }
        }
    });

    browser.loadHTML(loadHelloPath);

}
}

I have script type="text/javascript" src="cytoscape.js"> in the head of my HTML file as well, so I assume it would import the external library which is in the same file path as the index file itself.
Any ideas?
EDIT:
Index.html I am aiming to use:

  <title>Visualisation</title>

Thanks, Jack


text:
Q: BibTeX with XeLaTeX using TeX Live 2015 I am trying to compile an article using XeLaTeX. The article also contain a bibliography file, which I want to print inside the article, without citing any of the bib entry.
Please see below the complete tex code-
\documentclass[a4paper,10pt]{article}
\usepackage{marvosym}
\usepackage{fontspec}                       %for loading fonts
\usepackage{xunicode,xltxtra,url,parskip}   %other packages for formatting
\RequirePackage{color,graphicx}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage[big]{layaureo}              %better formatting of the A4 page
\usepackage{supertabular}               %for Grades
\usepackage{titlesec}                   %custom \section

%FONTS
\defaultfontfeatures{Mapping=tex-text}
\setmainfont[
SmallCapsFont = Fontin-SmallCaps.otf,
BoldFont = Fontin-Bold.otf,
ItalicFont = Fontin-Italic.otf
]
{Fontin.otf}

\usepackage{biblatex}
\addbibresource{publications.bib}

\begin{document}
\pagestyle{empty} % non-numbered pages

\font\fb=''[cmr10]'' %for use with \LaTeX command

\section{Section before Publications}
Section before Publications

\section{Publications}
\nocite{*}
\printbibliography

\section{Section after Publications}
Section after Publications
\end{document}

To compile this code, I initially run XeLaTeX followed by BibTeX. The BibTeX reports following error-
Process started

This is BibTeX, Version 0.99d (TeX Live 2015) The top-level auxiliary file: sample.aux I found no \citation commands---while reading file sample.aux I found no \bibdata command---while reading file sample.aux I found no \bibstyle command---while reading file sample.aux (There were 3 error messages)

Process exited with error(s)

Below is the necessary detail-

*

*Tex Live 2015

*Texmaker 4.5

I don't see the bib entries in the generated article. What's wrong here?

A: The biblatex package has support for two backends for processing/extracting entries from the bib file, bibtex and biber although bibtex is only supported for a subset of the possible biblatex functions detailed in 3.14 Using the fallback BibTeX backend of the biblatex documentation.
By default the preferred backend of biber is expected when biblatex is loaded and thus different information is written to the aux file, incompatible with the necessary code for bibtex.  In order to run bibtex with biblatex the package call must explicitly say that bibtex will be used by passing the backend=bibtex option to biblatex i.e. \usepackage[backend=bibtex]{biblatex} if no other options are called.


text:
Q: Можно ли в android написать приложение без графического интерфейс Мне нужно написать приложение которое работало бы в фоне, без GUI, выполняло сетевый запросы на сервер с периодичностью в 5 минут, в зависимости результата, выполняла нотификацию. То есть сделали запрос, дынные не валидные (к примеру), показываем notification. Возможно ли это и если да, то как?

A: Создать сервис с START_STICKY и запускать его:
public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        startService(new Intent(this, YourService.class));
    }
}

public class YourService extends Service {
    [...]

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // do your jobs here
        return  return START_STICKY;
    }
}


text:
Q: Javascript/Jquery Refresh timer I have a simple system that refreshes a div every few seconds:
$(document).ready(function() {
         $("#nownext").load("response.php");
       var refreshId = setInterval(function() {
          $("#nownext").load('response.php?randval='+ Math.random());
       }, 20000);
    });

Now, because of what the content is, it is more likely to update on the hour, or at half past. (Though not always). What I'd like to do it make the system refresh MORE often between a few minutes before and after the hour (and half past), just to make it more precise.
Is this possible/how would I do it without stressing out the client's computer too much?

A: Use setTimeout instead of setInterval so you can dynamically alter the timing of the next interval.  I'm not sure what the performance implications of creating and checking the Date() object ever millisec in the "Fast" period would be, but you could always tune that frequency up closer to every second if its an issue.
start_timer = function(timing) {
   var timer, d = new Date(), min = d.getMinutes(),
     timeout = 20000; /* slow timeout */
   if((min >= 28 && min <= 30) || min >= 58) {
     timeout = 100; /* fast timeout */
   }
   timer = setTimeout(start_timer, timeout);
   // Call your code here.
};

$(document).ready(function() {
    start_timer();
});

A: Since the interval itself is going to be dynamic, you're going to have to use setTimeout instead.
Something like this (untested):
$(document).ready(function() {
    $("#nownext").load('response.php?randval='+ Math.random());
    var minutes = new Date().getMinutes(), interval = 60*10*1000; // default 10 mins
    if (minutes <= 10 || (minutes > 30 && minutes < 35) || minutes > 50) {
        // update once-per-minute if within the first/last 10mins of the hour, or 5mins within the half hour
        interval = 60*1000;
    }
    setTimeout(arguments.callee, interval);
});


text:
Q: Worth getting USB 3.0 enclosure for old HDD? I have a WD 500GB MyPassport which is a couple of years old (2009-2010). Will I be able to see a noticeable speed difference if I remove the HDD and use it with a USB 3.0 caddy instead?

A: I don't think you'll be able to put this into a standard USB caddy. From what I remember, drives like this have proprietary connectors attached to the drive itself and it'll only work with that specific case. There are however USB 3.0 cases now that are very cheap so it's probably not even worth cracking open your old drive.

A: I have done exactly what you're talking about.  Mine was a portable Seagate USB 2.0 drive (thankfully no proprietary connector/bridge on that one).
Moving it to a USB 3.0 case improved the sequential read speed from around 30 MB/s to 60 MB/s.  Sequential write speeds improved from around 30 MB/s to 45 MB/s.  I only used the drive for large files so I can't comment on random read/write performance.
Based on my experience, I am confident you would see similar results.  Noticeable improvement?  Probably, for sequential reads/writes (i.e. large files).
Worth doing?  Maybe not given the attractive pricing of new portable USB 3.0 drives.  Besides, the latest USB 3.0 drives are really fast.  My new Toshiba portable drive blazes away at over 100 MB/s sequential read and write.


text:
Q: How does one close an opened file with a Windows script? I want to set up a script to be run daily as a Windows Scheduled Task. The script should open an Excel spreadsheet, wait for it to run a macro (which is set up to run every time the spreadsheet is opened), and then close the file after the macro finishes saving the changes. The macro itself won't take very long to run. If my script can just wait for about a minute before closing the file again, that should be sufficient.

A: Completely untested code and mostly written from memory but hopefully enough to get you started:
Set app = GetObject(, "Excel.application") ' assumes Excel is already running, otherwise use Set app = CreateObject("Excel.Application")
app.Visible = True ' useful while testing
app.run "MyMacro", "Param1" ' run the MyMacro macro with a string parameter "Param1"
WScript.Sleep(60000) ' wait 60,000 ms = 1 minute
app.ActiveDocument.Close
app.Quit
Set app = Nothing


text:
Q: send message (String) from file to MainActivity I have a file with contains my server that get's content from a client app. How can I send the content the server receives to my MainActvity?
if I try MainActivity main = new MainActivity(); in the server file the app crashes.
Server file.
class ServerThread implements Runnable {

    public void run() {

        Socket socket = null;
        try {
            serverSocket = new ServerSocket(SERVERPORT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (!Thread.currentThread().isInterrupted()) {
            try {
                socket = serverSocket.accept();
                CommunicationThread commThread = new CommunicationThread(socket);
                new Thread(commThread).start();
                connected_server = true;
            } catch (IOException e) {
                connected_server = false;
                e.printStackTrace();
            }
        }
    }
}

class CommunicationThread implements Runnable {
    private Socket clientSocket;
    private BufferedReader input;
    public CommunicationThread(Socket clientSocket) {
        this.clientSocket = clientSocket;
        try {
            this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));

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

    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                String read = input.readLine();
                updateConversationHandler.post(new updateUIThread(read));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

class updateUIThread implements Runnable {
    private String msg;
    public updateUIThread(String str) {
        this.msg = str;
    }

    @Override
    public void run() {
        if (msg != null){
          //Where I need to send the received content to the main activity

            Log.e("INPUT", msg);
        }
    }
}

  Main Activity
   public class MainActivity extends Activity {
  …
public void  message_recieve(String msg){
   // do stuff with messages
}

}

A: You need to implement a callback, so that you can receive the result correctly when the server request ends


text:
Q: Grouping by time intervals with non-fixed ranges in MySQL I'm trying to write a query that will scan through a database of connection attempts and find a group of records that exceed x attempts within 1 hour of time.
However, these one-hour ranges can't be fixed (i.e. not just 6:00-7:00, but 6:01-7:01, 6:15-7:15, etc.)
Here's an illustration
Given Max Attempts per hour = 2

num Date
1   5:58
2   6:09
3   6:30
4   8:00
5   9:01
6   9:40
7   9:50
8   9:55
9   11:20

In this example, the query would return the rows 1, 2, 3, 5, 6, 7, because (1, 2, 3) and (5, 6, 7, 8) were within 1 hour of eachother and total more than 2 attempts.

A: SELECT num FROM table t1
WHERE EXISTS (
    SELECT 1 FROM table t2
    WHERE t2.num <> t1.num
    AND TIMESTAMPDIFF(MINUTE,t1.date,t2.date) <= 60
)

The query below should be faster especially if your date column is indexed
SELECT num FROM table t1
WHERE (MINUTE(TIMEDIFF((SELECT MAX(t2.date)
    FROM table t2
    WHERE t2.num <> t1.num
    AND t2.date < t1.date),t1.date)) <= 60)
OR (MINUTE(TIMEDIFF((SELECT MIN(t2.date)
    FROM table t2
    WHERE t2.num <> t1.num
    AND t2.date > t1.date),t1.date)) <= 60)


text:
Q: how do i build a website using access 2010? has anyone done this yet? please show me some good tutorials on building websites with databases using ACCESS 2010
you can build a website using it: http://www.youtube.com/watch?v=AU4mH0jPntI


text:
Q: C++: Why I can change the assignment of reference on my computer? I am new to C++, and I am studying the concept of reference.
I have studied the fact that a reference should not be assigned to something else once defined and initialized, the description of reference on C++ primer states that once you have bound a reference to an object, then you can't change the object which the reference is bounded to.
I am confused by this statement. I tried the following code on my computer, the compiler didn't report neither warnings nor errors.
int a = 2;
int b = 4;
int &ref = a;
cout << "ref = " << ref << endl;
ref = b;
cout << "ref = " << ref << endl;

On my computer, the compilation passes, and outputs were printed, one is 2, the other is 4, there's no problem at all.
I am confused by this concept of reference, is it the condition that we SHOULD NOT change the object which the reference is bounded to, or we CANNOT change the object which the reference is bounded to?
P.S. Even the page 58 on C++ primer also demonstrates the example where the reference refers to new object, and the book says it's ok to do that. Like this:
int i = 42;
int *p;
int *&r = p;
r = &i; // isn't this changing r to an new object?
*r = 0;

A:
then you can't change the object which the reference is bounded to.
I am confused by this statement

The statement tries to say, that the reference cannot be modified to refer to another object. The object that is referred can be modified.
When left hand operand of assignment is a reference, you are indirecting through the reference, and assigning the value of the referred object.

ref = b;

ref still refers to the object named by a. That object is modified by this assignment. After the assignment, the value of a is 4.

r = &i; // isn't this changing r to an new object?

r still refers to the object named by p. That object is modified by this assignment. After the assignment, p points to i.


text:
Q: Loading cookies in python I am a novice programmer attempting to access google insights using python.  I can access sites which dont require cookies fine, but i cant seem to properly pass the cookies along.  The cookines file was exported from mozilla firefox, is in the Z: drive which is also where im running python from.
Im also pretty sure my code for saving the file could be better done than reading and writing but I dont know how to do that either.  Any helpo would be appreciated.
import urllib2
import cookielib
import os

url = "http://www.google.com/insights/search/overviewReport?q=eagles%2Ccsco&geo=US&cmpt=q&content=1&export=2"
cj = cookielib.MozillaCookieJar()
cj.load('cookies6.txt')
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
file = opener.open(url)
output = open('test2.csv','wb')
output.write(file.read())
output.close()

A: I haven't tested your code however:
As far as I can tell there seems to be nothing wrong with your code
I've tried the url you're searching and had no problems downloading the csv without any cookies
In my previous experience with google, you might be looking at the problem the wrong way, it is not that you don't have the right cookies but that google automatically blocks requests from bots. If this is the case you must replace the user agent http header to mimic an actual browser. Beware however that this is against googles terms of service and if you make too many requests per minute google will block all requests from your ip for about 8h.


text:
Q: Error: : could not find an object to spy upon for Foo() I tried to create a simple Foo method in my LoyaltyService.
    public Foo(): Observable<string> {
    return of('1');
  }

injecting it in the spec.ts like this -
  //const loyaltyService: LoyaltyService = TestBed.inject(LoyaltyService);
  const loyaltyService: LoyaltyService = fixture.debugElement.injector.get(LoyaltyService);
  spyOn(loyaltyService, 'test').and.returnValue(of('1'));

But getting error:
Error:  : could not find an object to spy upon for Foo().
I have tried the TestBed.inject method and also injector.get method.

A: when we wrote tests in AngularJS and stub promises using SpyOn we did something like this:
spyOn(someService,'get').and.returnValue(deferred.promise);

The code above is completely valid — unlike observables, promises are always asynchronous. But How to test Observables?
Using jasmine-marbles is the best parctice here. So try something like this:
app-foo.component.ts
@Component({
  selector: 'app-foo',
  template: `
    <div class="foo">
      {{ foo | async }}
    </div>
  `
})
export class FooComponent implements OnInit {
  foo: string = "";

  constructor(private fooService: FooService) { }

  ngOnInit() {
    this.fooService.get().subscribe(res => {
      this.foo = res;
    });
  }

}

app-foo.component.spec.ts
import { cold, getTestScheduler } from 'jasmine-marbles';

const fooServiceStub = {
  get() {
    const foo$ = cold('--x|', { x: `1` });
    return foo$
  }
};

describe('FooComponent', () => {

  it('should work', () => {
    const foo = element.querySelectorAll('.foo');
    getTestScheduler().flush(); // flush the observables
    fixture.detectChanges();
    expect(element.querySelectorAll('.foo').length).toEqual(1);
  });

});

For more information about observables test see these articles:
Testing Observables in Angular
How to test Observables


text:
Q: counter for relational database entries So I have a database with a bunch of google maps markers and I give users the ability to 'follow' markers. This 'following' information is stored in a separate relational database.
When I load my map and all the associated markers, I would like each marker to display an infowindow (I suspect you all know what this looks like) showing how many people are following the marker. i.e. "23 people are following this marker"
The problem with this would seem to be that if I count the relational database 'followers' while loading the markers, this could be extremely slow, given 1000+ markers. Instead I am thinking of making a marker counter and including it in the original marker database, so I only have to query one database.
Having never made a counter as such (and not finding many specifics on the web), I am wondering if there are any pitfalls I should be aware of? I can see problems arising when users delete their accounts, as I would have to update the counter based on that (not impossible, just kind of a pain), but this could get complicated if I allowed the users to add back their account (as with facebook or something).
Would there be any way for that counter to count the relational database entries periodically so I do no have to update the counter?
from a noob, sincere thanks for any help! It is greatly appreciated.

A: *

*Databases are pretty good at counting, quickly! The recommended approach is to not store calculated values in your operational database. Try it that way first, measure performance, if it's the slowest part of your app, and there are significant costs associated with that, then start storing counts.

*If you need to store counts, then consider using caching on your web server, or materialized views and re-generating the counts as required.


text:
Q: Should I apply string manipulation after or before joining tables in Oracle I have two tables need to inner join, one table has relatively small number of records compared to the other one. I need to apply some string manipulation to the smaller table, and my question is can I apply the string function after the join, or should I apply them in a sub query and then join the sub select to the bigger table?
An example would be something like this:
Option 1:
SELECT SUBSTR("SMALL_TABLE"."COL_NAME",x,y) "NEW_COL" FROM "BIG_TABLE"
JOIN "SMALL_TABLE" ON ...

Option 2:
SELECT "NEW_COL"
FROM "BIG_TABLE"
JOIN
(
SELECT SUBSTR("SMALL_TABLE"."COL_NAME",x,y) "NEW_COL" FROM "SMALL_TABLE"
) "T"
ON ...

Which is better for performance option 1 or 2?
I am using oracle 11g.

A: Regardless of how you structure the query, Oracle's optimizer is free to evaluate the function before or after the join.  Assuming that the string manipulation is only done as part of the projection step (i.e. it is done only in the SELECT clause and is not used as a predicate in the WHERE clause), I would expect that Oracle would apply the SUBSTR before joining the tables if you used either formulation because it would then have to apply the function to fewer rows (though it can probably treat the SUBSTR as a deterministic call and cache the results if it applies the function after the join).
As with any query optimization question, the first step is always to generate a query plan and see if the different queries actually produce different plans.  I would expect the plans to be identical and, thus, the performance to be identical.  But there are any number of reasons that one of the two options might produce different plans on your system given your optimizer statistics, initialization parameters, etc.

A: It is better to apply the operations before doing the join and then joining and querying for the final result. This is called query optimization.
By doing so for ur question you will perform lesser operations when "join"ing as u will be eliminating the useless rows beforehand.
Lots of examples here : http://beginner-sql-tutorial.com/sql-query-tuning.htm
and this is the best one I could find :  http://www.cse.iitb.ac.in/~sudarsha/db-book/slide-dir/ch14.ppt


text:
Q: Is this sufficient to define a regular polytope? I'm writing a Bachelor thesis on the symmetries of the Platonic Solids. However, I'm not very strong in geometry and I start the thesis by proving that there are only 5 Platonic Solids. When I define a regular polytope (the majority of the thesis deals with polyhedrons of course, but I'm also showing a few examples of higher dimensional regular polytopes such as the $n$-simplex) I'm uncertain about how to properly define it without including too much geometry, since it's not my main focus. If I define the regular polygon, is it then enough to say that a regular $n$-polytope is an $n$-polytope whose facets are regular $(n-1)$-polytopes, which implies recursion down to $n=2$?

A: It is not enough to say that all its $n-1$ facets are regular. This includes for example the uniform and Johnson solids. It is sufficient to add that they must be also be congruent and the same number meet around any vertex.
A more succinct definition is based on the idea of flags. For this purpose a flag is a connected or incident set of $j$-faces, for one face of each $0 \leq j \leq (n-1)$. We can then say that:

A polytope is regular if its symmetries are transitive on its flags.

That is to say, under any symmetry transformation of the polytope, the flags are permuted into each other.

A: No. The angles between the facets also have to be equal. Otherwise you could, for example, glue two regular tetrahedra together and get a polytope with six triangular faces.


text:
Q: What is the meaning of "interesting" in a mathematical context? Does it have an abstract mathematical model? I, from time to time, see the word "interesting" in a mathematical context when models are explained, and I realized that there is actually a philosophical depth to that.

*

*Is there a philosophical definition of what makes a mathematical model or mathematical finding interesting?

*Does "interesting" have an abstract mathematical model? (in category theory perhaps?)

A: Terence Tao wrote an article entitled "What is Good Mathematics?" that may provide you with some food for thought. Whether it answers your question or not is hard to say. Personally, I think that something being interesting is highly subjective. In any case, here are the opening sentences from Tao's article. Please see the link above for the whole piece.

We all agree that mathematicians should strive to produce good mathematics. But
how does one define "good mathematics", and should one even dare to try at all? Let
us first consider the former question. Almost immediately one realises that there are
many different types of mathematics which could be designated "good". For instance,
"good mathematics" could refer (in no particular order) to
(i) Good mathematical problem-solving (e.g. a major breakthrough on an important mathematical problem);
(ii) Good mathematical technique (e.g. a masterful use of existing methods, or the
development of new tools);

Another thought on interesting mathematics comes from Richard Brown's TEDx talk Why mathematics?, in which he defines "interesting" roughly as "hard, but worthy of study".


text:
Q: How can I prepare an old PC for educational use by a child? I have an old PC of mine that I'm thinking of preparing for use by a school-going child. It's a decade old PC with a 40GB hard disk, Pentium 4 processor, and I believe 1GB of RAM.
As of now, I have:

*

*Installed Lubuntu and Windows XP on it (Vista and 7 don't have drivers for this hardware, and yes I've searched the manufacturer's site and other places)

*Installed Avast and Outpost Security Suite on the XP

*"Pinned" Khan Academy, Coursera, Udacity and Codecademy on the Firefox "new tab" page
Other than this, what can I do to prepare this computer for this purpose? My knowledge of desktop software for education is lacking, in both Windows and Linux. I'm not sure if whoever buys this will have a good Internet connection (I'm in India), so desktop software will probably prove much more useful that the bookmarks above.
I'm also looking at free parental control software to install on this, I'll make that a separate question. Edit: The question is now at the Software Recommendations site.
(I wasn't sure where on StackExchange this would belong, but superuser seemed the closest candidate. If there's a better suited site, please do migrate, thanks.)

A: The first thing I think is to eliminate Windows XP, it is already obsolete.
Because it is an old computer, I believe it is not feasible to install a system like Windows Vista, it requires better hardware to run properly.
I would advise you to install any Linux distribution, such as the UberMix.

The ubermix is an all-free, specially built, Linux-based operating
  system designed from the ground up with the needs of education in
  mind. Built by educators with an eye towards student and teacher
  empowerment, ubermix takes all the complexity out of student devices
  by making them as reliable and easy-to-use as a cell phone, without
  sacrificing the power and capabilities of a full operating system.
  With a turn-key, 5 minute installation, 20 second quick recovery
  mechanism, and more than 60 free applications pre-installed, ubermix
  turns whatever hardware you have into a powerful device for learning.

A: The Ubuntu series is great if you're trying to teach someone how to use a computer. So is Windows XP at the presiding moment.
If they are learners they need to probably have something around 1.7 Ghz with maybe 100-200 Gb and 2 GB of Ram and 32 Bit.
Once they have mastered the two, I suggest buying a new laptop with amazing specs if they can take care of it right. Probably something with 2.4+ Ghz, 400+ Gb, An intel processor, and 4+ GB of RAM and probably 64 Bit.
Regarding the Operating Systems when they've mastered, you should probably go with Arch Linux, Linux Mint, or Debian if they wish to pursue Linux more and want to begin programming or wish to play a lot of Java games like Minecraft.
If they wish to pursue a more Sims/Professional Computing Experience, look into Windows 8/8.1. They have state-of-the-art technology (so does Linux as well).


text:
Q: Neo4j - how to group and count by property? I have two node types in my Graph.
Node1 {id, name, node2id}
Node2 {id, name}
There are not relationships at this point, but I need to create between a:Node1 and b:Node2 only where Node2 are less than 100.
So, in SQL the query to get the nodes would be something like:
select Node1.Id, count(Node2.Id) as connections
from Node1 left join Node2
    on (Node1.node2id = Node2.Id)
group by Node1.Id
having count(Node2.Id) < 100

How can I do this in Neo4J?
Ideally, I would like to add relationship between these Nodes, like
CREATE (n:Node1)-[:HAS_CONNECTION]->(k:Node2)

A: You could use something like:
MATCH (n1:Node1), (n2:Node2)
WHERE n1.node2id = n2Id
WITH n1, collect(n2) as nodes, count(*) AS count
WHERE count < 100
UNWIND nodes AS n
CREATE (n1)-[:HAS_CONNECTION]->(n)

You use the WITH statement to collect all the node2 that have the same id as node1, count them, and then apply a filter to them.


text: Q: How do I encrypt every write function call in the system and decrypt every read function call? I want to make an app similar to Bitlocker. I have to encrypt everything that any application writes to the disk and decrypt everything read from the disk on Windows. I have heard there is a way of hooking system calls, but I need to hook every read/write on the entire operating system. I have also heard I have to write some kind of driver for it, but I really don`t know where to get started. Is there any library that does something like this? Any suggestion is appreciated.


text:
Q: jquery validation-with mvc is not working I am using jquery vaidation in mvc and it is working every where except in one view which contains other view like so :

          @using (Ajax.BeginForm("AnsComm", new { ProdductID =
          item.ProductID, CommentID = item.ID }, new AjaxOptions {
          HttpMethod ="POST", LoadingElementId = "LoadingAns", UpdateTargetId = "DivAns}))
                 {
                    <input type="submit" value="answer" />

                 }

my create action returns this partial view which where the validation doesn't work :
          @model honar.Models.Domain.Tbl_Comments
          @using (Ajax.BeginForm(new AjaxOptions { Url =
          "/Home/InsertComment", HttpMethod = "POST", LoadingElementId =
          "Loading", UpdateTargetId = "Msg" }))
            {@Html.AntiForgeryToken()

           @Html.ValidationSummary(true)
           @Html.HiddenFor(model => model.ProductID)

        @Html.LabelFor(model => model.Name, new { @class = "control-label
         col-md-2" })

            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)


text:
Q: How to check if a ChromeCast Session is already in progress The use case is that a user starts playback from their iPhone, lets say, and then picks up their iPad (both running my app) and wants to contect to and control the running video from this other iOS device.
On iOS, I do not see any way to determine if there is a instance of my receiver app already running on the Google ChromeCast device. Once I create my session it seems the only thing I can do is to attach a new protocol message stream, which interrupts whatever might be playing already.
It this suppose to be handled in the iOS client side Framework, perhaps there is some coding I need to do in the HTML receiver app?
Thanks.

A: There is a way outside the API to determine if an app is running. Do a HTTP GET on the apps URL for the ChromeCast IP address: http://192.168.0.x:8008/apps/
If the HTTP response is 200, nothing is running. If the HTTP response is 204, then an app is running and the HTTP response would be redirected to a URL like: http://192.168.0.x:8008/apps/GoogleMusic
Which tells you which app is running.
Interestingly, Google Play Music cannot be controlled by 2 devices simultaneously, but YouTube can. I suspect Play Music is using RAMP which is what the Cast SDK does for media streams. YouTube could be using a proprietary message stream to control the media playback. So you might have to do the same if you want to have the an app on a device controlled by multiple sender apps.

A: One method is to check the playStatus after you start your session and before you initiate a loadMedia().  If your app is already running - it should return a non-nil (ie. IDLE, PLAYING, ...) result.


text:
Q: Why does GCC diagnose a unused variable for structured bindings while Clang doesn't? Let's start with a minimal example:
#include <utility>

int main()
{
    auto [a, b] = std::pair(1, 'A');
    return a;
}

Compiling with GCC 7.3 passing -std=c++17 and -Wunused-variable, and running it:
<source>: In function 'int main()':
<source>:5:15: warning: unused variable 'b' [-Wunused-variable]
     auto [a, b] = std::pair(1, 'A');
               ^

GCC may be correctly reporting the absent use of b, but it wrongly calls it a variable. Quoting [dcl.struct.bind]/1:

A structured binding declaration introduces the identifiers v0, v1, v2, … of the identifier-list as names ([basic.scope.declarative]) of structured bindings.

So b clearly isn't a variable, but rather a name. Compiling the same code with Clang 6.0.0, and with the same flags, we get no warning whatsoever. Removing the return a; statement from the code:
#include <utility>

int main()
{
    auto [a, b] = std::pair(1, 'A');
    // return a;
}

and compiling it again with Clang, we get:
<source>:5:10: warning: unused variable '[a, b]' [-Wunused-variable]
    auto [a, b] = std::pair(1, 'A');
         ^

Which, from my interpretation, correctly treats [a, b] as a variable, and a and b separately as just names. My question then is why does GCC diagnose a warning for b being unused, considering that the variable is in fact being used in the return a; statement from the first code?

A: This was indeed a bug in gcc: https://gcc.gnu.org/bugzilla/show_bug.cgi?format=multiple&id=81767 and was solved in: https://gcc.gnu.org/viewcvs/gcc?view=revision&revision=248483


text:
Q: How to make a Python function run concurrently or sequentially depending on the number of function calls and function arguments? I have the following sample function:
def set_value(thing, set_quantity):
    set_function(thing, set_quantity) #sets "thing" to the desired quantity
    read_value = read_function(thing) #reads quantity of "thing"
    if read_value != set_quantity:
        raise Exception('Values are not equal')

I then have some test cases (they're Robot Framework test cases but I don't think that really matters for the question I have) that look something like this:
#test case 1
set_value('Bag_A', 5)

#Test case 2
set_value('Bag_B', 3)

#Test case 3
set_value('Bag_A', 2)
set_value('Bag_B', 8)
set_value('Purse_A',4)

This is the desired behavior I want:
For Test Case 1, set_value() is called once and is executed right after the function call.
Test Case 2 is similar to #1 and its behavior should be the same.
For Test Case 3, we have 3 items: Bag_A, Bag_B, and Purse_A. Bag_A and Bag_B each call set_value(), but I want them to run concurrently. This is because they're both "Bags" (regardless of the _A or _B assignation), so I want the function to recognize that they are both "Bags" and should be run concurrently. Once those are executed and finished, then I want the Purse_A function call to set_value() to be executed (since "Purse" is not in the same category as "Bag").
The object type ("bag", "purse", etc) can be anything, so I'm not expecting a particular value from a small amount of pre-defined possibilities.
How would I go about doing this? By the way, I cannot change anything in the way the Test Cases are written.
I tried looking into the asyncio module since you're able to run things concurrently using tasks, but the things is I don't understand how to get set_function() to know how many tasks there will be since it all depends on any future functions calls which depends on each test case.

A: Sometimes, if you want your program to do some thing, you just have to write your own code to do the thing:
thread_pool = concurrent.futures.ThreadPoolExecutor(...)

def do_one(task):
    ...

def do_something_with(result):
    ...

def do_concurrently(tasks):
    global thread_pool
    futures = []
    for task in tasks:
        futures.append(thread_pool.submit(do_one, task))
    for future in futures:
        result = future.result()
        do_something_with(result)

def do_sequentially(tasks):
    for task in tasks:
        result = do_one(task)
        do_something_with(result)

def task_performer(...):
    tasks = ...construct list of tasks...
    if ...tasks should be performed concurrently...:
        do_concurrently(tasks)
    else:
        do_sequentially(tasks)

Very procedural. I can't help it, I'm an old-fart. Maybe there's some more modern, stylish way to do it, but you get the idea, right?


text:
Q: rolling pyramid app to a production site I'm trying to roll out a pyramid app to a production site.
As of now, I've created the env file where the app is placed in out of the public_html, something like below:
    [~/env] $

So I've typed
    $ ../bin/pserve production.ini,

However, when I access www.mydomain.com, it is still showing the index.html. How should I resolve this?
I'm using a CentOS 64bit + Apache + mod_wsgi.
Settings are as followed:
    Apache/2.2.24 (Unix)
    mod_ssl/2.2.24
    OpenSSL/1.0.0-fips
    mod_wsgi/3.3
    Python/2.6.6
    mod_auth_passthrough/2.1
    mod_bwlimited/1.4
    FrontPage/5.0.2.2635 configured -- resuming normal operations

In my production.ini file, it is as followed
    [app:main]
    use = egg:ECommerce
    reload_templates = false
    debug_authorization = false
    debug_notfound = false
    debug_routematch = false
    debug_templates = false
    default_locale_name = en
    mongodb.url = mongodb://my.ip.address
    mongodb.db_name = mycart_demo

    [filter:weberror]
    use = egg:WebError#error_catcher
    debug = false
    ;error_log =
    ;show_exceptions_in_wsgi_errors = true
    ;smtp_server = localhost
    ;error_email = janitor@example.com
    ;smtp_username = janitor
    ;smtp_password = "janitor's password"
    ;from_address = paste@localhost
    ;error_subject_prefix = "Pyramid Error"
    ;smtp_use_tls =
    ;error_message =

    #[pipeline:main]
    #pipeline =
    #    weberror
    #    ECommerce

    [server:main]
    use = egg:waitress#main
    host = 0.0.0.0
    port = 8080

    # Begin logging configuration

    [loggers]
    keys = root, ecommerce

    [handlers]
    keys = console

    [formatters]
    keys = generic

    [logger_root]
    level = WARN
    handlers = console

    [logger_ecommerce]
    level = WARN
    handlers =
    qualname = ecommerce

    [handler_console]
    class = StreamHandler
    args = (sys.stderr,)
    level = NOTSET
    formatter = generic

    [formatter_generic]
    format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s

    # End logging configuration

I've managed to roll out on a production site, however, now, it's showing a 500 internal server error...
In the apache error_log, it's showing:
    [Sun Apr 07 23:17:47 2013] [alert] [client <ip_address>]
        /home/vretnet9/public_html/.htaccess: WSGIScriptAlias not allowed here

So I went ahead to take a look at .htaccess
.htaccess
    Options +ExecCGI
    AddHandler cgi-script .cgi
    AddHandler wsgi-script .wsgi

    WSGIScriptAlias ECommerce /home/vretnet9/modwsgi/env/pyramid.wsgi
    WSGIDaemonProcess root processes=5 threads=1 display-name=%{GROUP}
    WSGIProcessGroup root
    WSGIApplicationGroup %{GLOBAL}

I don't know if it should actually be calling the .htaccess or if the scriptalias should be the same as the one in my .conf which is located in
    /usr/local/apache/conf/userdata/std/1/$user/$domain/modwsgi.conf

the contents of modwsgi.conf is as followed:
    WSGIApplicationGroup %{GLOBAL}
    WSGIPassAuthorization On
    WSGIDaemonProcess pyramid user=vretnet9 group=vretnet9 threads=4 \
    python-path=/home/vretnet9/modwsgi/env/lib/python3.3/site-packages
    WSGIScriptAlias /ECommerce /home/vretnet9/modwsgi/env/pyramid.wsgi

    <Directory /home/vretnet9/modwsgi/env>
         WSGIProcessGroup pyramid
         Order allow,deny
         Allow from all
    </Directory>

EDIT
In the apache error_log, the following is being recorded:
    [Mon Apr 08 02:17:22 2013] [error] Traceback (most recent call last):
    [Mon Apr 08 02:17:22 2013] [error] File
          "/home/vretnet9/modwsgi/env/pyramid.wsgi", line 5, in <module>
    [Mon Apr 08 02:17:22 2013] [error] from pyramid.paster import get_app,
          setup_logging
    [Mon Apr 08 02:17:22 2013] [error] File "/home/vretnet9/modwsgi/env/
          lib/python3.3/site-packages/pyramid/paster.py", line 1, in <module>
    [Mon Apr 08 02:17:22 2013] [error]     import os
    [Mon Apr 08 02:17:22 2013] [error] ImportError: No module named os

EDIT #2
This is my result when running in shell:
    [~/modwsgi/env]# python
    Python 3.3.0 (default, Mar 27 2013, 09:31:49)
    [GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import os
    >>> print (os.getcwd())
    /home/vretnet9/modwsgi/env

A: That is not how you will put a pyramid project into production using mod_wsgi + Apache. I recommend reading The official documentation
When you run ../bin/pserve production.ini it starts a paste HTTP server at port 8080 (defined in production.ini)
Ideally you will want to install pyramid in a fresh virtualenvironment and then configure mod_wsgi to use that instance of python. You will have to add a .wsgi script to your project and configure mod_wsgi to run that script on Apache startup.
EDIT
The ScriptAlias (and all related parts) should be in your modwsgi.conf (Make sure you import modwsgi.conf in your actual apache conf).
In that file you should define your PYTHONPATH and PYTHONHOME( esp. If you have a virtualenv) and the rest of the stuff you have already defined (WSGIApplicationGroup, WSGIScriptAlias etc.)
IMPORTANT - Make sure your apache user (apache) has read-execute permissions to the .wsgi script all the way. This means even your /home directory should be accessible to apache.
I would recommend creatijg a seaparate directory (say /opt/proj) for hosting the app and another (say /opt/env for the environment).
Here's how my pyramid.conf looks. I have Python 2.6 and keep my project (only the static things like css,images,js, and the .wsgi script) at /opt/save_project. My virtualenv is /opt/pyra
WSGIPythonHome /opt/pyra
WSGIPythonPath /opt/pyra/lib/python2.6
<VirtualHost 31.1.1.22:8005>
    DocumentRoot /opt/save_project
    WSGIApplicationGroup %{GLOBAL}
    WSGIPassAuthorization On
    WSGIProcessGroup %{GLOBAL}
    WSGIDaemonProcess pyramid user=apache group=apache \
      python-path=/opt/pyra/lib/python2.6
    WSGIScriptAlias / /opt/save_project/pyramid.wsgi
   # Get the static and favicon.ico pages working by properly aliasing them
   Alias /favicon.ico /opt/save_project/static/images/favicon.ico
   Alias /static /opt/save_project/static
   <Directory /opt/save_project>
       AllowOverride all
       Options -MultiViews
   </Directory>
</VirtualHost>

You may see mod_wsgi docs for more information


text:
Q: Traversing an object in typescript I have an array that looks like this
  "Meta Data": {
    "1. Information": "Intraday (5min) open, high, low, close prices and volume",
    "2. Symbol": "IBM",
    "3. Last Refreshed": "2022-09-30 19:45:00",
    "4. Interval": "5min",
    "5. Output Size": "Compact",
    "6. Time Zone": "US/Eastern"
  },
  "Time Series (5min)": {
    "2022-09-30 19:45:00": {
      "1. open": "119.0500",
      "2. high": "119.0500",
      "3. low": "119.0500",
      "4. close": "119.0500",
      "5. volume": "100"
    },
    "2022-09-30 19:45:00": {
      "1. open": "119.0500",
      "2. high": "119.0500",
      "3. low": "119.0500",
      "4. close": "119.0500",
      "5. volume": "100"
    },
    "2022-09-30 19:45:00": {
      "1. open": "119.0500",
      "2. high": "119.0500",
      "3. low": "119.0500",
      "4. close": "119.0500",
      "5. volume": "100"
    },
  }

I'm trying to get the closed value in the first object in time series. I've tried using something like this(where result is the obj) to get it but I'm getting a "Object is of type 'unknown'." error.
Object.values(result["Time Series (5min)"])[0]["4. close"]


text:
Q: Laravel project deployment gives the HTTP ERROR 500 Before you assume, I did read ALL other posts on this problem and I was unable to find a solution to my problem.
So the thing is, however and wherever i upload my files and folders on my web host i get the same result giving me the "currently unable to handle this request. HTTP ERROR 500". I'm using the 000webhostapp.
So I uploaded the project in my root directory "/", content of the public to the public_html project, and it gave me the text above. Then I tried moving my whole project into the public_html(public was its own directory inside public_html) and it gave me the same result. I've tried some solutions with .htaccess file but whatever I tried won't make it work. In my localhost project is installed somewhat like this "htdocs/kola/..", but on the web hosting it is just in the root, no other dir(that's something I think might help but I'm unable to use). So after 30 hours of trying and reuploading the project 5 times,  still can't make it work and I'd be rather grateful if someone could even try to help me with this.
Thanks in advance

A: The right way is to get to the root of your folder ... ie /home/ and create a folder for your project.  Then move the all the contents of your project into this folder except the public folder.  Now go to the public_html folder and add all the contents of the public folder there.
Update your index.php as below:
<?php

/**
 * Laravel - A PHP Framework For Web Artisans
 *
 * @package  Laravel
 * @author   Taylor Otwell <taylor@laravel.com>
 */

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels great to relax.
|
*/

require __DIR__.'/../(name of your root folder)/bootstrap/autoload.php';

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

$app = require_once __DIR__.'/../(name of your root folder)/bootstrap/app.php';

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

$kernel->terminate($request, $response);

Configure the .env file and have the right database configuration.

A: Need not to create new dir. Just delete the content of index.php file and paste the above code and replace your (name of your root folder) with public_html.


text:
Q: Getting X window id for GLUT program? or, How to remote control a GLUT program on X? I want to send a keystroke to a GLUT program on X11, but I can't find there's an X11 client attached to the GLUT program.
I do this, using the most excellent demo program for the chipmunk 2d physics package:
xlsclients -a|sort >aa
chipmunk_demos  (in another window)
xlsclients -a|sort >bb
diff aa bb

and there's no difference.
My eventual hope is that I can control the GLUT program by sending key events with the equivalent of:
xdotool key --window 0x4000002 a

So my questions:

*

*how can I remote control a GLUT program running on linux/X11?

*Is there a way to get an X11 window id for a GLUT program?

A: Install xtrace, then:
In Terminal 1:
xtrace -d :0 -D :8 | grep CreateWindow
In Terminal 2:
DISPLAY=:8 chipmunk_demos
You should get a line with:
... CreateWindow depth=0x18 window=0x04a00002 ...
Update: xdotool actually contains powerful search functionality, which recent versions make even easier to use.  It doesn't make sense to use xtrace like this, just use xdotool search instead


text:
Q: Nodejs - Express - What could be the problem that I cannot connect to the Socket IO object? I'm facing an issue only in the remote server side, it means that locally works fine even through a self-signed cert through https. But when I move the code into the server, it also works locally but it does't work remotely.
I have created a node app which is being hosted in the server under https port 3000. This app has the Socket IO lib which I have attached it to the same https server. I'm not using nodeiis because I'm using rewrite rules to pass it through the Windows IIS.
I have installed the websocket module in the IIS already. In fact I was already using websockets instead Socket.IO and it was working fine with the same configuration that I have now, I just replaced it with Socket.IO because is better for what I need.
Now my code
Html Page
<script src="/socket.io/socket.io.js"></script>
<script src="/js/Client.js"></script>

Client.js
$(document).ready(function() {

    var address = window.location.protocol + '//' + window.location.host;
    var details = {
       resource: (window.location.pathname.split('/').slice(0, -1).join('/') + '/socket.io').substring(1)
    };
    const socket = io.connect(address, details);

    socket.on('connect', function () {
        console.log('Client Connected');
        socket.emit('ping', 'hi server ping sent!');
    });

    socket.on('error', function (reason){
        console.log('Connection failed', reason); //Here is where it launch the error
    });
});

App.js
....
const https = require('https');

var socketlib = require('./socketLib');
const fs = require('fs');
const app = express();
var cookieParser = require('cookie-parser');
app.use(sessionParser);
var expiryDate = new Date( Date.now() + 60 * 60 * 1000 );

const sessionParser = session({
  secret: 'secret', resave: true, cookieName: 'sessionName',
  name: 'sessionId', saveUninitialized: true,
  ephemeral: true,
  cookie: { secure: true, expires: expiryDate, SameSite : 'None',
    maxAge: 24000 * 60 * 60, // One hour
  }
});

//// HTTPS Server ////
const options = {
  key: fs.readFileSync(config.certKey),
  cert: fs.readFileSync(config.certCert)
};

var httpsServer = https.createServer(options, app, function (req, res) {
    console.log('request starting...https');
});

httpsServer.listen(3000, function(req, res) {
  console.log('Server is running at', config.nodeApiUrl + ':', port)
});

socketlib(httpsServer, sessionParser);

app.all('/*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', 'https://localhost:3000')
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Access-Token,X-Key");
    return next();
})

socketLib.js
module.exports = async function(httpsServer, sessionParser) {
    var io = require("socket.io")(httpsServer);

    io.use(function(socket, next) {
        sessionParser(socket.request, socket.request.res, next);
    });

    io.use((socket, next) => {
        if (socket.request.headers.cookie)
            return next();
        next(new Error('Authentication error'));
    });

    io.sockets.on('connection', function(socket) {
        console.log(`New connection from: ${socket.handshake.address}`)
    });
}

iis webconfig
<rule name="Websocket" stopProcessing="true" enabled="true">
      <match url="socket.io" ignoreCase="true" />
      <action type="Rewrite" url="https://localhost:3000/{R:0}/socket.io.js" appendQueryString="false" redirectType="Found" />
        <conditions>
           <add input="{HTTP_HOST}" pattern="domainxxx.com" />
        </conditions>
    </rule>

And this is the error I can see in the Browser console
socketio.js:57 Error Error: server error
    at r.onPacket (socket.io.js:7)
    at o.<anonymous> (socket.io.js:7)
    at o.r.emit (socket.io.js:6)
    at o.r.onPacket (socket.io.js:7)
    at n (socket.io.js:7)
    at Object.e.decodePayload (socket.io.js:7)
    at o.r.onData (socket.io.js:7)
    at i.<anonymous> (socket.io.js:7)
    at i.r.emit (socket.io.js:6)
    at i.onData (socket.io.js:7)

if I click in any if those lines, this is where it takes me to:
switch(a('socket receive: type "%s", data "%s"',t.type,t.data),this.emit("packet",t),this.emit("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"pong":this.setPing(),this.emit("pong");break;case"error":var e=new Error("server error");e.code=t.data,this.onError(e);break;

You will see the:
var e=new Error("server error")

Finally, basically when I try to get accessed through domainxxx.com is like something happen where the socket cannot get connected just remotely, locally works fine, so I guess the only issue is after the rewrite rule, for what I can see, the rewrite rule is 100% correct but is obviously I'm missing something.
I hope you can help me! I did a lot of research and I couldn't find the cure for this!
Thank you in advance!

A: Thanks to a 4 years old post I could fix the problem. The issues was on the rewrite rule. I just replaced it with the following and it worked like a charm.
        <rule name="WebSocketTestRule" stopProcessing="true">
            <match url=".*" />
            <conditions>
                <add input="{CACHE_URL}" pattern="domainxxx.com" />
            </conditions>
            <action type="Rewrite" url="https://localhost:3000/{R:0}" />
        </rule>


text:
Q: Regex check between two integer values? Is there a regular expression check for a number that is within the range of (for example) 18 and 65?
[RegularExpression(@"^[18-65]$", ErrorMessage = "Customers must be
 between the ages of 18 and 65. This is due to our insurance policy.")]

A: ^(?:1[89]|[2-5]\d|6[0-5])$

Try this.See demo.
https://regex101.com/r/sJ9gM7/121

A:
Is there a regular expression check for a number that is within the range of (for example) 18 and 65?

Yes, there is. @vks already posted a suggestion. But the question is "should I use a regex for that?".
Regex is not used for matching things like you're trying to. Depends on the language you're using, there are much better alternatives.
[18-65] is invalid Regex, it tries to match 1, 5 or numbers in range [8,6], since the range is illegal, it's not a valid.


text:
Q: Как в Adobe After Effects присвоить значение положения через скрипт? Допустим в параметре opacity я спокойно могу прописать:
 transform.opacity = 50;

и объект будет полупрозрачным!
А вот с параметром position так уже не получается....
я прописал так:
transform.position[0] = 400;
transform.position[1] = 400;

Но обьект даже не сдвинулся и высветилась ошибка...

A: Вместо этого всего
transform.position[0] = 400;
transform.position[1] = 400;

напишите просто [400,400]
Таким образом вы задаете x и y [x,y] или [x,y,z]
Подробней можно прочитать в документации
В примере в документации есть строка:
 temp = thisComp.layer("Layer 1").transform.position[1];
  [temp, temp]

Где transform.position[1] - это геттер (получаем значение y слоя 1) [temp, temp] - сеттер (задаем значение x и y данному элементу)


text:
Q: Parsing JSON to a regular JavaScript array How can I load a regular array from a JSON Response like this:
{"project":"8","powerline":"188.396496","road":"7.876766","cost":"69885005.45"}

to
var cars = [8, 188.396496, 7.876766, 69885005.45];

I already tried something like this:
req.done(function(data) {
var cars = JSON.parse(data);
});

but it is not doing the job.

A: You can simply run a for..in loop like this. and keep pushing the values into a new array.
var obj = {
    "project" : "8",
    "powerline" : "188.396496",
    "road" : "7.876766",
    "cost" : "69885005.45"
}

var arr = [];
for (var key in obj) {
    var val = parseFloat("0" + obj[key]);
    arr.push(val)
}

A: You can manipulate JSON object as Array, please try this way
req.done(function(data) {
 var cars = $.map(JSON.parse(data), function(value, index){
   return i;
});
 console.log(cars);
});

A: That's because you're getting an object when you're calling JSON.parse. You can run the following to get the values without keys:
req.done(function (data) {
    var jsonData = JSON.parse(data),
        cars = []

    for (var key in jsonData) {
        cars.push(jsonData[key])
    }
})


text:
Q: How can we port an ASP Project in ASP.Net Project I am trying to improve the features of website that is already done with Classic ASP.
I am willing to work on other modules with ASP.Net
Can I port it to an ASP.Net project .
What's easier to port a Classical ASP project to ASP.Net or ASP.net MVC?

A: Rewrite it.
Really it depends on what you want to do here. Do you want to add a new stand alone feature? That's sort of easy, just put the new app in a virtual directory. Do you want to share authentication? That's way more complicated. Do you want to share session? Forget it, it's not worth the pain.
Porting = rewrite. Pretty much a complete rewrite, unless your ASP site has some COM components you wrote which you could repurpose and call from .NET. As it's a rewrite there's no easiest for this, whatever you find easier to use.

A: I have tried to migrate Classic ASP web applications to ASP.NET sites at the early age of ASP.NET. What it got produced is just another ASP site running on .NET Framework sandbox and it turned out to be a garbage sooner or later.
ASP.NET is completely a different paradigm than ASP, although the name stayed same. ASP is completely depends upon inline codes where you make all your business logic in your ASP files (more or less). ASP.NET has its own level of execution at a different level of its total life cycle. Even though ASP.NET MVC has no similarity with ASP.NET Webforms.
My suggestion would be to rewrite your application for better maintainability and manageability. You may consider ASP.NET MVC on your design phase for better concern of separation.


text:
Q: How to do data search in dataset with Python Django I am new to Django and I'm working on dataset search.
Given this
class Student(models.Model):
  score_1 = models.IntegerField(default=0)
  score_2 = models.IntegerField(default=0)

I know how get the students with the score_1 higher than 90, which is something like this:
s = Student.objects.filter(score_1__gte=90)

However, I'm having problem getting the students who have their score_1 10 points more than their score_2, aka score_1 - score_2 >= 10.
Since there are lots of student data, I cannot just pull all the data out and then do the search, which will apparently take forever. So is there any other way to do this?
Thanks so much!

A: You can try F expression to use model fields in filter:
from django.db.models import F
s = Student.objects.filter(score_1__gte=F('score2') + 10)


text:
Q: UPC code proof help i'm trying to prove the following problem..
1. Prove that if a single digit of a valid UPC is changed then the new code is not valid.

Answer - When the question asks to prove it, does it mean to litteraly do a mathematical problem where I prove that a UPC code is valid and then alter any digit and prove that that is not valid? (If so, that's really easy) On the other hand, does it want me to generalize the proof?
2. If two digits are changed in a valid UPC, the new code may or may not be valid. Determine the type of changes to two digits that result in a valid code, and determine the change to two digits that result in a code that is not valid. Justify both of your answers.

Answer - For this problem, I need a direction to go about solving the problem rather than computing various mathematical checks.
Thanks guys!

A: Usually the earlier questions are very easy and don't expect you to do much if anything beyond what is explicitly asked. Later questions go more in depth and typically expect you to draw on results obtained answering earlier questions.
For the first question, all you have to do is show that changing only one digit of the UPC makes it invalid, nothing more, nothing less. It's enough to show that each possible choice for a particular digit corresponds to a different check digit. For example, in GTIN-$12$:

*

*0000000000000

*0000000000017

*0000000000024

*0000000000031

*0000000000048

*0000000000055

*0000000000062

*0000000000079

*0000000000086

*0000000000093
What you have to understand is that one of the design considerations for the UPC system is operator dyslexia, and, as the OEIS points out, this is still cause for concern today, despite the ubiquitousness of optical scanners. Generally, a dyslexic person will make the mistake of exchanging two adjacent digits. Compare:

*

*0000000000017

*0000000000109
It's possible, but far less likely, for a dyslexic person to switch non-adjacent digits, and that can easily result in the same check digit:

*

*0000000000017

*0000000001007

*0000000100007

*0000010000007

*0001000000007

*0100000000007
And similarly

*

*0000000000109

*0000000010009

*0000001000009

*0000100000009

*0010000000009

*1000000000009
Addition is commutative, but as you already know, the multiplier for the odd-indexed digits is different from the multiplier in the even-indexed positions. Exchanging two odd-indexed or two even-indexed digits does not change the check digit. But there are only ten possibilities for the check digit and millions of possible combinations for the other digits. If you want the check digit to be $7$, you can do:

*

*0000000000017

*0000000000147

*0000000000277

*0000000000307

*0000000000437

*etc.

A: I believe part of the UPC code is a checksum-you could have told us that.  If so, you should be able to prove that changing any one digit makes the sum not check.  All the noncheck digits are interchangeable, and clearly changing the check digit causes it to fail.  For 2, you can just demonstrate one change of two digits that is valid and one change that is not.