text:
Q: Dirichlet energy given Dirichlet boundary condition Let $\Omega = B(0,1) \subset \mathbb R^n$. Given $f \in C(\partial \Omega)$ (though I guess what I want to do may make more sense in some other space of functions), we can solve the Dirichlet problem for $u_f$ with boundary condition $f$:
$$
\Delta u_f(x) = 0, x\in\Omega,
$$
$$
u_f(s) = f(s), s \in \partial\Omega
$$
which has a unique solution.
Then we can consider the Dirichlet energy of $u$
$$
I(f) := I[u_f] = \int_{\Omega} \vert \nabla u_f \vert^2.
$$
Using this procedure we have a map from the space of boundary conditions to $\mathbb R$.
This map is clearly not linear but it satisfies
$$
I(f+g) = \int_{\Omega} \vert \nabla u_{f+g} \vert^2
= \int_{\Omega} \vert \nabla u_f + \nabla u_g \vert^2 \leq 2 I(f) + 2I(g).
$$
The natural way to study this map is (probably) using the representation of solutions using the Poisson kernel but I haven't had much success.
Also, by using the divergence theorem, we have that $2\int_\Omega \vert \nabla u \vert^2 = \int_\Omega \Delta(u^2) = \int_{\partial\Omega} \nabla(u^2) \cdot \nu = 2\int_{\partial\Omega} f \nabla u \cdot \nu$.
I have several questions about this map

*

*Is this map continuous? I guess it depends on the space of boundary conditions I choose so which one is the natural candidate?

*Can I control from below and above this quantity using some norm? Clearly, $L^p$ norms are not enough since constant functions $f$ have $I(f) = 0$.

*Does anyone have some reference on something similar to this?


text:
Q: PHP incomplete result table from sql query I am new to web development and starting learning about CRUD.
My question is that while I successfully show the table listing 3 product on 1 row, that on the second row the product no 4 are missing and skipping to the product no 5 and keep missing every last 3 row.
function getData(){
    global $connect;
    $query = "SELECT id, name, category, price, image, info FROM product_data";
    $results = mysqli_query($connect, $query) or die(mysql_error());
    echo "
";
    $x=1;
    echo "
";
    while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
        if($x<=3){
            $x = $x + 1;
            extract($row);
            echo "";
            echo "";
            echo '
';
            echo '
'. $name .'

';
            echo "";
            echo 'Rp.'.$price .'
';
            echo "	";
        } else {
            $x=1;
            echo "

";
        }
    }
        echo "
";
    }

Thanks in advance!

A: Your problem is that you have a wrong condition here:
if($x <=3)... else{...}

Change the if/else to this:
if($x <3){$x++;}

//...do something

if($x == 3){
 $x = 1;
 //Close and open tr
 }

And you need to close the  tag, and the last
 tag outside of the loop

A: Perhaps you can write it like this:
function getData()
{
  global $connect;
  $query = 'SELECT id, name, category, price, image, info FROM product_data';
  $result = mysqli_query($connect, $query) or die(mysql_error());
  echo '
';
  $x=0;
  while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
  {
    if($x % 3 == 0)
    {
      // number of articles is a multiple of 3 - so close the row
      if($x) echo '
'; // but only if there was at least 1 article
      echo '
';
    }
    $x ++;
    echo '

'.$row['name'].'

      Rp. '.$row['price'].'

      	';
  }
  if($x) echo '
'; // only close the row if there was at least 1 article
  echo '
';
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: CherryPy XML-RPC-Server as Windows Service I'm trying to start an CherryPy XML-RPC-Server as Windows Service in combination with pywin32. This works on windows 7 but not on windows xp.
The script runs fine in the debug mode (i. e. not as service) but as a service I get the following log output:

2015-08-14 16:55:18,187 INFO    BuildServerService  Start Service...
2015-08-14 16:55:18,187 INFO    cherrypy.error  [14/Aug/2015:16:55:18] ENGINE Bus STARTING
2015-08-14 16:55:18,187 ERROR   cherrypy.error  [14/Aug/2015:16:55:18] ENGINE Set handler for console events.
2015-08-14 16:55:18,187 INFO    cherrypy.error  [14/Aug/2015:16:55:18] ENGINE Started monitor thread '_TimeoutMonitor'.
2015-08-14 16:55:18,218 ERROR   cherrypy.error  [14/Aug/2015:16:55:18] ENGINE Error in HTTP server: shutting down
Traceback (most recent call last):
File "C:\Programme\WinPython-32bit-3.3.5.0\python-3.3.5\lib\site-packages\cherrypy\process\servers.py", line 206, in _start_http_thread
self.httpserver.start()
File "C:\Programme\WinPython-32bit-3.3.5.0\python-3.3.5\lib\site-packages\cherrypy\wsgiserver\wsgiserver3.py", line 1648, in start
raise socket.error(msg)
OSError: No socket could be created -- (('0.0.0.0', 9000): [WinError 10106] Der angeforderte Dienstanbieter konnte nicht geladen oder initialisiert werden)
2015-08-14 16:55:18,218 INFO    cherrypy.error  [14/Aug/2015:16:55:18] ENGINE Bus STOPPING
2015-08-14 16:55:18,218 INFO    cherrypy.error  [14/Aug/2015:16:55:18] ENGINE HTTP Server cherrypy._cpwsgi_server.CPWSGIServer(('0.0.0.0', 9000)) already shut down
2015-08-14 16:55:18,218 ERROR   cherrypy.error  [14/Aug/2015:16:55:18] ENGINE Removed handler for console events.
2015-08-14 16:55:18,218 INFO    cherrypy.error  [14/Aug/2015:16:55:18] ENGINE Stopped thread '_TimeoutMonitor'.
2015-08-14 16:55:18,218 INFO    cherrypy.error  [14/Aug/2015:16:55:18] ENGINE Bus STOPPED
2015-08-14 16:55:18,218 INFO    cherrypy.error  [14/Aug/2015:16:55:18] ENGINE Bus EXITING
2015-08-14 16:55:18,218 INFO    cherrypy.error  [14/Aug/2015:16:55:18] ENGINE Bus EXITED
2015-08-17 08:50:16,665 INFO    cherrypy.error  [17/Aug/2015:08:50:16] ENGINE Console event 0: shutting down bus

Interesting is the part OSError: No socket could be created but why exactly is that not possible in a service ?
My Implementation is as follow:
import builtins, os, win32event, win32serviceutil, win32service, servicemanager, socket, logging
from UseCases.ProductionEngineering.Development.Ctt.Deployment.BuildServer.BuildXMLRPCInterface import BuildXMLRPCInterface as Interface

class BuildServerService(win32serviceutil.ServiceFramework):
    '''
    classdocs
    '''
    _svc_name_ = "BuildServerService"
    _svc_display_name_ = "Build Server Service"
    _WORKING_DIRECTORY = "C:\BuildServerService\Sources"
    _svc_deps_ = None  # sequence of service names on which this depends
    # Only exists on Windows 2000 or later, ignored on Windows NT
    _svc_description_ = "Build Server Service"
    def __init__(self, args, debug=False):
        self.debug = debug
        if not self.debug:
            builtins.RUNNING_AS_SERVICE = True
            # disable user interfaces in services because this causes errors during startup
            builtins.NO_UserInterface = True
            win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.hSockEvent = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(60)
        logging.basicConfig(filename=os.path.join(self._WORKING_DIRECTORY, "service.log"), level=logging.DEBUG, format='%(asctime)s\t%(levelname)s\t%(name)s\t%(message)s')
        self.logger = logging.getLogger(__name__)
        self.logger.log(1, 'Load ' + __file__)
    def SvcDoRun(self):
        import  os.path, cherrypy
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))
        path = os.path.dirname(os.path.abspath(__file__))
        os.chdir(path)

        self.logger.info("Start Service...")
        config = {
              'global' : {
                'server.socket_host' : '0.0.0.0',
                'server.socket_port' : 9000,
                'server.thread_pool' : 8,
                'log.screen': True,
                'engine.autoreload.on': False,
                'engine.SIGHUP': None,
                'engine.SIGTERM': None,

              },
              '/' : {
                'tools.xmlrpc.on': True,
                'tools.xmlrpc.allow_none' : True
              }
            }
        cherrypy.quickstart(Interface(), '/api', config)

    def SvcStop(self):
        import  cherrypy
        # close server and call inherited class method
        self.logger.info("Stop Service...")
        win32event.SetEvent(self.hWaitStop)
        cherrypy.engine.exit()
        if self.debug:
            return
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STOPPED,
                              (self._svc_name_, '. Bye'))

if __name__ == '__main__':
    #sc = BuildServerService(None, debug=True)
    #sc.SvcDoRun()
    win32serviceutil.HandleCommandLine(BuildServerService)

I use the winpython distribution with python 3.3.5 and the following modules:
CherryPy==3.8.0
Cython==0.20.1
Django==1.7
Jinja2==2.7.2
MarkupSafe==0.18
Pillow==2.4.0
Polygon==3.0.5
PyOpenGL==3.0.2
PyQtdesignerplugins==1.1
PyQtdoc==4.8.4
PySide==1.2.1
PyWavelets==0.3.0
Pygments==1.6
SQLAlchemy==0.9.4
Scidoc==1.8.0
SocksiPy-branch==1.02
Sphinx==1.2.2
TTFQuery==1.0.4
VPython==5.74
astroid==1.0.1
certifi==2015.04.28
chardet==2.3.0
colorama==0.2.7
comtypes==1.1.1
cx-Freeze==4.3.2
django-pyodbc-azure==1.2.1
docutils==0.11
docx==0.2.4
fonttools==2.3
formlayout==1.0.15
genicam==0.0.0-20150331112308-pylon-4.2.1.4845
guidata==1.6.1
guiqwt==2.3.2
h5py==2.2.1
ipython==2.0.0
logging==0.4.9.6
logilab-common==0.61.0
lxml==3.4.4
mahotas==1.1.0
matplotlib==1.3.1
mpld3==0.2
networkx==1.8.1
nose==1.3.1
numexpr==2.3.1
numpy==1.8.1
opencv3-python==3.0.0.dev0
pandas==0.13.1
patsy==0.2.1
psutil==2.1.0
pyhdf==0.8.3
pylint==1.1.0
pylon==0.0.0-20150331112313-pylon-4.2.1.4845
pyodbc==3.0.7
pyparsing==2.0.1
pyreadline==2.0
pyserial==2.7
python-dateutil==2.2
python-docx==0.8.5
pytz==2013.9
pywin32==218.5
pyzmq==14.0.1
regex==2015.06.24
reportlab==3.0
requests==2.5.0
scikit-image==0.9.3
scikit-learn==0.14.1
scipy==0.13.3
simplejson==3.3.3
six==1.6.1
spyder==2.3.0beta2
statsmodels==0.5.0
sympy==0.7.5
tables==3.1.1
tornado==4.2.1
vispy==0.2.1
wheel==0.24.0
winpython==1.0
xlrd==0.9.3
xml-diff==0.6.0

What do you think is that a pywin32 or a CherryPy issue ?
Thank you in advance


