text:
Q: How to make ffmpeg executable everywhere? I have installed ffmpeg by following this tutorial on trac.ffmpeg.org
Now, ffmpeg works if I cd to bin and execute it with ./ffmpeg
I wonder if I could execute ffmpeg just by typing ffmpeg in a terminal from anywhere.

A: You don't need to edit your PATH or ~/.bashrc

*

*The guide "installs" ffmpeg inside ~/bin so it does not potentially interfere with conflicting repository packages.

*There is no need to edit your PATH or ~/.bashrc as shown in the accepted answer. ~/bin is already in the PATH by default (take a look at ~/.profile), but ~/bin is not included when you login if it does not exist (and it did not exist before you compiled), but you can easily "refresh" it as shown below.
All you need to do is this:
hash -r
. ~/.profile

Alternatively you can simply log out then log in.
Now you can run ffmpeg from any directory and it will automatically execute the ffmpeg binary in ~/bin (for the particular user who compiled ffmpeg). All of this is explained in the guide you linked to.
Getting it to work for all users
The above instructions are for the single user who compiled ffmpeg. If you have multiple users you can just move or copy the compiled ffmpeg binary into /usr/local/bin.

A: You can simply add ffmpeg directory to your $PATH.
Assuming you're using bash open ~/.bashrc file and add at the bottom:
export PATH=$PATH:<path where you installed ffmpeg>

and reload bash ( close and open terminal again or type 'bash' ).
edit:
PATH represents list of directories that your shell is using to find binary files. So you need to add directory, not the file, path to that variable.
Assuming that you executed everything exactly the way that manual said you need to add to you .bashrc that command:
export PATH=$PATH:$HOME/bin


text:
Q: How do I only print every 5th line I have a text file ("name_data.txt") that has the following contents:
name: Kelo
family name: Lam
location: Asia
members: Kelo, Kiko, Jil

name: Miko
family name: Naiton
location: Japan
members: Miko,Kayati

The text file keeps going with the same pattern (name, family name, location, members)
I want to print out the first line and then print every 5th line so I would be printing only the line with "name" in the beginning.
I then want to have a list of the names
I want my output to be :
["Kelo","Miko"]

So far, I have gotten (although, it is wrong):
name_data= load_local_file('name_data.txt',ignore_header=False,delimiter='\t')

def __init __(name_reader):

    names=list()
    count=0
    name_line=5
    line_number=0

    for name in name_data:

        if line_number<5:

            line_number +=1

        if line_number ==5:

            names.append(line_number)

A: You can identify every fifth line by comparing the linenumber modulo 5 against a number. In your case this should be 0 because you want the first line and the 6th, the 11th, ... (note that python starts with index 0)
To get the line-numbers as well as the content you can iterate over the file with enumerate.
Then to discard the name: part of the string and keep what comes after, you can use str.split().
A working implementation could look like this:
# Create an empty list for the names
names = []

# Opening the file with "with" makes sure it is automatically closed even
# if the program encounters an Exception.
with open('name_data.txt', 'r') as file:
    for lineno, line in enumerate(file):
        # The lineno modulo 5 is zero for the first line and every fifth line thereafter.
        if lineno % 5 == 0:
            # Make sure it really starts with "name"
            if not line.startswith('name'):
                raise ValueError('line did not start with "name".')
            # Split the line by the ":" and keep only what is coming after it.
            # Using `maxsplit=1` makes sure you don't run into trouble if the name
            # contains ":" as well (may be unnecessary but better safe than sorry!)
            name = line.split(':', 1)[1]
            # Remove any remaining whitespaces around the name
            name = name.strip()
            # Save the name in the list of names
            names.append(name)

# print out the list of names
print(names)

Instead of enumerate you could also use itertools.islice with a step argument:
from itertools import islice

with open('name_data.txt', 'r') as file:
    for line in islice(file, None, None, 5):
        ... # like above except for the "if lineno % 5 == 0:" line

Depending on your needs you might consider using the re module to completly parse the file:
import re
# The regular expression
group = re.compile(r"name: (.+)\nfamily name: (.+)\nlocation: (.+)\nmembers: (.+)\n", flags=re.MULTILINE)
with open(filename, 'r') as file:
    # Apply the regex to your file
    all_data = re.findall(group, file)
# To get the names you just need the first element in each group:
firstnames = [item[0] for item in all_data]

The firstnames will be ['Kelo', 'Miko'] for your example and similar if you use [item[1] for item in all_data] then you get the last names: ['Lam', 'Naiton'].
To successfully use a regular expression you must ensure it really matches your file layout otherwise you'll get wrong results.

A: A simple way to do this would be as follows:
with open('name_data.txt', 'r') as file:

    index = 0
    for line in file:
        if index % 5 == 0:
            print(line.split()[1])
        index += 1

A: You could do this in one line with a list comprehension
c = open('test.txt', 'r').readlines()

# for every fifth line extract out name and store in list
a = [i.replace('name: ', '').replace('\n', '') for i in c[::5]]

print(a) # ['Kelo', 'Miko']

A: Assuming that name_data is a list of lines in the file, you can do
names = []
for i in range(1, len(name_data), 5):
    names.append(name_data[i].split(":")[1].strip())

A: Having a name_data.txt file with data as follows:

1
2
3
4
5
6
7
8
9
10

Here's how you can print the first and every 5th line of it:
content = [line.rstrip('\n') for line in open('name_data.txt')]
names = []
limit = 4
fp = open("name_data.txt")
names.append(content[0])
for i, line in enumerate(fp):
    if i == limit:
        names.append(line)
        limit += 5
fp.close()
print(names)

Checkout http://shortcode.pro/code/read-txt-file-and-print-first-and-every-5th-line/

A: You can use regular expressions - Python's module for that is re.
Then with name_data.txt being:
name: Kelo
family name: Lam
location: Asia
members: Kelo, Kiko, Jil

name: Miko
family name: Naiton
location: Japan
members: Miko,Kayati

Getting the names is simple one-liner:
import re

def get_names():

    with open('name_data.txt', 'r') as f:
        print(re.findall(r'^name:\s*(\w+)', f.read(), flags=re.MULTILINE))

if __name__ == '__main__':

    get_names()

Note the multiline flag setting - when the setting is global, the regex would also match lines with family name: ....
See the regex in interactive mode here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why don't the two forces balance each other In Newton 3rd law? Why don't the two forces of action and reaction balance each other ?
I imagine that although they are opposite forces, they have different points of application. Is this true?

A: Yes.Thats true.
For example the earth pull the moon and by Newtons 3rd law the moon also pull the earth.
Forces are on two different object.
if there is a body in between the line joining the earth's centre and the moon's centre then only the net force on the body(vector sum of forces by the moon and earth) can be zero(if the body is on the right place)because its on the same body.

A: I just guess that 1 and 2 are two different bodies. So, the answer is in your question itself. F(1->2) is the force with which 1 acts on 2, and F(2->1) is the force with which 2 acts on 1. The forces don't act on the same body.


text:
Q: Two different time periods for a movement with constant acceleration? I'm studying for my physics exam and I keep running into the same problem. It's so specific I have no idea how to phrase it in a Google or stack exchange search, and I've already wasted 2 hours on it. So apologies if this is too simple a question.
The problem I will use as an example is complicated but I will simplify it (a lot) to address the confusion I'm having:

How long will it take for an object moving at $5.0~\mathrm{m/s}$ and slowing down by $0.5 ~\mathrm{m/s^2}$ to travel a distance of $17$ meters?

With the formula:
$$x_\mathrm{final} = x_\mathrm{initial} + v_\mathrm{start}*dt + a / 2*dt^2$$
Assuming $x_\mathrm{initial} = 0$ and $x_\mathrm{final} = 17 ~\mathrm{m}$, I can use the $dt$ or "change in time" as an unknown, and can call it $t$.
This gives the function:
$$-0.25t^2 + 5t - 17 = 0$$
When solving this function I get:
$$D = 5^2 - 4*(-0.25)*(-17) = 8\quad ,\\
t1 = \frac{-5 + 8^{1/2}}{-0.5}\quad,\\
t2 = \frac{-5 - 8^{1/2}}{-0.5}$$
The two answers rounded off are: $t1 = 4.3431~\mathrm{seconds}$ and $t2 = 15.6569 ~\mathrm{seconds}$.
How the is it possible that an item with a constant acceleration can displace over the same distance in two different time periods? This is really confusing to me. I would expect one of the answers to be a negative number, which usually is the case in these types of situations. Then it is logical that negative time is not possible and that the positive number is the only answer. Why is that no longer the case here?
At first I thought I had used the wrong $+$ and $-$ symbols for my given values but I made like 20 different drawings and made the calculation over and over again and I don't understand what I am doing wrong. If we put the movement on the $x$-axis, the movement is going from $x=0$ to $x =17$. The speed must be positive so: $v=5.0$. The acceleration is slowing the movement down so: $a = -0.5$.
When I plug this in to the formula that I have triple checked from the book lying right next to me I still get the same answer.
Again, I apologize for asking such a stupid question because this is just elementary physics and I have never had these issues in high school. I don't understand why this is suddenly so confusing for me. I study computer science now and this is one of our minor subjects, so I don't put a lot of thought into the subject throughout the year.
I'm guessing that I am somehow using the formula in a wrong way because if I solve the function: $-0.25t^2 + 5t + 17 = 0$ then I do find a correct answer but I don't get why i should be using $17$ as a positive number instead of a negative one.

A: That you get two answers for time $t$ is perfectly fine!

How the is it possible that an item with a constant acceleration can displace over the same distance in two different time periods?

Remember, that the $17$ meters you put in is not distance, but a position. The object passes this position at $t1$, then it decelerates, speeds down, gets a negative speed, comes back, and passes that position again at $t2$.
See my plot here:

The blue line is the 17 meters. Position $x$ at the y-axis. There are two perfectly fine cases where your equation is true: at the intersections between the two lines.

A: There's nothing wrong here about the equation giving you two instants. Say, your object is moving in the positive $x$ direction, it started with $v=5$ , but it's slowing down. "Slowing down" basically means that the direction of the acceleration is opposite to your velocity, that is, $a$ is in the negative $x$ direction. The object will cover a certain amount of distance before it stops. Now at $t=4.3$, this object would have already covered $17$ meters, then it'll continue covering some additional distance before it stops.
Then what happens after it stops? that is, after $v=0$?, well, it will start to speed up and move in the negative $x$ direction($a$ is negative, remember?). So that at $t=15.6$, it will cover another $17$ meters.

