text:
Q: Running multiple simultaneous VNC sessions I'm working on a project for a client that wants to access some Windows-apps via my website using noVNC, that gave me an idea for setting up a server with multiple users.
I've installed TigerVNC-server on my CentOS 7 VPS, which works well when one user is connected, but when the second user connects, he/she will only get a black screen as it seems like gnome won't start for the second user.
If i, for example run the vncservice@:1 it all works fine and the user will be logged in no problem but when vncservice@:2 starts, it won't start gnome and he/she will get a black screen with only a cursor. When vncservice@:2 starts first, that user will be launched in to gnome but vncservice@:1 won't see their desktop etc. etc.
This is what my setup looks like:
[User 1 and 2 ~/.vnc/xstartup]
#!/bin/sh

unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS
/etc/X11/xinit/xinitrc
# Assume either Gnome or KDE will be started by default when installed
# We want to kill the session automatically in this case when user logs out. In case you modify
# /etc/X11/xinit/Xclients or ~/.Xclients yourself to achieve a different result, then you should
# be responsible to modify below code to avoid that your session will be automatically killed

sleep 60

if [ -e /usr/bin/gnome-session -o -e /usr/bin/startkde ]; then
    vncserver -kill $DISPLAY
    killall -u $USER
fi

[/etc/X11/xinit/xinitrc]
#!/bin/sh

# Mandatorily source xinitrc-common, which is common code shared between the
# Xsession and xinitrc scripts which has been factored out to avoid duplication
. /etc/X11/xinit/xinitrc-common

# The user may have their own clients they want to run.  If they don't,
# fall back to system defaults.
if [ -f $HOME/.Xclients ]; then
    exec $CK_XINIT_SESSION $SSH_AGENT $HOME/.Xclients || \
    exec $CK_XINIT_SESSION $SSH_AGENT $HOME/.Xclients
elif [ -f /etc/X11/xinit/Xclients ]; then
    exec $CK_XINIT_SESSION $SSH_AGENT /etc/X11/xinit/Xclients || \
    exec $CK_XINIT_SESSION $SSH_AGENT /etc/X11/xinit/Xclients
else
    # Failsafe settings.  Although we should never get here
    # (we provide fallbacks in Xclients as well) it can't hurt.
    [ -x /usr/bin/xsetroot ] && /usr/bin/xsetroot -solid '#222E45'
    [ -x /usr/bin/xclock ] && /usr/bin/xclock -geometry 100x100-5+5 &
    [ -x /usr/bin/xterm ] && xterm -geometry 80x50-50+150 &
    [ -x /usr/bin/twm ] && /usr/bin/twm
fi

[vncserver@:1 and vncserver@:2,  is replace with the actual username]
[Unit]
Description=Remote desktop service (VNC)
After=syslog.target network.target

[Service]
Type=forking
User=<USERNAME>
Group=<USERNAME>

ExecStartPre=-/usr/bin/vncserver -kill %i
ExecStart=/usr/bin/vncserver %i
PIDFile=/home/<USERNAME>/.vnc/%H%i.pid
ExecStop=-/usr/bin/vncserver -kill %i

[Install]
WantedBy=multi-user.target

[Second user VNC log]
[root@.... ~]# systemctl status vncserver@:5
● vncserver@:5.service - Remote desktop service (VNC)
   Loaded: loaded (/etc/systemd/system/vncserver@:5.service; disabled; vendor preset: disabled)
   Active: active (running) since za 2021-07-24 19:04:54 CEST; 59s ago
  Process: 25990 ExecStart=/usr/bin/vncserver %i (code=exited, status=0/SUCCESS)
  Process: 25981 ExecStartPre=/usr/bin/vncserver -kill %i (code=exited, status=2)
 Main PID: 25997 (Xvnc)
   CGroup: /system.slice/system-vncserver.slice/vncserver@:5.service
           ├─25997 /usr/bin/Xvnc :5 -auth /home/AHtYezzDXegQScyu/.Xauthority -desktop <HOSTNAME>:5 (AHtYezzDXegQScyu) -fp catalogue:/etc/X11/fontpath.d -geometry 1024x768 -pn -rfbauth /home/AHtYezzDXegQScyu/.vnc/passwd -rfbport 5905 -rfbwait 30000
           ├─26006 /bin/sh /home/AHtYezzDXegQScyu/.vnc/xstartup
           ├─26018 dbus-launch --sh-syntax --exit-with-session
           ├─26019 /usr/bin/dbus-daemon --fork --print-pid 5 --print-address 7 --session
           ├─26053 /usr/libexec/imsettings-daemon
           ├─26057 /usr/libexec/gvfsd
           ├─26062 /usr/libexec/gvfsd-fuse /home/AHtYezzDXegQScyu/.gvfs -f -o big_writes
           ├─26126 /usr/libexec/at-spi-bus-launcher
           ├─26131 /usr/bin/dbus-daemon --config-file=/usr/share/defaults/at-spi2/accessibility.conf --nofork --print-address 3
           ├─26135 /usr/libexec/at-spi2-registryd --use-gnome-session
           ├─26158 /usr/bin/gnome-keyring-daemon --start --components=ssh
           ├─26241 /usr/libexec/xdg-permission-store
           ├─26246 /usr/libexec/gnome-shell-calendar-server
           ├─26251 /usr/libexec/evolution-source-registry
           ├─26258 /usr/libexec/goa-daemon
           ├─26269 /usr/libexec/goa-identity-service
           ├─26275 /usr/libexec/mission-control-5
           ├─26286 /usr/libexec/gvfs-udisks2-volume-monitor
           ├─26293 /usr/libexec/gvfs-mtp-volume-monitor
           ├─26299 /usr/libexec/gvfs-goa-volume-monitor
           ├─26305 /usr/libexec/gvfs-gphoto2-volume-monitor
           ├─26310 /usr/bin/dbus-daemon --fork --print-pid 5 --print-address 7 --session
           ├─26311 /usr/libexec/gvfs-afc-volume-monitor
           ├─26411 /usr/libexec/gsd-print-notifications
           ├─26413 /usr/libexec/gsd-rfkill
           ├─26418 /usr/libexec/gsd-screensaver-proxy
           ├─26454 sleep 60
           └─26458 /usr/libexec/evolution-calendar-factory

jul 24 19:05:22 <HOSTNAME> gnome-session-binary[26007]: WARNING: Failed to start app: Unable to start application: Failed to fork (Resource temporarily unavailable)
jul 24 19:05:22 <HOSTNAME> gsd-print-notif[26411]: Could not execute system-config-printer-udev handler: Failed to fork (Resource temporarily unavailable)
jul 24 19:05:22 <HOSTNAME> gnome-session-binary[26007]: WARNING: Application 'org.gnome.SettingsDaemon.Power.desktop' killed by signal 5
jul 24 19:05:22 <HOSTNAME> gnome-session[26007]: gnome-session-binary[26007]: WARNING: Application 'org.gnome.SettingsDaemon.Power.desktop' killed by signal 5
jul 24 19:05:22 <HOSTNAME> gnome-session-binary[26007]: GLib-WARNING: GError set over the top of a previous GError or uninitialized memory.
                                                                       This indicates a bug in someone's code. You must ensure an error is NULL before it's set.
                                                                       The overwriting error message was: Unable to start application: Failed to fork (Resource temporarily unavailable)...
jul 24 19:05:22 <HOSTNAME> gnome-session[26007]: gnome-session-binary[26007]: GLib-WARNING: GError set over the top of a previous GError or uninitialized memory.
jul 24 19:05:22 <HOSTNAME> gnome-session[26007]: This indicates a bug in someone's code. You must ensure an error is NULL before it's set.
jul 24 19:05:22 <HOSTNAME> gnome-session[26007]: The overwriting error message was: Unable to start application: Failed to fork (Resource temporarily unavailable)
jul 24 19:05:22 <HOSTNAME> evolution-calen[26465]: creating thread 'gdbus': Error creating thread: Resource temporarily unavailable
jul 24 19:05:47 <HOSTNAME> gnome-shell-cal[26246]: Could not load source 'birthdays': Timeout was reached

[/etc/X11/xinit/Xclients]
#!/bin/bash

GSESSION="$(type -p gnome-session)"
STARTKDE="$(type -p startkde)"

# check to see if the user has a preferred desktop
PREFERRED=
if [ -f /etc/sysconfig/desktop ]; then
    . /etc/sysconfig/desktop
    if [ "$DESKTOP" = "GNOME" ]; then
        PREFERRED="$GSESSION"
    elif [ "$DESKTOP" = "KDE" ]; then
        PREFERRED="$STARTKDE"
    fi
fi

if [ -n "$PREFERRED" ]; then
    exec "$PREFERRED"
fi

# now if we can reach here, either no desktop file was present,
# or the desktop requested is not installed.

if [ -n "$GSESSION" -a -f /usr/share/xsessions/gnome.desktop ]; then
    # by default, we run GNOME.
    exec "$GSESSION" --session=gnome
elif [ -n "$STARTKDE" ]; then
    # if GNOME isn't installed, try KDE.
    exec "$STARTKDE"
fi

# We should also support /etc/X11/xinit/Xclients.d scripts
XCLIENTS_D=/etc/X11/xinit/Xclients.d
if [ "$#" -eq 1 ] && [ -x "$XCLIENTS_D/Xclients.$1.sh" ]; then
    exec -l $SHELL -c "$SSH_AGENT $XCLIENTS_D/Xclients.$1.sh"
fi

# Failsafe.

# these files are left sitting around by TheNextLevel.
rm -f $HOME/Xrootenv.0

# Argh! Nothing good is installed. Fall back to twm
{
    # gosh, neither fvwm95 nor fvwm2 is available;
    # fall back to failsafe settings
    [ -x /usr/bin/xsetroot ] && /usr/bin/xsetroot -solid '#222E45'

    if [ -x /usr/bin/xclock ] ; then
        /usr/bin/xclock -geometry 100x100-5+5 &
    fi
    if [ -x /usr/bin/xterm ] ; then
        /usr/bin/xterm -geometry 80x50-50+150 &
    fi
    if [ -x /usr/bin/firefox -a -f /usr/share/doc/HTML/index.html ]; then
        /usr/bin/firefox /usr/share/doc/HTML/index.html &
    fi
    if [ -x /usr/bin/twm ] ; then
        exec /usr/bin/twm
    fi
}

The stupid thing is, after trying to start the second vncserver about 50 times, it usually works one time, when i stop and start the service again it won't show anything again, except for a mouse cursor.
There is plenty of free memory left (about 5 gigs), there also is plenty of storage space left (about 100 gigs). When i edit my ~/.vnc/xstartup file to include only a file manager, it works fine everytime, trying to run a session for multiple users seems to be the problem.
Thanks for reading trough all of this, i've already lost countless hours trying to debug this without any (major) improvements.
UPDATE 1:
After many hours of more tinkering, i still didn't get gnome working. Desperate times call for desperate measures so i just ended up installing Xfce and made it prettier with a nice theme and a icon pack. It just worked after i installed it. I removed all gnome references from the xstartup files and added startxfce4.


text:
Q: Ambari Server fails to start because of missing stack definitions II successfully built the Apache Ambari from git repository, installed and configured the ambari-server. But it just won't start. In the log is the following error:
 Error injecting constructor, org.apache.ambari.server.AmbariException: Unable to