text:
Q: How can I put a desired value in an object array based on a condition? I have an array object value called tags.
    tags = [
        {
            "tagId": 12,
            "value": 24.2,
            "time": "2022-10-12T02:00:00Z"
        },
        {
            "tagId": 12,
            "value": 25,
            "time": "2022-10-12T06:00:00Z"
        },
        {
            "tagId": 12,
            "value": 28,
            "time": "2022-10-12T09:00:00Z"
        },

        {
            "tagId": 13,
            "value": 23,
            "time": "2022-10-12T02:00:00Z"
        },
        {
            "tagId": 13,
            "value": 23.5,
            "time": "2022-10-12T06:00:00Z"
        },
        {
            "tagId": 13,
            "value": 23.3,
            "time": "2022-10-12T09:00:00Z"
        },

        {
            "tagId": 14,
            "value": 24,
            "time": "2022-10-12T02:00:00Z"
        },
        {
            "tagId": 14,
            "value": 25.4,
            "time": "2022-10-12T06:00:00Z"
        },
        {
            "tagId": 14,
            "value": 26.4,
            "time": "2022-10-12T09:00:00Z"
        },
    ]

When I execute the renderChartControl function, I want to put the value I want in the renderData variable.
I want to compare the Atempid and Ahumid values with the e.tagId value and put the value corresponding to the condition in each property value.
    Atempid = 12;

    Ahumid = 13;

    groundtemp = 14;

    const renderChartControl = () => {

    let renderData = tags.map((e) => {

        return {
            label: Atempid === e.tagId ? 'temp' : Ahumid === e.tagId ? 'hum' : 'groundtemp',

            data: e.value,

            borderColor: Atempid === e.tagId ? 'red' : Ahumid === e.tagId ? 'orange' : 'yellow',

            backgroundColor: Atempid === e.tagId ? 'red' : Ahumid === e.tagId ? 'orange' : 'yellow',
        }
    })

    }

this is what i want answer
expected answer =

    rederData = [
        {
            "label": "temp",
            "data": [
                24.2,
                25,
                28
            ],
            "borderColor": "red",
            "backgroundColor": "red"
        },
        {
            "label": "hum",
            "data": [
                23,
                23.5,
                23.3
            ],
            "borderColor": "orange",
            "backgroundColor": "orange"
        },

        {
            "label": "groundtemp",
            "data": [
                24,
                25.4,
                26.4,
            ],
            "borderColor": "yellow",
            "backgroundColor": "yellow"
        }

    ]

but if i use my code this answer comes out
this is not answer what i want
    rederData[
        {
            "label": "temp",
            "data": 24.2,
            "borderColor": "red",
            "backgroundColor": "red"
        },
        {
            "label": "temp",
            "data": 25,
            "borderColor": "red",
            "backgroundColor": "red"
        },
        {
            "label": "temp",
            "data": 28,
            "borderColor": "orange",
            "backgroundColor": "#01C38D"
        },

        {
            "label": "hum",
            "data": 23,
            "borderColor": "orange",
            "backgroundColor": "orange"
        },
        {
            "label": "hum",
            "data": 23.5,
            "borderColor": "orange",
            "backgroundColor": "orange"
        },
        {
            "label": "hum",
            "data": 23.3,
            "borderColor": "orange",
            "backgroundColor": "orange"
        },

        {
            "label": "groundtemp",
            "data": 24,
            "borderColor": "yellow",
            "backgroundColor": "yellow"
        },
        {
            "label": "groundtemp",
            "data": 25.4,
            "borderColor": "yellow",
            "backgroundColor": "yellow"
        },
        {
            "label": "groundtemp",
            "data": 26.4,
            "borderColor": "yellow",
            "backgroundColor": "yellow"
        }

    ]

How can i fix my code??

A: You cannot do this using .map(..), you can do it using .reduce(..), here is an example:

const tags = [{ "tagId": 12,"value": 24.2,"time": "2022-10-12T02:00:00Z"}, {"tagId": 12,"value": 25,"time": "2022-10-12T06:00:00Z"}, {"tagId": 12,"value": 28,"time": "2022-10-12T09:00:00Z"}, {"tagId": 13,"value": 23,"time": "2022-10-12T02:00:00Z"}, {"tagId": 13,"value": 23.5,"time": "2022-10-12T06:00:00Z"}, {"tagId": 13,"value": 23.3,"time": "2022-10-12T09:00:00Z"}, {"tagId": 14,"value": 24,"time": "2022-10-12T02:00:00Z"}, {"tagId": 14,"value": 25.4,"time": "2022-10-12T06:00:00Z"}, {"tagId": 14,"value": 26.4,"time": "2022-10-12T09:00:00Z"}];

const Atempid = 12;
const Ahumid = 13;
const groundtemp = 14;

const result = tags.reduce((a, c) => {
  const label = c.tagId === Atempid ? 'temp' : (c.tagId === Ahumid ? 'hum' : 'groundtemp');
  const found = a.find((o) => o.label === label);
  if (found) {
    found.data.push(c.value);
  } else {
    const color = c.tagId === Atempid ? 'red' : (c.tagId === Ahumid ? 'orange' : 'yellow');
    a.push({
      label,
      data: [c.value],
      borderColor: color,
      backgroundColor: color
    });
  }
  return a;
}, []);

console.log(result);

What this does is to go through all the tags, check if there is already an entry in the result array (the a variable, the accumulator) for a specific label, if that is the case, add this tag's value value to the data array, if not, create a new entry in the result array.

A: You can do this by updating your renderChartControl function to this.
const renderChartControl = () => {
    let items = {};
    tags.forEach(e => {
        if(!items[e.tagId]) {
            items[e.tagId] = {
                label: Atempid === e.tagId ? 'temp' : Ahumid === e.tagId ? 'hum' : 'groundtemp',
                data: [e.value],
                borderColor: Atempid === e.tagId ? 'red' : Ahumid === e.tagId ? 'orange' : 'yellow',
                backgroundColor: Atempid === e.tagId ? 'red' : Ahumid === e.tagId ? 'orange' : 'yellow'
            }
        } else {
            items[e.tagId].data.push(e.value);
        }
    })
    return Object.values(items);
}


text:
Q: Startup Disk is full but can't do Dropbox My Mac says that the Startup Disk is full. I know I have way too many pictures in Photos so I got a huge Dropbox subscription to add pics before deleting from my hard drive to free up space. However, now it won't let me download pics since there is not enough free space on the hard drive to do it, so I'm caught in a Catch 22. My ultimate goal is to put pics in Dropbox and external hard drive and delete from computer so that I can have a place to access them when I need them.

A: Are you syncing your Photos app using iCloud? Using that in conjunction with the setting "Optimize Mac Storage" should solve your problem (provided you have enough iCloud storage space). When set up this way, Photos stores your entire library on Apple's servers, and only downloads full-resolution photos and videos onto your local hard drive as you view them. If you have a lot of empty space, it'll cache more of them locally, but if you start to run out, it will get purge the high-res versions to make room. The thumbnails remain for browsing.
The big advantage to this over moving things manually onto Dropbox, external drives, etc etc is that your photos and videos stay right there in Photos, and are available on all your Apple devices without any real work on your end. Everything is backed up, and you aren't spending all this time manually shuffling things around. The one (and only, IMO) disadvantage is that you need to pay for whatever level of iCloud storage suits your Photos library size.

A: Photos is storing all your photographs in a local file in your user folder on your main hard drive. Even when you move a photograph to another location, Photos keeps the photograph in this file unless you delete the photograph from Photos. When you delete a photograph from Photos, the photograph goes to "Recently deleted", but it is still in this local file! You have to delete the photograph from Recently deleted to get that space back. If you do not delete the file, it will delete itself after 30 days — this is the same way Photos works on iOS. If you have a lot of photographs, this file can get really huge.
To locate this file:

*

*Open the Finder

*Press Command + Shift + G to open the "Go to the folder:" dialog box.

*Type ~/Pictures and click "Go"

This will show you your Pictures folder inside your user folder on your Mac.
The file I am talking about will be called "Photo library" followed by an underscore ( _ ) and the date the library was created (for example: "Photo library_2015.11.05"). However big this file is, it is most likely the source of your problems with not having the free space you expect.
The quickest way to safely free up space is to:

*

*Copy your Photo library file to an external hard drive (if it is a big file, it might take a while to copy over)

*Rename the Photo library file so there's no confusion. For example, something like "Photo library_external_drive".

*If Photos is open, you will have to quit Photos (Command + Q)

*Before opening Photos again, hold down the "option" key — the easiest way to do this is to hold down the "option" key and then click the Photos icon in the Dock. This will open the "Choose Library" dialog.

*From the "Choose Library" dialog, click the button that says "Other library..." and choose your external drive, then the Photo library file you just copied over (this is where having renamed the file is useful)

*Once you have selected your renamed Photo library file, click "Open"

*Verify that all your photographs are there and that everything is right before doing step 8

*Go back to the Pictures folder inside your user folder (you could use Command + Shift + G and ~/Pictures again to be sure) and delete the Photo library file (Command + delete). Because you renamed the file on the external drive in step 2, you know that you're not deleting the file you just copied.

To get your free space back you will have to empty the trash. Once that is done, you will get back however much space this file has been taking up on your system.
The next time you open Photos, it will use the new library file that you copied and renamed on your external drive without issue.


text:
Q: html table using js I'm trying to fill up a html body table with javascript, but it's not rendering, anyone can tell me why?

var shepard = {
  name: "Commander",
  victories: 3,
  ties: 1,
  defeats: 6,
  points: 0
};
var lara = {
  name: "RaiderOfTombs",
  victories: 2,
  ties: 1,
  defeats: 7,
  points: 0
};
var altair = {
  name: "HiddenOne",
  victories: 4,
  ties: 1,
  defeats: 5,
  points: 0
};

function calculatePoints(player) {
  var points = player.victories * 3 + player.ties;
  return points;
}

shepard.points = calculatePoints(shepard);
lara.points = calculatePoints(lara);
altair.points = calculatePoints(altair);

var players = [shepard, lara, altair];

function showPlayersOnScreen(players) {
  var element = "";
  for (var i = 0; i < players.lenght; i++) {
    element += "
" + players[i].name + "	";
    element += "" + players[i].victories + "	";
    element += "" + players[i].ties + "	";
    element += "" + players[i].defeats + "	";
    element += "" + players[i].points + "	";
    element += "<button class='w' onClick='addVictory(" + i + ")'>Victory</button>	";
    element += "<button class='t' onClick='addTie(" + i + ")'>Tie</button>	";
    element += "<button class='d' onClick='addDefeat(" + i + ")'>Defeat</button>	";
    element += "
";
  }

  var playerTable = document.querySelector("tbody");
  playerTable.innerHTML = element;
}

showPlayersOnScreen(players);

function addVictory(i) {
  var player = players[i];
  player.victories++;
  player.points = calculatePoints(player);
  showPlayersOnScreen(players);
}

function addTie(i) {
  var player = players[i];
  player.ties++;
  player.points = calculatePoints(player);
  showPlayersOnScreen(players);
}

function addDefeat(i) {
  var player = players[i];
  player.defeats++;
  showPlayersOnScreen(players);
}

      Player
      Victories
      Ties
      Defeats
      Points
      Actions

I've tried changing the selector to the id and using getElementById, creating the tbody on the script with createElement, also try creating the whole thing there, have writE and rewrite all the code, I'm hopeless.

A: Probably you do not have closing tag for tbody

should be

A: You have a typo in your for loop declaration, it should be players.length not players.lenght. The later will be undefined and thus the loop won't execute.
Here's the corrected version:

var shepard = {
  name: "Commander",
  victories: 3,
  ties: 1,
  defeats: 6,
  points: 0
};
var lara = {
  name: "RaiderOfTombs",
  victories: 2,
  ties: 1,
  defeats: 7,
  points: 0
};
var altair = {
  name: "HiddenOne",
  victories: 4,
  ties: 1,
  defeats: 5,
  points: 0
};

function calculatePoints(player) {
  var points = player.victories * 3 + player.ties;
  return points;
}

shepard.points = calculatePoints(shepard);
lara.points = calculatePoints(lara);
altair.points = calculatePoints(altair);

var players = [shepard, lara, altair];

function showPlayersOnScreen(players) {
  var element = "";
  // "length" not "lenght"
  for (var i = 0; i < players.length; i++) {
    element += "
" + players[i].name + "	";
    element += "" + players[i].victories + "	";
    element += "" + players[i].ties + "	";
    element += "" + players[i].defeats + "	";
    element += "" + players[i].points + "	";
    element += "<button class='w' onClick='addVictory(" + i + ")'>Victory</button>	";
    element += "<button class='t' onClick='addTie(" + i + ")'>Tie</button>	";
    element += "<button class='d' onClick='addDefeat(" + i + ")'>Defeat</button>	";
    element += "
";
  }
  var playerTable = document.querySelector("tbody");
  playerTable.innerHTML = element;
}

showPlayersOnScreen(players);

function addVictory(i) {
  var player = players[i];
  player.victories++;
  player.points = calculatePoints(player);
  showPlayersOnScreen(players);
}

function addTie(i) {
  var player = players[i];
  player.ties++;
  player.points = calculatePoints(player);
  showPlayersOnScreen(players);
}

function addDefeat(i) {
  var player = players[i];
  player.defeats++;
  showPlayersOnScreen(players);
}

      Player
      Victories
      Ties
      Defeats
      Points
      Actions

A: Instead of adding html like this into the table, you can use the HTML DOM Table insertRow() function to insert data into a table.
You can read more about it here for how this would work: https://www.w3schools.com/jsref/met_table_insertrow.asp
A quick example of how it would work:

var shepard = {
  name: "Commander",
  victories: 3,
  ties: 1,
  defeats: 6,
  points: 0
};
var lara = {
  name: "RaiderOfTombs",
  victories: 2,
  ties: 1,
  defeats: 7,
  points: 0
};
var altair = {
  name: "HiddenOne",
  victories: 4,
  ties: 1,
  defeats: 5,
  points: 0
};

function calculatePoints(player) {
  var points = player.victories * 3 + player.ties;
  return points;
}

shepard.points = calculatePoints(shepard);
lara.points = calculatePoints(lara);
altair.points = calculatePoints(altair);
var players = [shepard, lara, altair];

function showPlayersOnScreen(players) {
  var element = "";
  const table = document.getElementById("player-table")
  for (const player of players) {
    var row = table.insertRow(0);
    var cell1 = row.insertCell(0);
    cell1.innerHTML = player.name;
    var cell2 = row.insertCell(1);
    cell2.innerHTML = player.victories;
    var cell2 = row.insertCell(2);
    cell2.innerHTML = player.ties;
    var cell2 = row.insertCell(3);
    cell2.innerHTML = player.defeats;
    var cell2 = row.insertCell(4);
    cell2.innerHTML = player.points;
  }
}

showPlayersOnScreen(players);

function addVictory(i) {
  var player = players[i];
  player.victories++;
  player.points = calculatePoints(player);
  showPlayersOnScreen(players);
}

function addTie(i) {
  var player = players[i];
  player.ties++;
  player.points = calculatePoints(player);
  showPlayersOnScreen(players);
}

function addDefeat(i) {
  var player = players[i];
  player.defeats++;
  showPlayersOnScreen(players);
}

      Player
      Victories
      Ties
      Defeats
      Points
      Actions


text: Q: Configure External Run in PyScripter to run IronPython Any Iron PyScripter's in da the house?  I'm seeking the "External Run" parameters/variables needed to configure IronPython to run the current script.  I don't understand any of variable examples, so verbatim instructions or a screen shot of how to configure the "External Tools Properties" configuration page is really what I need.  Thanx!


text:
Q: Dotnetcore Decorator is not getting called? My project is in dotnet core 3.1 and I'm using Scrutor tool to inject dependency for decorator. I have following structure:
internal interface IProvider
{
     Task<Response> Get()
}

internal sealed class Provider : IProvider
{
    public async Task<Response> Get()
    {
          Console.writeline("Some stuff");
    }
}

internal static class ProvideExtensions
{
    public static Task<Response[]> Get(this IProvider provider)
    {
      provider.Get()
    }
}

internal sealed class ProviderDecorator : IProvider
{
    private readonly IProvider _inner;

    ProviderDecorator(IProvider inner){
    _inner = inner;

    }

    public async Task<Response> Get()
    {
          Console.writeline("Some stuff");
          Console.writeline("Some stuff" + "other stuff");
    }

}

Dependency Injection on the Startup.cs:
    services.AddSingleton<IProvider, Provider>();
    services.Decorate<IProvider, ProviderDecorator>();

A: Make IProvider public
public interface IProvider
{
    Task<Response> Get();
}
internal sealed class Provider : IProvider
{
    public async Task<Response> Get()
    {
        Console.WriteLine("Some stuff");
        return new Response();
    }
}
internal static class ProvideExtensions
{
    public static Task<Response> Get(this IProvider provider)
    {
        return provider.Get();
    }
}
internal sealed class ProviderDecorator : IProvider
{
    private readonly IProvider _inner;

    public ProviderDecorator(IProvider inner)
    {
        _inner = inner;
    }

    public async Task<Response> Get()
    {
        Console.WriteLine("Some stuff");
        Console.WriteLine("Some stuff" + "other stuff");

        return new Response();
    }

}
public class Response { }


text:
Q: sqlite timecode calculations I have two tables which I export from my video editing suite, one ("MediaPool") containing a row for each media file imported into the project, another ("Montage") for the portions of that file used in a specific edit. The fields that are associated between the two are MediaPool.FileName and Montage.Name, which are very similar (Filename only adds the file extension).

# MediaPool

Filename       | Take
---------------------------------
somefile.mp4   | Getty
file2.mov      | Associated Press
file3.mov      | Associated Press

and

# Montage

Name           | RecordIn    | RecordOut
------------------------------------------
somefile       | 01:01:01:01 | 01:01:20:19
somefile       | 01:05:15:23 | 01:05:16:10
somefile       | 01:25:19:10 | 01:30:16:04
file2          | 01:30:11:10 | 01:31:18:12
file2          | 01:40:15:22 | 01:42:21:17

The tables contain many more columns of course, but only the above is relevant.
Only the "MediaPool" table contains the field called "Take" which designates the file's copyright holder (long story). It can't be included in the "Montage" export. I needed to calculate the total duration of footage used from each source, by subtracting the RecordIn timecode from RecordOut and adding each result. This turned out to be more complicated than I expected, as I have some notions of programming but almost none when it comes to SQL (sqlite in my case).
I managed to come up with the following, which works fine and runs in under 4 seconds. However, from the little programming I've done, it seems overlong and very inelegant. Is there a shorter way to achieve this?
BTW, I'm using 25 fps timecode and I can't use LPAD in sqlite.

    SELECT
        Source,
        SUBSTR('00' || CAST(DurationFrames/(60*60*25) AS TEXT), -2, 2) || ':' ||
        SUBSTR('00' || CAST(DurationFrames%(60*60*25)/(60*25) AS TEXT), -2, 2) || ':' ||
        SUBSTR('00' || CAST(DurationFrames%(60*60*25)%(60*25)/25 AS TEXT), -2, 2) || ':' ||
        SUBSTR('00' || CAST(DurationFrames%(60*60*25)%(60*25)%25 AS TEXT), -2, 2)
        AS DurationTC
    FROM
    (
    SELECT
        MediaPool.Take AS Source,
        Montage.RecordIn,
        Montage.RecordOut,
        SUM(CAST(SUBSTR(Montage.RecordOut, 1, 2) AS INT)*3600*25 +
            CAST(SUBSTR(Montage.RecordOut, 4, 2) AS INT)*60*25  +
            CAST(SUBSTR(Montage.RecordOut, 7, 2) AS INT)*25 +
            CAST(SUBSTR(Montage.RecordOut, 10, 2) AS INT) -
            CAST(SUBSTR(Montage.RecordIn, 1, 2) AS INT)*3600*25 -
            CAST(SUBSTR(Montage.RecordIn, 4, 2) AS INT)*60*25 -
            CAST(SUBSTR(Montage.RecordIn, 7, 2) AS INT)*25 -
            CAST(SUBSTR(Montage.RecordIn, 10, 2) AS INT))
        AS DurationFrames
    FROM
        MediaPool
    JOIN
        Montage ON MediaPool.FileName LIKE '%' || Montage.Name || '%'
    GROUP BY
        Take
    ORDER BY
        Take
    )

A: Here's a simplified query that produces the same results as yours on your test data. Mostly it uses printf() instead of a bunch of string concatenation and substr()s, and uses strftime() to calculate the total seconds of the hours minutes seconds part of the timecode:
WITH frames AS
 (SELECT Take, sum((strftime('%s', substr(RecordOut,1,8))*25 + substr(RecordOut,10))
                 - (strftime('%s', substr(RecordIn,1,8))*25 + substr(RecordIn,10)))
                  AS DurationFrames
  FROM MediaPool
  JOIN Montage ON MediaPool.Filename LIKE Montage.Name || '.%'
  GROUP BY Take)
SELECT Take AS Source
     , printf("%02d:%02d:%02d:%02d", DurationFrames/(60*60*25),
                                     DurationFrames%(60*60*25)/(60*25),
                                     DurationFrames%(60*60*25)%(60*25)/25,
                                     DurationFrames%(60*60*25)%(60*25)%25)
                                     AS DurationTC
FROM frames
ORDER BY Take;


text:
Q: Managing traffic on Google Cloud Run I'm actually using Cloud Build & Cloud Run in my project.
For the CI/CD, I use a cloudbuild.yaml file to define the steps I need to perform to deploy my new revision of Cloud Run.
After several issue on traffic management, I had to add to my Cloud Build file a step to specify that the traffic should be set to 100% to the latest built revision. That is weird but it is working so... be it
cloudbuild.yaml step
# Allocate 100% of the traffic to that new revision
- name: gcr.io/cloud-builders/gcloud
  args: ['run', 'services', 'update-traffic', '${_APP_NAME}', '--to-revisions=LATEST=100', '--platform', 'gke', '--cluster', 'xxxxxx', '--cluster-location', 'xxxxxxxxxxx', '--namespace', 'xxxxxxxx']

Unfortunately, even if the traffic is well set, it always keeps "alive" the old revision  .

What is strange is that it is not doing it when I'm doing it remotely using gcloud command.
Did you already have that issue in the past ?
Thanks for the help :)