A: I haven't checked your calculations, but the reason you can have 2 solutions is as follows.  After 4.3 seconds, the object has travelled 17m from its start point, say heading along positive x axis.  After 10 seconds it reaches a halt and starts to go backwards, and after 15.6 seconds, it's back at  the point 17m from the start.


text:
Q: Informal way of saying some time expressions I was wondering what the informal equivalent for the following expressions are:
A matter of time

It is a matter of time, before somebody find it

As time goes by

As time goes by, he found that his colleague is dishonest.

In other words, How can I use these phrases in my conversation?

A: Do you want equivalent expressions or do you want to know how to use the given phrases? These seem like contradictory requests. Nevertheless...
A matter of time is not particularly formal. It's used in everyday conversation. But you should use It's in conversational English, remove the comma, and use the correct verb conjugation:

It's a matter of time before somebody finds it.

Note that somebody is correctly used rather than the somewhat more formal someone.
Again, as time goes by is not necessarily formal. But over time is probably less formal than it.
One problem is that you cannot use a past tense with as time goes by. So

*As time goes by, he found that his colleague is dishonest.

is ungrammatical, which is what the asterisk (*) before it means.
You can say as time went by with a past tense verb,  but that is somewhat formal.
I suggest

Over time he found that his colleague  was dishonest.

Hope this helps!


text:
Q: TrainVectorClassifier returns no result when using Artificial Neural Network I experimented with the TrainVectorClassifier from ORFEO-Toolbox,
I created trainingdata and tried different classification methods, however for some reason I cannot get the Classifier to work when using ANN as parameter.
Does somebody know what I did wrong?
Training Data Head (there are actually 4 classes in MC_ID):

fid
MC_ID
value_0
value_1
value_2

1
1
43.5757064819336
67.1139984130859
23.9567775726318

2
1
44.5364456176758
67.6646423339844
24.185676574707

3
1
46.7659378051758
71.6526565551758
24.8563995361328

4
1
40.2990226745605
60.2364349365234
21.3831405639648

5
1
46.2593841552734
70.1774063110352
26.6104145050049

Using Artificial Neural Network:
Eingabeparameter:
{ 'io.vd' : ['/home/raphi/Robonav/Wiesen/test_clip/smpls.gpkg|layername=output'], 'io.stats' : '', 'io.out' : 'TEMPORARY_OUTPUT', 'io.confmatout' : 'TEMPORARY_OUTPUT', 'layer' : 0, 'feat' : '\"value_0 value_1 value_2\"', 'valid.vd' : None, 'valid.layer' : 0, 'cfield' : 'MC_ID', 'v' : True, 'classifier' : 'ann', 'classifier.ann.t' : 'back', 'classifier.ann.sizes' : '\"10 5\"', 'classifier.ann.f' : 'sig', 'classifier.ann.a' : 0, 'classifier.ann.b' : 1, 'classifier.ann.bpdw' : 1, 'classifier.ann.bpms' : 1, 'classifier.ann.rdw' : 0.1, 'classifier.ann.rdwm' : 0, 'classifier.ann.term' : 'all', 'classifier.ann.eps' : 0.01, 'classifier.ann.iter' : 1000, 'rand' : 1 }

2021-04-21 10:56:04 (INFO) TrainVectorClassifier: Default RAM limit for OTB is 256 MB
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: GDAL maximum cache size is 774 MB
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: OTB will use at most 16 threads
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: Reading vector file 1/1
2021-04-21 10:56:04 (WARNING) TrainVectorClassifier: The validation set is empty. The performance estimation is done using the input training set in this case.
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: Computing model file : /tmp/processing_gZqRCM/ac95332ec44f42d8afac20072e049ecc/io_out.file
Training model...: 100% [**************************************************] (0s)
Validation...: 100% [**************************************************] (0s)
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: Predicted list size : 5116
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: ValidationLabeledListSample size : 5116
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: Training performances:
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: Confusion matrix (rows = reference labels, columns = produced labels):
[1] [2] [3] [4]
[ 1] 1279 0 0 0
[ 2] 1279 0 0 0
[ 3] 1279 0 0 0
[ 4] 1279 0 0 0

2021-04-21 10:56:04 (INFO) TrainVectorClassifier: Precision of class [1] vs all: 0.25
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: Recall of class [1] vs all: 1
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: F-score of class [1] vs all: 0.4

2021-04-21 10:56:04 (INFO) TrainVectorClassifier: Precision of class [2] vs all: 0
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: Recall of class [2] vs all: 0
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: F-score of class [2] vs all: 0

2021-04-21 10:56:04 (INFO) TrainVectorClassifier: Precision of class [3] vs all: 0
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: Recall of class [3] vs all: 0
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: F-score of class [3] vs all: 0

2021-04-21 10:56:04 (INFO) TrainVectorClassifier: Precision of class [4] vs all: 0
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: Recall of class [4] vs all: 0
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: F-score of class [4] vs all: 0

2021-04-21 10:56:04 (INFO) TrainVectorClassifier: Global performance, Kappa index: 0
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: mapOfIndicesValid[0] = 1
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: mapOfIndicesValid[1] = 2
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: mapOfIndicesValid[2] = 3
2021-04-21 10:56:04 (INFO) TrainVectorClassifier: mapOfIndicesValid[3] = 4

Using Random Forest:
Eingabeparameter:
{ 'io.vd' : ['/home/raphi/Robonav/Wiesen/test_clip/smpls.gpkg|layername=output'], 'io.stats' : '', 'io.out' : 'TEMPORARY_OUTPUT', 'io.confmatout' : 'TEMPORARY_OUTPUT', 'layer' : 0, 'feat' : '\"value_0 value_1 value_2\"', 'valid.vd' : None, 'valid.layer' : 0, 'cfield' : 'MC_ID', 'v' : True, 'classifier' : 'rf', 'classifier.rf.max' : 5, 'classifier.rf.min' : 10, 'classifier.rf.ra' : 0, 'classifier.rf.cat' : 10, 'classifier.rf.var' : 0, 'classifier.rf.nbtrees' : 100, 'classifier.rf.acc' : 0.01, 'rand' : 1 }

2021-04-21 10:55:51 (INFO) TrainVectorClassifier: Default RAM limit for OTB is 256 MB
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: GDAL maximum cache size is 774 MB
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: OTB will use at most 16 threads
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: Reading vector file 1/1
2021-04-21 10:55:51 (WARNING) TrainVectorClassifier: The validation set is empty. The performance estimation is done using the input training set in this case.
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: Computing model file : /tmp/processing_gZqRCM/15a7b601692c4dcbac7834ab4bb56025/io_out.file
Training model...: 100% [**************************************************] (0s)
Validation...: 100% [**************************************************] (0s)
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: Predicted list size : 5116
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: ValidationLabeledListSample size : 5116
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: Training performances:
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: Confusion matrix (rows = reference labels, columns = produced labels):
[1] [2] [3] [4]
[ 1] 1232 0 47 0
[ 2] 0 1277 0 2
[ 3] 124 0 1155 0
[ 4] 0 5 0 1274

2021-04-21 10:55:51 (INFO) TrainVectorClassifier: Precision of class [1] vs all: 0.908555
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: Recall of class [1] vs all: 0.963253
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: F-score of class [1] vs all: 0.935104

2021-04-21 10:55:51 (INFO) TrainVectorClassifier: Precision of class [2] vs all: 0.9961
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: Recall of class [2] vs all: 0.998436
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: F-score of class [2] vs all: 0.997267

2021-04-21 10:55:51 (INFO) TrainVectorClassifier: Precision of class [3] vs all: 0.960899
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: Recall of class [3] vs all: 0.903049
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: F-score of class [3] vs all: 0.931076

2021-04-21 10:55:51 (INFO) TrainVectorClassifier: Precision of class [4] vs all: 0.998433
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: Recall of class [4] vs all: 0.996091
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: F-score of class [4] vs all: 0.99726

2021-04-21 10:55:51 (INFO) TrainVectorClassifier: Global performance, Kappa index: 0.95361
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: mapOfIndicesValid[0] = 1
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: mapOfIndicesValid[1] = 2
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: mapOfIndicesValid[2] = 3
2021-04-21 10:55:51 (INFO) TrainVectorClassifier: mapOfIndicesValid[3] = 4
Ausführung nach 0.66 Sekunden abgeschlossen
Ergebnisse:
{'io.confmatout': '/tmp/processing_gZqRCM/8cb2b811345b4ac3bb877e16388cff25/io_confmatout.file',
'io.out': '/tmp/processing_gZqRCM/15a7b601692c4dcbac7834ab4bb56025/io_out.file'}

A: This loos like this bug, hopefully it will be corrected in version 8.0.0.
In the meantime, you should une another classifier (RFs are great!).


text:
Q: Using Roku "roTimeSpan" and Pause/Play/Resume I'm currently working on using the setProgressIndicator method to display the progress for audio files. I'm using a timer and the "start of play" message from the roAudioPlayer. I'm wondering if there is a way to set a timer to a particular value. This is my function. The idea is that each index corresponds to a button pressed. When no buttons are pressed the timer will just run normally but if for instance pause/play is selected then the timer should continue from where it last left off. I don't understand how to go about doing that though.
Function keep_track_progress(timer, currentPos, screen As Object, finalPlayList As Object, track_count As Integer, playing As Boolean, index As Integer)

    if finalPlayList[track_count].ContentType = "audio"

        if index = 2 or index = 3 or index = 4 or index = 5
            screen.SetProgressIndicator(currentPos, int(finalPlayList[track_count].Length))

        else
            screen.SetProgressIndicator(timer.TotalSeconds(), int(finalPlayList[track_count].Length))
        end if

    else
        screen.SetPosterStyle("default")
        print "this should happen like once"

    end if

End Function

Also when paused,
currentPos = currentPos + timer.TotalSeconds()

When pressing play,
timer.mark()

"Start of play" has the same code as well...Any suggestions? Also why is it that you can't use the progress indicator with the SetPosterStyle. Is this a known issue?


text:
Q: JavaScript code gives no answer to my isset, how do I solve the problem? I have programmed a point system, after successful redeeming I give with isset($succesMsg) a message that it was successful.
Now I want to show a small animation using JavaScript, but it does not work.
My PHP Code
$succesMsg= "

+ {$codeCoins['coins']}

My HTML Button is:
<input type="submit" name="code" class="btn btn-primary w-100" value="CODE EINLÖSEN">

My JavaScirpt Code is