find stack definitions under stackRoot = /var/lib/ambari-server/resources/stacks
  at org.apache.ambari.server.stack.StackManager.<init>(StackManager.java:149)
  while locating org.apache.ambari.server.stack.StackManager annotated with @com.google.inject.internal.UniqueAnnotations$Internal(value=1)
  at org.apache.ambari.server.api.services.AmbariMetaInfo.init(AmbariMetaInfo.java:272)
  at org.apache.ambari.server.api.services.AmbariMetaInfo.class(AmbariMetaInfo.java:131)
  while locating org.apache.ambari.server.api.services.AmbariMetaInfo
    for field at org.apache.ambari.server.controller.AmbariServer.ambariMetaInfo(AmbariServer.java:180)
  at org.apache.ambari.server.controller.AmbariServer.class(AmbariServer.java:180)
  while locating org.apache.ambari.server.controller.AmbariServer

What could be the problem?

A: I've got it running now at least ambari server, but not the stack.
Thank you for the hint.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to handle different messages (from content script) in different functions of background script? The content script of my chrome extension has two event listener functions. The two functions sends different variable as message. So if the background script wants to distinguish between these events / variables how do I do this?
Can I have multiple functions in background scripts to listen to particular type of events only? If yes, how can I achieve this.
Currently I am sending an id 1 and 2 (along with the message to background script) from each of the function and using if-else to distinguish which message is from which function. I don't think this is a very elegant solution.
Content Script:
document.getElementById("myBTN").addEventListener('click', wordSelected) {
// code
chrome.runtime.sendMessage(var1, (response) => { // id = 1
// code
});
}

window.addEventListener('change', (e)=> {
// code
chrome.runtime.sendMessage(var2, (response) => { // id = 2
// code
});
}

Background Script:
chrome.runtime.onMessage.addListener(receiver);
function receiver(request, sender, sendResponse) {
if (request.id == 1) {
// code
}
else if (request.id == 2) {
// code
}

A: Sending an id or cmd or action or method property along with the actual value is the standard solution, there is no better one conceptually. You can use id: 'clicked' and id: 'changed' instead of numeric indexes.
As far as the cosmetic "solutions" go, you can use Proxy API to wrap chrome.runtime.sendMessage, for example as HQ ("headquarters") object:
async function queryHQ() {
  if (await HQ.test(1, 2, 3) === 123) {
    console.log('ok!');
  } else {
    console.log(await HQ.download());
  }
}

For this to work, first let's define HQ in the content script:
const HQ = new Proxy({}, {
  get: (_, cmd) =>
    (...args) =>
      new Promise((resolve, reject) =>
        chrome.runtime.sendMessage({cmd, args}, r =>
          !r || 'error' in r ? reject(r && r.error) : resolve(r.data)))
});

In the background script define a command map:
const handlers = {

  test(a, b, c) {
    console.log(a, b, c);
    return 123;
  },

  async download() {
    return (await fetch(this.url)).text();
  },

};

...and a listener:
const wrapError = error => ({error: error && error.message || `${error}`});

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  const {cmd, args} = msg;
  const fn = handlers[cmd];
  try {
    const res = fn.apply(sender, args);
    if (typeof res?.then === 'function') {
      res.then(data => ({data}), wrapError)
        .then(sendResponse);
      return true;
    } else if (res !== undefined) {
      sendResponse({data: res});
    }
  } catch (error) {
    sendResponse(wrapError);
  }
});

There are libraries for chrome extensions that implement a similar approach.


text:
Q: How is this logic of moderation conducive to a growing learning environment? How is this logic of moderation conducive to a growing learning environment (in the context that Meta is a general platform for building Stack Exchange as opposed to asking for help in another community)?

*

*Downvoting because a question was previously asked

*Downvoting because of incorrect grammar, punctuation, typo, etc. (as some are not native-English speakers.)

*Downvoting for not formatting

*Any of these upvoted for the same/opposite reason

None of these reasons adequately vote on the policy/feature in question. It only addresses the questions structure which is why moderators have a hold/merge/duplicate option.
Why are we voting on Meta in the first place, the policy or the condition of the question?
Is it because we like/dislike a policy/feature or because we like/dislike the capitalization (in short).
THIS question is not about the downvoting policy. This is about alternative ways to moderate a voting policy. I only added this as an example:
My experience is that actual questions are avoided being answered in lieu of being downvoted purely because of a duplicate. If a user doesn't have enough reputation points he/she can not cast a vote for a policy he/she agrees with thus his/her only way to 'vote' is to express it in a new (duplicate) question.
Not only reminded several times I should not post a new question, it still doesn't leave me with an alternative option. Catch-22.
The original question at hand was about "Should a person be required to leave a comment when down voting?" and my question can be found here:
https://meta.stackexchange.com/questions/243608/down-voting-policy-what-is-the-communities-idea-on-this-feature
The same question by another poster:
Encouraging people to explain downvotes
Yes, I get that the question was asked before. I'll say it again another way (seeing as it's the only response anyone has given), I understand that I should not ask a duplicate question.
I think I make many valid arguments over the course of these comments and I think they all have been poorly addressed or better yet: not addressed at all.
In my opinion, Meta is the most useless of all Stack Exchange when it should be the opposite. I'm only expressing how I believe Meta could be better. It should be.
If anyone can actually post a real answer, it would be greatly appreciated.
Below are the comments below if you don't want to navigate to the original post:
Note my comments and the actual responses. (Yes, I actually copy and pasted this to save it from the 'extended discussion' rule and 'comment trimming'.)

Downvotes mostly happens on questions that are not useful and don't
  show research effort (because they have been asked before) –  rene 16
  hours ago
Maybe consider improving the search strings. I didn't see these posts
  at all. Maybe then people wouldn't duplicate as many questions then.
  :) –  David 16 hours ago
Even if I visit the questions that are tagged down-votes I see
  relevant posts. Maybe consider reading up on some faq's ;) –  rene 15
  hours ago
Maybe. But most posts I see here (on Meta) are down voted. It can't be
  that everyone is because of a duplicate? If the question has been
  asked many times then it must be a good idea. My question was down
  voted but the same question was up voted over 550 times. How many
  votes does it take for a policy to be made? –  David 15 hours ago
@David This idea gets proposed several times a day and rejected
  several times a day. The reason why they get downvoted is that
  everyone is tired of seeing the same proposal over and over again and
  also for the lack of research effort. Your best chance of getting this
  policy implemented is to become majority shareholder of Stack
  Exchange. –  Mysticial 15 hours ago
The only people I really see down voting (on Meta) are the moderators.
  So a good idea is down voted simply because it was asked previously?
  Like the link in the first comment, upvoted. So are you down voting
  the question itself or the policy? This is what I don't understand. –
  David 15 hours ago
Also, why have a voting policy if I have to be a shareholder? If we
  are voting for features it doesn't make it very democratic. Don't get
  me wrong, I like Stack Exchange but voting doesn't seem helpful in this
  case either. –  David 15 hours ago
@David You completely missed the point of my comment. I'm saying that
  the policy you're proposing (mandatory comment for downvoting) has
  been rejected by the company and will never be implemented. One way
  you can get it implemented is to buy Stack Exchange. Then you can do
  whatever you want with it. –  Mysticial 15 hours ago
Now it sounds cleaner (still not democratic to the voters). Your
  'reason' before was "everyone is tired of seeing the same proposal
  over and over again and also the lack of research effort" Leaving me
  to think it's just a sort of carelessness (on both parts). I don't
  want to buy Stack Exchange, I don't like it that much. I missed the
  point only because you failed to state the actual reason. I'll leave
  it at that. Meta doesn't seem very interested in much anyway, in my
  opinion. –  David 15 hours ago
@David ordinary (non-moderating) members like me also downvote this
  kind of request - as I have seen it many times over, heard the same
  arguments over and over. It boils down to the fact that no one can
  force anyone to write a coherent comment explaining the downvote. –
  Sabre Tooth 10 hours ago
-1, asdfghjkklaihwbdnmfowg –  Doorknob 1 hour ago
Maybe I am failing to understand something. I get the fact that there
  should technically be only one question/answer (it's more apparent in
  other communities but often don't see the question down voted - only
  merged/moved/held) I would think Meta is about the development of the
  site and would less likely down vote something because it was simply
  asked before. It doesn't have anything to do with the policy in
  question. In fact, one post similar to mine has over 550 vote ups
  (quite a number) and the fact that people are still 'many times over'
  asking for it seems a good reason to consider it. –  David 1 hour ago
and then there are snide/useless comments like doorknob's comment
  which should be down voted but aren't. You can down vote a question on
  the basis it was asked before and leave snide comments that can't be
  down voted. I'm not sure how this leads to a learning environment in
  this case. –  David 1 hour ago
and also, I can't even vote up the original question because I don't
  have enough rep. It only leaves me the option to ask a new question as
  a way to cast my vote. –  David 1 hour ago

A:
How is this logic of moderation condusive to a growing learning environment?

Ah. I think I see where you are going wrong. It is in this bit: "a growing learning environment".
That's not what Stack Exchange is about. It is about building a compendium of great questions and answers - questions about specific issues and answers to them.
It is not a learning environment. It never was. If it were, you would see tutorials, recommendations and more here. You don't see them as what we are looking for is not to educate people - it is to give them direct answers to their specific questions.

There is also a certain naive notion there that in a learning environment moderation is not required - of course it is. In a school, disruptive students are sent to the head teacher, do they not? And if you tell me that learning environments don't have disruptive people, you must have been in different ones than I.

I will not rehash the reasons for why we don't require downvoters to explain themselves (unless you ask me to).


text:
Q: How do I use the vxWorks debug agent to perform pre-kernel debugging? The vxWorks documentation states:

The WDB agent itself is independent of the target operating system: it
  attaches to run-time OS services through a virtual-function run-time
  interface. The WDB agent can execute before VxWorks is running (as in
  the early stages of porting a BSP to a new board)."

How can I use the debug agent before the vxWorks kernel is running?

A: First, in order to be able to use the agent to perform pre-kernel debugging, you must have a serial port available for debugging. This serial port has to be initialized and functional as it will be the debug channel.
There is a limitation on how early you can start debugging.  WDB based debugging will start after the first hardware initialization function runs (sysHwInit) and before the kernel initialization proper (kernelInit).
Depending on the version of vxWorks being used, there are different ways to achieve this result.
Workbench-based vxWorks builds
In the kernel configuration tool, you must select the following components:

*

*WDB serial connection

*WDB system debugging

*WDB pre kernel system initialization