text:
Q: Find all natural $n$ numbers. Find all natural $n$ numbers such that
$15(n!)^2+1$ is divisible by $2n-3$.
My try: First I assumed $2n-3$ is not prime number. Let $a$ be divisor of $2n-3$. It's clear that $a<n-1$, so $15(n!)^2$ is divisible by $a$. Which means $15(n!)^2+1$ is not divisble by $a$. But it is given that $15(n!)^2+1$is divisble by $n$ which means it is divisible by $a$ too. But we have already proved it is not. Contradiction!
So $2n-3$ must be prime number. Now if we change $2n-3$ as $p$. We can say $((p+3)/2)!*((p+3)/2)!$ is congruent to $-1$ by $p$ module. By Wilson's theorem $((p+3)/2)!*((p+3)/2)!$ is congruent to $(p-1)!$ by $p$ module

A: it has been checked by a computer up to n = 40000. the set now contains the numbers {1,2,10,77}. I do not have a proof that there are no new numbers that satisfy the conditions for the set above n = 40000. I can see why people thought this question was impossible. it may actually be a nice problem that is solvable if you can prove that the statement is false for n > 77. the rest are checked by computer.


text:
Q: returns false for data value loadComplete jqGrid EDITED JS:
$.extend($.jgrid.defaults,
    {
        mtype: "POST",
        viewRecords: true,
        rowNum: 10,
        sortable: false,
        shrinkToFit: true,
        rowList: [10,20,50],
        xmlReader: {
            root: "tasks",
            row: "task",
            repeatitems: false
        }
    });

I am using this event to get the value inside the cell. When i run the code the alert returns "false" for the first couple of cells even though they have a value assigned and then returns the right value for all the corresponding ones. How do i fix this?
I tried gridComplete event and the result was the same.
XML:
<?xml version="1.0" encoding="UTF-8" ?>
<tasks>
    <task>
        <TaskID>job0001</TaskID>
        <UserID>admin</UserID>
        <AssignID></AssignID>
        <AssignDate></AssignDate>
        <DueDate></DueDate>
        <AssignUser>1</AssignUser>
        <TaskSubject></TaskSubject>
        <Notes>Urgent!</Notes>
        <TrackID>1</TrackID>
        Not Started
        <Submitted></Submitted>
        <folderLink></folderLink>
    </task>
    <task>
        <TaskID>job00004</TaskID>
        <UserID>admin</UserID>
        <AssignID></AssignID>
        <AssignDate>2012-02-07</AssignDate>
        <DueDate>2012-02-16</DueDate>
        <AssignUser>1</AssignUser>
        <TaskSubject></TaskSubject>
        <Notes>ajsbaljb</Notes>
        <TrackID>7</TrackID>
        Not Started
        <Submitted></Submitted>
        <folderLink></folderLink>
    </task>
</tasks>

EDIT 2: If I do this
loadComplete : function()
                        {

                            var data = $grid.getCol('Details');
                            alert(data);
                        },

it returns everything correctly!

A: loadComplete : function()
                    {
                        var data = $grid.getCol('Details', true);
                    },

This returns exactly what I had in the Details Cell with the rowIds. This solved where I was stuck but I would still like to know why the other function returned false.


text:
Q: How to convert Promise to String? I used Axios and return the data to my react Component I have an API call to Cloudinary after the image was uploaded it returns a promise instead of a string. I wanted to to get the URL on my uploaded image to be saved on my database.
Here is the return screenshot:

Here is my Axios code:
export const uploadImage = imageUpload => async dispatch => {
  try {

    const formData = new FormData();
    formData.append('file', imageUpload);

    const res = await axios.post(
      'https://api.cloudinary.com/v1_1/frank/image/upload',
      formData
    );

    return res.data.secure_url;
  } catch (err) {
    const errors = err.response.data.error;
  }
};

I also tried using .then(), but my variable returns undefined.

A: Okay so I dispatch my res through my redux thunk
dispatch({
  type: UPLOAD_SUCCESS,
  payload: res.data.secure_url
});

Then on my Component I used useEffect hook to set my formData. I also used useState hook for my props
const [formData, setFormData] = useState({photo: '', imgURL: ''});

If the the dispatch is triggered
useEffect(() => {
  setFormData({ ...formData, photo: image });
}, [image]);

Now my photo is set to a String. Thanks for sharing you ideas. It helped.


text:
Q: SQL to return matches from multiple queries I need to return values that appear across two or more queries from the same table. Feeling a bit like a noob here but just can't see the wood for the trees.
I have a table of users assigned to different groups. I need to return only the users that appear in all of the requested groups:
User   Group
frank  1
Jane   2
Tom    2
frank  2
Jane   1
Tom    3

This is want I need to output:
Result for Group 1 & 2:
frank
Jane

Result for Group 2 & 3:
Jane
Tom

Seems a very 101 question, but grateful for any pointers.

A: select user
from users
where group_id in (1,2)
group by user
having count(*) = 2;

You need to adjust the having count(*) = 2 condition to the number of groups that you want.
If a user can be assigned to the same group more than once, then Madhivanan's comment need to be taken into account:
select user
from users
where group_id in (1,2)
group by user
having count(distinct group_id) = 2;

(I used the column name group_id because group is a reserved word and should be used as a column name).

A: select user from table
where group in (1,2)
group by user
having count(distinct group)=2