When I click on redeem I see in the source code that the div fields are set (body-overlay and overlay) but the animation does not work.
If I try without the PHP migration it works, but unfortunately brings me nothing.
I can't find the error, I'm searching all the time.

A: Two mistakes I can see in your code:

*

*$(".btn btn-primary w-100")
Whenever you want to add an any event using multiple classes of single html element. It should be without space also with dot(.).
Explaining: .btn btn-primary w-100
It will look for an nested elements with mentioned classes. Like you have html elements are as

Change it to:
.btn.btn-primary.w-100

*About $succesMsg
you have written a html code in it. Which needs to be loaded first
before javascript code.
Do like: keep your html ready in html only and set varibale true or false in php. And you can check that variable in script. If it is true thane .show() or else .hide()
Note: Isset checks whether a variable is set and is not NULL only.


text:
Q: Plugin Utils not working I installed tha cakephp Utils plugin via composer, and then I loaded all plugins in my bootstrap.php file, I added a field in my database model for the image path (cause I want to upload image profile using Uploadable), and then I add the following code I my model table:
$this->addBehavior('Utils.Uploadable', [
        'foto_dir',
    ]);

but when I access the model I get the following error:

Utils.UploadableBehavior could not be found.
Make sure your plugin Utils is in the C:\wamp\www\siec2\plugins\ directory and was loaded.

Screenshot:

Please help.

A: Plugins installed with composer are stored inside the vendor folder. Please make sure, you have the Utils Plugin in the following folder /vendor/cakemanger/cakephp-utils
If so, check cakephp-plugins.php inside the vendor folder for this:
return [
  'plugins' => [
    ...
    'Utils' => $baseDir . '/vendor/cakemanager/cakephp-utils/'
  ]
];

Also make sure, you loaded the plugin in your bootstrap.php: Plugin::load('Utils');
See Plugins Section on CakeBook.


text:
Q: Is it Pythonic to depend on ValueError when parsing a parameter string? My specific concerns are

*

*When parsing a parameter, is it intuitive for a future maintainer to understand code that depends on throwing an error?

