text:
Q: I get this error when I am trying to bing an image in wpf
System.Windows.Data Error: 40 : BindingExpression path error: 'Icon' property not found on 'object' ''Detail' (HashCode=52423952)'. BindingExpression:Path=Icon; DataItem='Detail' (HashCode=52423952); target element is 'Image' (Name=''); target property is 'Source' (type 'ImageSource')

what does this error mean and what is that I am doing wrong?

A: I was missing the Icon property in Detail object. Creating Icon property worked like magic !!


text:
Q: simulate TinyMCE RTL button click after toolbar is instantiated Is there any way to change the directionality of a textarea that is connected to a TinyMCE toolbar, by directly using the same commands that are created in plugins? What I mean is, I want to programmatically run the RTL directionality without actually clicking on the toolbar's icon.
In the source code of the directionality plugin, the following code is included:
        ed.addCommand('mceDirectionRTL', function() {
            setDir("rtl");
        });

This means that mceDirectionRTL is a command. Can I use it directly in the code? I tried but it isn't recognized.
The reason I'm asking is that I want to run this command AFTER a tinyMCE instance is started, not during the initialization/setup function of the TinyMCE toolbar. I have a bunch of texraeas, some are english and some have the class ar to denote they are for Arabic, which is RTL.
But when I do this:
$('ID of my textarea'_ifr').contents().find('body').attr('dir', 'rtl');
Then everything is fine except that the mceExternalToolbar (the whole toolbar!) not just the textarea, becomes rtl. So the external toolbar basically goes out of place, and leans to the right side of the page. But I only want the textarea that it is connected to to have RTL text, not the whole toolbar!
So I want to somehow externally simulate clicking the RTL button on the toolbar AFTER the toolbar is instantiated. Is this possible?

A: Set and redraw may be a solution:
http://www.tinymce.com/forum/viewtopic.php?id=9735
tinyMCE.settings['directionality'] = 'rtl';
tinyMCE.execCommand( 'mceRemoveControl', false, 'editor );
tinyMCE.execCommand( 'mceAddControl', false, 'editor );

A: If you "install" the directionality plugin you can do something like this. You also need the reference to tinyMCE.
function(directionality){
    var command = directionality == 'ltr' ? 'mceDirectionLTR' : 'mceDirectionRTL'
    for(var i = 0; i++; i<tinyMCE.editors.length;{
    tinyMCE.editors[i].execCommand(command)
    }
}

I have two editors on my site. It seems to get the job done for me.

A: No need to build a new plugin

*

*Use the directionality plugin

*Then add rtl & ltr buttons to toolbar
      options:{
          selector: '#editor1',
          height: 350,
          language: 'fa_IR',
          plugins: 'directionality',
          toolbar: 'rtl ltr',
      }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is my crontab not working, and how can I troubleshoot it?
This is a Canonical Question about using cron & crontab.

You have been directed here because the community is fairly sure that the answer to your question can be found below. If your question is not answered below then the answers will help you gather information that will help the community help you. This information should be edited into your original question.
The answer for 'Why is my crontab not working, and how can I troubleshoot it?' can be seen below.  This addresses the cron system with the crontab highlighted.

A: PHP-specific
If you have some cron job like:
php /bla/bla/something.php >> /var/logs/somelog-for-stdout.log

And in case of errors expect, that they will be sent to you, but they not -- check this.
PHP by default not sending errors to STDOUT. @see https://bugs.php.net/bug.php?id=22839
To fix this, add in cli`s php.ini or in your line (or in your's bash wrapper for PHP) these:

*

*--define display_startup_errors=1

*--define display_errors='stderr'

1st setting will allow you to have fatals like 'Memory oops' and 2nd -- to redirect them all to STDERR. Only after you can sleep well as all will be sent to your root's mail instead of just logged.

A: How to fix all of your crontab related woes/problems (Linux)

This is a community wiki, if you notice anything incorrect with this answer or have additional information then please edit it.

First, basic terminology:

*

*cron(8) is the daemon that executes scheduled commands.

*crontab(1) is the program used to modify user crontab(5) files.

*crontab(5) is a per user file that contains instructions for cron(8).

Next, education about cron:
Every user on a system may have their own crontab file. The location of the root and user crontab files are system dependant but they are generally below /var/spool/cron.
There is a system-wide /etc/crontab file, the /etc/cron.d directory may contain crontab fragments which are also read and actioned by cron.  Some Linux distributions (eg, Red Hat) also have /etc/cron.{hourly,daily,weekly,monthly} which are directories, scripts inside which will be executed every hour/day/week/month, with root privilege.
root can always use the crontab command; regular users may or may not be granted access.  When you edit the crontab file with the command crontab -e and save it, crond checks it for basic validity but does not guarantee your crontab file is correctly formed.  There is a file called cron.deny which will specify which users cannot use cron.  The cron.deny file location is system dependent and can be deleted which will allow all users to use cron.
If the computer is not powered on or crond daemon is not running, and the date/time for a command to run has passed, crond will not catchup and run past queries.
crontab particulars, how to formulate a command:
A crontab command is represented by a single line. You cannot use \ to extend a command over multiple lines. The hash (#) sign represents a comment which means anything on that line is ignored by cron. Leading whitespace and blank lines are ignored.
Be VERY careful when using the percent (%) sign in your command. Unless they are escaped \% they are converted into newlines and everything after the first non-escaped % is passed to your command on stdin.
There are two formats for crontab files:

*

*User crontabs
 # Example of job definition:
 # .---------------- minute (0 - 59)
 # |  .------------- hour (0 - 23)
 # |  |  .---------- day of month (1 - 31)
 # |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
 # |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
 # |  |  |  |  |
 # *  *  *  *  *   command to be executed

*System wide /etc/crontab and /etc/cron.d fragments
 # Example of job definition:
 # .---------------- minute (0 - 59)
 # |  .------------- hour (0 - 23)
 # |  |  .---------- day of month (1 - 31)
 # |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
 # |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
 # |  |  |  |  |
 # *  *  *  *  * user-name  command to be executed

Notice that the latter requires a user-name. The command will be run as the named user.
The first 5 fields of the line represent the time(s) when the command should be run.
You can use numbers or where applicable day/month names in the time specification.

*

*The fields are separated by spaces or tabs.

*A comma (,) is used to specify a list e.g 1,4,6,8 which means run at 1,4,6,8.

*Ranges are specified with a dash (-) and may be combined with lists e.g. 1-3,9-12 which means between 1 and 3 then between 9 and 12.

*The / character can be used to introduce a step e.g. 2/5 which means starting at 2 then every 5 (2,7,12,17,22...). They do not wrap past the end.

*An  asterisk (*) in a field signifies the entire range for that field (e.g. 0-59 for the minute field).

*Ranges and steps can be combined e.g. */2 signifies starting at the minimum for the relevant field then every 2 e.g. 0 for minutes( 0,2...58), 1 for months (1,3 ... 11)  etc.

Debugging cron commands
Check the mail!
By default cron will mail any output from the command to the user it is running the command as. If there is no output there will be no mail. If you want cron to send mail to a different account then you can set the MAILTO environment variable in the crontab file e.g.
MAILTO=user@somehost.tld
1 2 * * * /path/to/your/command

Capture the output yourself
You can redirect stdout and stderr to a file. The exact syntax for capturing output may vary depending on what shell cron is using. Here are two examples which save all output to a file at /tmp/mycommand.log:
1 2 * * * /path/to/your/command &>/tmp/mycommand.log
1 2 * * * /path/to/your/command >/tmp/mycommand.log 2>&1

Look at the logs
Cron logs its actions via syslog, which (depending on your setup) often go to /var/log/cron or /var/log/syslog.
If required you can filter the cron statements with e.g.
grep CRON /var/log/syslog

Now that we've gone over the basics of cron, where the files are and how to use them let's look at some common problems.
Check that cron is running
If cron isn't running then your commands won't be scheduled ...
ps -ef | grep cron | grep -v grep

should get you something like
root    1224   1  0 Nov16 ?    00:00:03 cron

or
root    2018   1  0 Nov14 ?    00:00:06 crond

If not restart it
/sbin/service cron start

or
/sbin/service crond start

There may be other methods; use what your distro provides.
cron runs your command in a restricted environment.
What environment variables are available is likely to be very limited.  Typically, you'll only get a few variables defined, such as $LOGNAME, $HOME, and $PATH.
Of particular note is the PATH is restricted to /bin:/usr/bin. The vast majority of "my cron script doesn't work" problems are caused by this restrictive path.  If your command is in a different location you can solve this in a couple of ways:

*

*Provide the full path to your command.
 1 2 * * * /path/to/your/command

*Provide a suitable PATH in the crontab file
 PATH=/bin:/usr/bin:/path/to/something/else
 1 2 * * * command

If your command requires other environment variables you can define them in the crontab file too.
cron runs your command with cwd == $HOME
Regardless of where the program you execute resides on the filesystem, the current working directory of the program when cron runs it will be the user's home directory.  If you access files in your program, you'll need to take this into account if you use relative paths, or (preferably) just use fully-qualified paths everywhere, and save everyone a whole lot of confusion.
The last command in my crontab doesn't run
Cron generally requires that commands are terminated with a new line. Edit your crontab; go to the end of the line which contains the last command and insert a new line (press enter).
Check the crontab format
You can't use a user crontab formatted crontab for /etc/crontab or the fragments in /etc/cron.d and vice versa.  A user formatted crontab does not include a username in the 6th position of a row, while a system formatted crontab includes the username and runs the command as that user.
I put a file in /etc/cron.{hourly,daily,weekly,monthly} and it doesn't run

*

*Check that the filename doesn't have an extension see run-parts

*Ensure the file has execute permissions.

*Tell the system what to use when executing your script (eg. put #!/bin/sh at top)

Cron date related bugs
If your date is recently changed by a user or system update, timezone or other, then crontab will start behaving erratically and exhibit bizarre bugs, sometimes working, sometimes not.  This is crontab's attempt to try to "do what you want" when the time changes out from underneath it.  The "minute" field will become ineffective after the hour is changed.  In this scenario, only asterisks would be accepted.  Restart cron and try it again without connecting to the internet (so the date doesn't have a chance to reset to one of the time servers).
Percent signs, again
To emphasise the advice about percent signs, here's an example of what cron does with them:
# cron entry
* * * * * cat >$HOME/cron.out%foo%bar%baz

will create the ~/cron.out file containing the 3 lines
foo
bar
baz

This is particularly intrusive when using the date command. Be sure to escape the percent signs
* * * * * /path/to/command --day "$(date "+\%Y\%m\%d")"

How to use sudo in cron jobs
when running as a non-root user,
crontab -e

will open the user's crontab, while
sudo crontab -e

will open the root user's crontab. It's not recommended to run sudo commands in a cron job, so if you're trying to run a sudo command in a user's cron, try moving that command to root's cron and remove sudo from the command.

A: Adding my answer from here for completeness, and adding another potentially helpful resource:
The cron user has a different $PATH than you do:
A frequent problem users make with crontab entries is that they forget that cron runs in a different environment than they do as a logged-in user. For example, a user creates a program or script in his $HOME directory, and enters the following command to run it:
$ ./certbot ...

The command runs perfectly from his command line. The user then adds that command to his crontab, but finds this does not work:
*/10 * * * * ./certbot ....

The reason for the failure in this case is that ./ is a different location for the cron user than it is for the logged-in user. That is, the environment is different! The PATH is part of the environment, and it is usually different for the cron user. Complicating this issue is that the environment for cron is not the same for all *nix distributions, and there are multiple versions of cron
A simple solution to this particular problem is to give the cron user a complete path specification in the crontab entry:
0 22 * * * /path/to/certbot .....

What is the cron user's environment?
In some instances, we may need to know the complete environment specification for cron on our system (or we may just be curious). What is the environment for the cron user, and how is it different from ours? Further, we may need to know the environment for another cron user - root for example... what is the root user's environment using cron? One way to learn this is to ask cron to tell us:

*

*Create a shell script in your home directory (~/) as follows (or with the editor of your choice):

$ nano ~/envtst.sh

*Enter the following in the editor, after adjusting for your system/user:

#!/bin/sh
/bin/echo "env report follows for user "$USER >> /home/you/envtst.sh.out
/usr/bin/env >> /home/you/envtst.sh.out
/bin/echo "env report for user "$USER" concluded" >> /home/you/envtst.sh.out
/bin/echo " " >> /home/you/envtst.sh.out

*Save the file, exit the editor and set file permissions as executable.

$ chmod a+rx ~/envtst.sh

*Run the script you just created, and review the output in /home/you/envtst.sh.out. This output will show your current environment as the $USER you're logged in as:

$ ./envtst.sh $$ cat /home/you/envtst.sh.out

*Open your crontab for editing:

$ crontab -e -u root

*Enter the following line at the bottom of your crontab:

* * * * *  /home/you/envtst.sh >> /home/you/envtst.sh.err 2>&1

ANSWER: The output file /home/you/envtst.sh.out will contain a listing of the environment for the "root cron user". Once you know that, adjust your crontab entry accordingly.
I can't specify the schedule I need in my crontab entry:
The schedule entry for crontab is of course defined in man crontab, and you should read this. However, reading man crontab, and understanding the schedule are two different things. And trial-and-error on a schedule specification can become very tedious. Fortunately, there is a resource that can help: the crontab guru.. Enter your schedule specification, and it will explain the schedule in plain English language.
Finally, and at risk of being redundant with one of the other answers here, do not get trapped into thinking that you are limited to a single crontab entry because you have one job to schedule. You are free to use as many crontab entries as you need to get the schedule you need.

A: Debian Linux and its derivative (Ubuntu, Mint, etc) have some peculiarities that may prevent your cron jobs from executing; in particular, the files in /etc/cron.d, /etc/cron.{hourly,daily,weekly,monthly} must :

*

*be owned by root

*only be writable by root

*not be writable by group or other users

*have a name without any dots '.' or any other special character but '-' and '_' .

The last one hurts regularly unsuspecting users; in particular any script in one of these folders named whatever.sh, mycron.py, testfile.pl, etc. will not be executed, ever.
In my experience, this particular point has been by far the most frequent reason for a non-executing cronjob on Debian and derivatives.
See man cron for more details, if necessary.

A: If your cronjobs stop working, check that your password hasnt expired., since once it has, all cron jobs stop.
There will be messages in /var/log/messages similar to the one below which show issues with authenticating the user:

(username) FAILED to authorize user with PAM (Authentication token is no longer valid; new one required)

A: Uncommon and irregular schedules
Cron is all things considered a very basic scheduler and the syntax does not easily allow an administrator to formulate slightly more uncommon schedules.
Consider the following job which commonly would be explained to "run command every 5 minutes":
*/5 * * * * /path/to/your/command

versus:
*/7 * * * * /path/to/your/command

which  does not always run command every 7 minutes.
Remember that the / character can be used to introduce a step but that steps don't wrap beyond the end of a series e.g. */7 which matches every 7th minute from the minutes 0-59  i.e. 0,7,14,21,28,35,42,49,56 but between one hour and the next there will be only 4 minutes between batches, after  00:56 a new series starts at  01:00,  01:07 etc. (and batches won't run on 01:03 , 01:10 , 01:17 etc.).

What to do instead?
Create multiple batches
Rather than a single cron job, create multiple batches that combined result in the desired schedule.
For instance to run a batch every 40 minutes (00:00, 00:40, 01:20, 02:00 etc.) create two batches, one that runs twice on the even hours and second one that runs only the odd hours:
# The following lines create a batch that runs every 40 minutes i.e.

# runs on   0:00, 0:40,        02:00, 02:40         04:00 etc to 22:40
0,40 */2 * * * /path/to/your/command

# runs on               01:20,               03:20,       etc to 23:20
20 1/2 * * * /path/to/your/command

# Combined: 0:00, 0:40, 01:20, 02:00, 02:40, 03:20, 04:00 etc.

Run your batches less frequently
Rather than running your batch every 7 minutes, which is a difficult schedule to break down in multiple batches, simply run it every 10 minutes instead.
Start your batches more frequently (but prevent multiple batches from running concurrently)
Many odd schedules evolve because the batch runtimes increase/fluctuate and then the batches get scheduled with a bit of additional safety margin to prevent subsequent runs of the same batch from overlapping and running concurrently.
Instead, think differently and create a cronjob that will fail gracefully when a previous run has not finished yet, but which will run otherwise. See this Q&A:
* * * * * /usr/bin/flock -n /tmp/fcj.lockfile /usr/local/bin/frequent_cron_job

That will almost immediately start a new run once the previous run of  /usr/local/bin/frequent_cron_job has completed.
Start your batches more frequently (but exit gracefully when the conditions are not right)
Since cron syntax is limited you may decide to place more complex conditions and logic in the batch job itself (or in a wrapper script around the existing batch job). That allows you to utilize the advanced capabilities of your favorite scripting languages, to comment your code and will prevent hard-to-read constructs in the crontab entry itself.
In bash the seven-minute-job would then look something like something like:
#!/bin/bash
# seven-minute-job
# This batch will only run when 420 seconds (7 min) have passed
# since the file /tmp/lastrun was either created or updated

if [ ! -f /tmp/lastrun ] ; then
    touch /tmp/lastrun
fi

if [ $(( $(date +%s) - $(date -r /tmp/lastrun +%s) )) -lt 420 ] ; then
     # The minimum interval of 7 minutes between successive batches hasn't passed yet.
    exit 0
fi

####  Start running your actual batch job below

/path/to/your/command

#### actual batch job is done, now update the time stamp
date > /tmp/lastrun
#EOF

Which you can then safely (attempt) to run every minute:
* * * * * /path/to/your/seven-minute-job

A different, but similar problem would to schedule a batch to run on the first Monday of every month (or the second Wednesday) etc. Simply schedule the batch to run every Monday and exit when date is neither between the 1st or 7th and the day of the week is not Monday.
#!/bin/bash
# first-monday-of-the-month-housekeeping-job

# exit if today is not a Monday (and prevent locale issues by using the day number)
if [ $(date +%u) != 1 ] ; then
  exit 0
fi

# exit if today is not the first Monday
if [ $(date +%d) -gt 7 ] ; then
  exit 0
fi

####  Start running your actual batch job below

/path/to/your/command

#EOF

Which you can then safely (attempt) to run every Monday:
0 0 * * 1 /path/to/your/first-monday-of-the-month-housekeeping-job

Don't use cron
If your needs are complex you might consider using a more advanced product that is designed to run complex schedules (distributed over multiple servers) and that supports triggers, job dependencies, error handling, retries and retry monitoring etc. The industry jargon would be  "enterprise" job scheduling and/or "workload automation".

A: As @Seamus said, 99% of my crontab problems come from having different environmental variables or different PATH variables so crontab can't find the script and it fails silently. Therefore my solution was to write a wrapper script that would:

*

*Sets the PATH variable to the same one I'm used to

*Sets my PYTHONPATH to my custom one to include all of my common functions

*Changes the DISPLAY AND DBUS variables so that gui apps like notify-send messages actually make it to the screen

*Changes the current working directory to the same one as the script. (If applicable)

*Launches the script with nice ionice -c3 to save on resources.

*Logs the stdout and stderr of the script in the "logs" directory so that when something goes wrong I can actually find out what happened.

Now if I want to launch a script I just edit mycrontab with crontab -e to:
 mm hh * * * /path-to.../cron.launcher.py script.name.sh

and it runs the script just as if I was trying to from the terminal without any aggravation. This was originally a BASH script, but it got hung up on arguments with spaces so I rewrote it all in python. It will even launch GUI apps into the userspace:
#!/usr/bin/python3

# Runtime directories:
SYSPATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"
PYTHONPATH = ""

################################################################################
import os
import time
import sys
import subprocess

# Get username passed by crontab
user = os.environ['LOGNAME']
uid = subprocess.check_output(('id -u ' + user).split()).decode().strip()
gid = subprocess.check_output(('id -g ' + user).split()).decode().strip()

# Set Environmental Variables:
os.environ["PATH"] = SYSPATH
os.environ["PYTHONPATH"] = PYTHONPATH
os.environ["DISPLAY"] = ":0"
os.environ["XAUTHORITY"] = os.path.join('/home', user, '.Xauthority')
os.environ["DBUS_SESSION_BUS_ADDRESS"] = 'unix:path=' + os.path.join('/run/user', uid, 'bus')
os.environ["XDG_RUNTIME_DIR"] = os.path.join("/run/user", uid)

# Get args:
script = sys.argv[1]
args = sys.argv[2:]
name = os.path.basename(script)
basedir = os.path.dirname(sys.argv[0])

# Log dir
logdir = os.path.join(basedir, 'cron.logs')
log = os.path.join(logdir, name + '.' + str(int(time.time())) + '.log')
os.makedirs(logdir, exist_ok=True)
if not os.access(logdir, os.W_OK):
    print("Can't write to log directory", logdir, file=sys.stderr)
    sys.exit(1)

# If running as root, lock up any scripts so others can't edit them before root runs them.
if os.geteuid() == 0:
    cron_log = os.path.join(logdir, 'cron.launcher.root.log')
    for path in [script, sys.argv[0]] + list(filter(None, PYTHONPATH.split(':'))):
        print("Setting permisisons for", path)
        subprocess.run(('chown root -R ' + path).split(), stderr=subprocess.PIPE, check=False)
        subprocess.run(('chmod og-w -R ' + path).split(), stderr=subprocess.PIPE, check=False)
else:
    cron_log = os.path.join(logdir, 'cron.launcher.log')
cron_log = open(cron_log, 'a')
logger = lambda *args: cron_log.write(' '.join(map(str, args)) + '\n')

# Run the script
output = open(log, mode='w')
if os.path.exists(script):
    os.chdir(os.path.dirname(script))
cmd = ['nice', 'ionice', '-c3'] + [script] + args
logger(time.strftime('\n%m-%d %H:%M', time.localtime()).lstrip('0'), user, "running:")
logger(cmd)
logger("in directory", os.getcwd(), "with log in", log)
start = time.time()
ret = subprocess.run(cmd, stdout=output, stderr=output, check=False)

# Cleanup
fmt = lambda num: ("{0:.3g}").format(num) if abs(num) < 1000 else str(int(num))
logger("Returned", ret.returncode, "after", fmt(time.time() - start), 'seconds')
output.close()
cron_log.close()

Make sure you double check your $PATH and $PYTHONPATH variables in case you need to edit them to be different.


text:
Q: REGEX to match a string I'm trying to match string on statement
Need a single regex(perl) to match 123 in following condition

*

*TEST|^~\&|NET^OPT|123^FL|

*TEST|^~\&|NET^OPT|123|

A: Something as simple as ^(?:[^|]+\|){3}(\w+) should work. All you need to make sure is to escape a bunch of the characters.
^(?:[^|]+\|){3}(\w+)

DEMO


text:
Q: document.onclick only execute for a specific div I've this code below:

document.onclick = function () {
    console.log("Hello");
}

Click me

I want to execute the console.log only when I click in this div class="label-search"without add onclick in div.
Thank you.

A: Select the div to apply the onclick to that div
Using
document.getElementsByClassName

document.getElementsByClassName('label-search')[0].onclick = function () {
    console.log("Hello");
}

aa

Using querySelector

document.querySelector('.label-search').onclick = function () {
    console.log("Hello");
}

aa

A: You have to target the div element to execute the function on clicking on it. You can use Document.querySelector()

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

document.querySelector('.label-search').onclick = function () {
    console.log("Hello");
}

Click

A: You need to specify the element you want to set the click functionality of using it's onclick property. At the moment you are adding it to the entire document.
In this case you can use:
document.querySelector('.label-search')
to get your div which has the class label-search, and then use .onclick to set its click functionality.
See working example below:

document.querySelector('.label-search').onclick = function() {
  console.log("Hello");
}

Label Search

Using this you can avoid adding the onclick attribute to your div

A: You need to assign unique attribute (id) to your element:

 and attach event listener to your specific element:

document.querySelector('#clickmediv').addEventListener('click',function(){console.log("Hello!");});
.label-search {
  width: 100px;
  height: 100px;
  background-color: blue;
}

Click me

A: Other answers used querySelector and getElementsByClassName. If you want to take in consideration performance, you could do something like this:

let element = document.getElementById("elementToBeClicked");
element.onclick = () => console.log("I was clicked !!!!");

Click Me Please!

The Document method getElementById() returns an Element object representing the element whose id property matches the specified string

I advise you to use getElementById because is faster then using queryselector (check this to see the performance differences and test your self here).
Also, if you don't know what is arrow function () => console.log("I Was Clicked!!!") you can check in here a nice explanation.

A: You can do this by below 3 methods:

*

*User querySelector:
document.querySelector('.label-search').onclick = function () {
    console.log("Hello");
}

*GetElementByClassName
document.getElementsByClassName('label-search')[0].onclick = function () {
    console.log("Hello");
}

*If you can replace class with id
class="label-search" replace with id="label-search"
let element = document.getElementById("label-search");
element.onclick = () => console.log("Hello");


text:
Q: Understanding how to construct an Infinitival Relative Clause

*

*The best place from which to set out is Aberdin (Pullum) - correct

*There is one wood in the entire town in which to find wood peckers - wrong

*Jellyfish tentacles are barbed venomous stingers not to be touched -  wrong

*That's a magnificent waterfall spot at which to have a good time. - wrong

*This year Antarctica saw the highest ever temperature to have been recorded by researchers. - ???

The basic principle I used in constructing the sentences (2-5 ) is identical to the one in Pullum's example. (wh-type/ non-wh, guess, doesn't make any difference).
Why the 1st sentence is correct and the others, built on the same principle, are not?
Is Infinitival RC used in Superlative constructions only?
How about

This is one of the problems to be solved.

Here's a very interesting item for you to read (+for)

Would very much appreciate any help, because I am so much confused.


text:
Q: Is this a proper small signal H-bridge? The inductor in the middle is the coil of a single-coil latching relay, which requires a H-bridge to drive.
How do I add flyback to the 74HC04's internal MOSFETs? Or should I just rely on body diodes?

simulate this circuit – Schematic created using CircuitLab

A: The absolute maximum ratings of the LVC family do not allow for 12V to be applied to an output (6.5V max), even of an OD device. You should either use a NMOSFET directly (since you seem to want to invert the input regardless) or use a 7406/7416 (since you want 3.3V interfacing) instead.

A: Modern logic gates are not rated for 12Vdc ! The old HEFcmos series that would handle the volts has a very low gaurenteed Output current capability.Another hassle with old HEF is that inputs should be 12V so you would be up for some sort of level shifting .Why not use a mosfet driver like a mc4426 or similiar .They come in 8 pin package ,They are made by many manufacturers,They are generaly rated at 18V ,They accept 3v3 or 5v logic with thier mosfet inputs .You dont need pull up resistors or freewheeling diodes with these mosfet driver chips .It really is a full bridge .


text:
Q: How to Check NPM Dependencies with CI I've recently been trying to find a way to have a regular check on the dependencies of a project, this would ideally look for new versions of packages as well as deprecation.
At the moment, npm-check, depcheck and other such plugins seem to either not work or aren't returning the results that I'd expect (i.e. not flagging unused dependencies).
Does anyone know of a good way to test for this kind of thing?

A: For new versions of packages, I've been pleased with greenkeeper. It sends you pull requests whenever a new version of a package you depend on is released. Then your CI configuration should run tests against the code in the PR.
Not sure if they currently warn about deprecated packages, but the theory is if you are always using the latest release, you will never be using a deprecated version. That is unless the entire package and all versions get deprecated for some reason.
I don't believe it flags unused dependencies either, but you might consider asking them to add that feature. Their support seems pretty attentive to the needs of users.

A: I ended up using the David NPM module to check the status of the packages and pass / fail a mocha test based on the result:
https://github.com/alanshaw/david
You can see the example code on web-starter-kit:
https://github.com/google/web-starter-kit/blob/11562f490fe17cfc88ba86742de6345469b70779/test/dependency-checker.js


text:
Q: WHMCS - Editing purchased theme by overriding specific files I want to customize the purchased WHMCS theme but I don't want to loose the changes when the theme is updated.
So, is there a way to create a child type of theme just like we do on Wordpress. If not, please advice the best method to do it in WHMCS.

A: WHMCS doesn't support clientarea template files overriding as in WP.
Use git to follow changes in the original purchased template, as described in Six template page


text:
Q: Can I install Ubuntu on a USB stick when running it in a virtual machine? Can I create (for example) an Ubuntu virtual machine, plug in my USB stick and then install Ubuntu on the USB stick from the Ubuntu running in the virtual machine?

A: Yes you can make the bootable Ubuntu on USB from Ubuntu on Virtual Box.
In the VirtualBox menu select your flash drive from the USB devices, now the virtual Ubuntu detects and mounts the USB flash drive. Now go to  System → Administration → Startup Disk Creator.

Thats it!
Installing onto the USB
I think it can be done, I tried it.

Selected my 8 GB pendrive and configured it to EXt3/Journal file system where flash drive is usually fat32, ext filesystem is usually recommend by the Ubuntu site.

and click Install Now.
A half hour passed and the progress bar reached 60% but it was my bad. The power was gone and the system shut down.
I can't do the same and confirm the procedure for you but I hope my experience helps you. This is enough to say that it works.


text:
Q: Restart a windows 7 machine programmatically I have a requirement to trigger a reboot on a windows7 machine programmatically. This is to support a scenario for customers where when they log out of an intenet kiosk machine the machine reboots. On XP this was achieved using WTSSystemShutdown but Im wondering if theres another way. Any pointers greatly appreciated.

A: You can call ExitWindowsEx to restart, shutdown, logoff, etc.
Use InitiateShutdown (Vista) or InitiateSystemShutdownEx (Win2k or higher) to shutdown a computer remotely.

A: I answered a similar question here (complete with sample code):

Log off user from Win XP programmatically in C# (ExitWindowsEx)

Just change the uFlags parameter to ExitWindows.Reboot.


text:
Q: Hash in front of a SASS argument I was wondering what was the difference between :
@mixin transition($args...) {
  -webkit-transition: $args;
  -moz-transition: $args;
  -ms-transition: $args;
  -o-transition: $args;
  transition: $args;
}

and
@mixin transition($args...) {
  -webkit-transition: #{$args};
  -moz-transition: #{$args};
  -ms-transition: #{$args};
  -o-transition: #{$args};
  transition: #{$args};
}

what is the purpose of having an # in front of the argument ?

A: The #{} syntax will interpolate the value in the curly braces into a string. This is useful, for example, in the following situations, when your variable only makes up part of the string. eg:
@mixin background-image($directory) {
    background-image: /#{$directory}image.jpg;
}

In this way, the SASS interpreter understands where the variable $directory ends.
If you were to do it this way, the compiler would get confused:
@mixin background-image($directory) {
    background-image: $directoryimage.jpg;
}

In your given example, it is not needed. Both versions would produce the same results.
You can do this outside of mixins as well. Consider this example using a for loop:
@for $i from 1 through 3 {
  .item-#{$i} { width: 2em * $i; }
}

Which would produce:
.item-1 { width: 2em; }
.item-2 { width: 4em; }
.item-3 { width: 6em; }

A: The #{} syntax in SASS is used to escape strings. Probably in your example it won't be really usefull unless you are performing really complicated stuff.
Usually you would use the escape # symbol to variabilize the names of attributes. For example to automatically create a series of themes just using lists:
$themes: theme1, theme2, theme3;
$colors: red, blue, green;

@mixin colorTheme($keyColor) {
  color: nth($colors, $keyColor);
}

@each $theme in $themes {
  .class-#{$theme} {
    @include colorTheme(index($themes, $theme));
  }
}

Would compile to:
.class-theme1 {
  color: red;
}

.class-theme2 {
  color: blue;
}

.class-theme3 {
  color: green;
}


text:
Q: clang and gcc linters checks syntax wrong I use ALE vim plugin which lints with clang and gcc by default. If I write program on C and define variable of ssize_t type ALE will marks it as mistake with message "unknown type name 'ssize_t'; did you mean 'size_t'?", regardless of ssize_t is defined in stdio.h and program is compiled successfully by gcc. I suppose that gcc and clang linters doesn't follow stdio.h and need to be configured. Probably I should set g:ale_c_clang_options and g:ale_gcc_options variables in vim. I have tried

let g:ale_c_clang_options = '-std=c11 -Wall -I/usr/include'
let g:ale_linters = {'c': ['clang']}

Result is the same.
UPD:
I have changed linters dictionary in .vimrc and error message disappears.
let g:ale_linters = {'c': ['clangtidy']}
But I still don't know how to configure clang and gcc linters proper way.


text:
Q: How to change the color of the green background present when compiling apps using Emscripten-qt (behind the window) I am using Emscripten-qt to compile Native Qt apps into Javascript.   The application is simple and works fine.  The only problem I am having is that  the   Canvas  has a green background that displays behind the Window.   I want to know how I can change that green background to a different color in order to stick with my color scheme.

Thanks..
mike


text:
Q: Crontab errors running a Python Script I have the simple test script:
#! /usr/local/bin/python3
import os
from datetime import date

tday = date.today().strftime('%-m%-d%-y')
dirName = 'Repository' + tday
os.mkdir(dirName)

I set the script by chmod x+a test.py
I place this script on my Desktop, and created a crontab to run it:
* 12 * * * ~/Desktop/test.py
the script runs, but errors up as
'directory already exists' (logged to email).
where have I erred?

A: You're running the script every minute from 12:00 to 12:59. The first time it runs, it creates the directory for that day. The next 59 runs get an error because the directory already exists.
You only need it to run once a day, so change the schedule to
0 12 * * * ~/Desktop/test.py


text:
Q: how to calculate shoutPower for my libGdx game? this.maxHp = 100;
this.hp = this.maxHp;
it's mean objeact got 100hp and  if we hit object,  it's  subtracted 5 hp from object.
here is method th check if object take damage:
 public boolean takeDamage(int dmg) {

    hp -= dmg;

    reddish += 1.0f;

    if (hp <= 0) {

        return true;
  }
    return false;
}

here is method to check if bullet hit object:
public void checkCollisions() {
    List<Bullet> b = bulletEmitter.getActiveList();
    for (int i = 0; i < b.size(); i++) {
        for (int j = 0; j < players.size(); j++) {
            if (b.get(i).isArmed() && players.get(j).getHitArea().contains(b.get(i).getPosition())) {
                b.get(i).deactivate();
                 players.get(j).takeDamage(5);
                map.clearGround(b.get(i).getPosition().x, b.get(i).getPosition().y, 8);
                continue;
            }
        }

I need to show taking damage (int dmg), damage might be any variable which we put in  method  takeDamage(int dmg). int this case int dmg = 5;
I can't calculate it this:
result = maxHp - hp
increase result on 5hp with evry hit
5.. 10.. 15.. 20..
here is method, which i put font in:
        damageFont.draw(batch, "" + (maxHp - hp), position.x, position.y + 130, 85, 1, false);

    }
}

(maxHp - hp) - increase result on 5hp with evry hit  5.. 10.. 15.. 20..
instead this, i need to calculate ammount of deal damage, but not with constant values.
(maxHp - hp) something instead this just should return 5, if we put 5 in    takeDamage(int dmg)
or 10, if we put 10.
it's amount of damage take with evry hit:
should be 5, 5, 5, 5
not: 5... 10... 15... 20

A: Just like MarsAtomic mentioned you allready have your damage per hit, just save it as a new instance variable and display it instead of (maxHp - hp):
private int damageTaken;

public boolean takeDamage(int dmg) {
   damageTaken = dmg;
   hp -= dmg;

   reddish += 1.0f;

   if (hp <= 0) {

       return true;
   }
   return false;
}

and when you draw your font:
damageFont.draw(batch, "" + damageTaken, position.x, position.y + 130, 85, 1, false);


text:
Q: Php check if string contains multiple words I have looked around the internet for something that will do this but it will only work with one word.
I am trying to build a script that will detect a bad username for my site, the bad username will be detected if the username contains any of the words in an array.
Here's the code I made, but failed to work.
$bad_words = array("yo","hi");
$sentence = "yo";

if (strpos($bad_words,$sentence)==false) {
echo "success";
}

If anybody could help me, I would appreciate it.

A: use
substr_count
for an array use the following function
function substr_count_array( $haystack, $needle ) {
     $count = 0;
     foreach ($needle as $substring) {
          $count += substr_count( $haystack, $substring);
     }
     return $count;
}

A: You can use this code:
$bad_words = array("yo","hi");
$sentence = "yo you your";
// break your sentence into words first
preg_match_all('/\w+/', $sentence, $m);
echo ( array_diff ( $m[0], $bad_words ) === $m[0] ) ? "no bad words found\n" :
                                                      "bad words found\n";

A: // returns false or true
function multiStringTester($feed , $arrayTest)
{
    $validator = false;
    for ($i = 0; $i < count($arrayTest); $i++)
    {
            if (stringTester($feed, $arrayTest[$i]) === false )
            {
                continue;
            } else
            {
                $validator = true;
            }
    }
    return $validator;
}
//www.ffdigital.net

A: You're close. You can do it the following way:
$bad_words = array("yo","hi");
$sentence = "yo";
$match = false;
foreach($bad_words as $bad_word) {
  if (strpos($bad_word,$sentence) === false) {  # use $bad_word, not $bad_words
    $match = true;
    break;
  }
}
if($match) { echo "success"; }

A: <?php
function isUserNameCorrect()
{
    Foreach($badname in $badnames)
    {
        if(strstr($badname, $enteredname) == false)
        {
             return false;
        }
    }
    return true;
}

Maybe this helps

A: I believe a sentence is more than one single word
Try
$badwords = array("yo","hi");
$string  = "i am yo this is testing";
$word = array_intersect( $badwords,explode(" " , $string));
if(empty($word))
{
    echo "Sucess" ;
}

A: Unfortunately, you can't give an Array to functions strpos/strstr directly.
According to PHP.net comments, to do this you need to use (or create your own if you want) function like this:
function strstr_array($haystack, $needle)
{
     if ( !is_array( $haystack ) ) {
         return false;
     }
     foreach ( $haystack as $element ) {
         if ( stristr( $element, $needle ) ) {
             return $element;
         }
     }
}

Then, just change strpos to the new function - strstr_array:
$bad_words = array("yo","hi");
$sentence = "yo";

if (strstr_array($bad_words,$sentence)==false) {
     echo "success";
}

A: I'd implement this as follows:
$bad_words = array("yo","hi");
$sentence = "yo";

$valid = true;
foreach ($bad_words as $bad_word) {
    if (strpos($sentence, $bad_word) !== false) {
        $valid = false;
        break;
    }
}

if ($valid) {
    echo "success";
}

A sentence is valid unless it contains at least one word from $bad_words. Note the strict checking (i.e. !==), without this the check will fail when the result of strpos is 0 instead of false.


text:
Q: Simple Visual basic q in an excel macro Dim test As String

test = CStr(ActiveWorkSheet.VLookup("jpeg_lrg", B, 3))

stupid 424 error help!
for my macro in excel vba

Dim test As String

test = CStr(ActiveWorkSheet.VLookup("jpeg_lrg", B44, 3))

(didnt work as well)

also tried without the CSTR

A: I think you are trying to return the value of the cell of E44?
If that is the case, then this should work for you - replace MsgBox with the code you require.
For Each i In Range("B44")
    If i = "jpeg_lrg" Then
        MsgBox i.Offset(0, 2)
        Else
    End If
Next i

A: You can't just pass you ranges as variable names.
Dim test As String

test = Application.WorksheetFunction.VLookup("jpeg_lrg", ActiveSheet.Range("B:B"), 3)

That won't make any sense though, because "B:B" only contains one column, and you ask it for column three. With VLookup you want at least two columns in the range.


text:
Q: Error in Azure Functions when running locally which has nuget package reference I tried the approach that was discussed over here to run Azure Functions on local machine. I was able to compile and run locally fine with the samples. But when I tried referencing nuget package by adding a project.json file and adding the namespace in my function it started throwing compilation error. On the portal it works fine. Am I missing any step?
project.json
{
  "frameworks": {
    ".NETFramework,Version=v4.6": {
      "dependencies": {
        "Microsoft.Azure.DocumentDB": "1.6.3"
      }
    }
  }
}

run.csx
using System;
using System.Diagnostics;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.Documents;

public static void Run(TimerInfo input, TraceWriter log)
{
    log.Verbose("C# Timer trigger function executed.");
}

Thanks!

A: Krishh,
This should definitely work locally. You may need to check the following:

*

*Due to the way NuGet references are currently processed, please make sure you "touch" that file while the host is running. The host watches for file modifications and initiates a restore when it detects changes

*NuGet.exe (3.3.0 recommended) must either be in your path or you must have an environment variable named AzureWebJobs_NuGetPath set, with the path to nuget.exe

Hope this helps!


text:
Q: How can i use both folder path and file name in c# itextsharp? I have the following piece of code:
private void GeneratePDF()
        {

            string selectPath = "select * from PDFLocation";
            SqlCommand comm = con.CreateCommand();
            comm.CommandText = selectPath;
            con.Open();
            Int32 LocPath = (Int32)comm.ExecuteScalar();
            con.Close();

                string cln = NumCl.Text;
                string OrderID = NrComanda.Text;
                string DataAzi = dateTimePicker1.Text;
                string FileName = OrderID + "-" + cln + "-" + DataAzi + ".pdf";
                string fullpath = Path.Combine(LocPath.ToString(), FileName);

                Document doc = new Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 42, 35);
                PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(fullpath, FileMode.Create));
                doc.Open();
//-----PDF code after-----
}

The problem here is that i have a textbox which retrieves the pdf folder location path from a folder dialog and sends it to database. Now i want to retrieve the path stored in the database using this code so i can save the file there. If i use FileName variable instead of fullpath in the FileStream, it works but the file goes to the project folder, which i do not want. With fullpath in the FileStream like it is in the current code, it throws the error:
System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\Users\cloud\source\repos\Project\Project\bin\Debug\net6.0-windows10.0.22000.0\1\36-UserFile-14.12.2021.pdf'.'

Please tell me how to use both folder path and file name in the FileStream or is there any other way to do it?


text:
Q: Bad Response Code: URL returned a bad HTTP response code : 404 I have fixing this problem for many nights already....
Please help!
I have changed a lot of header to try. And I did put og:url and og:title on the html code of the page...
But the reports said I didn't do it....
The page cannot scraped....
https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Fwww.cmaj7th.com%2F
Is it something wrong which I don't know? Please help me!


text:
Q: Edit Custom Admin Page with Page Editor (e.g. Divi) I'm looking for a way to Edit a custom Wordpress Admin Page with a page builder, like Divi.
To create custom Admin Pages I used the Plugin 'Custom Admin Page' and it seems like it's not a custom Post type, so the way to enable Divi via custom post types doesn't work.
Is there maybe a way to make the plugin page as a custom post type and then enable Divi through that?

A: You can read how to use divi to create templates for custom post types in this


text:
Q: Delegate method not being called I have written some methods to implement push notifications (voip pushkit) in our app.  It works perfect in an Xcode project I created to test the code.  When I copy the code into the main project some delegate methods are not exceuted...
import UIKit
import PushKit
import AVFoundation
import CoreData
import Meteor
import Stripe

let Meteor = METDDPClient(serverURL: NSURL(string: "http://example.com/websocket")!)

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, PKPushRegistryDelegate {

    var voipRegistry:PKPushRegistry!
    let designAssets = DesignAssets()
    let stripePublishableKey: String = "xxxxx"
    var ringing: AVAudioPlayer!
    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        registerForVoIPPushes()
        return true
    }

    func registerForVoIPPushes() {

        let notificationSettings: UIUserNotificationSettings! = UIApplication.sharedApplication().currentUserNotificationSettings()

        if (notificationSettings.types == UIUserNotificationType.None) {
            let notificationTypes: UIUserNotificationType = [.Badge, .Sound, .Alert]
            let notificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
            UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
        }

        voipRegistry = PKPushRegistry(queue: dispatch_get_main_queue())
        voipRegistry.delegate = self
        voipRegistry.desiredPushTypes = Set([PKPushTypeVoIP])
        print("VOIP Push registered")
    }

    func pushRegistry(registry: PKPushRegistry!, didUpdatePushCredentials credentials: PKPushCredentials!, forType type: String!) {
        let voipToken: String! = credentials.token.description
        print("\n\n##### PushKit credential: \n\n", voipToken)
    }

The last method (didUpdatePushCredentials) is never evaluated, the token is never printed to the console... why ?  It works perfectly fine in the test project.

A: Duuuhhh, had forgotten to add the Background Modes


text:
Q: Write a (better)query that returns an aggregate with an associated value? Say I have table with 3 columns:
col1        col2        col3
1           green        10
1           blue         15
3           red          20
3           yellow        5
4           purple       17
4           black        11

I would like to obtain the max of col3, grouped by col1, while having the value of col2 that belongs to the same row as max(col3):
In other words, the following result set is the desired result:
col1        col2        col3
1           blue         15
3           red          20
4           purple       17

One way I thought of doing this is:
SELECT col1, col3, col2
FROM
(
    SELECT ROW_NUMBER() OVER (PARITTION BY col1 ORDER BY col3 DESC) AS rn, col1, col3, col2

) sub
WHERE sub.rn = 1;

But it feels like overkill(if it works), and I'd like to know if there is a much better, more efficient way?
Thanks

A: Here's a performance test using the code examples that @Bernie156 was kind enough to put together.  Be aware that his "TOP(1) With Ties" code does actually return ties, though.
Here's the test table... 1 million rows total (100K rows, 10 colors)
--===== Create a million row test table with an index.
     -- This takes less than a second with or without
     -- the index on my box and will produce some "Ties".
   DROP TABLE IF EXISTS #TestTable;
GO
 CREATE TABLE #TestTable
        (
          col1 INT
         ,col2 VARCHAR(10)
         ,col3 INT
        )
;
   WITH cteTally AS
(
 SELECT TOP 100000
         col1 = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
   FROM      sys.all_columns ac1
  CROSS JOIN sys.all_columns ac2
)
 INSERT INTO #TestTable WITH (TABLOCK)
        (col1,col2,col3)
 SELECT  t.col1
        ,v.col2
        ,v.col3
   FROM cteTally t
  CROSS APPLY
        (VALUES
         ('red'   ,CRYPT_GEN_RANDOM(1)%10)
        ,('orange',CRYPT_GEN_RANDOM(1)%10)
        ,('yellow',CRYPT_GEN_RANDOM(1)%10)
        ,('green' ,CRYPT_GEN_RANDOM(1)%10)
        ,('blue'  ,CRYPT_GEN_RANDOM(1)%10)
        ,('indigo',CRYPT_GEN_RANDOM(1)%10)
        ,('violet',CRYPT_GEN_RANDOM(1)%10)
        ,('purple',CRYPT_GEN_RANDOM(1)%10)
        ,('black' ,CRYPT_GEN_RANDOM(1)%10)
        ,('white' ,CRYPT_GEN_RANDOM(1)%10)
        )v(col2,col3)
;
  CREATE NONCLUSTERED INDEX ix_t ON #TestTable (Col1 ASC,col3 DESC,col2)
;
GO

Here's the test code.  If you only want one "winner" for each distinct instance of Col1, ROW_NUMBER() work just fine, especially with how simple it is.  If you want ties for the top spot of each instance of Col1 to be returned, just replace the ROW_NUMBER() with RANK() and "Bob's your Uncle".
Here's the test code...
GO
-------------------------------------------------------------------------------
PRINT REPLICATE('=',119);
RAISERROR('===== RANK Method ===== (Allows Ties)',0,0) WITH NOWAIT;
   DROP TABLE IF EXISTS #Results;
GO
    SET STATISTICS TIME,IO ON;

   WITH cteRank AS
(
 SELECT col1,col2,col3,TheRank = RANK() OVER(PARTITION BY col1 ORDER BY col3 DESC)
   FROM #TestTable
)
 SELECT col1,col2,col3
   INTO #Results
   FROM cteRank
  WHERE TheRank = 1
;
    SET STATISTICS TIME,IO OFF;
GO
-------------------------------------------------------------------------------
PRINT REPLICATE('=',119);
RAISERROR('===== ROW_NUMBER Method ===== (No Ties)',0,0) WITH NOWAIT;
   DROP TABLE IF EXISTS #Results;
GO
    SET STATISTICS TIME,IO ON;

SELECT col1, col3, col2
INTO #Results
FROM
(
    SELECT ROW_NUMBER() OVER (PARTITION BY t.col1 ORDER BY t.col3 DESC) AS rn, col1, col3, col2
    FROM #TestTable AS t
) sub
WHERE sub.rn = 1
;
    SET STATISTICS TIME,IO OFF;
GO
-------------------------------------------------------------------------------
PRINT REPLICATE('=',119);
RAISERROR('===== Traditional Aggregates ===== (Allows Ties)',0,0) WITH NOWAIT;
   DROP TABLE IF EXISTS #Results;
GO
    SET STATISTICS TIME,IO ON;

SELECT t.col1, t.col3, t.col2
INTO #Results
FROM
(
  SELECT t.col1, col3 = MAX(t.col3)
  FROM   #TestTable AS t
  GROUP BY t.col1
) AS s
JOIN #TestTable AS t ON t.col1 = s.col1 AND t.col3 = s.col3
;
    SET STATISTICS TIME,IO OFF;
GO
-------------------------------------------------------------------------------
PRINT REPLICATE('=',119);
RAISERROR('===== TOP 1 WITH TIES ===== (Doesn''t Actually Allow Ties)',0,0) WITH NOWAIT;
   DROP TABLE IF EXISTS #Results;
GO
    SET STATISTICS TIME,IO ON;

SELECT col1, col3, col2
INTO #Results
FROM
(
    SELECT TOP(1) WITH TIES col1, col3, col2
    FROM #TestTable AS t
    ORDER BY ROW_NUMBER() OVER (PARTITION BY t.col1 ORDER BY t.col3 DESC)
) sub
;
    SET STATISTICS TIME,IO OFF;

And, here are the results from my box...
=======================================================================================================================
===== RANK Method ===== (Allows Ties)
Table '#TestTable__________________________________________________________________________________________________________000000000090'.
 Scan count 1, logical reads 3891, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 SQL Server Execution Times:
   CPU time = 281 ms,  elapsed time = 283 ms.

(155903 rows affected)
=======================================================================================================================
===== ROW_NUMBER Method ===== (No Ties)
Table '#TestTable__________________________________________________________________________________________________________000000000090'.
 Scan count 1, logical reads 3891, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 SQL Server Execution Times:
   CPU time = 172 ms,  elapsed time = 160 ms.

(100000 rows affected)
=======================================================================================================================
===== Traditional Aggregates ===== (Allows Ties)
Table 'Workfile'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table '#TestTable__________________________________________________________________________________________________________000000000090'.
 Scan count 2, logical reads 7130, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 SQL Server Execution Times:
   CPU time = 375 ms,  elapsed time = 372 ms.

(155903 rows affected)
=======================================================================================================================
===== TOP 1 WITH TIES ===== (Doesn't Actually Allow Ties)
SQL Server parse and compile time:
   CPU time = 0 ms, elapsed time = 0 ms.
Table '#TestTable__________________________________________________________________________________________________________000000000090'.
 Scan count 13, logical reads 3985, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 SQL Server Execution Times:
   CPU time = 1562 ms,  elapsed time = 285 ms.

(100000 rows affected)

A: First, the best way to get a good answer here is to include some easily composable sample data and DDL. This allows us to actually play around and post a solution you can copy/paste and run locally. Something like this:
DECLARE @t TABLE
(
  col1 INT,
  col2 VARCHAR(10),
  col3 INT
  --,INDEX ix_t NONCLUSTERED (Col1 ASC,col3 DESC,col2)
);

INSERT @t(col1,col2,col3) VALUES
(1,'green',10),(1,'blue',15),(3,'red',20),(3,'yellow',5),(4,'purple',17),(4,'black',11);

The solution you posted is fine (though your syntax is wrong) There are a few ways to handle this. The window function solution (ROW_NUMBER() OVER...) is a actually quite elegant and efficient. Another approach would be to use traditional aggregation and a self-join. In either case, proper indexing is key.
Let's compare three solutions:
(1) Your ROW_NUMBER solution
(2) Aggregation + self-join
(3) a TOP(1) WITH TIES solution that uses your ROW_NUMBER logic in the ORDER BY clause
(1) ROW_NUMBER solution
SELECT col1, col3, col2
FROM
(
    SELECT ROW_NUMBER() OVER (PARTITION BY t.col1 ORDER BY t.col3 DESC) AS rn, col1, col3, col2
    FROM @t AS t
) sub
WHERE sub.rn = 1;

(2) Traditional Aggregates
SELECT t.col1, t.col3, t.col2
FROM
(
  SELECT t.col1, col3 = MAX(t.col3)
  FROM    @t AS t
  GROUP BY t.col1
) AS s
JOIN @t AS t ON t.col1 = s.col1 AND t.col3 = s.col3;

(3) TOP 1 WITH TIES
SELECT col1, col3, col2
FROM
(
    SELECT TOP(1) WITH TIES col1, col3, col2
    FROM @t AS t
    ORDER BY ROW_NUMBER() OVER (PARTITION BY t.col1 ORDER BY t.col3 DESC)
) sub;

Each query returns:
col1        col3        col2
----------- ----------- ----------
1           15          blue
3           20          red
4           17          purple

The TOP(1) WITH TIES solution is my favorite but it's the least efficient (sadly). To understand which will perform the best let's look at the execution plans with and without the proper index.

No Index plans

Here the GROUP BY solution is actually a wee-bit better as it does not require a filter or sequence project. The TOP(1) with TIES solution is the worst in that it requires two sorts. Now let's run this with the index on it.
Execution plan with an index

In this case the your solution is the best but not by much. The second index seek is trivial in that it's quickly retrieving the col2 value. The TOP(1) with TIES still gets a sort despite the index.
(note that col2 should be an include column but I went with a temp table)
Parallel Execution
For testing you can append each query with OPTION (QUERYTRACEON 8649) to see how the query does when ran with multiple CPUs. In this case all three are close but your ROW_NUMBER solution does not get a sort, the other two do.
The lesson here is that you need to try different methods and evaluation the execution plans.


text:
Q: Change href destination of child I have a bunch of blocks (divs) with child divs that have links (sp-pcp-readmore) I want to change the href value of every link (sp-pcp-readmore) with jQuery. The HTML for one div (block) is as follows:

        Machines

                Explore Now

The javascript I am having trouble with is this and it is not changing the href at all
        $(".sp-pcp-title").each(function() {
            switch($(this).text()) {
                case "Machines":
                        $(this).find(".pcp-readmore-link").attr('href', '/product-category/machines/');
                    break;
                case "Weights":
                        $(this).find(".pcp-readmore-link").attr('href', '/product-category/weights/')
                    break;
                case "Dumbells":
                        $(this).find(".pcp-readmore-link").attr('href', '/product-category/dumbells/')
                    break;
                case "Barbels":
                        $(this).find(".pcp-readmore-link").attr('href', '/product-category/barbels/')
                    break;
            }
        });

A: This can be vastly simplified
$(".sp-pcp-title").each(function() {
  let text = $("a",this).text().trim();
  $(this).next().find(".pcp-readmore-link").attr('href', `/product-category/${text.toLowerCase()}`);
});

$(".sp-pcp-title").each(function() {
  let text = $("a",this).text();
  $(this).next().find(".pcp-readmore-link").attr('href', `/product-category/${text.toLowerCase()}`);
});

    Machines

      Explore Now

Alternative
const hrefs = { "Machine":"machine", "Bar- and dumbells":"weights" }
$(".sp-pcp-title").each(function() {
  let text = $("a",this).text().trim();
  $(this).next().find(".pcp-readmore-link").attr('href', `/product-category/${hrefs[text]}`);
});

    const hrefs = { "Machines":"machines", "Bar- and dumbells":"weights" }
    $(".sp-pcp-title").each(function() {
      let text = $("a",this).text().trim();
      $(this).next().find(".pcp-readmore-link").attr('href', `/product-category/${hrefs[text]}`);
    });

    Bar- and dumbells

      Explore Now

A: This is changed according to your sample HTML code, the target link is not a child of .sp-pcp-title but next sibling inside .sp-pcp-post-content

   $(".sp-pcp-title").each(function() {
            switch($(this).children('a').text()) {
                case "Machines":
                        $(this).next('.sp-pcp-post-content').find(".pcp-readmore-link").attr('href', '/product-category/machines/');
                    break;
                case "Weights":
                        $(this).next('.sp-pcp-post-content').find(".pcp-readmore-link").attr('href', '/product-category/weights/')
                    break;
                case "Dumbells":
                        $(this).next('.sp-pcp-post-content').find(".pcp-readmore-link").attr('href', '/product-category/dumbells/')
                    break;
                case "Barbels":
                        $(this).next('.sp-pcp-post-content').find(".pcp-readmore-link").attr('href', '/product-category/barbels/')
                    break;
            }
        });

        Machines

                Explore Now


text:
Q: Summarizing Data Within SQL Hi everyone I am new hear and I'm stuck summarizing within my SQL Database.
To make the example very simple here is my data below.
GAME_ID       GOALIEID       SCORED
2001             5             N
2001             4             N
2001             5             Y
2001             4             N
2001             5             Y

This is a shootout and I want to summarize the amount of saves each goalie made by Game_ID, GoalieID, and how many saves were actually made by each.
The N=SAVE AND Y=GOAL GIVEN UP
I am trying to output my result as shown below in descending order:
GAME_ID      GOALIEID      SAVES
 2001           4           2
 2001           5           1

Currently based on my code:
SELECT GAME_ID, GOALIEID, COUNT(SCORED) AS SAVES
FROM GIRAFFE.MLS
WHERE SCORED = 'N'
GROUP BY GAME_ID
ORDER BY COUNT (SCORED) DESC

But the result I am getting is just adding up all saves and attributing it to one goalie as show below.
GAME_ID    GOALIEID    SAVES
 2001         5          3

THE ABOVE WAS RESOLVED.
The FINAL QUESTION TO FINALIZE THIs is how do you query for a STREAK in SQL
For example:
GAME_ID   GOALIEID    TEAMID    TEAMSHOTNUM  OVERALLSHOT   SCORED
2001         5           1            1            1          Y
2001         4           2            1            2          N
2001         5           1            2            3          N
2001         4           2            2            4          N
2001         5           1            3            5          N
2001         4           2            3            6          N

Based on this simple example:
How can I query for the most consecutive "Saves" which would be "N" by a "GoalieID" now imagine my data has multiple games to look through but for simplicity I only have the one game here.
My result I would hope to look like this:
GAME_ID     GOALIEID     STREAK
   2001        4           3

This would show that "GOALIEID" #4 made 3 consecutive saves to win the game showing that the highest consecutive streak of saves was in fact 3. Note remember this will be across thousands of games. But i made it simple here with just 1 game.
THANK YOU ALL FOR YOUR HELP!

A: Actually you should group by GAME_ID AND GOALIEID :
SELECT GAME_ID, GOALIEID, COUNT(SCORED) AS SAVES
FROM a
WHERE SCORED = 'N'
GROUP BY GAME_ID, GOALIEID
ORDER BY SAVES DESC


text:
Q: Emulator Nexus5X Android 8.0 Instant App I want to try to launch an Instant App (already deployed : like wish, or buzzfeed).
Now, I use Android Studio 3.0 to emulate a Nexus 5X API 26 With Android 8.0, I got the Instant App development SDK installed (1.1.0).
I have activated in Settings > Google > Instant App my account to use it. But when I'm searching with google for wish I cannot acceded to the Instant App (it only launch the normal website).
I tried :

*

*Change the countries of my device with a VPN

*Change the Android Version 7.1

*I update google chrome (61.0.3163.98) and services (11.5.18)

*I changed the device with a Nexus 5

*I tried to launch with gmail (vimeo, buzzfeed tasty ...)
I don't find why this is not working.
Name: Nexus_5X_API_26

CPU/ABI: Google Play Intel Atom (x86)

Target: google_apis_playstore [Google Play] (API level 26)

Skin: nexus_5x

SD Card: 100M

hw.dPad: no

hw.lcd.height: 1920

runtime.network.speed: full

hw.accelerometer: yes

hw.device.name: Nexus 5X

vm.heapSize: 256

skin.dynamic: yes

hw.device.manufacturer: Google

hw.lcd.width: 1080

hw.gps: yes

hw.initialOrientation: Portrait

image.androidVersion.api: 26

hw.audioInput: yes

image.sysdir.1: system-images/android-26/google_apis_playstore/x86/

tag.id: google_apis_playstore

showDeviceFrame: yes

hw.camera.back: emulated

hw.mainKeys: no

AvdId: Nexus_5X_API_26

hw.camera.front: emulated

hw.lcd.density: 420

avd.ini.displayname: Nexus 5X API 26

hw.gpu.mode: auto

hw.device.hash2: MD5:bc5032b2a871da511332401af3ac6bb0

hw.ramSize: 1536

hw.trackBall: no

PlayStore.enabled: true

fastboot.forceColdBoot: no

hw.battery: yes

hw.cpu.ncore: 2

hw.sdCard: yes

tag.display: Google Play

runtime.network.latency: none

hw.keyboard: yes

hw.sensors.proximity: yes

disk.dataPartition.size: 800M

hw.sensors.orientation: yes

avd.ini.encoding: UTF-8

hw.gpu.enabled: yes

Thank you for your help

A: Two things:

*

*Emulators can't talk to the instant apps backends, due to a bug (see SO question). They only work for local development.

*Some instant apps (e.g., wish) were published with targetSdkVersion < 26, and that's not supported on O devices (just instant apps. Installed apps don't have that restriction.) The developer console now disallows publishing with target < 26, but we continue to serve legacy, pre-restriction apps to pre-O devices. Unfortunately, it means that you'll see some of our popular instant apps stop working when you move to O. If you have access to an O device, try searching for "yummly". I verified that one this morning.

A: This is probably because "https://www.buzzfeed.com/tasty" is no longer showing up in Google search results (for reasons unknown), but instead as "https://tasty.co". Their instant app probably only supports the "www.buzzfeed.com" domain.
Try "buzzfeed nifty", I can currently see that.


text:
Q: Just in time help for Meta "Why downvotes?" comments Upvotes and downvotes are different on Meta, a lesson lots of users learn every day on SE. Often one's first experience with this results in "Why downvotes" or "Could someone explain why this is getting downvotes?"
Thinking out loud, but how about some sort of just in time message saying something to the effect of:

Stop right there criminal scum Downvotes on Meta are different and often indicate disapproval of a post's premise rather than attacks on you. They don't mean it's a bad question, just that others disagree.

Ideally this would be displayed only to low rep users or users with low Meta participation, and show as a non-modal information box before they post a comment on their own question containing some reference to downvoting to try and catch the "Why downvotes?" comments. This would be similar to the "Hey, your title looks subjective and is likely to be closed" notice.
I noticed the formatting help box is a nice format to offer this help:

Yes, users can manually explain this, but it gets tiring and it would be nice to have the system acknowledge this fact rather than leaving the asker stranded and confused until some good (non-sarcastic) Samaritan explains the system yet again.


text:
Q: Lead resistance of 3 wire RTD100 I am using a three wire RTD100 as a temperature sensor.

I know the advantage of the 3 wire RTD100 is that it gives accurate temperature output by canceling the lead resistance. First the resistance between line RED (R1) and BLACK (R2) is measured the total resistance is R1 + R2 + RE and then the resistance between line BLACK (R2) and BLACK(R3) is measured. All three wires have the same resistance i.e R1=R2=R3 therefore we will have to subtract (R2+R3) from (R1 + R2 + RE) to get an accurate temperature value.
I researched about the circuits that I can use with 3 wire RTD100. A Wheatstone bridge is used to find the resistance change in the RTD100.
Circuit 1:

In the above circuit, the wire resistance of the RTD100 is labelled as RW1, RW2, RW3. I understand that the change in resistance will unbalance the Wheatstone bridge.  The output nodes of the Wheatstone bridge are given to the difference amplifier where we get the voltage output corresponding to the change in temperature, but I am not understanding how the Wheatstone bridge and the difference amplifier is canceling the lead resistance.

A: Important Note- the above circuit is only applicable when all the resistances are nominally at the same value i.e. the same magnitude balance current flows into both R1 and R2. I'm mentioning this because if the left half of the bridge has a different impedance to the right half, 3-wire connections to an external device don't produce wire-resistance cancellation correctly. In other words, at balance, R3 must equal R4.
So, I've added a label in red (inside a red circle) called "C". This is the "new lower power feed point" and you can now ignore the old node in black called "C": -

Can you see that R3 is in series with RW2 and equally, R4 is in series with RW1 and hence the balance is maintained? No? Read below: -
Consider that in balance, R3 equals R4 and R1 equals R2. This produces 0 volts output between "a" and "b". If R3 and R4 both increased by 10%, the bridge would still be in balance. And increasing both by 10% is the same as adding series resistance to them both. That series resistance comes from the interconnecting wires (RW1 and RW2) and, it can be presumed to be identical for both. So the bridge remains in balance no matter what value RW1 and RW2 is providing that they are both the same value.
RW3 is a red-herring because it doesn't imbalance anything when its value changes; it just affects the "gain" of the circuit.

A: Wheatstone won't help here.
Two matched current sources, then \$ V_{dif}=I_1\cdot R_W + V_{rtd} - I_2\cdot R_W \$
I1=I2, Rw equal then
Vdif=Vrtd
A reference voltage for ADC is then Vref=(I1+I2)/Rref;

simulate this circuit – Schematic created using CircuitLab