text:
Q: Creating container resize function in jQuery Infinite Carousel I'm creating a custom implementation of jquery Infinite Carousel on a wordpress site, http://cambridgeuplighting.com/scale-test.  I want to give my client the option to add photos of any resolution and have the container element resize to fit it.  I'm going for the same animated resize effect as in Lightbox/Slimbox or SimpleViewer.
I have got an OK start, but there are some flaws in the code.  Here is the modification to the "thumbClick" function in infinitecarousel.js`
//Get the rel attribute of the thumbnail (this is set to the index # of the thumbnail)
var activeLi = $(this).attr('rel');
//Find the Li elemement whose rel attribute (set to the initial index # of the li element onLoad) matches that of the thumbnail, so we can know which image is active
var whichLi = $('#singleSlide ul li[rel='+activeLi+']');
var whichLiImg = $('#singleSlide ul li[rel='+activeLi+'] img');
//Get the width and margin necessary to resize and center the container element
var activeImgWidth = whichLi.width();
var activeImgMargin = 628-activeImgWidth;
//Set the Width attribute of the Li element equal to that of the image it contains
whichLi.css( { 'width' : activeImgWidth } );
//Animate the width of the container element (the div with the gray border)
$('div#singleSlide').animate( {
     width: activeImgWidth,
     marginLeft: activeImgMargin/2
     },300);

Here is the code that I added to my own init.js to set the li elements' rel attribute to their index value
jQuery(function( $ ){
 $("#singleSlide ul").each(function() {
     $(this).children("li").each(function(i) {
         $(this).attr("rel", i);
     });
 });

 $('#singleSlide ul li a').attr('rel', 'lightbox-gallery');
});

So as you can see on the test page: cambridgeuplighting.com/scale-test, This code is not selecting the correct images with the correct widths to resize to.  I know one problem i need to fix is instead of setting the Li widths onClick, I need to set them right when the page loads.
Thanks for your help!

A: In my opinion you should create a variable that reads the size of the image and a class that modifyes the size of the container according to the size of the picture :D


text:
Q: App crashes when the setContentView of searchActivity I created a search box on the ActionBar. If I use SearchView to search a string on  the MainActivity it activates the SearchActivity which handles the search query. But when I call setContentView() to set the layout of the SearchActivity the app crashes.
public class SearchActivity extends ListActivity {

private TextView textview;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_search);
    handleIntent(getIntent());
    //textview=findViewById(R.id.search_result);
}

public void onNewIntent(Intent intent) {
    setIntent(intent);
    handleIntent(intent);
}

private void handleIntent(Intent intent) {
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        doSearch(query);
    }
}

public void doSearch(String query) {
    //textview.setText("You have searched for "+query);
}
}

This is my MainActivity
   public class MainActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);
    }

    @Override
    public boolean onCreateOptionsMenu( Menu menu )
    {
        getMenuInflater().inflate( R.menu.search_menu, menu );

        // Add SearchWidget.
        SearchManager searchManager = (SearchManager) getSystemService( Context.SEARCH_SERVICE );
        SearchView searchView = (SearchView) menu.findItem( R.id.search_box ).getActionView();

        searchView.setSearchableInfo( searchManager.getSearchableInfo( getComponentName() ) );

        return super.onCreateOptionsMenu( menu );
    }

    }

This is my search_layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/search_result"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</RelativeLayout>

This is the AndroidManifest.xml file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.anjaleeps.loancomparison">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <meta-data
        android:name="android.app.default_searchable"
        android:value=".SearchActivity" />
    <activity
        android:label="@string/app_name"
        android:launchMode="singleTop"
        android:name=".SearchActivity" >
        <intent-filter >
            <action android:name="android.intent.action.SEARCH" />
        </intent-filter>
        <intent-filter >
            <action android:name="android.intent.action.VIEW" />
        </intent-filter>
        <meta-data
            android:name="android.app.searchable"
            android:resource="@xml/searchable" />
    </activity>

</application>
</manifest>

A: Try extending AppCompatActivity to your SearchActivity. If your intent is not null, it should work.
public class SearchActivity extends AppCompatActivity

for more , you can refer to https://developer.android.com/reference/android/app/Activity


text:
Q: Determine types of edges using networkx Is there a built in function in networkx to tell me the type of edges I have in my directed graph using BFS?
If not, does anyone have any good strategies for identifying the forward, backward, and cross edges in a BFS?
Thanks
MORE INFORMATION
 a = [(0,1), (2,1), (1,2), (0,3), (3,2)]
 G = nx.DiGraph(a)
 bfs = nx.breath_first_search.bfs_tree(G, source=3)
 # ISSUE identify the edge types for each edge from source 3


text:
Q: Convert the rows of frequency "table" (NOT matrix or dataframe) to separate lists I'm running frequency table of frequencies, I want to convert the table to two lists of numbers.
numbers <- c(1,2,3,4,1,2,3,1,2,3,1,2,3,4,2,3,5,1,2,3,4)

freq_of_freq <- table(table(numbers))

> freq_of_freq

1 3 5 6
1 1 1 2

From the table freq_of_freq, I'd like to get create two list, x and y, one containing the numbers 1,3,5,6 and the other with the frequency values 1,1,1,2
I tried this x <- freq_of_freq[ 1 , ] and y <- freq_of_freq[ 2 , ], but this doesn't work.
Any help greatly appreciated. Thanks

A: One approach is to use stack() to create a list.
numbers <- c(1,2,3,4,1,2,3,1,2,3,1,2,3,4,2,3,5,1,2,3,4)
freq_of_freq <- table(table(numbers))

stack(freq_of_freq)
#>   values ind
#> 1      1   1
#> 2      1   3
#> 3      1   5
#> 4      2   6

To exactly match your expected output, you could do:
x = as.integer(names(freq_of_freq))
y = unname(freq_of_freq)

Note, the OP attempt of freq_of_freq[1, ] does not work because table returns a named integer vector for this example dataset. That is, we can't subset using matrix or data.frame notation because we only have one dimension.


text:
Q: SQL Compact lock timeout on __SysObjects I'm using SQL Compact 3.5 SP2. My application is multi-threaded, but it does not share connections across threads. Instead, I use a custom object pool to ensure that each thread gets its own connection. That said, it's possible that a connection might be re-used on different threads at different times... in other words, I'm assuming that the connections don't have thread affinity. Also, not sure if it matters, but I'm using Entity Framework in .NET 3.5 SP1.
Anyway, when I've got high load situations (8+ threads), I'm getting lock timeout exceptions (regardless of the length of the timeout setting), and the exception always says the lock was on the __SysObjects table.
I'm not doing any DDL, so I don't understand why I would get locking timeouts on that table. Ideas?

A: I somewhat resolved this issue by making sure that my connections were closed after each use (as opposed to pooling the open connections), but if I let the code run for a long period of time I started getting OutOfMemoryException and AccessViolation exceptions.
This smells like the SqlCeConnection class has some kind of thread affinity dependency. Either that, or it has a memory leak of some kind.
At any rate, I've given up on trying to pool these objects.
EDIT: This actually appears to be an issued address by Cummulative Update 2. Since updating my references to the new libs, I haven't seen this problem. See: http://support.microsoft.com/kb/983516


text:
Q: Structure initialization and assignment vs adhoc creation and assignment -- are they identical? Consider the following code:
struct Foo {
   int i;
   char c;
   float f;
};

int main() {
    struct Foo f1 = { .i = 1 };
    struct Foo f2;
    f2 = (struct Foo){ .i = 1 };
}

Afaik f1 is a structure partially initialized with designated initializer, and all its omitted fields are guaranteed to be initialized with zeros. But Does C standard guarantee that f1 would be identical to f2? And how exactly f2 creation syntax called?

A:
But Does C standard guarantee that f1 would be identical to f2?

After the code shown in main, the named members of f1 and f2 will have identical values. Any padding bytes in the structures will not necessarily be identical. Thus, comparing f1 and f2 with memcmp(&f1, &f2, sizeof f1) may indicate they are different. Also, it is rare these days, but any padding bits in the members will not necessarily be identical.

And how exactly f2 creation syntax called?

(struct Foo){ .i = 1 }; is a compound literal, defined in C 2018 6.5.2.5. The grammar for a compound literal is ( type-name ) { initializer-list }, and there may be a comma at the end of the initializer list. A compound literal outside a function has static storage duration. A compound literal inside a function has automatic storage duration associated with its enclosing block.

A: In this assignment statement
f2 = (struct Foo){ .i = 1 };

there is used a compound literal that creates an unnamed object of the type struct Foo that is initialized the same way as the object f1. Then this unnamed object of the type struct Foo is assigned to the object f2.
That is in this statement there is created one more object of the type struct Foo that has automatic storage duration.
Pay attention to that there is a typo in your code snippet
f2 = (struct Foo){ .i = 1 );
                         ^^^

you need to write
f2 = (struct Foo){ .i = 1 };
                         ^^^

A: f2 = (struct Foo){ .i = 1 ); is called an assignment
They are not identical. The latter theoretically  (or if you compile without optimizations) will create the object which time of life is the same as enclosing scope. This object will be used in the assignment
But in this trivial example, both will be optimized out. Optimizing compiler ( if the program is more complex) will optimize out the compound literal as you do not use reference to it, so the generated code will be identical in both cases
PS
Checked without the optimizations the unnamed object is not created.
main:
        push    rbp
        mov     rbp, rsp
        mov     QWORD PTR [rbp-12], 0
        mov     DWORD PTR [rbp-4], 0
        mov     DWORD PTR [rbp-12], 1
        mov     QWORD PTR [rbp-24], 0
        mov     DWORD PTR [rbp-16], 0
        mov     DWORD PTR [rbp-24], 1
        mov     eax, 0
        pop     rbp
        ret

A: The assignment below:
struct Foo f2 = (struct Foo){ .i = 1 };

is using a compound literal. It is equivalent using an anonymous variable:
struct Foo _anonymous_ = { .i = 1 };
struct Foo f2 = _anonymous_;

The lifetime of the compound literal is the same as lifetime of a variable defined at the same scope.
Moreover it allowed to take an address of the literal or even do bizarre things like assigning values to it:
(int){ 0 } = 42; // valid !

In practice there is no functional difference for local variables, the compiler will likely treat compound literal and initializers the same it the context for the OP's question.
However, there is a difference for initialization of static and global objects because they must initialized with constant expressions. However, compound literal is not a constant expression.
static struct Foo f1 = { .i = 1 };  // ok
static struct Foo f2 = (struct Foo){ .i = 1 }; // illegal


text:
Q: Mockito: inject a class mock into a private interface field I'm using Mockito 1.9.5 to do some unit testing. I'm trying to inject a concrete class mock into a class that has a private interface field. Here's an example:
Class I'm testing
@Component
public class Service {

    @Autowired
    private iHelper helper;

    public void doSomething() {
        helper.helpMeOut();
    }
}

My test for this class
@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {

    @Mock
    private iHelper helper;

    @InjectMocks
    private Service service;

    @Before
    public void setup() {
        service = new Service();
    }

    @Test
    public void testStuff() {
        doNothing().when(helper).helpMeOut();
        service.doSomething();
    }
}

This code throws a NullPointerException when trying to call helper.helpMeOut() in doSomething(). I debugged and found that helper was null when running the test. I also tried changing iHelper to the concrete class Helper, and the same issue happened.
Any suggestions? How can I get Mockito to correctly inject a mock into an interface private field?

A: @acdcjunior's comment helped me figure out the issue. Instantiating service using the new keyword caused Spring to not inject the dependencies (in this case helper) correctly. I fixed this by autowiring in service in the test. My final working code looks like this:
Class I'm testing
@Component
public class Service {

    @Autowired
    private iHelper helper;

    public void doSomething() {
        helper.helpMeOut();
    }
}

My test for this class
@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {

    @Mock
    private iHelper helper;

    @InjectMocks
    @Autowired
    private Service service;

    @Test
    public void testStuff() {
        doNothing().when(helper).helpMeOut();
        service.doSomething();
    }
}

Hope this helps someone else. Thanks for the suggestions!

A: According to the docs you are missing the setup.
@Before
public void initMocks() {
    MockitoAnnotations.initMocks(this);
}

Edited*
Take at look at this page why you should not use @InjectMock to autowire fields


text:
Q: Subtransactions in functions that can commit I read that I can use a BEGIN-EXCEPTION block to have a subtransaction in a FUNCTION that can be rolled back. But why is it not possible to commit this subtransaction?
How can I circumvent the "all-or-nothing" transaction behavior of functions written in PL/pgSQL? Is it possible to have the function make commits using subtransactions while the outer transaction could be rolled back?

A: You can't circumvent it at the time of writing (PG 9.3).
Or more precisely, not directly. You can mimic autonomous subtransactions by using dblink, but be wary that doing so is a can of worms: what's supposed to happen, for instance, if your outer transaction is rolled back?
For background and references to discussions related to the topic on the PG-Hackers list, see:
http://wiki.postgresql.org/wiki/Autonomous_subtransactions
http://www.postgresql.org/message-id/20111218082812.GA14355@leggeri.gi.lan


text:
Q: Fetch snap SPARQL query using OWL API in java web oke, I have this snap SPARQL query using protege
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX :<http://www.semanticweb.org/astrid/ontologies/2019/5/mpasiv2#>

SELECT ?resep_makanan
WHERE {
    ?resep_makanan rdf:type :resep_makanan.
    ?resep_makanan :resep_untuk :6-7_bulan.
}
ORDER BY ?resep_makanan

and it works, i get instance for my resep_makanan which are food name, with object property resep_untuk (recipe_for) baby who is 6-7_bulan (6-7_month old).
then in my java web code, i write
PREFIX :<http://www.semanticweb.org/astrid/ontologies/2019/5/mpasiv2#>
SELECT DISTINCT ?resep_makanan
WHERE {
Type (?resep_makanan, :resep_makanan),
PropertyValue(?resep_makanan, :resep_untuk, :6-7_bulan)
}
order by ?resep_makanan

But i get 0 query result.
Im using OWL API.
How should i write it correctly?

A: Looking up 'snap SPARQL' brings the https://github.com/protegeproject/snap-sparql-query project, which I believe is what you're actually using to run your queries (as it's used in Protege).
If that's the case, you're not using OWL API for the SPARQL part of your code, as OWL API does not support SPARQL itself; I don't know the snap sparql project but, as it integrates with Protege, which is OWL API based, I assume OWL API is used for interfacing a SPARQL based API with Protege. From the project dependencies, I think that's de-derivo-sparqldlapi.
To answer your question, if the same query does not produce a result outside of Protege this must depend on it not being sent to the same SPARQL endpoint or to a different set up of the endpoint (e.g., does your query depend on reasoning for its results?)
Some of this information might be in the code that you're running and have not shown here, but we won't be able to tell without seeing it.


text:
Q: Error during Websocket handshake with error code 500 using Daphne on Heroku So I tried to deploy my docker django chat app to heroku. Previously I had been running the app with runserver command, but now I'm switching to daphne since I need to use websocket but I can't use runserver anymore in order to connect to webserver. After deployment, when I access the app page that shows the chat window this error occurs
WebSocket connection to 'wss://xxx.herokuapp.com/ws/chat/room/' failed: Error during WebSocket handshake: Unexpected response code: 500
(xxx is actually the url of my app)
Here's a piece of my js code
<script>
    var roomName = "{{ room_name|escapejs }}";
    var wsStart = 'ws://';
    if (window.location.protocol === 'https:') {
                wsStart = 'wss://';
       }
    var chatSocket = new WebSocket(
        wsStart + window.location.host +
        '/ws/chat/' + roomName + '/');

    chatSocket.onmessage = function(e) {
        var data = JSON.parse(e.data);
        var message = data['message'];
        document.querySelector('#chat-log').value += (message + '\n');
    };

ws didn't work (error message Django can only use ASGI not websocket) so I changed to wss (according to another post in stackoverflow it's because security reason), which made the other error go away but still can't connect to websocket
This is my run command:
daphne -p $PORT --bind 0.0.0.0 -v2 test_project.asgi:application
EDIT: if I don't use wss (just use ws instead) this is the error message in js console
The page at 'https://xxx/chat/m/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://xxx/ws/chat/room/'. This request has been blocked; this endpoint must be available over WSS.
Extremely appreciate any help, or ideas of what went wrong. Thank you so much!

A: Turns out it has just about nothing to do with daphne or my js code that doesn't work. I didn't connect to a heroku-redis at the time and thus was not running redis. Configured REDISTOGO_URL with
heroku config --app  <appname> | grep REDISTOGO_URL

, changed host in channel_layer from "hosts": ('redis', 6379), (something similar) to "hosts": [os.environ.get('REDISTOGO_URL',('redis', 6379))] allowed me to connect to heroku redis.


text:
Q: How to make a IF that its value is equal to the string?
if text = "abc" --- then---  txt.setText=Hi

 TextView txt=(TextView)findViewById(R.id.txt);
if(txt.setText()="text"){
   // do something
}

i mean txt equals to text

A: use equals() method to compare string.

if text = "abc" --- then--- txt.setText=Hi

if(text.equals("abc")){
     txt.setText("Hi");
}

A: Try this,
if(txt.getText().toString().equals("text")){
//do something.
txt.setText("Hi");
}

A: Hey and welcome to SO!
You are trying to get text with setText() method. You need to use getText() method. And you can't use == for comparing text. In java you will need to use equals() to compare value of the object otherwise it will just compare refrence.
So for your case the code would be something like this:
TextView txt=(TextView)findViewById(R.id.txt);
if(txt.getText().toString().equals("text")){
   // do something
}

A: Try this one
if (TextUtils.equals(txt.getText().toString(), "text")){
    txt.setText("Hi");
}

A: For preventing null pointer exception, you must put "text" in front of the variable.
TextView txt=(TextView)findViewById(R.id.txt);
if("text".equals(txt.getText().toString())){
  //do something here
}

A: Try following code:
if(txt.getText().toString().equals("abc")){  // if txt = abc --then--
   txt.setText("Hi");                        // txt.setText=Hi
}

A: Try This ,
if(txt.getText().toString().trim().equals("text"))
{
 txt.setText("Hi");
}


text:
Q: how to add a "space" in certain location in string when scraping the data from web by using python I was scraping a web for practicing and I encountered a problem.
I'd like to print data like:

Level :2
DC Fast :12
Level :2

I used browser[0].find("div",{"class":"pin_info"}).text[1:] However, what I got isLevel :2DC Fast :12Level :2, there is no space between each part.
Below is the html I scraped:

  A

  Level 2
  : 2

  DC Fast
  : 12

  Level 2
  : 2

I have no clue how to separate each part right now. Does anybody have any ideas?
  Any response will be appreciated!

A: You can use the getText method instead of the .text attribute, since it has an optional separator argument which allows you to replace separations with whatever you want ("\n" here) like this:
browser[0].find("div",{"class":"pin_info"}).getText(separator="\n")
Result:
A

Level 2
: 2

DC Fast
: 12

Level 2
: 2

Then you can do string manipulation with that until you get to your desired result, something like this:
info = browser[0].find("div",{"class":"pin_info"}).getText(separator="\n")[5:].split("\n\n")
'\n'.join(map(lambda x: x.replace("\n", " "), info))

Output:
Level 2 : 2
DC Fast : 12
Level 2 : 2


text:
Q: Twitter Search API v1.1 not working I'm using the Twitter Search API v1.1 to simply search by hashtag #monstercareers.  This bit of code works for other hashtags, but will not work for this particular one.  I know this API is slightly different from the one Twitter actually uses (which makes it difficult to test), but if you search #monstercareers on Twitter.com it works fine.
<?php

  require_once('lib/TwitterAPIExchange.php');

  $url = "https://api.twitter.com/1.1/search/tweets.json";
  $getfield = "?q=#monstercareers";
  $requestMethod = "GET";

  $settings = array(
    'oauth_access_token' => "xxx",
    'oauth_access_token_secret' => "xxx",
    'consumer_key' => "xxx",
    'consumer_secret' => "xxx"
  );

  $twitter = new TwitterAPIExchange($settings);
  echo $twitter->setGetfield($getfield)->buildOauth($url, $requestMethod)->performRequest();

?>

Here is the empty response I get with the above code:
{
  statuses: [ ],
  search_metadata: {
   completed_in: 0.006,
   max_id: 396701092337053700,
    max_id_str: "396701092337053696",
    query: "%23monstercareers",
    refresh_url: "?since_id=396701092337053696&q=%23monstercareers&include_entities=1",
    count: 15,
    since_id: 0,
    since_id_str: "0"
   }
}

Does anyone have any idea on why this might be an inconsistency, and if there's a better way around this?

A: Doing some research I have found that the twitter API only looks back up to 6-9 days of tweets, so in the case you might want to look back on time, you need to use the until param.
Checkout the documentation on https://dev.twitter.com/docs/using-search on the Best Practices Section.


text:
Q: D3.js various link distance I am in need to implement a various link distance. I added a function call during the initialization of the force / simulation. Still, it looks like the settings are ignored. I want to add another node very close, that barely a hair would fit between. Is this even possible?
I noticed a similar question on stackoverflow but this requires another plugin, furthermore this question was created 4 years ago. Maybe vanilla d3.js already added the feature.

            var graph = {
                "nodes": [
                    {
                        "id": 0
                    },
                    {
                        "id": 1
                    },
                    {
                        "id": 2
                    },
                    {
                        "id": 3
                    }
                ],
                "links": [
                    {
                        "source": 0,
                        "target": 1,
                        "distance": 0.1
                    },
                    {
                        "source": 0,
                        "target": 2,
                        "distance": 150
                    },
                    {
                        "source": 0,
                        "target": 3,
                        "distance": 20
                    }
                ]
            }

            var svg = d3.select("svg")
                .attr("class", "canvas")
                .attr("width", window.innerWidth)
                .attr("height", window.innerHeight)
                .call(d3.zoom().on("zoom", function (event) {
                    svg.attr("transform", event.transform)
                }))
                .append("g")

            var linksContainer = svg.append("g").attr("class", linksContainer)
            var nodesContainer = svg.append("g").attr("class", nodesContainer)
            var sourceNode;

            var force = d3.forceSimulation()
                //.force("link", d3.forceLink().id(function (d) { return d.id }).distance(80))
                .force("link", d3.forceLink().distance(linkDistance).strength(0.1))
                .force("charge", d3.forceManyBody().strength(-100))
                .force("center", d3.forceCenter(window.innerWidth / 2, window.innerHeight / 2))
                .force("collision", d3.forceCollide().radius(90))

            function linkDistance(d) {
                console.log(d.distance)
                return d.distance;
            }

            initialize()

            function initialize() {

                link = linksContainer.selectAll(".link")
                    .data(graph.links)
                    .join("line")
                    .attr("class", "link")
                    .style("stroke", "black")
                    .style("stroke-width", 1)

                node = nodesContainer.selectAll(".node")
                    .data(graph.nodes, d => d.id)
                    .join("g")
                    .attr("class", "node")
                    .call(d3.drag()
                        .on("start", dragStarted)
                        .on("drag", dragged)
                        .on("end", dragEnded)
                    )
                    .on("click", addNode)

                node.selectAll("circle")
                    .data(d => [d])
                    .join("circle")
                    .attr("r", 30)
                    .style("fill", "whitesmoke")

                node.append("text")
                    .attr("dominant-baseline", "central")
                    .attr("text-anchor", "middle")
                    .attr("font-size", 15)
                    .attr("pointer-events", "none")
                    .text(function (d) {
                        return d.id
                    })

                force
                    .nodes(graph.nodes)
                    .on("tick", ticked);

                force
                    .force("link")
                    .links(graph.links)
            }

            function ticked() {
                // update link positions
                link
                    .attr("x1", function (d) {
                        return d.source.x;
                    })
                    .attr("y1", function (d) {
                        return d.source.y;
                    })
                    .attr("x2", function (d) {
                        return d.target.x;
                    })
                    .attr("y2", function (d) {
                        return d.target.y;
                    });

                // update node positions
                node
                    .attr("transform", function (d) {
                        return "translate(" + d.x + ", " + d.y + ")";
                    });
            }

            function dragStarted(event, d) {
                if (!event.active) force.alphaTarget(0.3).restart();
                d.fx = d.x;
                d.fy = d.y;

                PosX = d.x
                PosY = d.y
            }

            function dragged(event, d) {
                d.fx = event.x;
                d.fy = event.y;
            }

            function dragEnded(event, d) {
                if (!event.active) force.alphaTarget(0);
                d.fx = undefined;
                d.fy = undefined;
            }

            function addNode(event, d) {
                const nodeId = graph.nodes.length

                graph.nodes.push({id: nodeId})
                graph.links.push({source: d, target: nodeId, distance: 1})

                initialize()
            }
        body {
            height: 100%;
            background: #e6e7ee;
            overflow: hidden;
            margin: 0px;
        }

        .faded {][1]
            opacity: 0.1;
            transition: 0.3s opacity;
        }

        .highlight {
            opacity: 1;
        }
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- d3.js framework -->
        <script src="https://d3js.org/d3.v6.js"></script>
        <!-- fontawesome stylesheet https://fontawesome.com/ -->
        <script src="https://kit.fontawesome.com/39094309d6.js" crossorigin="anonymous"></script>
    </head>

    <style>
    </style>

    <body>
        <svg id="svg"></svg>
    </body>

A: The distance function is correctly set and specified.
Problem comes from the forceCollide, which is set to a radius of 90, and pushes the nodes apart regardless of specified distance.
Decreasing the radius of forceCollide fixes the problem, as illustrated below :)

var graph = {
                "nodes": [
                    {
                        "id": 0
                    },
                    {
                        "id": 1
                    },
                    {
                        "id": 2
                    },
                    {
                        "id": 3
                    }
                ],
                "links": [
                    {
                        "source": 0,
                        "target": 1,
                        "distance": 0.1
                    },
                    {
                        "source": 0,
                        "target": 2,
                        "distance": 150
                    },
                    {
                        "source": 0,
                        "target": 3,
                        "distance": 20
                    }
                ]
            }

            var svg = d3.select("svg")
                .attr("class", "canvas")
                .attr("width", window.innerWidth)
                .attr("height", window.innerHeight)
                .call(d3.zoom().on("zoom", function (event) {
                    svg.attr("transform", event.transform)
                }))
                .append("g")

            var linksContainer = svg.append("g").attr("class", linksContainer)
            var nodesContainer = svg.append("g").attr("class", nodesContainer)
            var sourceNode;

            var force = d3.forceSimulation()
                //.force("link", d3.forceLink().id(function (d) { return d.id }).distance(80))
                .force("link", d3.forceLink().distance(linkDistance).strength(.1))
                .force("charge", d3.forceManyBody().strength(-100))
                .force("center", d3.forceCenter(window.innerWidth / 2, window.innerHeight / 2))
                .force("collision", d3.forceCollide().radius(9))

            function linkDistance(d) {
                console.log('distance: ', d.distance)
                return d.distance;
            }

            initialize()

            function initialize() {

                link = linksContainer.selectAll(".link")
                    .data(graph.links)
                    .join("line")
                    .attr("class", "link")
                    .style("stroke", "black")
                    .style("stroke-width", 1)

                node = nodesContainer.selectAll(".node")
                    .data(graph.nodes, d => d.id)
                    .join("g")
                    .attr("class", "node")
                    .call(d3.drag()
                        .on("start", dragStarted)
                        .on("drag", dragged)
                        .on("end", dragEnded)
                    )
                    .on("click", addNode)

                node.selectAll("circle")
                    .data(d => [d])
                    .join("circle")
                    .attr("r", 30)
                    .style("fill", "whitesmoke")

                node.append("text")
                    .attr("dominant-baseline", "central")
                    .attr("text-anchor", "middle")
                    .attr("font-size", 15)
                    .attr("pointer-events", "none")
                    .text(function (d) {
                        return d.id
                    })

                force
                    .nodes(graph.nodes)
                    .on("tick", ticked);

                force
                    .force("link")
                    .links(graph.links)
            }

            function ticked() {
                // update link positions
                link
                    .attr("x1", function (d) {
                        return d.source.x;
                    })
                    .attr("y1", function (d) {
                        return d.source.y;
                    })
                    .attr("x2", function (d) {
                        return d.target.x;
                    })
                    .attr("y2", function (d) {
                        return d.target.y;
                    });

                // update node positions
                node
                    .attr("transform", function (d) {
                        return "translate(" + d.x + ", " + d.y + ")";
                    });
            }

            function dragStarted(event, d) {
                if (!event.active) force.alphaTarget(0.3).restart();
                d.fx = d.x;
                d.fy = d.y;

                PosX = d.x
                PosY = d.y
            }

            function dragged(event, d) {
                d.fx = event.x;
                d.fy = event.y;
            }

            function dragEnded(event, d) {
                if (!event.active) force.alphaTarget(0);
                d.fx = undefined;
                d.fy = undefined;
            }

            function addNode(event, d) {
                const nodeId = graph.nodes.length

                graph.nodes.push({id: nodeId})
                graph.links.push({source: d, target: nodeId, distance: 1})

                initialize()
            }
body {
    height: 100%;
    background: #e6e7ee;
    overflow: hidden;
    margin: 0px;
}

.faded {][1]
    opacity: 0.1;
    transition: 0.3s opacity;
}

.highlight {
    opacity: 1;
}
<!-- d3.js framework -->
<script src="https://d3js.org/d3.v6.js"></script>
<!-- fontawesome stylesheet https://fontawesome.com/ -->
<script src="https://kit.fontawesome.com/39094309d6.js" crossorigin="anonymous"></script>
<svg id="svg"></svg>


text:
Q: Manage View of a Table Row at runtime In my application i am creating and displaying a table at runtime. The table is developed in an Activity class. Everything working fine, only issue is the view of the table. There are four textviews in a row in the table. they are shown adjacently without seperation. How could i make a proper view with a definite space between textviews.
            text1.setText("24/02/2011"); //TextView text
            text2.setText("Andy");       //TextView text
            text3.setText("3");          //TextView text
            text4.setText("Repeat");     //TextView text
            tableRow.addView(text1);     //TableRow tableRow
            tableRow.addView(text2);     //TableRow tableRow
            tableRow.addView(text3);     //TableRow tableRow
            tableRow.addView(text4);     //TableRow tableRow
            dueTL.addView(tableRow);     //TableLayout dueTL

It display the data like : 24/02/2011Andy3Repeat

A: You can add weight to each TextView, also be sure that your TableView has fill_parent in its width. Also check the padding and margins of the TextViews
I hope this helps

A: If for some reason setting weights doesn't work for your situation, take a look at padding, paddingBottom, paddingLeft, paddingRight, and paddingTop in http://developer.android.com/reference/android/widget/TextView.html

A: You could either manually add a space to the strings in "setText" or you could set a right margin, if the surrounding ViewGroup supports it, on the TextViews either in XML (layout_marginRight) or via Code (LayoutParams).


text:
Q: Storing data in Excel file from an android application My application generates data and i want to share this data, like transfer to my PC and work or send it to others as excel sheet.
Can we store data from an android application to a Excel sheet programatically ? Then how do we open and Excel file and write to it ?

A: In theory, libraries like Apache POI and JExcel should work on Adroid but there are some issues with them at this point.
Only option is to generate XL that can be read by Excel. Steps are:

*

*Create an Excel file on PC with formatting that you need

*Save that file as XML, Excel will insert Tags for formatting/ formulas

*Write java code to generate similar XML file on Android

*On Android, save this XML file on SD Card

*Transfer the XML to PC and open that in Excel

A: Take a look at this tutorial, How to create file in SD-Card.


text:
Q: Inconsistent indentation: 9 spaces used for identation I tried to modify the Gitlab index.html.haml file in server. I just want to display my message instead of Default message. So I modified 14 line to following code
%i GitLab team
can add the members. Please request the team if you need.

But I get following error in production.log

I modified the space before the %i GitLab team to 8 space and tried the same thing. But I got the same issue. I tried restart and reconfigure also in the machine. But it is not worked. It is not worked even I modified the content to original old content. How can I overcome this?


text:
Q: Leveraging the wordpress API in an android reader app I'm writing an android magazine reader for a campus publication I work for. We use wordpress to publish our website, and I want to leverage the wordpress REST API to pull stories (posts) directly from the website, without publishers having to take any additional steps to publish posts on the app after publishing them on the site. I'll do this by getting JSON objects representing posts and deserializing them into POJOs of the Story class (defined in the android application), around which views will then be built dynamically.
I've just discovered the Wordpress REST API and am really excited because I think that the implementation as described above is going to be pretty simple. Are there any obvious roadblocks that I'm missing that might complicate things?
I know that the API responds with a "content" parameter that is a string containing the HTML code for the post, with references to included images/media in the appropriate places. How can I get Android to load that html and display it properly in a WebViewer?

A: If you don't want to parse the html and separately load images and other resources, simply use
loadDataWithBaseURL like so:
WebView storyView = (WebView) findViewById( .... );
String htmlToDisplay = ....;
storyView.loadDataWithBaseURL( "http://storysite.com/', htmlToDisplay, mimeType, encoding, "" );

The baseURL will be prepended to all relative partial URIs found in the document, so that the WebView can take care of loading all other assets for you.


text:
Q: Can the generalized divisor summatory function $D_z$ be expressed explicitly in terms of Zeta Zeros? Mertens function has, by residues, an explicit formula of
$M(n)=\displaystyle\sum_{\rho}\frac{x^\rho}{\rho\zeta'(\rho)}-2+\sum_{n=1}^\infty\frac{(-1)^{2 n}(2\pi)^{2n}}{(2n)! n \zeta(2n+1)x^{2n}}$
where $\rho$ are the zeros of $\zeta(s)$, as usual.
Meanwhile, if we use the following generalized identity for the number of divisors function, $d_z(n)=\displaystyle\prod_{p^\alpha | n}\frac{(z)(z+1)..(z+\alpha-1)}{\alpha!}$ (Aleksander Ivic provides this), it's not much work to see that the Moebius function $\mu(n)$ is equal to $d_{-1}(n)$, and, with $D_z(n) = \sum_{j=1}^n d_z(j)$, that $M(n) = D_{-1}(n)$.  Which is to say, we can express $D_{-1}(n)$ in terms of the zeros of the zeta function.
Here's my question: is there an explicit formula, for the more general case of $D_z(n)$ for arbitrary z, that the explicit formula for $M(n)$ is a specialization of?  Is there some way to express a general explicit formula for $D_z(n)$ in terms of zeta zeroes?  Or could there be?  Or if not, why not?

Here's motivation for this question:
I want to make a visual, intuitive argument here.  Here's a tidy way to express $D_z(n)$ for complex z.
Define
$\displaystyle P_k(n)=\sum_{j=2}^{n}\frac{\Lambda(j)}{\log j} P_{k-1}(\lfloor \frac{n}{j} \rfloor)$ with $P_0(n)=1$
where $\Lambda(j)$ is the Von Mangoldt function.  Note by inspection that $P_k(n) = 0$ if $n < 2^k$.
Then our identity for a generalized $D_z(n)$ is
$\displaystyle D_z(n) = \sum_{k=0}^{\lfloor \log_2 n \rfloor}\frac{z^k}{k!}P_k(n)$
(p.28 of P. Bateman and H. Diamond's 2004 edition of "Analytic Number
Theory – An Introductory Course" covers this general topic, though not this specific identity).
Now, use this identity to animate, in Mathematica, $\displaystyle\frac{(D_z(n)-1)}{z}$ over the range $z = -1$ to $z = 1$.
P[n_, k_] := P[n, k] = Sum[ MangoldtLambda[j]/Log[j] P[Floor[n/j], k - 1], {j, 2, n}];P[n_, 0] := 1
DD[n_, z_] := Sum[ z^k/k! P[n, k], {k, 0, Log[2, n]}]
Animate[DiscretePlot[ (DD[n, z] - 1)/z, {n, 1, 100}], {z, -1, 1, .01}]
What you'll see, if you watch this animation, is a graph of a function that starts at the function (1-Mertens Function) at z=-1, slowly transforms into the Riemann Prime Counting function right when z=0, and then finally transforms into a straight line, as f(x)=(x-1) at z=1 - all in all, a nice, gradual, fairly smooth transformation between those three important functions.
Now, we have an explicit formula in terms of zeta zeros when z=-1 (due to residues, as given above), and an explicit formula in terms of zeta zeros when z=0 (due to Riemann's original explicit formula for the Riemann Prime Counting function).  Given the relatively smooth transition in the animation, it seems very tempting to me to think that there could be an explicit formula using the zeta zeros when $-1<z<0$, connecting these two formulas, or perhaps even more...but I realize it's only an appeal to visuals, of course.
A Few More Notes
As visualized above, $\displaystyle \lim_{z \to 0}\frac{D_z(n)-1}{z} = \Pi(n)$, the Riemann Prime Counting Function.
You can show this more easily by taking $d_z(n)=\displaystyle\prod_{p^\alpha | n}\frac{(z)(z+1)..(z+\alpha-1)}{\alpha!}$ and noting that $\displaystyle \lim_{z \to 0}\frac{d_z(n)}{z} = \frac{\Lambda(n)}{\log n}$ except at 1, where the limit is infinity.
There are a bunch of interesting ways to express a generalized $D_z(n)$.  I've collected several such ways, with Mathematica demonstrations, on pages 7-11 of this non-rigorous document.

A: The short answer is that, in all likelihood, a formula of the type you seek only exists if $z$ is a negative integer.
The way to approach a question like this is to first note that $\sum_{n=1}^{\infty} \frac{d_{z}(n)}{n^{s}} = \zeta(s)^{z}$, and by Perron's inversion formula,
$$
  \sum_{n \leq x} d_{z}(n) = \frac{1}{2 \pi i} \int_{2-i \infty}^{2 + i \infty}
  \frac{\zeta(s)^{z} x^{s}}{s} \, ds.
$$
at least as long as $x$ is not an integer. The approach is then to attempt to move the contour to the left, use Cauchy's theorem and compute residues. There are a number of wrinkles, however. In fact, the formula for $z = -1$ which you quote is proven by Titchmarsh, and the reference you give states that additional assumptions are needed (the Riemann hypothesis, the simplicity of zeroes of $\zeta(s)$, and also that the limit of the partial sum of the terms involving the zeta zeroes is taken in a very specific and careful way).
I suspect it should be possible to play the same game if $z$ is another negative integer, under the same assumptions that Titchmarch used.
On the other hand if $z$ is a positive integer then $|\zeta(s)|$ will become large when ${\rm Re}(s)$ is negative, and this makes moving the contour a bad idea since the size of one of the contour integral pieces is large. This is (one the reasons) that the Dirichlet divisor problem is hard.
Now, if $z$ is not an integer, then $\zeta(s)^{z}$ isn't a meromorphic function anymore (for the same reason that $f(z) = \sqrt{z}$ isn't). This is discussed at some length in the passage you quote from Ivic, and indeed Theorem 14.9 from Ivic shows that no formula that is directly analogous to Titchmarsh's can exist for $\sum_{n \leq x} d_{z}(n)$ except in the unlikely event that all of the analytic functions $c_{1}(z), c_{2}(z), \ldots$ vanish.


text:
Q: Prove that $\det(M) = 0$ iff $f_i$ are linearly dependent, where $M_{ij}= \int f_i f_j dx$ and $f_i$ are real and continuous
Let $a < b$ be real numbers and $f_1,...,f_n:[a,b] \to \mathbb R$ continuous funtions. Define an $n$ by $n$ matrix $M = (m_{ij})_{i,j = 1,...,n}$ where
$$m_{ij} = \int_a^bf_i(x)f_j(x)dx. $$
Prove that
$$\det(M) = 0 \iff f_1,...,f_n \text{ are linearly dependent}.$$

Since the matrix $M$ is symmetric, we know that it is orthogonally diagonalizable. If $M$ is a diagonal matrix, then one of $m_{ii}$ is zero, which means that (since $f_i^2$ is nonnegative and continuous) one of $f_i$ is zero, so that $f_i$'s are linearly dependent. Conversely, if one of the $f_i$ can be expressed as a linear combination of the other, say $f_n = \sum_1^{n-1}c_kf_k$ then we may use the fact that $M$ is a diagonal to deduce algebraically that the determinant is zero.
However, I am not sure how to get from this special case to the general case. By looking at the problem when $n = 2$ it seems like Cauchy-Schwartz inequality may come up somewhere, but I am not sure how it would exactly.
I would like to know how I can solve this problem and also about what would be the motivation for someone to come up with this problem.
EDIT: Thank you for the link given by @AnneBauval. However, I found the answers on the link to be insufficient for my understanding. When we write $G = A^TA$, are we not assuming that we are simply doing the standard inner product as we compute the product $A^TA$ entry by entry? In our case of the matrix $M$ defined as above, how would a matrix that satisfy $G = A^TA$ look like? The link from @AnneBauval gave me greater sense of the problem though, and I thank her for that.

A: $M$ is the Gram matrix of $(f_1,\dots,f_n),$ i.e. $m_{i,j}=f_i\cdot f_j,$ for the inner product on $C([a,b])$ defined by
$$f\cdot g=\int_a^bf(x)g(x)\,\mathrm dx.$$
Let us now forget about $C([a,b]),$ and prove that for any family $(f_1,\dots,f_n)$ of vectors in any inner product space, its Gram matrix $M\in M_n(\Bbb R)$ is singular iff the $n$ vectors are linearly dependent.
$\Rightarrow:$ if $M$ is singular, let $v=\begin{pmatrix}a_1\\\vdots\\a_n\end{pmatrix}\in M_{n,1}(\Bbb R)$ be a non-zero vector of its kernel, i.e. $Mv=0.$ Then,
$$0=v^TMv=\sum_{i,j}a_im_{i,j}a_j=\sum_{i,j}a_i(f_i\cdot f_j)a_j=w\cdot w$$
where
$$w:=\sum_ia_if_i.$$
From $\|w\|^2=0,$ we deduce that $w=0,$ which (since $v\ne0$) proves that $f_1,\dots,f_n$ are linearly dependent.
$\Leftarrow:$ if $f_1,\dots,f_n$ are linearly dependent, then $\sum_ja_jf_j=0$ for some non-zero $v=\begin{pmatrix}a_1\\\vdots\\a_n\end{pmatrix}\in M_{n,1}(\Bbb R).$ Then, $f_i\cdot\sum_ja_jf_j=0$ for all $i,$ i.e. $Mv=0,$ which (since $v\ne0$) proves that $M$ is singular.

A: Consider an inner product space and linearly independent vectors $v_1,v_2,\ldots,v_n.$ We will show that the determinant of the Gram matrix is nonzero by induction with respect to $n.$ Assume it holds for $n-1.$ Define the vector $$w = \begin{vmatrix}\langle v_1,v_1\rangle & \langle v_1,v_2\rangle &\ldots &\langle v_1,v_n\rangle\\
\langle v_2,v_1\rangle & \langle v_2,v_2\rangle &\ldots &\langle v_2,v_n\rangle\\
\vdots & \vdots&&\vdots\\
\langle v_{n-1},v_1\rangle & \langle v_{n-1},v_2\rangle &\ldots &\langle v_{n-1},v_n\rangle\\ v_1& v_2 & \ldots& v_n
\end{vmatrix}$$ This vector is a linear combinations of the vectors $v_1,v_2,\ldots,v_n.$ Observe that $\langle v_k,w\rangle =0$ for $k=1,2,\ldots,{n-1}$ as we obtain a determinant where two rows are equal. The Gram determinant is equal $\langle v_n,w\rangle.$ If it vanishes then $w $ is orthogonal to all the vectors $v_1,v_2,\ldots,v_n.$ Hence $w$ is orthogonal to itself, i.e. $w=0.$ This means that the nontrivial linear combination of the vectors $v_2,v_2,\ldots,v_n$ is equal $0,$ a contradiction. Nontriviality of the combination follows from the fact that the coefficient of $v_n$ in this linear combination is equal to the determinant of the Gram matrix of the first $n-1$ vectors, which is nonzero by the induction hypothesis.
Remark In case the vectors $v_1,v_2,\ldots,v_n$ are linearly independent this method provides explicit construction of the orthogonal vectors showing up in the Gram-Schmidt procedure.


text:
Q: Auto-incrementing attribute with custom logic in SQLAlchemy I have a simple "Invoices" class with a "Number" attribute that has to
be assigned by the application when the user saves an invoice. There
are some constraints:
1) the application is a (thin) client-server one, so whatever
assigns the number must look out for collisions
2) Invoices has a "version" attribute too, so I can't use a simple
DBMS-level autoincrementing field
I'm trying to build this using a custom Type that would kick in every
time an invoice gets saved. Whenever process_bind_param is called with
a None value, it will call a singleton of some sort to determine the
number and avoid collisions. Is this a decent solution?
Anyway, I'm having a problem.. Here's my custom Type:
class AutoIncrement(types.TypeDecorator):
   impl = types.Unicode

   def copy(self):
       return AutoIncrement()

   def process_bind_param(self, value, dialect):
       if not value:
           # Must find next autoincrement value
           value = "1" # Test value :)
       return value

My problem right now is that when I save an Invoice and AutoIncrement
sets "1" as value for its number, the Invoice instance doesn't get
updated with the new number.. Is this expected? Am I missing
something?
Many thanks for your time!
(SQLA 0.5.3 on Python 2.6, using postgreSQL 8.3)
Edit: Michael Bayer told me that this behaviour is expected, since TypeDecorators don't deal with default values.

A: Is there any particular reason you don't just use a default= parameter in your column definition?  (This can be an arbitrary Python callable).
def generate_invoice_number():
    # special logic to generate a unique invoice number

class Invoice(DeclarativeBase):
    __tablename__ = 'invoice'
    number = Column(Integer, unique=True, default=generate_invoice_number)
    ...


text:
Q: Identifying blobs in image as that of a vehicle Any idea how I can get the smaller blobs belonging to the same vehicle count as 1 vehicle? Due to background subtraction, in the foreground mask, some of the blobs belonging to a vehicle are quite small, and hence filtering the blobs based on their size won't work.

A: Try filtering things based on colorDistance() and the comparing the mean color of the blobs in the image with the vehicle against a control image of the background without the car in it.  The SimpleCV docs have a tutorial specifically on this topic.  That said... it may not always work as expected.  Another possibility (just occurred to me) might be summing up the area of the blobs of interest and seeing if that sum is over a given thresh-hold, rather than just any one blob itself.


text:
Q: Does Amazon provide S3DistCp java api? I want to integrate s3 to hadoop file transfer in Java Code. Does Amazon provide any API for this task. I want to use S3DistCp.

A: not AFAIK, but you can use the apache one, it's in the org.apache.hadoop/hadoop-distcp module. I use it in tests (more specifically, the Hadoop azure & s3a clients use it to verify that distcp works with their object stores).

A: You can use the Java de-compiler to see the source code and the implementation by using the s3distcp.jar. This can be downloaded from this following location.
s3://elasticmapreduce/libs/s3distcp/1.latest/s3distcp.jar


text:
Q: How to prevent Quartus RTL Viewer from optimizing my Verilog code? module temp (

    input [1:0] A,
    output [1:0] O

);

    wire w0, w1;

    nand (w0, A[0], A[1]);
    nor (w1, A[0], A[1]);
    not (O[0], w0);
    not (O[1], w1);

endmodule

When I do an Analysis&Synthesis to above code, and then go for Tools->Netlist Viewers->RTL Viewer ;
I see the below one,

Now, the thing is, I have to implement a circuit with using NAND, NOR and NOT gates only, and there, I have an OR statement. So, I though I can do an OR out of NOR+NOT. But, as you see, the RTL viewer optimizes(?) my code and replaces NOR+NOT with an OR. Is there a way to prevent it doing so?
Thanks.

edit:

A: No, there isn't a way of stopping the gate reduction.
It's not optimisation, as it's an integral part of how Quartus interprets an HDL design and reduced to boolean equations during synthesis.


text:
Q: How would you compare IIS & Cassini as production servers? I have an ASP.NET website which is running currently on IIS. Now I want to move that site to run on Cassini.
What are the advantages of Cassini over IIS? What are its disadvantages?
What are your experiences using Cassini as a production web-server?

A: UltiDev Web Server Pro is a free, redistributable, light-weight web server with lots of enterprise-level feature for ASP.NET applications (from ASP.NET 1.1 to 4). Unlike Cassini, its design has nothing precluding it from serving Internet-facing applications. Created by UltiDev, the vendor of UltiDev Cassini fork, new UWS Pro is functionally closer to IIS than to Cassini. More screenshots.
.

A: Easy choice: it's simply not possible to use Cassini in production, because it's not accessible from remote machines (it only listens on localhost).

A: I would say you are better off, going with something proven to handle scaling, like mod_mono on apache if you are looking for alternative servers.
The integrated pipeline, routing, compression and caching features of iis are hard to replicate. But the app pool and failure rapid response stuff is hard to do without knowledge of the OS and the network stack at a root level.
Cassini doesn't claim to be multi threaded or handle any of the advanced e-tags or other header control issues that can be issues with iis, but are also usually set at sensible defaults in later versions of iis.
For the sake of completeness, you could do the older rails-mongrels model, spin up say 10 cassini's on ports 10100 - 10110, then use ngenx or apache to load ballance requests on those threads, and using a monitoring tool to redo requests to new threads when old ones go out to lunch and constantly be restarting 2 or so ports, because you get overloaded.

A: There is a good comparison of Cassini and IIS here at StackOverflow

A: As far as I know, you cannot use Cassini in production because it listens for localhost requests only. You will have to modify source code and recompile the webserver by yourself.
Another thing is that IIS is built on top of http.sys kernel-level library for maximum performance. I'm not familiar with the latest Cassini versions but last time I checked, it used slower managed TCP sockets.
If your website is not very popular and Cassini has all the features you need, why not... there is nothing wrong with Cassini. It's simple webserver but it's not the only alternative to IIS.
There is Abyss, UltiDev Cassini and I think a few other open-source servers with ASP.NET support.

A: There is no possible angle you can look at cassini or any of it's derivatives and consider using it as anything other than a development/testing server.


text:
Q: How to select generated element in Javascript When I click start,some choices will be displayed.
I would like to select each choice by getElementById is it possible?
How can I change my work to achieve it ?
Thanks

document.getElementById("start").addEventListener('click',function(){
  html=" ";
  for (let i=1;i<=4; i++){
    html+= "<button id='choice'>"+"choice"+i+"</button>
";
  }
  document.querySelector('.btn').innerHTML = html;
});

document.getElementById("choice").addEventListener('click',function(){
  console.log(this);
});

<button id="start">start</button>

A: You should attach the event on elements when they are present in the DOM. Also, the attribute id must be unique in a document.
You can try the following way:

document.getElementById("start").addEventListener('click',function(){
  html=" ";
  for (let i=1;i<=4; i++){
    html+= `<button id=choice${i}>choice${i}</button><br>`;
  }
  document.querySelector('.btn').innerHTML = html;

  document.querySelectorAll("[id*=choice]").forEach(function(el){
    el.addEventListener('click',function(){
      console.log(this);
    });
  });
});

<button id="start">start</button>