Depending on the order you select components, you might get complaints from workbench because some components are mutually exclusive (you can't have WDB END driver with pre-kernel debugging).  The order above should be ok.
Command-line builds
Edit the config.h file, and select the following options:

#define WDB_INIT        WDB_PRE_KERNEL_INIT
#define WDB_COMM_TYPE   WDB_COMM_SERIAL
#define WDB_MODE        WDB_MODE_SYSTEM

When vxWorks is compiled with those options, it will perform perform the first phase of hardware initialization and then suspend, waiting for the debug agent running on the host to connect to the target.
At that point, you can perform debugging, single step, etc...


text:
Q: Accessing files in a project that is on the build path of another I'm working on a framework-type project in Eclipse, that has a res folder attached with, as you guessed Resources inside of it. At the moment, they are crucial text-files that are to be read.
I also have a main test rig that is apart of it's own Eclipse project, as I plan to expand it in the future. This test rig has included the framework project on it's Build Path, so I can access classes from the framework as they are added.
But this is where my problems lie: If I want to import a class, that works fine. If I want to access a file through an InputStream, or Reader, it breaks. I know this is because the files included from the secondary project aren't placed inside the test rigs bin folder, rather they reside in their own bin in the other project.
Is there a way I can get my main project to access resources from the other without having to do ../../ trickery in my file paths? I plan on making this a real thing and don't want file paths doing things like that.

A: In eclipse do this,
Build Path ---> Configure Path ----> Click Project Tab ---> Add the project.

Also, you can package the other project in a jar and import it as an external jar.


text:
Q: Motion doesn't detected my webcam : UNABLE TO OPEN VIDEO DEVICE I would use a USB webcam with Motion software, installed in Ubuntu on my Windows PC (WSL2 ) But when I started Motion as a service and i check on browser at the address [LOCALHOLST:port 8080 or 8081 ] it appears the Motion interface but never has been detected my webcam. Always It is showed a gray screen, for the MyCam1 option, with written at the top on the left "UNABLE TO OPEN VIDEO DEVICE".
I tried many types of configurations in the camera1-dist.conf and motion.conf files, but unfortunately  they still doesn't work
Someone who could suggest me what type of configurations and in wich file, do I have to use to detected a USB webcam with Motion software ?
Thank you in advance.
Hi, many thanks your indications has been very useful!
I have followed all the steps and I have attached the webcam to my Ubuntu distribution and now Ubuntu 'lsusb' comand gives the following output
root@LAPTOP-5OFK2AK7:/home/daniele# lsusb
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 002: ID 3443:950a SHENZHEN AONI ELECTRONIC CO.,LTD NexiGo N950P 4K Webcam
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Unfortunately it still doesn't work..Motion still showes a grey screen and the UNABLE TO OPEN VIDEO DEVICE..
I think now the problem is in the camera1-dist.conf file.
I'd like to set the webcam in localhost:8080 (port) or ( 8081 ) but i don't understand, it still doesn't work what and where I have to write in this camera1-dist.conf file
This config file was generated by motion 4.2.2
###########################################################
Configuration options specific to camera 1
############################################################
User defined name for the camera.
camera_name MyCam1
Numeric identifier for the camera.
camera_id 101
The full URL of the network camera stream.
netcam_url http://127.0.0.1:8080
Image width in pixels.
width 1280
Image height in pixels.
height 720
Text to be overlayed in the lower left corner of images
text_left CAMERA 1
File name(without extension) for movies relative to target directory
movie_filename CAM01_%t-%v-%Y%m%d%H%M%S

A: Because you are using WSL2, the host OS (i.e. Windows) is currently managing the webcam with its own drivers.
To allow a program running within the WSL2 instance to access an USB device like a webcam, you must tell Windows to turn over the control of that USB device to WSL2.
Source: https://devblogs.microsoft.com/commandline/connecting-usb-devices-to-wsl/
You'll need WSL2 with Linux kernel version 5.10.60.1 or later.
You'll also need to have a recent version of usbipd-win installed in Windows. You can find it here.
Within the WSL2, you'll need to install the USB/IP user-space tools and a database of USB hardware identifiers. On Ubuntu 20.04 LTS, this would be:
sudo apt install linux-tools-5.4.0-77-generic hwdata
sudo update-alternatives --install /usr/local/bin/usbip usbip /usr/lib/linux-tools/5.4.0-77-generic/usbip 20

Note that the 5.4.0-77-generic part may vary if you are using a different distribution or kernel version.
To see the available USB devices and their bus IDs, open a command prompt as Administrator and enter this command:
usbipd wsl list

Find the bus ID of the USB device you wish to use within WSL2, and enter this command in the Administrator command prompt:
usbipd wsl attach --busid <bus ID>

This will apparently cause the WSL to prompt for a password, to run a sudo command. After this, the USB device will be visible in the WSL2 lsusb output, and available to the WSL2 applications (and, as a consequence, not available to native Windows applications).
Once you're done using the device in WSL2, you can either physically unplug it, or return it to Windows by running this command in the administrator command prompt:
usbipd wsl detach --busid <bus ID>


text:
Q: Zerar Page a cada click
Tenho na figura acima este UserForm pequeno com três pages.
Na primeira page, ao clicar no botão Habilitar, é inserido a próxima data com o TextBox Data como False, para o usuário não alterar.
O botão Habilitar habilita também o TextBox Previsto e os botões Inserir e Limpar.
Ao clicar na segunda page, tenho outra configuração, claro, e posso inserir dados atualizados.
Ao clicar novamente na primeira page, caso o usuário não tenha tomada nenhuma ação ao clicar no botão Habilitar, gostaria que a page volte ao seu estado original.
Estou utilizando este código, e gostaria de saber sé é realmente desta forma.
Vou utilizar para as três pages.
Private Sub MultiPage1_Click(ByVal Index As Long)
    With Me.MultiPage1
        If .Value = 0 Then Call Me.RestauraControles0
        If .Value = 1 Then Call Me.RestauraControles1
    End With
End Sub

Me.RestauraControles0 limpa tudo e deixa habilitado somente o botão Habilitar.

A: O código funciona da maneira que você está realizando, mas se quiser algo mais genérico crie um Módulo de Classe ou faça da seguinte maneira:
Como não sei como está toda estrutura do seu formulário e o que realmente deseja da página 2, este é um exemplo para aprender a realizar loops nos controles do formulário e generalizar algumas tarefas que podem funcionar em todas as páginas.
Código
Option Explicit
Private Sub MultiPage1_Change()
    Dim controle As Control
    Dim pagina_atual As Long
    Dim tudo_vazio As Boolean
    tudo_vazio = True
    With Me.MultiPage1
        pagina_atual = .Value
        For Each controle In .Pages(pagina_atual).Controls
            If TypeName(controle) = "TextBox" Then
                If Trim(controle.Value) <> "" Then
                    'Debug.Print controle.Name
                    tudo_vazio = False
                    Exit For
                End If
            End If
        Next controle
        If tudo_vazio Then
            For Each controle In .Pages(pagina_atual).Controls
                If TypeName(controle) = "CommandButton" Then
                    'Debug.Print controle.Name
                    If Not Trim(controle.Name) Like "*habilitar*" Then
                        controle.Enabled = False
                    End If
                End If
            Next controle
        End If
    End With
End Sub

Explicação
Em que realiza o loop nos controles de formulário da página atual e verifica se não há Caixas de Textos vazias.
Página Atual
O código pagina_atual = Me.MultiPage1.Value retorna o valor da página da multipágina selecionada.
Loop nos controles
For Each controle In Me.MultiPage1.Pages(pagina_atual).Controls
Next controle

Realiza o loop em todos os controles da página da multipágina selecionada.
Verificar se é caixa de texto
If TypeName(controle) = "TextBox" Then
End If

Verifica se o controle é uma caixa de texto.
Verificar se algo foi escrito na Caixa de Texto
If Trim(controle.Value) <> "" Then
End If

Verifica se o valor da caixa de texto é diferente de vazio.
Caso não seja vazio
tudo_vazio = False
Exit For

Caso o controle não esteja vazio, ou seja, com algum valor. Altera a flag tudo_vazio para False e sai do loop.
Verifica a flag tudo_vazio
If tudo_vazio Then
End If

Caso tudo_vazio seja verdadeiro, continua com o código.
Loop controles e verificação botão
Da mesma forma que anteriormente, o loop nos controles é relizado e é verificado se é Botão de Comando.
Verifica Nome do Botão de Comando
Como os Text_Box estão todos vazios, quer dizer que não houve alteração. Então todos os botões que não contenham a palavra habilitar no nome serão desabilitadas com controle.Enabled = False
If Not Trim(controle.Name) Like "*habilitar*" Then
End If


text:
Q: How to replace --cpus-per-proc with --map-by in OpenMPI I need to update some old codes to work with the most recent version of OpenMPI, but I'm very confused by the new --map-by system. In particular, I'm not sure how to replace --cpus-per-proc N.
Several websites have suggested using --map-by node:pe=N, but when I tried this it gives me a different result.
The original command is:
mpirun -np 3 --report-bindings --bind-to-core --cpus-per-proc 3 ./test.sh

Which gives:
[B/B/B/././././.] [./././././././.] [./././././././.] [./././././././.]
[./././././././.] [B/B/B/././././.] [./././././././.] [./././././././.]
[./././././././.] [./././././././.] [B/B/B/././././.] [./././././././.]

However, when I use the command:
mpirun -np 3 --report-bindings --bind-to core --map-by node:pe=3 ./test.sh

The output is:
[B/B/B/././././.] [./././././././.] [./././././././.] [./././././././.]
[./././B/B/B/./.] [./././././././.] [./././././././.] [./././././././.]
[././././././B/B] [B/././././././.] [./././././././.] [./././././././.]

Could someone please explain how to use the --map-by option?

A: To spread four MPI processes over four CPU sockets and have each process bound to three cores of the corresponding socket use:
-n 4 --map-by socket:pe=3 --bind-to core


text:
Q: UiKit Grid, Margin and Cover not working on html is loaded via ajax I am using uikit for my project.
I am loading a html content into a webpage via ajax using the code below. The page is loaded when a select option is selected:
$('.myselect').change(function(){
  if($(this).val() == '1'){
    $('#ajax-content').load('http://localhost/sites/mysite/items.html');
  }
});

The items.html contain the code below:

        <canvas width="400" height="200"></canvas>

        <canvas width="400" height="200"></canvas>

        <canvas width="400" height="200"></canvas>

However, when loaded, the uk-grid, uk-cover and uk-margin does not work properly as margin and column classes (e.g. uk-first-column) are not automatically added.
Is there a way to ensure these are initialized after ajax load?

A: call following method right after ajax html loaded, updated the codeblock
$('.myselect').change(function(){
  if($(this).val() == '1'){
    $('#ajax-content').load('http://localhost/sites/mysite/items.html', function(responseTxt, statusTxt, xhr){
     UIkit.update(element = document.body, type = 'update');
    });
  }
});


text:
Q: Expressions of multiplication
*

*Five times three equals 15.

*Five multiplied by three equals 15.

As I know, multiplication is an operation that consists of calculating the result of adding up the multiplicand as many times as indicated by the multiplier.
So in sentence(1), the multiplicand is 3 and the multiplier 5.
in sentence(2), the multiplicand is 5 and the multiplier 3.
Mathematically speaking, although the result is the same, the expressions are basically different.  Do I get it right? Thank you.


text:
Q: Best Swift way to write Dictionary of String to Country I want my Swift class FinderForCountry to find the Country with the specified name.
The code should also remember any countries (by name) that have already been found.
My existing Swift class has a [String: Country] variable, and a method findCountry() that takes both a String and a function that takes a Country.
public
class FinderForCountry {
    private
    var mapOfStringToCountry = [String: Country]()

    public
    func findCountry(from string: String, _ functionThatTakesCountry: @escaping (Country) -> Void) {
        if let country = mapOfStringToCountry[string] {
            functionThatTakesCountry(country)
        } else {
            DispatchQueue.main.async {
                let country = Country(string)
                self.mapOfStringToCountry[string] = country
                functionThatTakesCountry(country)
            }
        }
    }
}

Is this the best way to write the code, or is there a better way?  For example:
public
class FinderForCountry {
    private
    var mapOfStringToCountry = [String: Country]()

    public
    func findCountry(from string: String, _ functionThatTakesCountry: @escaping (Country) -> Void) {
        DispatchQueue.main.async {
            if let country = self.mapOfStringToCountry[string] {
                functionThatTakesCountry(country)
            } else {
                let country = Country(string)
                self.mapOfStringToCountry[string] = country
                functionThatTakesCountry(country)
            }
        }
    }
}

Many thanks.

A: Yes, there is indeed a better way.
The escaping completion handler and dispatching the code to the main thread make no sense as there is nothing which is executed asynchronously.
Just return the country.
public class FinderForCountry {

    private var mapOfStringToCountry = [String: Country]()

    public func findCountry(from string: String) -> Country
    {
        if let country = self.mapOfStringToCountry[string] {
            return country
        } else {
            let country = Country(string)
            self.mapOfStringToCountry[string] = country
            return country
        }
    }
}


text:
Q: Understanding this Linear Algebra Theorem Let $U$ be a self-adjoint operator on a finite-dimensional inner product space $V$. If <$x, U(x)$> = $0$ for all $x \in V$, then $U = T_0$.
What is $T_0$ in this case? Thank you.

A: $T_0$ here is the $0$-map.  That is, if $\langle x,Ux \rangle = 0$ for all $x$ (in a real vector space) and $U$ is self-adjoint, then we must have $U = 0$.
Notably: over a complex vector space (with a Hermitian inner product), we need not assume that $U$ is self-adjoint.  Also, the theorem still holds for infinite dimensional spaces.


text:
Q: Correlate data from two dataframes into one, retaining original ones' info I must transform information from two data frames into a matrix which is very specifically designed for my further analysis. I will start by introducing a toy example of the type of data I am working with.
Game1 <- structure(list(Score1 = c(5, 9), Score2 = c(4.8, 12.8), Score3 = c(7.22,
2.3), Class = structure(2:1, .Label = c("Dwarf", "Paladin"), class = "factor"),
    Race = structure(1:2, .Label = c("Dwarf,", "Elf"), class = "factor")), row.names = c("Stan",
"Kyle"), class = "data.frame")

Game2 <- structure(list(Score1 = c(3, 8.1), Score2 = c(6.3, 6.6), Score3 = c(1.2,
10.3), Class = structure(2:1, .Label = c("Rouge", "Wizard"), class = "factor"),
    Race = structure(2:1, .Label = c("Gnome", "Human,"), class = "factor")), row.names = c("Cartman",
"Kenny"), class = "data.frame")

I would like to perform a correlation of the scores for the different players, the ideal would be an average pearsons correlation. I would like to retain certain residual features from the original two data frames, which is shown below.
The output I wish from this is:
             Correlation Game1_Class Game1_Race Game2_Class Game2_Race

Stan:Cartman   -0.815    Paladin     Dwarf      Wizard      Human
Kyle:Cartman    0.942    Fighter     Elf        Wizard      Human
Stan:Kenny      0.947    Wizard      Human      Ranger      Gnome
Kyle:Kenny     -0.998    Rouge       Gnome      Ranger      Gnome

I've used a generic coefficient correlation to work out the correlations, I would prefer to use pearsons or spearman.
The number of rows in each data frame (in my real data) are vastly different.

A: you can define a customized function that creates such table
name_combn <- expand.grid(rownames(Game1), rownames(Game2),stringsAsFactors = FALSE)

cor_table <- function(names,df1, df2){
   n1 <- as.character(names[1])
   n2 <- as.character(names[2])
   # 1:3 are the col. positions with numeric scores:
   r <- cor(as.numeric(df1[n1, 1:3]),as.numeric(df2[n2, 1:3]))
  data.frame(names = paste(n1,":",n2, sep = ""),cor =r,
             df1[n1, -c(1:3)],
             df2[n2, -c(1:3)], row.names = "")
}

df <- do.call(rbind,apply(name_combn, 1, cor_table, df1 = Game1, df2 = Game2))

 #  names         cor         Class   Race Class.1 Race.1
 #  Stan:Cartman -0.8154535   Paladin Dwarf  Wizard Human
 #  Kyle:Cartman  0.9472246   Dwarf   Elf    Wizard Human
 #  Stan:Kenny    0.9426604   Paladin Dwarf  Rouge  Gnome
 #  Kyle:Kenny   -0.9987835   Dwarf   Elf    Rouge  Gnome


text:
Q: Unable to view page in browser from Views I've created the following folder and page in my MVC Core application:
Views->Adminstration->CreateRole.cshtml
I'm not bale to view the page in my browser after rebuilding it.
This localhost page can't be foundNo webpage was found for the web address: https://localhost:44310/Administration/createrole.cshtml
HTTP ERROR 404

could it be something in my routing or what could be the problem ?
startup.cs
 public void Configure(IApplicationBuilder app,
            IHostingEnvironment env, ApplicationDbContext context, RoleManager<ApplicationRole> roleManager, UserManager<ApplicationUser> userManager)
        {
            //
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            SeedIdentity.Initialize(context, userManager, roleManager).Wait();
        }

The AdministrationController below:
 public class AdministrationController : Controller
    {
        //private readonly RoleManager<IdentityRole> roleManager;
        RoleManager<IdentityRole> roleManager;
        UserManager<IdentityUser> userManager;
        public AdministrationController(RoleManager<IdentityRole> roleManager, UserManager<IdentityUser> userManager)
        {
            //_roleManager = roleManager;
            //_userManager = userManager;
        }
        /**
        public AdministrationController(RoleManager<IdentityRole> roleManager)
        {
            this.roleManager = roleManager;
        }**/

        [HttpGet]
        public IActionResult CreateRole()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> CreateRole(CreateRoleViewModel model)
        {
            if (ModelState.IsValid)
            {
                IdentityRole identityRole = new IdentityRole
                {
                    Name = model.RoleName
                };
                IdentityResult result = await roleManager.CreateAsync(identityRole);
                if (result.Succeeded)
                {
                    return RedirectToAction("index", "home");
                }
                foreach (IdentityError error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }

            }

            return View(model);
        }
    }

Am I missing something ?


text:
Q: Converting a multindex dataframe to a nested dictionary I have a grouped dataframe as shown in this link:
I want to convert it into a nested dictionary, where 'Dia' is the main key and inside contains another dictionary where the keys are the 'mac_ap' and the values are another dictionary where the key would be 'download' and 'upload' and the values would be the corresponding values to column 'bytes'
something like this:

A: Suppose this is your dataframe:
df = pd.DataFrame([['2010-12-06', 'MAC_AP_1', 'download', 1],
                    ['2010-12-06', 'MAC_AP_1', 'upload', 2],
                    ['2010-12-06', 'MAC_AP_2', 'download', 3],
                    ['2010-12-06', 'MAC_AP_2', 'upload', 4],
                    ['2020-01-01', 'MAC_AP_3', 'download', 5],
                    ['2020-01-01', 'MAC_AP_3', 'upload', 6],
                    ['2020-01-01', 'MAC_AP_4', 'download', 7],
                    ['2020-01-01', 'MAC_AP_4', 'upload', 8]]
                    , columns=['Dia', 'macap', 'transmission', 'bytes'])

    Dia         macap       transmission    bytes
0   2010-12-06  MAC_AP_1    download    1
1   2010-12-06  MAC_AP_1    upload  2
2   2010-12-06  MAC_AP_2    download    3
3   2010-12-06  MAC_AP_2    upload  4
4   2020-01-01  MAC_AP_3    download    5
5   2020-01-01  MAC_AP_3    upload  6
6   2020-01-01  MAC_AP_4    download    7
7   2020-01-01  MAC_AP_4    upload

You need to create a nested dictionary out of your dataframe. So you should groupby your dataframe columns recursively till you reach the branches:
d = df.groupby('Dia').apply(lambda a: dict(a.groupby('macap').apply(lambda x: dict(zip(x['transmission'], x['bytes'])))))
d = d.to_dict()

You first groupby on 'Dia' and then apply another groupby on the nested 'macap'. The last apply is used for making transmission and bytes a tuple and then converting them to a dictionay.
As you have 3 levels of nested dictionaries, you can see in the code that there are 3 conversions to dictionaries too.
The result would then be this:
{'2010-12-06': {'MAC_AP_1': {'download': 1, 'upload': 2},
                'MAC_AP_2': {'download': 3, 'upload': 4}},
'2020-01-01': {'MAC_AP_3': {'download': 5, 'upload': 6},
               'MAC_AP_4': {'download': 7, 'upload': 8}}}


text:
Q: How to get all the distinct values in a dictionary I have a dictionary like this: d = {"name": "john", "surname": "smith", "nickname: "john"}
I want to get all unique values, i.e: ["john", "smith"]
I have see this question which does the same a for list of dictionaries, and I have seen this question which uses values() but it does not return the unique list of values.

A: you can convert the value of a dict to a set to remove the duplicate and pass it back to a list list(set(d.values()))

A: You can use set
unique = list(set(d.values()))


text:
Q: Saving trained Tensorflow model to inference on another machine I'm relatively new to machine learning and the Tensorflow framework. I was trying to take my trained model heavily influenced by the code presented here, using the MNIST handwritten digit dataset and perform inferences on testing examples that I have created. However, I am doing the training on a remote machine with a GPU and am trying to save the data to a directory so that I can transfer the data and inference on a local machine
It seems that I was able to save some of the model with tf.saved_model.simple_save, however, I'm unsure of how to use the saved data to do inferencing and to use the data to make a prediction given a new image. It seems like there are multiple ways to save a model, but I am unsure of what the convention or of what the "correct way" is to do it with the Tensorflow framwork.
So far, this is the line that I think I would need, but am unsure if it is correct.
            tf.saved_model.simple_save(sess, 'mnist_model',
                inputs={'x': self.x},
                outputs={'y_': self.y_, 'y_conv':self.y_conv})

If someone could point me in the direction of how to properly save trained models and which variables to use to be able to inference using the saved model, I'd really appreciate it.

A: A way you could do this is to create a tf.train.Saver() object in your graph definition, then use that to save the network to a specified directory. The weights in that directory can then be downloaded from the remote machine to your local one and restored locally. Here is a small example network:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

# >>>> Config. Vars <<<<

TRAIN_STEPS = 1000

SAVE_EVERY  = 100

# >>>> Network <<<<

inputs = tf.placeholder(tf.float32, shape=[None, 784])

labels = tf.placeholder(tf.float32, shape=[None, 10])

h1     = tf.layers.dense(inputs, 256, activation=tf.nn.relu, use_bias=True)

logits = tf.layers.dense(h1, 10, use_bias=True)

predictions = tf.nn.softmax(logits)

prediction_ids = tf.argmax(predictions, axis=1)

# >>>> Loss & Optimisation <<<<

loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=logits)

opt  = tf.train.AdamOptimizer().minimize(loss)

# >>>> Utilities <<<<

init  = tf.global_variables_initializer()

saver = tf.train.Saver()

with tf.Session() as sess:

    sess.run(init)

    # >>>> Training - run on remote, comment out locally <<<<

    for i in range(TRAIN_STEPS):

        print("Train step {}".format(i), end="\r")

        batch_data, batch_labels = mnist.train.next_batch(batch_size=128)

        feed_dict = {
            inputs: batch_data,
            labels: batch_labels
        }

        l, _ = sess.run([loss, opt], feed_dict=feed_dict)

        if i % SAVE_EVERY == 0:

            saver.save(sess, "saved_model/network_weights.ckpt")

    # >>>> Using the network - run locally to use the network <<<

    saver.restore(sess, "saved_model/network_weights.ckpt")

    test_data, test_labels = mnist.test.images, mnist.test.labels

    feed_dict = {
        inputs: test_data,
        labels: test_labels
    }

    preds = sess.run(prediction_ids, feed_dict=feed_dict)

    print(preds)

So once you define the saver in the network, you can use it to save the weights to the specified directory - in this case in the directory "saved_models", which you'll need to have created before you run this particular code.
Restoring the model is as simple as calling saver.restore() then and passing it the session and the path to where your weights are stored. So you can run this code on your remote machine, download the "saved_models" directory to your local machine then run this code with the training part commented out to actually use the model.


text:
Q: Italicize Translated Title in Parentheses? I'm proofreading a book and came across the title of a  poem with the translation in parentheses (name changed for confidentiality):
"... in his poem, Les Amours des Dieux (The Loves of the Gods), ..."
"Les Amours des Dieux" should be italicized for 2 reasons: it's a foreign phrase and it's the title of a poem. But, since the translation is also the title of the poem, should it also be italicized?

A: This is a matter of style, really: there are no "rules", although you do have prominent "style guides" to (optionally) follow.
My take on it is that if you wrote the following:
in his poem, Les Amours des Dieux (The Loves of the Gods), ...
ie, with the parenthesised section in italics as well, that risks making the reader think that the parenthesised section is part of the title, rather than just a translation of it.  The version as you have it in your question is therefore clearer and less ambiguous:  it tells us that the title is "Les Amours des Dieux", and then adds some extra information for the reader in the brackets (ie the translation of the title for those who don't happen to speak French).
BTW, the translation is not "also the title of the poem".  That would be like saying the poem has a different title for every language in the world, when it actually only has one title, the one the author gave it.  All text could be translated differently, and so one person's English translation does not have the same status as the original title.


text:
Q: Vuejs bind variable in JSX with scope I am essentially looking for something like:

 {{ k }}
 ...

     {{ myvalue }}

I don't know how you would call such thing, but I can tell I have similar code in places and that could be handy.

A: You can use the computed property to make functions that transform the values into something else.
For example lets say you have this code here.

  {{ message.split('').reverse().join('') }}

You can add add a computed property to run some js code and just call it in the html template

Original message: "{{ message }}"

Computed reversed message: "{{ reversedMessage }}"
 //computed function

var vm = new Vue({
  el: '#example',
  data: {
    message: 'Hello'
  },
  computed: {
    // a computed getter
    reversedMessage: function () {
      // `this` points to the vm instance
      return this.message.split('').reverse().join('')
    }
  }
})

You can read more about it in the official documentation
Example with v-for

 {{ k }}

     {{ reversedMessage(k) }}

var vm = new Vue({
  el: '#example',
  computed: {
    // a computed getter
    reversedMessage(k){ //you receive the value for each k you have in keys
      return k.split('').reverse().join('')
    }
  }
})


text:
Q: Multiples Queries inside Loop not all work I try to optimize a script I have so that it loads faster.
Now I have been sitting here for hours already but do not get it to work correctly.
The first part works fine, but what does not work is getting the names of the sire_id ($sr query) and dam_id (($ dr query)
it shows as resuls "array" for all of them.
This is what I have written so far
$query = "SELECT COUNT(sire_id) as c, sire_id FROM dog WHERE sire_id IS NOT NULL GROUP BY sire_id ORDER BY c desc LIMIT 150";
$result = mysql_query($query) ;
$i=0;
while ($line = mysql_fetch_array($result)) {
    $sireQuery = "SELECT name, id, sire_id, dam_id FROM dog WHERE id = '$line[sire_id] '";
    $sireResult = mysql_query($sireQuery) ;
    $sireLine = mysql_fetch_array($sireResult);
    $sr = mysql_query("SELECT name FROM dog WHERE id like $sireLine[2]") ;
    $sl = mysql_fetch_array($sr);
    $dr = mysql_query("SELECT name FROM dog WHERE id like $sireLine[3]") ;
    $dl = mysql_fetch_array($sr);
    $i++;

    echo "	".$i. ' ', ' ', ' ',""  .$sireLine[0]. "
          ".$line[0]."
          ".$sl."
          ".$dl."
";
}

A: Ids are numeric by definition, you don't need to use quotes. Also, you added a space that is not necessary:
$sireQuery = "SELECT name, id, sire_id, dam_id FROM dog WHERE id = " . $line["sire_id"];

Also, the following lines may need adaptation (waiting for your answer about the datatype of the id column)
$sr = mysql_query("SELECT name FROM dog WHERE id = " . $sireLine["sire_id"]);
$sl = mysql_fetch_array($sr);
$dr = mysql_query("SELECT name FROM dog WHERE id = " . $sireLine["dam_id"]);
$dl = mysql_fetch_array($dr);   /* note the mistake in the variable name: this is $dr, not $sr */

...
" . $sl["name"] ."
" . $dl["name"] ."
";

A: I rewrited your example:
$query = "SELECT COUNT(sire_id) as c, sire_id FROM dog WHERE sire_id IS NOT NULL GROUP BY sire_id ORDER BY c desc LIMIT 150";
$result = mysql_query($query) ;
$i=0;

while ($line = mysql_fetch_assoc($result)) {
    $sireQuery = "SELECT name, id, sire_id, dam_id FROM dog WHERE id = {$line['sire_id']}";
    $sireResult = mysql_query($sireQuery) ;
    $sireLine = mysql_fetch_assoc($sireResult);
    $sr = mysql_query("SELECT name FROM dog WHERE id = {$sireLine['sire_id']}") ;
    $sl = mysql_fetch_assoc($sr);
    $dr = mysql_query("SELECT name FROM dog WHERE id = {$sireLine['sire_id']}") ;
    $dl = mysql_fetch_assoc($sr);
    $i++;

    echo "	".$i. ' ', ' ', ' ',""  .$sireLine[0]. "
          {$line['c']}
          {$sl['name']}
          {$dl['name']}
";
}


text:
Q: Is there a way of listing all the DoIts which have been done in a Smalltalk session? Is there a way of listing all the DoIts which have been done in a session in Pharo or Squeak as well as which workspaces they were done in?
Are the contents of workspaces also tracked, so they can be diffed?

A: There's a file in the same directory as your image and with the same name as your image but with the extension ".changes".  This file contains all the source code and all the doit's you've performed.  Workspace text isn't tracked unless you execute it in which case it appears in the .changes file.

A: In a recent Squeak (at least 4.3), you can select the Extras menu at the top, and go to "Recover Changes". This asks you how far back you want to look; for "stuff I've done this session" that's probably the topmost choice.
That will give you a ChangeList showing all the doIts (and some other stuff) up to the last time you saved the image. (The ChangeList gets all its info from the .changes file that David Buck mentions.)
However, this will not tell you in which Workspace these were evaluated. Workspaces do not version their contents.


text:
Q: load external JSON file using URL I have a JSON file on the server. I want to load it in my angular-typescript. I tried the following.
ngOnInit () {
  this.httpService
    .get("http://x.x.x.x/config_files/test/config.json")
    .subscribe(data => console.log(data));
}

I'm getting the following error when I refresh a page

Access to XMLHttpRequest at 'http://x.x.x.x/config_files/test/config.json' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Since there is no server-side API the header Access-Control-Allow-Origin cannot be added. How to fix the issue?

A: There are certain plugins that you can use to resolve the CORS issue one is Moesif Origin & CORS Changer, The link provided is for a chrome extension.
After installing the plugin just toggle the ON switch and refresh your app.
This plugin allows you to send cross-domain requests. You can also override Request Origin and CORS headers.

A: The CORS is mostly a backend issue. You can solve it on Node.js with a code such as:
var express = require('express');
var app = express();
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

But if you want to solve it in frontend, you may use this kind of code in Angular. Put this code into a proxy.conf.json (but beware, a trailing slash is enough to make it not to work):
{
  "/config_files/*": {            <-- you may change this for config_files/test/
      "target": "http://xxxxxx:<port>",
      "secure": false,
      "logLevel": "debug",
      "changeOrigin": true
  }
}

The following in package.json:
"scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.conf.json",
    ...
}

And add the proxy config in angular.json:
"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "options": {
    "browserTarget": "event:build",
    "proxyConfig": "proxy.conf.json"  <-- this line
  },...

Start it with npm start.
It should work in your case, but in other cases (not in prod of course), I find it easier to use temporarily an extension for Chrome or Firefox.
Also I found that because of some restriction it may not work in Chromium and Chrome Canary.


text:
Q: Generified implementation of Visitor pattern in Java I've made some research trying to develop a type conversion framework which provides an ability to convert instances of a source class (e.g., Foo) to instances of result classes (e.g., Bar or Baz). The framework should provide an ability to use different conversion logic (i.e., different converters) for the same pair of a source and result. It also should be extendable, i.e. allow of adding new converters for new and existing pairs of a source and result. One more requirement is typesafety, i.e. any attempt to convert an instance of some source class to an instance of a result class without converter implementing appropriate conversion logic should lead to compile time error.
I decided to use a Visitor pattern with converters as Visitors and convertable classes as Elements. To provide extendability and typesafety I decided to use generics. So the first implementation of the conversion framework I made being influenced by some article in the Internet (unfortunately I've lost the link) was...
Conversion framework with statefull converters
Here are the core interfaces of the framework, Converter and Convertable:
    public interface Converter<V extends Converter<V,A>, A extends Convertable<V,A>> {

        void convert(A convertable);
    }

    public interface Convertable<V extends Converter<V,A>, A extends Convertable<V,A>> {

        void convertWith(V converter);
    }

Generics make an implementation of Convertable accept only implementations of Converter which can convert them and make an implementation of Converter visit only implementations of Convertable which it's made to convert. Here is an example of such converters:
interface FooConverter extends Converter<FooConverter,Foo> {

    void convert(Foo convertable);

    void convert(FooChild1 convertable);

    void convert(FooChild2 convertable);
}

public class Foo2BarConverter implements FooConverter {

    private Bar result;

    public Bar getResult() {
        return result;
    }

    @Override
    public void convert(Foo convertable) {
        this.result = new Bar("This bar's converted from an instance of Foo");
    }

    @Override
    public void convert(FooChild1 convertable) {
        this.result = new Bar("This bar's converted from an instance of FooChild1");
    }

    @Override
    public void convert(FooChild2 convertable) {
        this.result = new Bar("This bar's converted from an instance of FooChild2");
    }
}

public class Foo2BazConverter implements FooConverter {

    private Baz result;

    public Baz getResult() {
        return result;
    }

    @Override
    public void convert(Foo convertable) {
        this.result = new Baz("This baz's converted from an instance of Foo");
    }

    @Override
    public void convert(FooChild1 convertable) {
        this.result = new Baz("This baz's converted from an instance of FooChild1");
    }

    @Override
    public void convert(FooChild2 convertable) {
        this.result = new Baz("This baz's converted from an instance of FooChild2");
    }
}

And here are some classes which could be converted with that converters:
public class Foo implements Convertable<FooConverter, Foo> {

    @Override
    public void convertWith(FooConverter converter) {
        converter.convert(this);
    }
}

public class FooChild1 extends Foo {

    @Override
    public void convertWith(FooConverter converter) {
        converter.convert(this);
    }
}

public class FooChild2 extends Foo {

    @Override
    public void convertWith(FooConverter converter) {
        converter.convert(this);
    }
}

Here are result classes, i.e. Bar and Baz:
public class Bar {

    private String message;

    public Bar(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

public class Baz {

    private String message;

    public Baz(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

And here is a code which tests that converters:
Foo fooObj = new Foo();
Foo fooChild1Obj = new FooChild1();
Foo fooChild2Obj = new FooChild2();

// converting to bar
Foo2BarConverter foo2BarConverter = new Foo2BarConverter();

fooObj.convertWith(foo2BarConverter);
System.out.println(foo2BarConverter.getResult().getMessage());

fooChild1Obj.convertWith(foo2BarConverter);
System.out.println(foo2BarConverter.getResult().getMessage());

fooChild2Obj.convertWith(foo2BarConverter);
System.out.println(foo2BarConverter.getResult().getMessage());

// converting to baz
System.out.println();
Foo2BazConverter foo2BazConverter = new Foo2BazConverter();

fooObj.convertWith(foo2BazConverter);
System.out.println(foo2BazConverter.getResult().getMessage());

fooChild1Obj.convertWith(foo2BazConverter);
System.out.println(foo2BazConverter.getResult().getMessage());

fooChild2Obj.convertWith(foo2BazConverter);
System.out.println(foo2BazConverter.getResult().getMessage());

and output built by this code
This bar's converted from an instance of Foo
This bar's converted from an instance of FooChild1
This bar's converted from an instance of FooChild2

This baz's converted from an instance of Foo
This baz's converted from an instance of FooChild1
This baz's converted from an instance of FooChild2

Take a look at result field in Foo2BarConverter and Foo2BazConverter. That's the main drawback of the implementation. It makes converters statefull which is not always handy. Trying to avoid this drawback I developed...
Conversion framework without double dispatching
The main point of this implementation is to parametrize converters with result classes and return results from convert method of Converter and convertWith method of Convertable. Here is how it looks in code:
public interface Converter<A extends Convertable<A>,R> {

    R convert(A convertable);
}

public interface Convertable<A extends Convertable<A>> {

    <R> R convertWith(Converter<A,R> converter);
}

public interface FooConverter<R> extends Converter<Foo,R> {

    @Override
    R convert(Foo convertable);

    R convert(FooChild1 convertable);

    R convert(FooChild2 convertable);
}

public class Foo2BarConverter implements FooConverter<Bar> {

    @Override
    public Bar convert(Foo convertable) {
        return new Bar("This bar's converted from an instance of Foo");
    }

    @Override
    public Bar convert(FooChild1 convertable) {
        return new Bar("This bar's converted from an instance of FooChild1");
    }

    @Override
    public Bar convert(FooChild2 convertable) {
        return new Bar("This bar's converted from an instance of FooChild2");
    }
}

public class Foo2BazConverter implements FooConverter<Baz> {

    @Override
    public Baz convert(Foo convertable) {
        return new Baz("This baz's converted from an instance of Foo");
    }

    @Override
    public Baz convert(FooChild1 convertable) {
        return new Baz("This baz's converted from an instance of FooChild1");
    }

    @Override
    public Baz convert(FooChild2 convertable) {
        return new Baz("This baz's converted from an instance of FooChild2");
    }
}

public class Foo implements Convertable<Foo> {

    @Override
    public <R> R convertWith(Converter<Foo,R> converter) {
        return converter.convert(this);
    }
}

public class FooChild1 extends Foo {

    @Override
    public <R> R convertWith(Converter<Foo,R> converter) {
        return converter.convert(this);
    }
}

public class FooChild2 extends Foo {

    @Override
    public <R> R convertWith(Converter<Foo,R> converter) {
        return converter.convert(this);
    }
}

V is removed from Convertable declaration because having a result class in Converter declaration would have us in fact to parametrize implementations of Convertable with result classes. It would bound each implementation of convertable to the only result class it could be converted to. So convertWith in Convertable refers received converters with Converter<A,R> interface. And that's the problem. Now implementations of Convertable invoking received converter will allways invoke convert which is defined in Converter interface and not convert methods which override it in Converter implementations. In other words convert(FooChild1 convertable) and convert(FooChild2 convertable) in Foo2BarConverter and Foo2BazConverter will never be called. Basically, it kills the main notion of Visitor pattern, double dispatching. Here is a test code...
Foo fooObj = new Foo();
Foo fooChild1Obj = new FooChild1();
Foo fooChild2Obj = new FooChild2();

// converting to bar
Foo2BarConverter foo2BarConverter = new Foo2BarConverter();
System.out.println(fooObj.convertWith(foo2BarConverter).getMessage());
System.out.println(fooChild1Obj.convertWith(foo2BarConverter).getMessage());
System.out.println(fooChild2Obj.convertWith(foo2BarConverter).getMessage());

System.out.println();

// converting to baz
Foo2BazConverter foo2BazConverter = new Foo2BazConverter();
System.out.println(fooObj.convertWith(foo2BazConverter).getMessage());
System.out.println(fooChild1Obj.convertWith(foo2BazConverter).getMessage());
System.out.println(fooChild2Obj.convertWith(foo2BazConverter).getMessage());

and its output which demonstrates that overriding methods aren't called in this implementation.
This bar's converted from an instance of Foo
This bar's converted from an instance of Foo
This bar's converted from an instance of Foo

This baz's converted from an instance of Foo
This baz's converted from an instance of Foo
This baz's converted from an instance of Foo

Next implementation I tried to make stateless converters with was...
Converters with parametrized methods
The main notion here is to parametrize only methods which I want to return a conversion result without parametrizing declarations of interfaces.
public interface Converter<V extends Converter<V,A>, A extends Convertable<V,A>> {

    <R> R convert(A convertable);
}

public interface Convertable<V extends Converter<V,A>, A extends Convertable<V,A>> {

    <R> R convertWith(V converter);
}

interface FooConverter extends Converter<FooConverter,Foo> {

    <R> R convert(Foo convertable);

    <R> R convert(FooChild1 convertable);

    <R> R convert(FooChild2 convertable);
}

public class Foo2BarConverter implements FooConverter {

    @Override
    public Bar convert(Foo convertable) {
        return new Bar("This bar's converted from an instance of Foo");
    }

    @Override
    public Bar convert(FooChild1 convertable) {
        return new Bar("This bar's converted from an instance of FooChild1");
    }

    @Override
    public Bar convert(FooChild2 convertable) {
        return new Bar("This bar's converted from an instance of FooChild2");
    }
}

public class Foo2BazConverter implements FooConverter {

    @Override
    public Baz convert(Foo convertable) {
        return new Baz("This baz's converted from an instance of Foo");
    }

    @Override
    public Baz convert(FooChild1 convertable) {
        return new Baz("This baz's converted from an instance of FooChild1");
    }

    @Override
    public Baz convert(FooChild2 convertable) {
        return new Baz("This baz's converted from an instance of FooChild2");
    }
}

public class Foo implements Convertable<FooConverter, Foo> {

    @Override
    public <R> R convertWith(FooConverter converter) {
        return converter.convert(this);
    }
}

public class FooChild1 extends Foo {

    @Override
    public <R> R convertWith(FooConverter converter) {
        return converter.convert(this);
    }
}

public class FooChild2 extends Foo {

    @Override
    public <R> R convertWith(FooConverter converter) {
        return converter.convert(this);
    }
}

Testing code
Foo fooObj = new Foo();
Foo fooChild1Obj = new FooChild1();
Foo fooChild2Obj = new FooChild2();

// converting to bar
Foo2BarConverter foo2BarConverter = new Foo2BarConverter();
System.out.println(fooObj.<Bar>convertWith(foo2BarConverter).getMessage());
System.out.println(fooChild1Obj.<Bar>convertWith(foo2BarConverter).getMessage());
System.out.println(fooChild2Obj.<Bar>convertWith(foo2BarConverter).getMessage());

System.out.println();

// converting to baz
Foo2BazConverter foo2BazConverter = new Foo2BazConverter();
System.out.println(fooObj.<Baz>convertWith(foo2BazConverter).getMessage());
System.out.println(fooChild1Obj.<Baz>convertWith(foo2BazConverter).getMessage());
System.out.println(fooChild2Obj.<Baz>convertWith(foo2BazConverter).getMessage());

and it's output
This bar's converted from an instance of Foo
This bar's converted from an instance of FooChild1
This bar's converted from an instance of FooChild2

This baz's converted from an instance of Foo
This baz's converted from an instance of FooChild1
This baz's converted from an instance of FooChild2

At first glance looks great. But in fact this solution isn't typesafe. For example the following call
fooObj.<Baz>convertWith(foo2BarConverter).getMessage()

wouldn't cause a compile time error. But it would lead to ClassCastException in runtime.
So the general question is the following.
Is there a way to make a stateless generifyed typesafe Visitor with Java?
UPD: I've added links to sources of all three implementations: 1st, 2nd and 3rd

A: Your converters are simply functions, you probably do not need a "framework" to compose them. And your third try do not make much sense:
<R> R convertWith(V converter);

mean: "given something (the V converter that know nothing about the R you want), give me anything (arbitrary R)". As you found out this does not work.
Simple Implementation using the corrected visitor pattern:
interface FooConverter<R> extends Function<Foo, R> {

  R convert(Foo convertable);

  R convert(FooChild1 convertable);

  R convert(FooChild2 convertable);

  default R apply(Foo foo) { return foo.convertWith(this); }
}

public class Foo2BarConverter implements FooConverter<Bar> {

  @Override
  public Bar convert(Foo convertable) {
    return new Bar("This bar's converted from an instance of Foo");
  }

  @Override
  public Bar convert(FooChild1 convertable) {
    return new Bar("This bar's converted from an instance of FooChild1");
  }

  @Override
  public Bar convert(FooChild2 convertable) {
    return new Bar("This bar's converted from an instance of FooChild2");
  }
}

public class Foo2BazConverter implements FooConverter<Baz> {

  @Override
  public Baz convert(Foo convertable) {
    return new Baz("This baz's converted from an instance of Foo");
  }

  @Override
  public Baz convert(FooChild1 convertable) {
    return new Baz("This baz's converted from an instance of FooChild1");
  }

  @Override
  public Baz convert(FooChild2 convertable) {
    return new Baz("This baz's converted from an instance of FooChild2");
  }
}

public class Foo{

  public <R> R convertWith(FooConverter<R> converter) {
    return converter.convert(this);
  }
}

public class FooChild1 extends Foo {

  @Override
  public <R> R convertWith(FooConverter<R>  converter) {
    return converter.convert(this);
  }
}

public class FooChild2 extends Foo {

  @Override
  public <R> R convertWith(FooConverter<R> converter) {
    return converter.convert(this);
  }
}

public void test() {
  Foo fooObj = new Foo();
  Foo fooChild1Obj = new FooChild1();
  Foo fooChild2Obj = new FooChild2();

  // converting to bar
  Foo2BarConverter foo2BarConverter = new Foo2BarConverter();
  System.out.println(fooObj.convertWith(foo2BarConverter).getMessage());
  System.out.println(fooChild1Obj.convertWith(foo2BarConverter).getMessage());
  System.out.println(fooChild2Obj.convertWith(foo2BarConverter).getMessage());

  System.out.println();

  // converting to baz
  Foo2BazConverter foo2BazConverter = new Foo2BazConverter();
  System.out.println(fooObj.convertWith(foo2BazConverter).getMessage());
  System.out.println(fooChild1Obj.convertWith(foo2BazConverter).getMessage());
  System.out.println(fooChild2Obj.convertWith(foo2BazConverter).getMessage());

  // does not compile:
  fooObj.<Baz>convertWith(foo2BarConverter).getMessage();
}

Then if you want some more framework, you may want to look into lenses: https://github.com/functionaljava/functionaljava/tree/master/core/src/main/java/fj/data/optic

A: You could just ditch Visitor Pattern as there is a better solution for Java.
The pitfall of Visitor Pattern:
It is intrusive, and anti-pattern
The visitor pattern use double-dispatch, that usually goes like this:
public class ParentDataModel
{
    public void accept(Visitor visitor)
    {
        visitor.visit(this);
    }
}

public class ChildDataModel extends ParentDataModel
{
    // no need to implement accept() by the child itself
}

public class Visitor
{
    public void visit(ParentDataModel model)
    {
        // do something with it
    }

    public void visit(ChildDataModel model)
    {
        // do something with it
    }
}

Why on earth a data model need to be aware of visitor? A data model should only hold the data relevant to the model.
Does not go well with existing objects from external frameworks
What if you need to do something with, say Number, Double, that are from the JDK.
Even say you're willing to make a wrapper around each object you need in your project, it's hell tedious, and think about how many classes you will have to refactor to get this to work.
public class NumberWrapper
{
    private Number value;

    public void accept(Visitor visitor)
    {
        visitor.visit(value);
    }
}

public class DoubleWrapper
{
    private Double value;

    public void accept(Visitor visitor)
    {
        visitor.visit(value);
    }
}

public class Visitor
{
    public void visit(Number value)
    {
        // do something with it
    }

    public void visit(Double value)
    {
        // do something with it
    }
}

Solution: One class rules them all
public static class SuperConsumer implements Consumer
{
    private Map<Class<?>, Consumer<?>> consumers = new HashMap<>();
    private Consumer<?> unknown = o -> System.err.println("Unknown object type");

    public SuperConsumer()
    {
        consumers.put(Number.class, o -> consumeNumber(o));
        consumers.put(Double.class, o -> consumeDouble(o));
    }

    private void consumeNumber(Number value)
    {
         System.out.printf("Consuming: %s\n", value.getClass().getName());
    }

    private void consumeDouble(Double value)
    {
         System.out.printf("Consuming: %s\n", value.getClass().getName());
    }

    private Consumer findConsumer(Object object)
    {
        Consumer consumer = consumers.get(object.getClass());

        Class superClazz = object.getClass().getSuperclass();
        while (consumer == null && superClazz != Object.class)
        {
            consumer = consumers.get(superClazz);
            superClazz = superClazz.getSuperclass();
        }

        Class<?>[] interfaces = object.getClass().getInterfaces();
        for (int i = 0; consumer == null && i < interfaces.length; i++)
        {
            consumer = consumers.get(interfaces[i]);
        }

        return consumer;
    }

    @Override
    public void accept(Object object)
    {
        Consumer consumer = findConsumer(object);
        if (consumer == null)
        {
            consumer = unknown;
        }
        consumer.accept(object);
    }

    public static void main(String[] args)
    {
        Consumer consumer = new SuperConsumer();
        Arrays.asList(new Double(1.0), new Integer(1), new Float(1.0f)).forEach(o -> consumer.accept(o));
    }
}


text:
Q: Slightly increasing complexity of function increases calculation time by magnitudes I am trying to calculate an impedance value from voltage and current functions. The calculation method is based on how an actual measurement device performs it.
I have two different current function, where one is slightly more complex.
iBV[t_, freq_] =
  i0*(-Exp[(alpha - 1)*bvVor*(U[t, freq] - E0)] +
  Exp[alpha*bvVor*(U[t, freq] - E0)]) + Cdl*DU[t, freq];
i[t_, freq_] = iBV[t, freq]*iLimit/(Abs[iBV[t, freq]] + iLimit);

If i use iBV directly, the calculations finish very rapidly. When I however use i I am still waiting for the results after half an hour and I don't understand why. Granted, it has to calculate iBV twice for each round but shouldn't that lead to twice the time and not 1000 times?
As you'll see I need to integrate. Is maybe the complexity of performing the integration much more complicated in the latter case for some reason?
The rest of the computation is as follows:
ClearAll[t, freq, U0, Harmonic, bvVor, i0, alpha, E0, T, z, cBulk,
  Cdl, iLimit];
ClearAll[U, DU, iVoigt, i, iL, Rea, Ima, tmax, ReZ, ImZ, Impe];

(* Current parameters *)
i0 = 0.0001; alpha = 0.5; E0 = 0; T = 293; z = 1; cBulk = 25; Cdl = \
0.000001; iLimit = 0.0005;

(* Voltage parameters and Misc *)
U0 = 0.1;
Harmonic = 0;
bvVor = z*96485/8.314/T;

(* Voltage Functions *)
U[t_, freq_] = U0*Sin[2*\[Pi]*freq*t];
DU[t_, freq_] = 2*freq*\[Pi]*U0*Cos[2*freq*\[Pi]*t];
(*iVoigt[t_,freq_]=Cdl*DU[t,freq]+U[t,freq]/100;*)

(* Current Function *)
iBV[t_, freq_] =
  i0*(-Exp[(alpha - 1)*bvVor*(U[t, freq] - E0)] +
      Exp[alpha*bvVor*(U[t, freq] - E0)]) + Cdl*DU[t, freq];
i[t_, freq_] = iBV[t, freq]*iLimit/(Abs[iBV[t, freq]] + iLimit);

(* Functions to calculate the real and imaginary part of the current \
by integration *)
ReaF[t_, freq_] = i[t, freq]*Sin[(Harmonic + 1)*2*\[Pi]*freq*t];
ImaF[t_, freq_] = i[t, freq]*Cos[(Harmonic + 1)*2*\[Pi]*freq*t];

(* Integration bound, 1 period *)
tmax[freq_] = 2/freq;

(* Real and Imaginary part of the current *)
ReI[freq_] = 2/tmax[freq]*Integrate[ReaF[t, freq], {t, 0, tmax[freq]}];
ImI[freq_] = 2/tmax[freq]*Integrate[ImaF[t, freq], {t, 0, tmax[freq]}];

(* The Impedance *)
Impe[freq_] = U0/(ReI[freq] + I*ImI[freq]);

(* Calculation of results *)
Freqs = 10^Range[-2,5,0.1];
Results = Impe[Freqs];

(* Output *)
Res = Re[Results];
Ims = Im[Results];
marker = Graphics[{Red, Disk[]}];
ListPlot[Transpose[{Res, -Ims}], {Joined -> True,
  PlotMarkers -> {marker, .03}, PlotStyle -> {Orange, Thick}}]
TraditionalForm[TableForm[Transpose[{Freqs, Res, Ims}]]]

If you want to test the difference, just rename i[t_, freq_] to something, and rename iBV[t_, freq_] to i[t_, freq_].
I also tried rewriting the whole stuff in Function/Module nomenclature, getting rid of doubled calculations in the process, but that just made everything slower (i guess due to overhead<->actual evaluation time bias).
Edit
I tried to do some benchmarks:
Timing[Do[iBV[0.1, 100], {10000}]]
Timing[Do[i[0.1, 110], {10000}]]

This does indeed report what I thought: {0.328, Null}, {0.657, Null}. So each function evaluation takes twice as long for the more complex function.
I also further narrowed it down: Everything is fast up to the integration.
I changed - as Edmund suggested in the comments - all definitions to SetDelayed, which did not improve the speed though.

A: You can increase the performance of i considerably simply by making sure that IBV is evaluated only once.
i0 = 0.0001;
alpha = 0.5;
E0 = 0;
T = 293;
z = 1;
Cdl = 0.000001;
iLimit = 0.0005;
U0 = 0.1;

bvVor = z*96485/8.314/T;

U[t_, freq_] := U0*Sin[2*π*freq*t]
DU[t_, freq_] := 2*freq*π*U0*Cos[2*freq*π*t]

iBV[t_, freq_] :=
  i0*(-Exp[(alpha - 1)*bvVor*(U[t, freq] - E0)] +
     Exp[alpha*bvVor*(U[t, freq] - E0)]) + Cdl*DU[t, freq]

i[t_, freq_] :=
  Block[{ibv = iBV[t, freq]}, ibv*iLimit/(Abs[ibv] + iLimit)]

Timing[Do[iBV[0.1, 100], {10000}]][[1]]

0.207059

Timing[Do[i[0.1, 100], {10000}]][[1]]

0.239106

The same technique can be applied to improve overall performance.
iBV[t_, freq_] :=
  Block[{u, v},
    u = bvVor*U[t, freq] - E0;
    v = Exp[u alpha] (1 - Exp[-u]);
    i0 v + Cdl DU[t, freq]]

With this version of iBV, I get
Timing[Do[iBV[0.1, 100], {10000}]][[1]]

0.173164

and, of course, the performance of i improves, too.
Timing[Do[i[0.1, 100], {10000}]][[1]]

0.216504

A: The source of your problem is using Integrate with i[t, freq] in the expression.
It doesn't integrate.
Using NIntegrate (as suggested by Michael E2) the problem can be solved in a reasonable amount of time. Below are two changes.
ReI[freq_] :=
 2/tmax[freq]*NIntegrate[ReaF[t, freq], {t, 0, tmax[freq]}]
ImI[freq_] :=
 2/tmax[freq]*NIntegrate[ImaF[t, freq], {t, 0, tmax[freq]}]

I also modified the function definitions by replacing = (Set) with := (SetDelayed).
I think you also should either give Impe the Listable attribute or use Map as shown below.
Results = Impe[#] & /@ Freqs

{332.822 - 0.00389736 I, 332.822 - 0.00490649 I,
 332.822 - 0.0061769 I, 332.786 - 0.00777461 I,
 332.822 - 0.00978973 I, 332.822 - 0.0123245 I, 332.822 - 0.0155157 I,
  332.822 - 0.0195331 I, 332.822 - 0.0245907 I, 332.822 - 0.0309578 I,
  332.822 - 0.0389736 I, 332.822 - 0.0490649 I, 332.786 - 0.0617559 I,
  332.822 - 0.0777626 I, 332.822 - 0.0978973 I, 332.822 - 0.123245 I,
 332.822 - 0.155157 I, 332.822 - 0.195331 I, 332.821 - 0.245907 I,
 332.821 - 0.309578 I, 332.821 - 0.389736 I, 332.821 - 0.490648 I,
 332.821 - 0.617688 I, 332.82 - 0.777622 I, 332.819 - 0.978965 I,
 332.818 - 1.23244 I, 332.816 - 1.55153 I, 332.813 - 1.95324 I,
 332.808 - 2.45894 I, 332.8 - 3.09553 I, 332.787 - 3.89685 I,
 332.766 - 4.90547 I, 332.734 - 6.17487 I, 332.683 - 7.77221 I,
 332.602 - 9.78165 I, 332.474 - 12.3084 I, 332.271 - 15.4836 I,
 331.95 - 19.4692 I, 331.443 - 24.4636 I, 330.646 - 30.7055 I,
 329.394 - 38.474 I, 327.441 - 48.0797 I, 324.42 - 59.8389 I,
 319.808 - 74.0175 I, 312.901 - 90.7301 I, 302.841 - 109.791 I,
 288.734 - 130.543 I, 269.913 - 151.741 I, 246.3 - 171.642 I,
 218.689 - 188.366 I, 188.743 - 200.469 I, 158.575 - 207.39 I,
 130.158 - 209.537 I, 104.868 - 207.972 I, 83.3488 - 203.979 I,
 65.645 - 198.712 I, 51.4232 - 193.038 I, 40.1789 - 187.519 I,
 31.3747 - 182.47 I, 24.5166 - 178.029 I, 19.1847 - 174.226 I,
 15.0388 - 171.028 I, 11.8104 - 168.374 I, 9.29146 - 166.193 I,
 7.32143 - 164.412 I, 5.7772 - 162.966 I, 4.56416 - 161.797 I,
 3.60948 - 160.855 I, 2.8569 - 160.097 I, 2.26279 - 159.489 I,
 1.79325 - 159.001 I}

Then you can plot it
Res = Re[Results];
Ims = Im[Results];
marker = Graphics[{Red, Disk[]}];

ListPlot[Transpose[{Res, -Ims}], {Joined -> True,
  PlotMarkers -> {marker, .03}, PlotStyle -> {Orange, Thick}}]

and make the table
TraditionalForm[TableForm[Transpose[{Freqs, Res, Ims}]]]


text:
Q: How to specify one-way mapping in Dozer using annotations How to specify one-way mapping in Dozer using annotation?
I can do that using XML Mapping as follows:
<field type="one-way">
    oneFoo2
    oneFooPrime2
</field>

However I don't see mention of this in annotation documentation.

A: This is not possible with the current (5.5.1) version. As described in the documentation, there is only one annotation, @Mapping which tells the destination field to map.


text:
Q: Google Chrome won't start When I try to start Google Chrome, it starts but it's just open for like 2-4 sec and then it's closing again..
When I try to start it from Terminal, i get this message?
ATTENTION: default value of option force_s3tc_enable overridden by environment.
[8820:8820:0405/095558:ERROR:background_mode_manager_aura.cc(14)] Not implemented reached in virtual void BackgroundModeManager::EnableLaunchOnStartup(bool)
Minnesegmentsfeil (core dumped)

I'm not new to Ubuntu, but new to problems like this... Somebody who can help me?

A: You can try to re-install chrome like this for 64bit
sudo apt-get purge google-chrome

sudo apt-get install libxss1 libappindicator1 libindicator7
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome*.deb

OR 32bit
sudo apt-get install libxss1 libappindicator1 libindicator7
wget https://dl.google.com/linux/direct/google-chrome-stable_current_i386.deb
sudo dpkg -i google-chrome*.deb

This will also install a PPA to stay up to date.


text:
Q: How to store multiple NSMutableDictionarys in NSUserDefaults I am trying to store multiple NSMutableDictionarys in NSUserDefaults I have tried this:
-(void)storeNotification:(NSDictionary*)dict{
    NSMutableDictionary *dic = [dict mutableCopy];
    //add read object to dic
    [dic setObject:@"NO" forKey:@"read"];

    //get stored arrayofdics
    NSMutableArray *arrayofdics = [[NSUserDefaults standardUserDefaults] objectForKey:@"arrayofdics"];
    if([arrayofdics count] == 0){
        arrayofdics = [[NSMutableArray alloc] init];
    }

    //add dic to arrayofdics
    [arrayofdics addObject:dic];

    //store arrayofdics
    [[NSUserDefaults standardUserDefaults] setObject:arrayofdics forKey:@"arrayofdics"];
    NSLog(@"stored: %@", arrayofdics);
}

So that I can then modify the read key in a dic like this:
-(void)markAsRead:(int)dic_index{
    NSMutableArray *arrayofdics = [[NSUserDefaults standardUserDefaults] objectForKey:@"arrayofdics"];
    NSMutableDictionary *dic = [arrayofdics objectAtIndex:dic_index];
    [dic setObject:@"YES" forKey:@"read"];
    [arrayofdics replaceObjectAtIndex:dic_index withObject:dic];
    [[NSUserDefaults standardUserDefaults] setObject:arrayofdics forKey:@"arrayofdics"];
}

and also am able to iterate all of the storeNotifications

The log is showing:
stored: (
        {
        read = NO;
...
})
but when storeNotification is called the second time I get an error:
Printing description of arrayofdics->isa:
(Class) isa = __NSCFArray
(lldb)

Which means the array is not being stored properly. Any ideas why? Or ways to do this better?

A: This error is due to calling mutable functions in immutable objects
Userdefaults always return a immutable objects.
so make mutable when u get objects from userdefaults.
 NSMutableArray *arrayofdics = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayofdics"] mutableCopy];


text:
Q: What is the office establishment of a Commissioner called? I have seen people using the word "Commissionerate" for the office establishment of a Commissioner.
I have made search on the Free Dictionary and on Oxford Dictionaries. But, I did not find the word there.
Is the word correct? Is so, will it be spelled as "Commissionerate" (i.e. with "e" at the end) or "Commissionerat" (i.e. without "e" at the end)?

A: I think it is a Indian English term:
From The Hindu:  What commissionerate means:

*

*After much deliberation, the State government accepted in principle that Kochi along with capital city Thiruvananthapuram would have magisterial commissionerates.  However instead of bringing clarity to the issue, the decision seems to have stepped up the confusion.

*At present, Kochi with a Deputy Inspector General (DIG) of police as chief comes under the Inspector General of Police, Kochi Range, along with Ernakulam Rural, Alappuzha, Kottayam and Idukki. The Kerala Police Act says that when the commissionerate is constituted, it should have an officer not less than the rank of a DIG.

From Encyclopaedia of North-East India (2007):

*

*Assam was then a mere commissionerate (Division) of Bengal  and Bengali officialdom convinced the authorities that Assamese was but a dialect of Bengali; hence the change which hurt the Assamese pride. Persistent agitation bore not fruit.

A: 'Commissionerate' doesn't appear in the OED Online. The sense it would convey is attested for 'commissionership' instead.

*

*The district under the jurisdiction of a commissioner.... Now chiefly hist.
Recorded earliest in chief commissionership.
Freq. with reference to the British Empire, esp. British India.

*The position, office, or term of office of a commissioner (in various senses).

["commissionership, n.". OED Online. December 2015. Oxford University Press. http://www.oed.com/view/Entry/37148?rskey=EZ6AnF&result=55&isAdvanced=false (accessed December 19, 2015).]
Examples of this use of 'commissionership' are given dating from 1625 to 2007 (Encycl. N.-E. India).
As for the correctness of 'commissionerate' or 'commissionerat', I'm not sure what 'correct' means.

*

*Because there are examples of the word in contemporary use, the word is in that limited way correct.

*The word will be understood with either spelling.

*Google and DuckDuckGo searches produce approximately the same number of results for 'commissionership' and 'commissionerate'.

*Other dictionaries than the OED list 'commissionership', but not 'commissionerate'.

*The '-ate' suffix is used chiefly to form

a. Substantives denoting office or function, or the persons performing it ....

*This meaning of '-ate' does not apply so readily to what I take to be your intended meaning as does the meaning of '-ship':

Added to ns. designating an official or person of rank to denote the office, position, dignity, or rank of the person designated ....

*The '-at' suffix is the original form of the '-ate' suffix with the meaning shown under (5) above. It is less likely than the '-ate' suffix to be considered correct.

All the foregoing aside, I suspect that by "office establishment" in your question, you intended "office building" or the "office suite" (where "suite" is a collection of physical offices within a building or set of buildings). In that case, the usual American English and likely the usual British English word you want is probably

Commission

where "Commission" is an abbreviation of the full title of the commission. For example, this

Commissionerate of Higher Education, Education Department - Government of Gujarat

(From the website of the Commissionerate of Higher Education, Education Department - Government of Gujarat.)
would be this

Commission of Higher Education, Education Department - Government of Gujarat

and this

Office of the Commissioner of Higher Education is responsible for executing policy initiatives, regulating & funding higher education system of the State, in a network of universities, affiliated colleges and research institutions. ...

would be this

Office of the Commission etc.

idiomatically in American English. If "Commission" (or the full title of the commission) is not sufficient to unambiguously refer to the buildings or suite of offices housing the Commission of Higher Education,

office (or offices) of the Commission of Higher Education

would be used idiomatically.
None of the foregoing is intended to suggest that the American or British dialects of English are any more correct than other dialects of English.


text:
Q: Protobuf-net: which nuget version corresponds to which git commit? Does anyone know how to figure out which commit in git corresponds to which Nuget version for Protobuf-net?
I use the Nuget version (2.0.0.668), but I have an error in my graph, and there is no good debug information without the source, so I would like to get a hint as to where the problem lies in my code.
The nuget package versions do not seem to be tagged in the repo I am using-
https://github.com/mgravell/protobuf-net.git
Any ideas?

A: Not sure this is really a stackoverflow question, but: I've added some tags to the git repo; however, the only interesting ones at the moment are r668 (aka 2.0.0.668) and v2.1.0-alpha-1 (the alpha core-clr release). I did not attempt to go back through all releases.


text:
Q: Finding Position of an Object in an Image Relative to a Camera Hopefully I have this in the correct place, but apologies if not. What I'm trying to do is given I know the pixel that I am measuring to, how would I find the x, y and z co-ordinates of that pixel relative to the camera in millimeters, given that I have the focal length, width of the sensor and height of the sensor from the centre of the image? Those three things are all in mm.
For example: focal length is 50.0mm, sensor width is 23.4mm, and height of the sensor from the image is 15.6mm, how would I determine x, y and z? x and y are in parallel and in the same direction as the x and y axis of the image, and z is the distance from the camera to the pixel.
Any help would be appreciated! Also perhaps worth noting is that the object is a playing card, so I suppose the size of it would be relatively constant if that were needed.


text:
Q: Promise subclassing with properties Is it possible to subclass Promise so that custom properties can be added that survive subsequent calls to .then() / .catch() etc?
Calls to these methods return a new Promise class which loses the context.
For example:
var myPromise = Promise.resolve();
myPromise.foo = 'Foo!'; // Mutate the promise base (this works fine)

var myPromise2 = myPromise.then(()=> 'result!'); // Attach a thennable
console.log(myPromise2.foo) // should = 'Foo!', but myPromise2 is actually just {} after any promise call


text:
Q: MongoDB - Most Recent 20 unique I'm trying to get the most recent unique value from a collection in MongoDB, however, the $group seems to be breaking the $sort somehow. Ie, in this case, im trying to get the most recent activity for a user (but only returning 20 activities total).
db.activities.aggregate([{ $sort: { timestamp:-1, firstname: 1 } }, { $limit: 20 }])

If i run the above, i get 20 results back and in the correct order, however, i have multiple doduments with the same firstname as the user has submitted multiple activities.
If i run the below, the top user from the first query is no longer in the list.  I get a completely different set of people back.
db.activities.aggregate([{ $sort: { timestamp:-1, firstname: 1 } },  { $group: { _id: "$firstname"} } , { $limit: 20 }])

How can i get the most recent activity per person, but limiting it to only 20 activities?

A: You need to first find unique values, then apply limit and in the end just sort however you want. Its your solution with right ordering:
db.activities.aggregate([
     { $group: { _id: "$firstname"} } ,
     { $limit: 20 },
     { $sort: { timestamp:-1, firstname: 1 } },
])

Edit: Above code will not return correct result because from docs $group doesn't respect ordering. Instead you should $sort them before selecting first 20 like this:
db.activities.aggregate([
     { $group: { _id: "$firstname"} } ,
     { $sort: { timestamp:-1, firstname: 1 } },
     { $limit: 20 },
])

This will return unique docs but if you need only recent docs without unique constraint then just remove the $group stage as its redundant and will consume performance exponentially. If you still need unique docs with better performance then you need to make time-related decision i.e. $match the docs greater than last 1 hour, $group them, $sort and $limit first 20.


text:
Q: javascript Uncaught ReferenceError in asp.net MVC application I'm kind of new to Javascript development and I'm having a problem when loading a specific View that uses a javascript file(created by me). When the page loads, I get the Uncaught ReferenceError.
IoTApp.createModule(

//some other functions here

[jQuery, resources, powerbi]);

In this module, when the Page Loads, it throws the Javascript Error, saying that: "resources is not defined"
I have also a "main" javascript that I load in the <head> tag of _Layout.cshtml:
<script type="text/javascript" src="~/Scripts/Views/IoTApp.js"></script>

The IoTApp.js is defined as bellow, where resources is defined:
var IoTApp =
{
    resources: {},
    createModule: function (namespace, module, dependencies) {
    //Some code here
    });
}

Debbuging this Page, I can see that the IoTApp is loading in the Network option from the browser's developer tools.
Am I missing anything?

A: Tracing the code I could understand it better.
Was just missing to create the resources object in the View that calls the Javascript code that uses "resources".
The resources object created in the IoTApp.js is not being used, so I removed it.