*Is it expensive to be throwing exceptions as a matter of course for the
default case? (seems like it might be according to https://stackoverflow.com/a/9859202/776940 )

Context
I have a parameter counter that determines the name of a counter to increment, and optionally can increment by a positive or negative integer separated from the counter name by an =. If no increment value is provided, the default magnitude of the increment is 1. The function is fed by breaking up a comma delimited list of counters and increments, so a valid input to the whole process can look like:
"counter1,counter2=2,counter3=-1"

which would increment "counter1" by 1, increment "counter2" by 2 and decrement "counter3" by 1.
How I Originally Wrote It
counterDescriptor = counterValue.split('=')
if len(counterDescriptor) == 1:
    counterName = counterDescriptor[0]
    counterIncr = 1
elif len(counterDescriptor) == 2:
    counterName = counterDescriptor[0]
    counterIncr = int(counterDescriptor[1])
else:
    counterName, counterIncr = ('counterParsingError', 1)

which strikes me, as I recently came back to look at it, as overly verbose and clunky.
Is this a more or less Pythonic way to code that behavior?
def cparse(counter):
    try:
        desc,mag = counter.split('=')
    except ValueError:
        desc = counter
        mag = ''
    finally:
        if mag == '':
            mag = 1
    return desc, int(mag)

With these test cases, I see:
>>> cparse("byfour=4")
('byfour', 4)
>>> cparse("minusone=-1")
('minusone', -1)
>>> cparse("equalAndNoIncr=")
('equalAndNoIncr', 1)
>>> cparse("noEqual")
('noEqual', 1)

These test cases that would have been caught how I originally wrote it (above) won't get caught this way:
>>> cparse("twoEquals=2=3")
('twoEquals=2=3', 1)
>>> cparse("missingComma=5missingComma=-5")
('missingComma=5missingComma=-5', 1)

and this last test case doesn't get caught by either way of doing it. Both make the int() vomit:
>>> cparse("YAmissingComma=5NextCounter")
ValueError: invalid literal for int() with base 10: '5NextCounter'

I'm glad I discovered this problem by asking this question. The service that consumes this value would eventually choke on it. I suppose I could change the one line return desc, int(mag) of the function to this:
    if desc.find("=")<0 and (mag=='0' or (mag if mag.find('..') > -1 else mag.lstrip('-+').rstrip('0').rstrip('.')).isdigit()):
        return desc, int(mag)
    else:
        return 'counterParsingError: {}'.format(desc), 1

(hat tip to https://stackoverflow.com/a/9859202/776940 for figuring out that this was the fastest way offered in that discussion to determine if a string is an integer)

A: I would consider that pythonic, though you might perhaps prefer:
def cparse(counter):
    if "=" not in counter:
        # early exit for this expected case
        return (counter, 1)
    desc, mag = counter.split("=", maxsplit=1)
    # note the use of the optional maxsplit to prevent ValueErrors on "a=b=c"
    # and since we've already tested and short-circuited out of the "no equals" case
    # we can now consider this handled completely without nesting in a try block.
    try:
        mag = int(mag)
    except ValueError:
        # can't convert mag to an int, this is unexpected!
        mag = 1
    return (desc, mag)

You can tweak this to ensure you get the right output while parsing strings like a=b=c. If you expect to receive ('a', 1) then keep the code as-is. If you expect ('a=b', 1) you can use counter.rsplit instead of counter.split.


text:
Q: JQuery Animation I am playing around with Jquery .animate, and trying to do some basic image animations where I expand an image on mouse over.  However, I have 4 images, and currently whenever one is expanded it effects the other images.  How do I make them independent of each other?

 $(document).ready(function () {

        $("#imgBuffalo").mouseover(function () {
            $("#imgBuffalo").animate({ width: "90px", height: "70px" }, 500);
        });

        $("#imgBuffalo").mouseleave(function () {
            $("#imgBuffalo").animate({ width: "80px", height: "60px" }, 500);
        });

        $("#imgIndianapolis").mouseover(function () {
            $("#imgIndianapolis").animate({ width: "90px", height: "70px" }, 500);
        });

        $("#imgIndianapolis").mouseleave(function () {
            $("#imgIndianapolis").animate({ width: "80px", height: "60px" }, 500);
        });

        $("#imgMiami").mouseover(function () {
            $("#imgMiami").animate({ width: "90px", height: "70px" }, 500);
        });

        $("#imgMiami").mouseleave(function () {
            $("#imgMiami").animate({ width: "80px", height: "60px" }, 500);
        });

        $("#imgNYJets").mouseover(function () {
            $("#imgNYJets").animate({ width: "90px", height: "70px" }, 500);
        });

        $("#imgNYJets").mouseleave(function () {
            $("#imgNYJets").animate({ width: "80px", height: "60px" }, 500);
        });

A: Using the animate method effectively alters the CSS on the elements it acts on. Since your images are simply inline with each other, changing the dimensions of one, will necessarily effect the others.
You could try playing with position: relative or position: absolute so that the images won't move when their dimensions change, however you're going to have inconsistent results across browsers.
If you're looking for a pop-up expansion type effect, I'd suggest creating a new div and then clone the image into that. You can then do whatever you'd like to the floating div/image without having an affect on the others.
Based on the animations you're currently using, it looks like you're trying to achieve something similar to the Apple dock animations. There are a number of jquery plugins available already that you might use instead of hand coding the animations directly.

A: You mean it moves the other images as the one image is expanding? If you don't want them affecting eachother you will have to put each image into an absolute div and change the z-index of the div containing the active animation to be on top.

A: Your best bet is to position your logos absolutely on the screen. This will keep them from conflicting with each other. Give each img a "logo" class or something like that.
.logo { position : 'absolute'; }

Then position each logo based on its ID.
Next, I'd suggest using .hover() instead of the mouseover and mouseleave. This gives you the ability to set two event handlers in less code.
$('.logo').hover(function() {
     $(this).animate({ width: "90px", height: "70px", top : "5 less px than set in css", left : "5 less than set in css" }, 500);
}, function() {
     $(this).animate({ width: "80px", height: "60px", top : "Reset to css", left : "reset to css" }, 500);
}

Read up on http://api.jquery.com/hover/ for more details.
You're on the right path to learning some cool effects in jQuery. Keep it up!


text:
Q: Turn subversion path into walkable directory I have a subversion repo ie "http://crsvn/trunk/foo" ... I want to walk this directory or for starters simply to a directory list.
The idea is to create a script that will do mergeinfo on all the branches in "http://crsvn/branches/bar" and compare them to trunk to see if the branch has been merged.
So the first problem I have is that I cannot walk or do
os.listdir('http://crsvn/branches/bar')

I get the value label syntax is incorrect (mentioning the URL)

A: You can use PySVN. In particular, the pysvn.Client.list method should do what you want:
import pysvn
svncl = pysvn.Client()
entries = svncl.list("http://rabbitvcs.googlecode.com/svn/trunk/")
# Gives you a list of directories:
dirs = (entry[0].repos_path for entry in entries if entry[0].kind == pysvn.node_kind.dir)
list(dirs)

No checkout needed. You could even specify a revision to work on, to ensure your script can ignore other people working on the repository while it runs.

A: listdir takes a path and not a url.  It would be nice if python could be aware of the structure on a remote server but i don't think that is the case.
If you were to checkout your repository locally first you could easly walk the directories using pythons functions.


text:
Q: How to make border with inside-radius? I'm trying to create a div with inside circle at the corner. It should look like the picture shown below

Can someone help to solve this problem?

A: You could do this:

.box {
  width: 200px;
  height: 200px;
  background:
    radial-gradient(circle at 0 100%, transparent 14px, red 15px) bottom left,
    radial-gradient(circle at 100% 100%, transparent 14px, red 15px) bottom right,
    radial-gradient(circle at 100% 0, transparent 14px, red 15px) top right,
    radial-gradient(circle at 0 0, transparent 14px, red 15px) top left;
  background-size: 50% 50%;
  background-repeat: no-repeat;
}

More info: Inset border-radius with CSS3
BUT (!) if you need more complexity on the shapes of that border, you could use a background image or a border image:

.box{
  width: 200px;
  height: 200px;
  background: #EEE;
  border: 30px solid transparent;
  border-image: url("http://i62.tinypic.com/2dh8y1g.jpg") 100 round;
}

More info: Decorative border css


text:
Q: C++ deleting function pointer before end of scope If I have a function:
std::string returnString() {
    return "Hello, World!";
}

the call:
std::string hello = returnString();
std::cout << hello << std::endl;

produces Hello, World!.
However, if I try:
const char* hello = returnString().c_str();

and try to print with:
for (const char* p = hello; *p; ++p ) {
    std::cout << *p;
}
std::cout << std::endl;

It gives me an error saying Invalid read of size 1, which means  p is NULL.
What is causing this behaviour?
Thanks for helping.

A: (Note: I'm glossing over some details here.  Look up Return Value Optimization and Copy Elision if you want to know the exceptions to the rules I'm mentioning here.  The don't change the behavior I describe in this answer though).
When you return an object from a function, the returned object is destroyed at the end of the line in which the function was called.  This is always the case.  Nomrally, you'll copy or move that object into another object in the local scope as in your last snippet:
std::string hello = returnString();

In this line, returnString returns one std::string object, hello is move-constructed from the returned object, and then the original object is destroyed.
If you consider a slightly different line, that's when problems arise:
const char* hello = returnString().c_str();

In this case, returnString returns a std::string object, you save a pointer to the char array owned by that std::string object, then the original std::string object is destroyed, taking the array of chars you have a pointer to with it.

std::string retains ownership of the array of chars pointed to by the pointer returned by c_str.  The std::string deletes the array it owns when it goes out of scope, which means that the lifetime of the array pointed is tied to the lifetime of the std::string object.
You can think of std::string as looking something like this:
class string
{
public:
    string(const char* str)
        : ptr_(new char[strlen(str) + 1])
    {
        strcpy(ptr_, str);
    }

    ~string()
    {
        delete[] ptr_;
    }

    const char* c_str()
    {
        return ptr_;
    }

    // other members

private:
    const char* ptr_;
};

The real std::string is a bit more complicated, but the basic idea is the same.  When the std::string object is constructed, it allocates an array of chars to hold the string data, and when the std::string object is destroyed it deletes that array.
The c_str method just returns a pointer to the std::string's internal char array.  Just because you have a pointer to that array doesn't mean that it won't be deleted when the std::string object dies, it just means you have a pointer to some memory that you no longer own.


text:
Q: Using SL4a to make intent that adds new contact I need to construct a meaningful intent in python to add a new contact i.e name, phone-number-cell, phone-number-work, email.
So far i have the following template i have been trying to follow and modify but it doesn't work. I don't expect the contacts application to open at all for this but my app should show a sigle prompt to agree and done.
# Add to contacts

import android

droid = android.Android()

activity = 'Intents.Insert.ACTION'
type = 'ContactsContract.RawContacts.CONTENT_TYPE'
extras = {}
extras['Insert.NAME'] = 'GodfreyTest'
extras['Insert.PHONE'] = '435313****'

packagename =  ''
classname = ''

intent = droid.makeIntent(activity, None, None, extras, None, packagename, classname).result


text:
Q: kdb/q: generate all possible "strings" of length N in KDB/Q, how do I generate all combinations given an alphabet universe (doesn't have to be string, could be like a list of numbers) for a given size n?
What I am looking for is similar to this in python, but in q.
How to generate all possible strings in python?

A: Using cross would be the easiest method:
q){y(x cross)/x}["ABC";1]
"AA"
"AB"
"AC"
"BA"
"BB"
"BC"
"CA"
"CB"
"CC"

q){y(x cross)/x}["ABC";2]
"AAA"
"AAB"
"AAC"
...


text:
Q: Display current logged in user's avatar outside of the loop? I use the famous User Photo plugin for my Wordpress site. I want to display the current logged in user's avatar outside the loop. How is this possible?
The current code I use to display the author avatar inside the loop is:
<?php userphoto_the_author_thumbnail('', '', array(width => '40', height => '40')); ?>

Google did not give me much to go on. One person referred to this code:
global $authordata;
$authordata=get_userdata(get_query_var( 'author' ));
userphoto_the_author_thumbnail();

But it did not work. What is the solution?

A: Try the below code.
It will select the current logged-in user's email and then display the avatar.
<?php
    wp_get_current_user();
    $current_user_email = $current_user->user_email;
?>
<?php echo get_avatar( '$current_user_email', 40 ); ?>

A: Use userphoto_thumbnail() and pass the user ID explicitly.
Usage:
userphoto_thumbnail($user, $before = '', $after = '', $attributes = array(), $default_src = '')

A: Please try one of thes two.
userphoto($user, $before = '', $after = '', $attributes = array(), $default_src = '')

or
userphoto_thumbnail($user, $before = '', $after = '', $attributes = array(), $default_src = '')

Both function work same as userphoto_the_author_thumbnail
thanks


text:
Q: how to upload image using php function This is my code. I tried to upload an image using this PHP code. $mainCName, $mainCImage save in the database. But, the image does not upload to the uploadedimage folder. Can you help me please?.
public function add_main_category($mainCName, $mainCImage){

        $query = "SELECT * FROM mainCategory WHERE mainCName='$mainCName'";

        $result = $this->db->query($query) or die($this->db->error);

        $count_row = $result->num_rows;

        if($count_row == 0){

            $imgfile=$_FILES["$mainCImage"];

        $extension = substr($imgfile,strlen($imgfile)-4,strlen($imgfile));

        $allowed_extensions = array(".jpg",".jpeg",".png",".gif");

        if(!in_array($extension,$allowed_extensions))
        {
            echo "<script>alert('Invalid format. Only jpg / jpeg/ png /gif format allowed');</script>";
        }
        else{
            $imgnewfile=md5($imgfile).$extension;

            move_uploaded_file($_FILES["mainCImage"]["tmp_name"],"uploadedimage/".$imgnewfile);

        }

            $query = "INSERT INTO maincategory(mainCName,mainCImage) VALUES('$mainCName','$mainCImage')";

            $result = $this->db->query($query) or die($this->db->error);

            return true;
            }
            else{return false;}

    }


text:
Q: DB design: one large DB for all customers or many small DBs Looking for any suggestions or advise or even best practices.
I have developed an online database using php and mysql.  It allows companies to log complaints and resolutions etc.  There is a user database for login and a cip database for logging the main data.  2 companies are trialing and testing the database.  At the moment each company is using separate databases and separate html pages.  I am wondering what the best way to add more companies.
Ideas that I have are:
1.
To have one large database for  users and one large database for cip and use a company id or similar to identify individual companies  records in the database.
2.
To use the same html pages for every company but select which database to use from the login details.  So that each company will have a separate cip database but all companies use the same users database.
3.
Or just keep everything separate for every company.  (this might be really bad for doing updates)
I hope I have made myself clear and look forward to any suggestions.
Thanks

A: One question I would want answered is do you ever need to see data across cutomers for your own reporting or use? In this case, you need to go with number one or you will have a nightmare to get good reporting.
Will you be doing any customization by customer? This would indicate that separating things out might be a better choice. If you will never customize, then don't separate out.
I have worked with systems in all of these options and the first one is by far the best for long term maintenance. However all are workable if you are organizaed and plan well. If you go for the separate otion, you must be able to push changes to all clients and thus must be doing changes to the database through scripts that are kept in source control. You may even need to keep a source control by database version, so that clients can choose to upgrade or not. In option 1 of course, no one has the option to stay on the old version. If that fits your business needs better, that is a plus for option 1.
I strongly agree with Ollie Jones, if you use option one, you must have a good database security design to prevent clients from seeing the data of other clients. We once moved a client from a server where they were the only client to a shared database and just one proc that missed asking for the client_ID (It wasn't needed in the old system and the developers had gotten sloppy) ended up emailing all the sales reps of all the other clients with information about the first client. This cost the company a lot of money (both to fix the problem, to send out email apologies and we almost lost a client as a result and had to give them some cost breaks to keep them) and many grovelling apologies and the developer just narrowly missed losing his job. Let this be a lesson you don't learn the hard way.

A: Personally I would go for candidate #3. Except for the users part, these kinds of databases can grow large rapidly. To keep performance to a maximum it is advisable to keep your tables as small as you can.
Selecting a different database based on the user's credentials shouldn't be hard to do, so application logic shouldn't suffer.
I understand your concern about maintainability. Does every customer live on the exact same app stack or do they have separate installations? Eitherway, maintenance should be easily scriptable to perform multi database updates. That shouldn't hold you back for choosing a design like this.

A: This is an interesting case of a conflict between your convenience and your responsibility to keep your customers' data secure. For your convenience, it's pretty clear a multi-tenant application, as described in your option (1), will be the easiest to get working.
But you are buying yourself a significant problem for the future, should your business succeed.  The way you have described your application, there is never a legitimate need for one of your customer companies to see data belonging to another.  In fact, if they were to see one anothers' data, you would have a serious security breach to deal with.  If the breach involved personal records, you would face business-threatening costs and penalties.
So if you do go for option (1) don't shortcut your code inspection and security testing.  If you do poor security testing you'll be sorry, and worse, so will your customers.
For better security you may want to consider a combination of option (2) and (3): a single web app code base, moving your multiple-tenancy locus from the web app to the mySQL server. The mySQL security system is decently good at multiple tenancy: Wordpress, Drupal, and Joomla all work that way, and they're all widely deployed.
This approach has another advantage.  If you do the development work necessary to build simple installation scripts for your web app and data base, you'll be able to provide your app to customers to run on their own servers if that's what they want.
I'm not saying avoid (1) completely.  Your business might offer a hosted multi-tenant  application (option 1) solution, with terms of service to cover your risks.  And, for bigger or better-equipped customers you could offer the private solution.

A: If you have 1 table called companies then each user can have a company_id so it relates to that company. You only need 1 database just use a one-to-many relationship.

A: Number 1 is best way to do so. Have one database for all the information you need and use IDs to identify companies. If you don't want to modify your current application files you may use this DB-layout, but create views, which simulate your old database structure.

A:

*

*To have one large database for users and one large database for cip and use a company id or similar to identify individual companies records in the database.

That's the best option. You can just store all the information in one database and differentiate them according to user login (where you can know which company the user is and store company id in session). However, careful with your codings as a mistake can show a company some information other company own.

A: just a single database for users and companies will do it. and I think you`ll need some php, asp or jsp in your pages to identify users and query the database ...

A: I would go for solution (1) or in case you think you will have thousands of customers using your web application for (2).
The (3) would be definitely a nightmare to be mantained.
BTW , i suppose in solution(1) you think to use same html pages too like in solution (2), Whether you use on large DB or many small ones, I would strongly advise to use anyway the same application logic (html/php pages) always for all.

A: for first point

*

*To have one large database for users
and one large database for cip and
use a company id or similar to
identify individual companies records
in the database.

my opinion is okay. because databases are built and tune to store and manage large data's. but only think is you should design the table properly. avoid situation of data duplication and so. build and manage big dataset is good. but should focus on design. you should tune you tables. for that you can search google for database designing and perfomance tuning.

*

*To use the same html pages for every
company but select which database to
use from the login details. So that
each company will have a separate cip
database but all companies use the
same users database.

the best is to build a basic template for all companies. this will help in managing you application. on login you select appropriate details what the company need or have and load it to the template. create a login table for companies, from their using an id point toto your information dataset and load it to a template. this will help you in debugging and its, its a standard way of making apps.
like facebook. every one have common home page template on login they filled with their relative data like pics, videos, post etc...
try to develop an app like that.
these are my suggestions..

A: You'll find it a lot easier just to use a single database.  You're on the right track, thinking about maintenance cost, etc.
Use properly designed/related tables -- for example:
Company Information Table
--------
Company_ID (primary key)
Company_Name
Other Fields...

Issue Table
--------
Issue_ID (primary key)
Company_ID (foreign key tied to the Company Information Table)
Issue_Text
Other Fields...

Hope that helps


text:
Q: adding tuple to new object instance field I'm attempting to run a function that passes and returns a Measurement object. Within the Measurement object, I have a variable volume which is a tuple and takes both a decimal and an enum called VolumeUnits which contains a range of liquid measurement types.
 public Measurement ConvertVolumeUnit(Measurement measure)
    {
        Measurement.VolumeUnits newUnit;
        decimal size = measure.volume.Item1;

        switch (measure.volume.Item2)
        {
            case Measurement.VolumeUnits.tsp:
                if (measure.volume.Item1 > 3)
                {
                    size = size / 3;
                    goto case Measurement.VolumeUnits.Tbsp;
                }
                else
                {
                    newUnit = Measurement.VolumeUnits.tsp;
                    break;

The function runs a switch that converts my units, but I am not sure how to establish a new Measurement instance and create a new Measurement.volume item to return the newly converted tuple.
             case Measurement.VolumeUnits.gal:
                 newUnit = Measurement.VolumeUnits.gal;
                 break;
             default:
                 break;
         }

         Measurement newMeasure = new Measurement();
         newMeasure.volume = Tuple.Create(size, newUnit);

Essentially, I want to return newMeasure but I have to fill that volume tuple first. My error is telling that newUnit is unassigned. Is this just because the default does not assign a value to newUnit?

A: After writing this all out it would appear that newUnit indeed must be assigned in the default section or initially to avoid this error.


text:
Q: Strange result from multiplying string by number In Excel 2010, "3-5" * 1 equals 41703:

A number is returned for any string in this format, as long as the first number is between 1 and 12, and the second number is between 1 and 99.
Below is a "multiplication" table, which hints at a pattern, but it throws a real curve ball at times (note the highlighted cell):

Questions:

*

*Can you confirm that other versions of Excel give the same results?

*Is there a pattern here?

If the answers to both questions are, "Yes," then this may be something we can exploit, especially when working with array formulas.

A: *

*In equivalent circumstances (eg locale) other versions of Excel will give the same results.

*Yes, the pattern is the date.
3-5 is being interpreted, for you, as March 5 (of this year) (Date serial number in 1900 system of 41703). The highlighted cell is because February does not have 30 days.


text:
Q: How to save number of buttom presses across all users and display the total number on screen The app is connected to Firebase and is using the Realtime database on the free spark plan. The app is based in kotlin.
This code properly stores the number of button presses across all devices and saves the number of presses after the application restarts, however I'm having trouble retrieving the number of times the button has been pressed from the database, to be displayed on screen.

    //private var database : DatabaseReference = FirebaseDatabase.getInstance().getReference("IncrementButton")

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_second)

    val rootRef = FirebaseDatabase.getInstance().reference
    val pressedRef = rootRef.child("pressed")

    button_increment.setOnClickListener {
        pressedRef.setValue(ServerValue.increment(1));
    }

    val valueEventListener = object : ValueEventListener {
        override fun onDataChange(dataSnapshot: DataSnapshot) {
            val pressed = dataSnapshot.getValue(Long::class.java)
            Log.d("TAG", "Button has been pressed $pressed times!")
        }

        override fun onCancelled(databaseError: DatabaseError) {
            Log.d("TAG", databaseError.getMessage()) //Don't ignore potential errors!
        }
    }
    pressedRef.addValueEventListener(valueEventListener)
}

Here is what I have in my data class:
data class IncrementButton(val pressed : Int? = null)

A: You can simply use
val counter = 0 //class level variable(global)

button.setOnClickListener {
    Log.d(TAG, "button clicked...increasing the counter")
    counter++
    updateTextOnScreen()
}

fun updateUI() {
    textView.text = counter.toString()
}

Everytime the button is clicked by the user, this will print a log statement you can see in logcat. Also, it will update the user interface with the number of times user has clicked the button.

A: Since you say that the button can be clicked by multiple users, there might be a situation in which two or even more users can click the button simultaneously. This means that you should implement a mechanism that can allow you to have consistent data. This can be done using transactions, as explained in my answer from the following post:

*

*How to save users score in firebase and retrieve it in real-time in Android studio
However, since a button click will always increment the counter by one, please see below an even simpler atomic solution:
button.setOnClickListener {
    rootRef.child("counter").setValue(ServerValue.increment(1))
}

Edit:
You are getting the following error:

UninitializedPropertyAccessException: lateinit property rootRef has not been initialized

Because by the time you are using the rootRef the is not yet object initialized. So please make sure you call first:
val rootRef = FirebaseDatabase.getInstance().reference

Edit2:
I've seen you have added a similar question here. Maybe I didn't understand that in the first place, but you cannot update a counter atomically using a model Total class. There is no need for that. It's true that you can read the data and update it using a transaction, but for a simple increment, you should only use the above code. That means that you can only take a reference of the field that needs to be incremented and that's it. No need for any model classes. Model classes are used when you want to map an object from the database into an object of the particular class.
Edit3:
To display the newly added counter, please use the following lines of code:
val rootRef = FirebaseDatabase.getInstance().reference
val counterRef = rootRef.child("counter")
val valueEventListener = object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        val counter = dataSnapshot.getValue(Long::class.java)
        Log.d("TAG", "counter: $counter")
    }

    override fun onCancelled(databaseError: DatabaseError) {
        Log.d("TAG", databaseError.getMessage()) //Don't ignore potential errors!
    }
}
counterRef.addValueEventListener(valueEventListener)

The output will always be the value of the incremented counter.
Edit4:
This is all you need:
//private lateinit var pressed : IncrementButton
//private var database : DatabaseReference = FirebaseDatabase.getInstance().getReference("IncrementButton")

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_second)

    val rootRef = FirebaseDatabase.getInstance().reference
    val pressedRef = rootRef.child("pressed")

    button_increment.setOnClickListener {
        pressedRef.setValue(ServerValue.increment(1));
    }

    val valueEventListener = object : ValueEventListener {
        override fun onDataChange(dataSnapshot: DataSnapshot) {
            val pressed = dataSnapshot.getValue(Long::class.java)
            Log.d("TAG", "Button has been pressed $pressed times!")
        }

        override fun onCancelled(databaseError: DatabaseError) {
            Log.d("TAG", databaseError.getMessage()) //Don't ignore potential errors!
        }
    }
    pressedRef.addValueEventListener(valueEventListener)
}

Edit5:
When you remove:
private var database : DatabaseReference = FirebaseDatabase.getInstance().getReference("IncrementButton")

It makes sense to get this error:

"unresolved reference: database"

As the line of code:
database.child("pressed").setValue(ServerValue.increment(1))

Because this line is notcorrect. It should be:
pressedRef.setValue(ServerValue.increment(1))
// ^ ^ See the reference?

So use the exact code I have provided in the Edit4, nothing else. Besides that, your schema should look like this:
Firebase-root
  |
  --- pressed: 2 <- Not counter, not anything else. Just "pressed"

In this way, you won't get:
"Button has been pressed null times!"

You certainly get:
"Button has been pressed 2 times!"


text:
Q: Comparing $\mathcal{O}$ and $\Omega$ By the definition of Big $\mathcal{O}$ and $\Omega$ of any function $f$, is it correct to say that the only common element in the two sets is $f$ and the two sets are otherwise disjoint?

A: No, Consider $f(x) = c x^2$ so that $f \in \Omega(x^2)$ and $f \in \mathcal{O}(x^2)$.
Now, you can see that the intersection contains infinitely many functions.


text:
Q: There is an ansi version of StrToInt? It seems there is no Ansi overload for StrToInt. Is this right? Or maybe I am missing something.
StrToInt insists to convert my ansistrings to string.

A: You are correct. There is no ANSI version of StrToInt. The place to find ANSI versions of standard function is the AnsiStrings unit, and there's nothing there.
Either write your own function to do the job, or accept the conversion required to use StrToInt.
It's not too hard to write your own function. It might look like this:
uses
  SysConst; // for SInvalidInteger
....
{$OVERFLOWCHECKS OFF}
{$RANGECHECKS OFF}
function AnsiStrToInt(const s: AnsiString): Integer;

  procedure Error;
  begin
    raise EConvertError.CreateResFmt(@SInvalidInteger, [s]);
  end;

var
  Index, Len, Digit: Integer;
  Negative: Boolean;
begin
  Index := 1;
  Result := 0;
  Negative := False;
  Len := Length(s);
  while (Index <= Len) and (s[Index] = ' ') do
    inc(Index);
  if Index > Len then
    Error;
  case s[Index] of
  '-','+':
    begin
      Negative := s[Index] = '-';
      inc(Index);
      if Index > Len then
        Error;
    end;
  end;
  while Index <= Len do
  begin
    Digit := ord(s[Index]) - ord('0');
    if (Digit < 0) or (Digit > 9) then
      Error;
    Result := Result * 10 + Digit;
    if Result < 0 then
      Error;
    inc(Index);
  end;
  if Negative then
    Result := -Result;
end;

This is a cut-down version of that found in StrToInt. It does not handle hexadecimal and is a bit more stringent regarding errors. Before using this code I'd want to test whether or not this really is your bottleneck.
It is quite interesting that this code, based on that in the RTL source, is incapable of returning low(Integer). It's not too hard to fix that up, but it would make the code more complex.

A: The code is actually very simple (hex strings aren't supported but prolly you don't need them):
function AnsiStrToInt(const S: RawByteString): Integer;
var
  P: PByte;
  Negative: Boolean;
  Digit: Integer;

begin
  P:= Pointer(S);
// skip leading spaces
  while (P^ = Ord(' ')) do Inc(P);
  Negative:= False;
  if (P^ = Ord('-')) then begin
    Negative:= True;
    Inc(P);
  end
  else if (P^ = Ord('+')) then Inc(P);

  if P^ = 0 then
    raise Exception.Create('No data');

  Result:= 0;
  repeat
    if Cardinal(Result) > Cardinal(High(Result) div 10) then
      raise Exception.Create('Integer overflow');
    Digit:= P^ - Ord('0');
    if (Digit < 0) or (Digit > 9) then
      raise Exception.Create('Invalid char');
    Result:= Result * 10 + Digit;
    if (Result < 0) then begin
      if not Negative or (Cardinal(Result) <> Cardinal(Low(Result))) then
        raise Exception.Create('Integer overflow');
    end;
    Inc(P);
  until (P^ = 0);
  if Negative then Result:= -Result;
end;

A: I followed this tip:
How to convert AnsiString to UnicodeString in Delphi XE4
Example:
var
  a : AnsiString;
  b : String;
  c : Integer;
begin
  a := '123';
  b := String(a);
  c := StrToInt(b);


text:
Q: Making a subdirectory with the mkdir posix command The latest assignment in my Operating Systems class required us to create a subdirectory(named tmpFolder) using the mkdir command, with no context whatsoever.  The code I currently have is based off of the Minix3 appendix and the manual for mkdir  My professor isn't the most helpful and the rest of the class is also having trouble with it so I figured I'd ask about it here.
Here is my relevant code:
#include <sys/stat.h>

{
    int tmpFolder;
    tmpFolder = mkdir(tmpFolder, 0777);
}

Can someone please explain to me why that is wrong because it is very frustrating having the professor not explaining why I'm wrong

A: mkdir's first argument is the path you want to create. You're providing tmpFolder which is an int. Something like this would make more sense:
int status;
status = mkdir("/tmp/subdir", 0777)


text:
Q: Line detection against darker shades I wants to detect lines from an image with black line drawing over white papers.
It could be easy if its ideal 'black and white', using histogram threshold would do.
But, as the image attached shows, some lines (e.g. in the light red circle) are in gray lighter than the shades (e.g. in the dark red circle). So some shades are obtained before light lines using histogram threshold.

Is there any ideas to divide lines from shades with some 'knowledge'? Thanks!

Edit:
Here are the raw images, a bit small because they are of original resolution.

Thanks :-)

A: I would add another method using Gaussian blur other than erosion+dilation, for your reference:
file='http://i.stack.imgur.com/oEjtT.png';
I=imread(file);
h = fspecial('gaussian',5,4);
I1=imfilter(I,h,'replicate');
h = fspecial('gaussian',5);
I2=imfilter(I,h,'replicate');
I3=I1-I2;
I3=double(I3(:,:,1));
I3=I3.*(I3>5);
imshow(I3)


text:
Q: maven versions:set not updating parent pom I've following parent pom file:
     <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.xyz</groupId>
        <artifactId>abc</artifactId>
        <version>1.0.0.36</version>
        <packaging>pom</packaging>
        <name>Common Data Access Framework</name>
        <build>
        <pluginManagement>
    ...
    ...

Now when I run following command from the same folder where I have this parent pom file:
mvn versions:set -DnewVersion=9.9.9.9

It will update the version details in all child modules and pom file "except" it's own (the parent). This is really strange as I'm running it from the very same folder.

A: I have hit a similar problem yesterday. The cause was that my parent pom.xml had leading whitespace before the xml  tag. After removing it version:set worked as expected, setting the version across all poms,parent and children.
I don't know if this was the solution in your case but I'm posting this to save another poor soul hours of stupid debugging.

A: Tried the following here with Maven 3.3.3's mvn version:set -DnewVersion=... in the root folder:
- root
  - sub-1
  - sub-2

*

*If the subs are just childs (with <parent>root</parent>), just the root POM's <project>/<version> is updated. The subs <parent>/<version>s are not!

*If the subs are childs and modules, the root POM's <project>/<version> and the subs <parent>/<version>s are updated.

*If the subs are just modules only the root POM's <project>/<version> is updated as expected.

This is different to your result but it's no less strange because versions:set says:

Sets the current project's version and based on that change propagates that change onto any child modules as necessary.

The sub modules were childs at each of two topmost runs mentioned above.
UPDATE
The reason for the parent POM not updated can be that 9.9.9.9 is not a standard Maven version:

*

*Maven: The Complete Reference, 3.1.1 Project versions:

A project's version number is used to group and order releases. Maven versions contain the following parts: major version, minor version, incremental version, and qualifier. In a version, these parts correspond to the following format:

<major version>.<minor version>.<incremental version>-<qualifier>

*

*Developing Applications Using Continuous Integration, 7.1 How Version Numbers Work in Maven:

If you use a nonstandard versioning scheme, Maven release and version plug-in goals might not yield the expected results. Because basic string comparison is performed on nonstandard versions, version comparison calculates the order of versions incorrectly in some cases.


text:
Q: Spring Batch distorts number 2,981.00 to 2-981.00 I am trying to load a file into batch. The file looks correct. The value is 2,981.00. but somewhere during processing the value changes to 2-981.00. Spring batch also downloads file as json . Even the json file looks correct . But when the file gets written into db, the value changes to 2-981.00. I get the following exception. Any suggestions please? Thanks!
Caused by: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'target' on field 'temp': rejected value [2-981.00]; codes [typeMismatch.target.temp,typeMismatch.temp,typeMismatch.java.math.BigDecimal,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [target.temp,temp]; arguments []; default message [temp]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.math.BigDecimal' for property 'temp'; nested exception is java.lang.NumberFormatException]


text:
Q: Connection Timeout exception for a query using ADO.Net Update: Looks like the query does not throw any timeout. The connection is timing out.
This is a sample code for executing a query. Sometimes, while executing time consuming queries, it throws a timeout exception.
I cannot use any of these techniques:
1) Increase timeout.
2) Run it asynchronously with a callback. This needs to run in a synchronous manner.
please suggest any other techinques to keep the connection alive while executing a time consuming query?
private static void CreateCommand(string queryString,
    string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        command.Connection.Open();
        command.ExecuteNonQuery();
    }
}

A: You should first check your query to see if it's optimized and it isn't somehow running on missing indexes. 30 seconds is allot for most queries, even on large databases if they are properly tuned. If you have solid proof using the query plan that the query can't be executed any faster than that, then you should increase the timeout, there's no other way to keep the connection, that's the purpose of the timeout to terminate the connection if the query doesn't complete in that time frame.

A: Since you are using ExecuteNonQuery which does not return any rows, you can try this polling based approach. It executes the query in an asyc manner (without callback)
but the application will wait (inside a while loop) until the query is complete. From MSDN. This should solve the timeout problem. Please try it out.
But, I agree with others that you should think more about optimizing the query to perform under 30 seconds.
        IAsyncResult result = command.BeginExecuteNonQuery();

        int count = 0;
        while (!result.IsCompleted)
        {
            Console.WriteLine("Waiting ({0})", count++);
            System.Threading.Thread.Sleep(1000);
        }
        Console.WriteLine("Command complete. Affected {0} rows.",
        command.EndExecuteNonQuery(result));

A: I have to agree with Terrapin.
You have a few options on how to get your time down. First, if your company employs DBAs, I'd recommend asking them for suggestions.
If that's not an option, or if you want to try some other things first here are your three major options:

*

*Break up the query into components that run under the timeout. This is probably the easiest.

*Change the query to optimize the access path through the database (generally: hitting an index as closely as you can)

*Change or add indices to affect your query's access path.

A: If you are constrained from using the default process of changing the timeout value you will most likely have to do a lot more work.  The following options come to mind

*

*Validate with your DBA's and another code review that you have truly optimized the query as best as possible

*Work on the underlying DB structure to see if there is any gain you can get on the DB side, creating/modifying an idex(es).

*Divide it into multiple parts, even if this means running procedures with multiple return parameters that simply call another param.  (This option is not elegant, and honestly if your code REALLY is going to take this much time I would be going to management and re-discussing the 30 second timeout)

A: We recently had a similar issue on a SQL Server 2000 database.
During your query, run this query on your master database on the db server and see if there are any locks you should troubleshoot:
select
  spid,
  db_name(sp.dbid) as DBname,
  blocked as BlockedBy,
  waittime as WaitInMs,
  lastwaittype,
  waitresource,
  cpu,
  physical_io,
  memusage,
  loginame,
  login_time,
  last_batch,
  hostname,
  sql_handle
from sysprocesses sp
where (waittype > 0 and spid > 49) or spid in (select blocked from sysprocesses where blocked > 0)

SQL Server Management Studio 2008 also contains a very cool activity monitor which lets you see the health of your database during your query.
In our case, it was a networkio lock which kept the database busy. It was some legacy VB code which didn't disconnect its result set quick enough.

A: If you are prohibited from using the features of the data access API to allow a query to last more than 30 seconds, then we need to see the SQL.
The performance gains to be made by optimizing the use of ADO.NET are slight in comparison to the gains of optimizing the SQL.
And you already are using the most efficient method of executing SQL.  Other techniques would be mind numbingly slower (although, if you did a quick retrieval of your rows and some really slow client side processing using DataSets, you might be able to get the initial retrieval down to less than 30 seconds, but I doubt it.)
If we knew if you were doing inserts, then maybe you should be using bulk insert.  But we don't know the content of your sql.

A: This is an UGLY hack, but might help solve your problem temporarily until you can fix the real problem
    private static void CreateCommand(string queryString,string connectionString)
    {
        int maxRetries = 3;
        int retries = 0;
        while(true)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    SqlCommand command = new SqlCommand(queryString, connection);
                    command.Connection.Open();
                    command.ExecuteNonQuery();
                }
                break;
            }
            catch (SqlException se)
            {
                if (se.Message.IndexOf("Timeout", StringComparison.InvariantCultureIgnoreCase) == -1)
                    throw; //not a timeout

                if (retries >= maxRetries)
                    throw new Exception( String.Format("Timedout {0} Times", retries),se);

                //or break to throw no error

                retries++;
            }
        }
    }

A: command.CommandTimeout *= 2;

That will double the default time-out, which is 30 seconds.
Or, put the value for CommandTimeout in a configuration file, so you can adjust it as needed without recompiling.

A: If you absolutely cannot increase the timeout, your only option is to reduce the time of the query to execute within the default 30 second timeout.

A: You should break your query up into multiple chunks that each execute within the timeout period.

A: I tend to dislike increasing the connection/command timeout since in my mind that would be a matter of taking care of the symptom, not the problem

A: just set sqlcommand's CommandTimeout property to 0, this will cause the command to wait until the query finishes...
    eg:
SqlCommand cmd = new SqlCommand(spName,conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 0;

A: have you thought about breaking the query down into several smaller chunks?
Also, have you ran your query against the Database Engine Tuning Advisor in:
Management Studio > Tools > Database Engine Tuning Advisor
Lastly, could we get a look at the query itself?
cheers

A: Have you tried wrapping your sql inside a stored procedure, they seem to have better memory management. Have seen timeouts like this before in plan sql statement with internal queries using classic ADO. i.e. select * from (select ....) t inner join somthingTable. Where the internal query was returning a very large number of results.
Other tips
1. Performing reads with the with(nolock) execution hint, it's dirty and I don't recommend it but it will tend to be faster.
2. Also look at the execution plan of the sql your trying to run and reduce the row scanning, the order in which you join tables.
3. look at adding some indexes to your tables for faster reads.
4. I've also found that deleting rows is very expensive, you could try and limit the number of rows per call.
5. Swap @table variables with #temporary tables has also worked for me in the past.
6. You may also have saved bad execution plan (heard, never seen).
Hope this helps

A:
Update: Looks like the query does not
  throw any timeout. The connection is
  timing out.

I.o.w., even if you don't execute a query, the connection times out? because there are two time-outs: connection and query. Everybody seems to focus on the query, but if you get connection timeouts, it's a network problem and has nothing to do with the query: the connection first has to be established before a query can be ran, obviously.

A: It might be worth trying paging the results back.


text:
Q: How to increase stack size in Bloodshed Dev-C++? We are using Blodshed Dev-C++ to in an image processing project. We are implementing connected component labelling on a video frame. We have to use a recursive function which recurses so many times that we get a stackoverflow. How can we have a larger stack size? Is it possible to change it through some linker parameters or anything similar?
void componentLabel(int i,int j,IplImage *img){
  //   blueFrame = img->imageData[i*3*width+j*3];
//     greenFrame = img->imageData[i*3*width+j*3+1];
//     redFrame = img->imageData[i*3*width+j*3+2];

     if(!( img->imageData[i*3*width+j*3]==0 && img->imageData[i*3*width+j*3+1]==0 && img->imageData[i*3*width+j*3+2]==0 )  ){
           //printf("iffffff aq\n");
           return;
     }
     else{
           //printf("else aq  %d\n",sayac_label);
               img->imageData[i*3*width+j*3]=1;

               new_object.pixel_count=new_object.pixel_count+1;
               new_object.total_row=new_object.total_row+i;
               new_object.total_col=new_object.total_col+j;

               if(j<width-1 ){
                         componentLabel(i,j+1,img);
               }
               if(j>0 ){
                         componentLabel(i,j-1,img);
               }
               if(i<height-1 ){
                         if(i>new_object.bottom.satir){
                              new_object.bottom.satir=i;
                              new_object.bottom.sutun=j;
                         }

                         componentLabel(i+1,j,img);
               }
               if(i>0 ){
                         if(i<new_object.top.satir){
                              new_object.top.satir=i;
                              new_object.top.sutun=j;
                         }
                         return componentLabel(i-1,j,img);
               }
     }

A: Only one approach will guarantee that you won't run out of stack size - reformulate the algorithm to be tail recursive (and ensure that your compiler is optimizing tail calls - usually an -O3 (or -O2?) optimization flag).
Short of that, have you increased the maximum stack size that the shell will grant your task?
  ulimit -s <maximum stack size>


text:
Q: Windows Backup failed with error 0x807800C5 I setup backup of my Windows 8 laptop with Windows 7 File Recovery (known as Backup and Restore in Windows 7).
Backup of files runs successfully. But if I try to create system image, it fails with error 0x807800C5:

Error details on the dialog:

The mounted backup volume is inaccessible.

Error details in the system log:

There was a failure in preparing the backup image of one of the volumes in the backup set.

I save the backup to a network location, WD MyBookLive.

Edit:
I tried some of the steps suggested in the various thread about this issue:

*

*Cleaned up the backup location:

*

*Removed MediaID.bin in the backup location.

*Removed folder <ComputerName> from WindowsImageBackup.

*Restarted backup resulted in the same error. However, the error dialog shows slightly different error message:

The specified backup disk cannot be found.

*Performed System File Check by running sfc /scannow. It showed no errors.
Running backup failed nevertheless.

I tried searching Google for error code but I've found no solution so far.
Update:
I submitted technical support request to Microsoft. The first suggestion was to clean boot, but it didn't help. I pointed out that I had tried all the methods from the same problem on MS Answers, and nothing had helped.
I tried to save full system image to an external hard drive, it was successful. So creating the image fails only when saved to a network location.

Note: This feature has been removed from Windows 8.1 in favor of File History. You can still create full system image yet I didn't find an option to schedule it for automatic creation.

A: I quote from How Windows 8's Backup System Differs From Windows 7's :

With Windows 7, you can back up any files on your computer – not only
  personal files, but program files, system files, and anything else.
  You can also create full system images that can be used to restore
  your computer to its current state in the future.
There's been a major philosophical change in Windows 8. You can no
  longer create full system images, nor can you back up everything on
  your hard drive. Instead, you can only back up files in your
  libraries, files on your desktop, your contacts, and your browser
  favorites. Windows 8's File History feature is designed to protect
  users' personal files, which are generally irreplaceable. In contrast,
  there's less need to back up system files because operating systems
  and applications can be reinstalled from elsewhere.

This seems to say that in Windows 8, Microsoft has decided for us that we no longer need
system images (!).
Nevertheless, some people claim they have managed to create system image backups
using Windows 7 File Recovery, as long as this was done to a local drive and not via the network.
So if you insist on system image backup (and rightly so), it is time to look for a third-party
product. The Windows backup utility has since always been a weak tool with many idiosyncrasies,
that I never recommended using.
There is a discussion of backup tools in Gizmo's article Best Free Drive Imaging Program and
in its comments, recommending several free products.
The best-noted product, and my personal favorite, is the free
AOMEI Backupper Standard.

A:
Backup service runs as Local System account, it has no way to see user's mapped drives

Map the drives as "Local System account" with proper credentials and use drive letters to access your target volume. The mentioned IOPL error may be an indication of wrong permissions, such as when a login-only drive is accessed anonymously.
I have to admit that I am guessing in this case. However, it's not a haphazard suggestion: An application will include support for accessing local files in a whole lot more cases than support for accessing "samba shares" directly. So if you let the OS handle file access over the network, your backup software will be more likely to succeed.

A: I still have no complete solution to this problem although I've found a workaround in my environment.

*

*System image is created successfully when using external hard drive attached directly to the laptop.

*System image is not saved to network share on a Windows 7 system.
(The same way it fails when using a Network Attached Storage.)

*System image is created successfully when the target has no access restrictions, in either case: NAS and Windows 7.

Workaround:
Use a network folder without access restrictions as the backup target, that is every user in the (local) network has read and write access to the folder. Windows does not require user name and password to view the contents of the folder.
If Windows asks for a password when you try to open the network folder, creating system image in Windows 8 fails. Of course, the correct credentials are provided to the Backup service, and file backup completes successfully. This feature works in Windows 7 without any errors.

My request to Microsoft support brought nothing. They made me follow the standard procedure which didn't fix the error. They even gave me the utility, wbdiag, to collect additional debugging logs. It didn't help either.
I pointed out that system image is created successfully when network folder is globally writable. Support engineer said he could not reproduce the problem when saving backup to a network folder which requires special credentials.
After that they closed my request as File Recovery feature in Windows 8 works correctly. Since NAS is not Microsoft product, they can't provide support for it. They didn't noticed the fact that saving system image to a network share on Windows 7 fails with the same error as when saving to the NAS.

A: I have a Buffalo TeraStation NAS and experienced the same issue. After providing the group 'Domain Computers' write access it worked for me.

A: I was facing the same error code while trying to create a system image backup in windows 10. The solution that worked for me was simply disabling windows defender.
I was able to create system images with no problem at first, my problem started after i changed windows defender settings to exclude certain folders. I believe by altering windows defender settings it altered the permissions for users on the system and denied access to the WindowsImageBackup folder on the drive in question.
When in doubt, disable windows defender.

A: Seems a computer with more than one EFI partition (including on a second disk, even if external) prevents the backup from executing.
My destination disk used to be the main disk of another laptop, which prevented the backup from executing. Doing a diskpart clean to erase the disk worked.

A: I had the problem after upgrading/updating Windows 10 (creators/anniv./.. update).I had a backup on my target (networkshare) already of my Windows 10 machine. Only one image is allowed of Windows in there. I guess that after upgrade it detects that it is a different Windows (not sure), and this might be the reason why it fails.
I removed the backup from that folder and it worked again.
After searching the web I found another user who had similar:

This happens after upgrading Windows while still using the same backup
  target disk. The problem is the three old backup files on the target
  disk that you need to remove. Consider the old backup files obsolete
  and delete them, or move them away into a temporary folder.

*

*Datafile - MediaID.bin

*Folder - Windowsimagebackup

*Computer-name-file - Guru (For example)

  Then restart your backup and find out that now it works.
Let us know the status of the issue. Your reply is need to assist you
  further. Regards,

Hope it helps.
(Of course make sure you have enough permissions to write on that target location… E.g. add "Domain computers" to it and give read/write permissions. Note that for example Nvidia creates also a user on your pc for its driver. I don't take this data in my backup, maybe this user doesn't have permissions on the target if you also include it in your backup… I only take my user data.)


text:
Q: Controls Layout Help in WPF I have a problem with layout
<ListBox Name="Tweets" Grid.Row="1" ItemsSource="{Binding Path=Tweets}" Background="#1F0000FE">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <local:TweetTemplate Margin="10"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

Here is my template:
<Grid Name="grid">
    <Grid.RowDefinitions>
        <RowDefinition Height="25*" />
        <RowDefinition Height="95*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="110" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Image Source="{Binding Path=FromImage}" Grid.RowSpan="2" Margin="7" />
    <TextBlock Text="{Binding Path=From}" Margin="5" Grid.Column="1" />
    <TextBlock Text="{Binding Path=Text}" TextWrapping="WrapWithOverflow" Grid.Row="1" Margin="7" Grid.Column="1" />
</Grid>

My problem is when this <TextBlock Text="{Binding Path=Text}" text is very long, it stretches the Grid. And then stretches Parent controls. I want that text don't stretch Listbox, and when it reaches the end of the ListBox width, switched to a new line. And when the window is resized, the size of ListBox should be increased. It means to use all of the window.

A: ListBox creates ScrollViewer for displaying items, so you should manually disable it with  ScrollViewer.HorizontalScrollBarVisibility property:
    <ListBox Name="Tweets"
             Grid.Row="1"
             ItemsSource="{Binding Path=Tweets}"
             Background="#1F0000FE"
             ScrollViewer.HorizontalScrollBarVisibility="Disabled">
        ...
    </ListBox>

A: You should be able to set a MaxWidth to the textblock, and set TextWrapping="Wrap".  That should provide you with the desired results.  In your listbox you can also say HorizontalContentAlignment="Stretch" so that your Templated items stretch to the inside limits of the itemscontrol.


text:
Q: How to get AOP-like object beforeConstruction hooks in Javascript properly? I'm trying to dynamically alter all objects in Javascript so that its construction can be hooked. This is what I've got now, which almost works properly:
Function.prototype.beforeConstruction = function(newFunc) {
    var oldObj = this;
    var newObj = function() {
        newFunc.apply(this, arguments);
        oldObj.apply(this, arguments);
    }
    newObj.prototype = oldObj.prototype;
    return newObj;
};

It is used like this:
someObj = someObj.beforeConstruction(function() {
    //executed before someObj is constructed
});

Now, the problem is that if the object has static fields like this:
someObj.staticField = "example";

These will get lost when resetting the object to the one with the hook. Copying the prototype does not help with this.
Can anyone help me out here? Keep in mind that this must work without the need to modify existing objects (so that it can be used for existing libraries).
Regards,
Tom

A: not sure if this is what you are after, but you could try looping over all the properties in the original someObj and copying their values to newObj.
Function.prototype.beforeConstruction = function(newFunc) {
    var oldObj = this;
    var newObj = function() {
        newFunc.apply(this, arguments);
        oldObj.apply(this, arguments);
    }

    // copy static fields here.
    for(var key in this) {
       // This will not copy static fields of any base classes.
       if(this.hasOwnProperty(key)) {
          newObj[key] = this[key];
       }
    }

    newObj.prototype = oldObj.prototype;
    return newObj;
};

MozDev has an article explaining hasOwnProperty -
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/hasOwnProperty


text:
Q: Limiting JOIN query to 5 of each type I have 2 tables, one has the categories within it, and the other has the distinct items in it.
What I want to do is to select
the item_id and cat_id, and limit it to 5 result for each category, for example:
cat_id item_id
1      1
1      2
1      3
1      4
2      5
2      6
3      7

etc...
The closest query i've come up with
SELECT cat.cat_id, cat.cat_name, item_id, item_author, item_name, item_pic_big
FROM item_table ipt
JOIN cat_table cat ON ipt.cat_id = cat.cat_id
GROUP BY item_id
HAVING COUNT(*) < 5
ORDER BY cat.cat_id

That's what I found on stackoverflow, however if I want to change the count to let's say... 2, it gives me the same result, and if I change the group by to cat_id, it only gives me 1 result.
Any help would be appreciated

A: What you actually need is something like:
SELECT
cat.cat_id, cat.cat_name, item_id, item_author, item_name, item_pic_big
FROM item_table a
JOIN cat_table b ON a.cat_id = b.cat_id
WHERE a.item_id IN (SELECT item_id
                    FROM item_table
                    WHERE cat_id = b.cat_id
                    LIMIT 5)
GROUP BY a.item_id
ORDER BY b.cat_id

Unfortunately, if you try to run this you will get this disappointing
error message:
This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

So you'll need a workaround. You can see a list of possible workarounds here:
http://www.artfulsoftware.com/infotree/queries.php#104
EDIT: The first solution there can be translated to your structure like this:
(I don't have your tables, so there may be minor column names issues)
SELECT temp2.cat_id, temp2.item_id,
       temp2.cat_name, temp2.item_author,
       temp2.item_name, temp2.item_pic_big
FROM
    (SELECT
          temp.cat_id,
          temp.item_id,
          temp.cat_name,
          temp.item_author,
          temp.item_name,
          temp.item_pic_big,
          IF( @prev <> temp.cat_id, @rownum := 1, @rownum := @rownum+1 ) AS rank,
          @prev := temp.cat_id
    FROM (SELECT
         a.item_id,
         b.cat_id,
         b.cat_name,
         a.item_author,
         a.item_name,
         a.item_pic_big
         FROM item_table a
         JOIN cat_table b ON a.cat_id = b.cat_id
         ORDER BY cat_id, item_id) AS temp
    JOIN (SELECT @rownum := NULL, @prev := 0) AS r
    ORDER BY temp.cat_id, temp.item_id) as temp2
WHERE temp2.rank <= 5
ORDER BY temp2.cat_id, temp2.item_id;


text:
Q: ng-packagr Angular 11 Error: Type AppModule does not have 'ɵmod' property I've just upgrade my solution to Angular 11 and Webpack 5. There are some packages that I build as part of the solution. When it tries to load one of the packages that I've built using ng-packagr I get the following:
Error: Type AppModule does not have 'ɵmod' property.
This error is coming from the Angular Core module. I have tried this with both ivy enabled and disabled.
Any ideas would be appreciated as this is driving me mad and I can't find much on this error.


text:
Q: Cross Compiling for Arm armv5tejl I am trying to cross compile a simple hello world program for a linux system.
I have the following information:
uname -a
Linux (none) 2.6.32.28 #130 PREEMPT Mon Feb 18 13:54:18 CST 2013 armv5tejl GNU/Linux

cat /proc/cpuinfo
Processor       : ARM926EJ-S rev 5 (v5l)
BogoMIPS        : 421.06
Features        : swp half fastmult edsp java
CPU implementer : 0x41
CPU architecture: 5TEJ
CPU variant     : 0x0
CPU part        : 0x926
CPU revision    : 5

Hardware        : KeyASIC Ka2000 EVM
Revision        : 0000
Serial          : 0000000000000000

I would like to know how to cross compile for this system. I have tried the following:

*

*arm-linux-gnueabi-gcc helloworld.c -march=armv5 -o helloworld

*arm-linux-gnueabi-gcc helloworld.c -mcpu=arm926ej-s -o helloworld

But when I try and run the executable I get the error message "command not found".
I am probably not compiling it correctly but I don't know what compile options to use given the information I have.
(I know the helloworld.c is all working).
ls -l helloworld
-rwxr-xr-x    1 0        0             8428 Jan  1 00:00 helloworld

which helloworld
which: applet not found

I put busybox-armv5l on
busybox which helloworld
(no output)

ldd is also not on the system I am trying to compile for (its the transcend WifiSD card).
ls -ln /lib/libc*
-rwxrwxrwx    1 0        0           244279 Jan 19  2012 /lib/libc.so.0
-rwxrwxrwx    1 0        0            13043 Jan 19  2012 /lib/libcrypt.so.0
-rwxr-xr-x    1 0        0          1251776 Jan  1 00:00 /lib/libcrypto.so.0.9.8

I tried to run /lib/libc.so.0 to get version information and I got a segmentation fault. It seems compiling with -static fixed the issue. So I guess it was an issue with the libc library. Thank you for the help.

A: I had to use -static flag to include c libraries in the binary. Thanks to auselen.


text:
Q: Computers That Can Compute in Femtoseconds I was watching a video about LCLS 2 and they mentioned that they can shoot and record up to 1 million x-ray pulses allowing them to see chemical reactions. They said that these pulses of x-ray last only for a few femtoseconds and if one femtosecond is 1x10^-15 how can we record that. Light only travels at approximately 300000 m/s so there is no way light can travel that fast for a camera, or sensor to see it. if an electron wanted to travel 1 meter, it would take it 3x10^-6 seconds which is still orders of magnitude slower than a femtosecond. This is especially true considering that electrons also travel at the speed of light. If that is true, how can a computer possibly record data that lasts 1 femtosecond?
The video I refer to: https://www.youtube.com/watch?v=X7CoLCTeqpE

A: There is a lot of confusion in this question.  Let me try to clear up some of it.
First, the LCLS II is not yet running. The LCLS II is expected to begin operation in 2022.  However, SLAC is doing experiments with the original LCLS (Linac Coherent Light Source).  This delivers pulses of X-rays at 120 Hz  (120 pulses per second).  Each pulse is ten billion times more intense than an X-ray pulse from a synchrotron, so it is possible to take a complete X-ray diffraction pattern for a molecule with each pulse.  Experimental groups have used the LCLS to make movies of chemical reactions.
Chemical reactions take place on 100 femtosecond (fs) to picosecond (ps) timescales, so an X-ray pulse with a length of a few fs will take a static diffraction pattern image of a molecule at an intermediate stage of a chemical reaction.   These pictures can be converted to pictures of the atoms in real space and then assembled to form a movie. To take the picture, the diffracted X-rays go out from the sample to an array of detectors.  Once the X-rays are absorbed by the detectors, there is plenty of time (1/120 sec) for the detectors to process and output these signals. However, it is not unreasonable that properly designed detectors could take 1 million pictures per second.  The tracking detectors at the CERN Large Hadron Collider take simpler pictures at the rate of 40 million pictures per second.
The LCLS is a free-electron laser.  That is, the X-rays are generated by wiggling an electron beam and forcing it to emit synchrotron radiation.  The length of the X-ray pulse is set by the length of the electron pulse that generates it.  The speed of light is, in convenient units, 1 foot (0.3 m) per nanosecond, so a few femtosecond pulse corresponds to an electron pulse of length about 1 micron. It is tricky to compress a pulse of electrons to this size, but not as tricky as it might appear.  The natural electron bunches in the SLAC linear accelerator are about 100 microns in length.
To summarize:  At regular intervals (now 120 per second, soon 1 million per second) the accelerators at SLAC produce very short bunches of electrons that in turn create very short bunches of X-rays.  These are intense enough to take a picture of a molecule with each pulse.  The pulses are short enough to capture molecules in the intermediate stages of chemical reactions.  The resulting pictures can be turned into movies.
The person who asked this question saw only a very brief video about the LCLS, but SLAC has longer videos that provide more information.  Many of these are on the SLAC Public Lecture web page:
https://www6.slac.stanford.edu/community/past-lectures
For better understanding of this question, I especially recommend the lectures from 4/11/2017 (by Raymond Sierra) and 9/29/2015 (by Mike Minitti). The lecture from 11/17/2009 (by Daniel Ratner) explains how the LCLS works.