text:
Q: High val_acc, but low accuracy in practice I have been following the code from this website to train a CNN that can distinguish between 10 monkey species. During the training phase I get decent results with 3 epochs:
Using TensorFlow backend.
Found 1097 images belonging to 10 classes.
Found 272 images belonging to 10 classes.
Epoch 1/3
46/46 [==============================] - 24s 521ms/step - loss: 1.4526 - acc: 0.5644 - val_loss: 0.5665 - val_acc: 0.9688
Epoch 2/3
46/46 [==============================] - 20s 445ms/step - loss: 0.5706 - acc: 0.8983 - val_loss: 0.4078 - val_acc: 0.9375
Epoch 3/3
46/46 [==============================] - 21s 449ms/step - loss: 0.3696 - acc: 0.9447 - val_loss: 0.4832 - val_acc: 0.8438

Then I wrote a prediction script that looks at a directory and makes a prediction from the saved model. I tried pointing it at both the training and validation folders, but both of the results seem correct about 16% of the time. Why does my val_acc seem high during training but when I actually use the model to make a prediction, it performs poorly?
Here is the prediction loop:
inputSize = (300, 400, 3)
for count, path in enumerate(allImages):
    img= cv2.imread(path)

    img = cv2.resize(img, (inputSize[0], inputSize[1]))
    img = np.reshape(img, (1, inputSize[0], inputSize[1], inputSize[2]))

    correct = path.split(os.path.sep)[-2] #get label from directory
    classes = labels[model.predict(img)[0].argmax(axis=0)]

    if args.show_predictions: #display prediction in a window
        fontSize = 0.8
        black = (0, 0, 0)
        white = (255, 255, 255)

        orig = cv2.resize(orig, (480, 480))
        cv2.putText(orig, 'prediction: {}'.format(classes), (0, 20),
            cv2.FONT_HERSHEY_SIMPLEX, fontSize, black, 10)
        cv2.putText(orig, 'prediction: {}'.format(classes), (0, 20),
            cv2.FONT_HERSHEY_SIMPLEX, fontSize, white, 2)

        cv2.putText(orig, 'answer: {}'.format(correct), (0, orig.shape[0] - 10),
            cv2.FONT_HERSHEY_SIMPLEX, fontSize, black, 10)
        cv2.putText(orig, 'answer: {}'.format(correct), (0, orig.shape[0] - 10),
            cv2.FONT_HERSHEY_SIMPLEX, fontSize, white, 2)
        cv2.imshow('prediction', orig)
        if cv2.waitKey(0) == ord('q'):
            break

    if args.verbose:
        print('prediction: {} --> answer: {}'.format(classes, correct))

    if classes == correct:
        totalCorrect += 1

    counter += 1
    if count%verbosity == 0:
        print('Predicting image {} out of {}'.format(count, len(allImages)))

print('total correct: {}/{} - {}%'.format(totalCorrect, counter, int(totalCorrect/counter * 100)))
cv2.destroyAllWindows()

Basically it reads the label from the directory and compares it to a label list I made earlier in the script.
Upon running the script with the training data (which I thought would be high since it was trained on it), I get:
Predicting image 600 out of 1097
Predicting image 650 out of 1097
Predicting image 700 out of 1097
Predicting image 750 out of 1097
Predicting image 800 out of 1097
Predicting image 850 out of 1097
Predicting image 900 out of 1097
Predicting image 950 out of 1097
Predicting image 1000 out of 1097
Predicting image 1050 out of 1097
total correct: 161/1097 - 14%

What makes the accuracy high during training, but low in practice?
EDIT: Running the script in verbose mode:
Predicting image 0 out of 272
prediction: common_squirrel_monkey --> answer: bald_uakari
prediction: bald_uakari --> answer: bald_uakari
prediction: common_squirrel_monkey --> answer: bald_uakari
prediction: common_squirrel_monkey --> answer: bald_uakari
prediction: bald_uakari --> answer: bald_uakari
prediction: japanese_macaque --> answer: bald_uakari
prediction: japanese_macaque --> answer: bald_uakari
prediction: common_squirrel_monkey --> answer: bald_uakari
prediction: common_squirrel_monkey --> answer: bald_uakari
prediction: common_squirrel_monkey --> answer: bald_uakari
prediction: common_squirrel_monkey --> answer: bald_uakari
prediction: common_squirrel_monkey --> answer: bald_uakari
prediction: common_squirrel_monkey --> answer: bald_uakari
prediction: white_headed_capuchin --> answer: bald_uakari
prediction: bald_uakari --> answer: bald_uakari
prediction: white_headed_capuchin --> answer: bald_uakari
prediction: japanese_macaque --> answer: bald_uakari
prediction: common_squirrel_monkey --> answer: bald_uakari
prediction: common_squirrel_monkey --> answer: bald_uakari
prediction: common_squirrel_monkey --> answer: bald_uakari
prediction: common_squirrel_monkey --> answer: bald_uakari
prediction: common_squirrel_monkey --> answer: bald_uakari
prediction: japanese_macaque --> answer: bald_uakari
prediction: common_squirrel_monkey --> answer: bald_uakari
prediction: common_squirrel_monkey --> answer: bald_uakari
prediction: common_squirrel_monkey --> answer: bald_uakari
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
Predicting image 50 out of 272
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: common_squirrel_monkey --> answer: black_headed_night_monkey
prediction: nilgiri_langur --> answer: common_squirrel_monkey
prediction: japanese_macaque --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: white_headed_capuchin --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: pygmy_marmoset --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: nilgiri_langur --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: white_headed_capuchin --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: nilgiri_langur --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: common_squirrel_monkey
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: japanese_macaque --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: japanese_macaque --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: japanese_macaque --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: pygmy_marmoset --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: japanese_macaque --> answer: japanese_macaque
prediction: japanese_macaque --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: pygmy_marmoset --> answer: japanese_macaque
prediction: japanese_macaque --> answer: japanese_macaque
prediction: japanese_macaque --> answer: japanese_macaque
Predicting image 100 out of 272
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: japanese_macaque --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: japanese_macaque --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: japanese_macaque
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: japanese_macaque --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: mantled_howler
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: white_headed_capuchin --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: white_headed_capuchin --> answer: nilgiri_langur
Predicting image 150 out of 272
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: nilgiri_langur
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: japanese_macaque --> answer: patas_monkey
prediction: nilgiri_langur --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: nilgiri_langur --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: nilgiri_langur --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: japanese_macaque --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: pygmy_marmoset --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: patas_monkey
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
Predicting image 200 out of 272
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: pygmy_marmoset --> answer: pygmy_marmoset
prediction: japanese_macaque --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: japanese_macaque --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: nilgiri_langur --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: common_squirrel_monkey --> answer: pygmy_marmoset
prediction: white_headed_capuchin --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: nilgiri_langur --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: japanese_macaque --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: nilgiri_langur --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: patas_monkey --> answer: silvery_marmoset
prediction: japanese_macaque --> answer: silvery_marmoset
prediction: japanese_macaque --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: japanese_macaque --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: silvery_marmoset
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: white_headed_capuchin --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: white_headed_capuchin --> answer: white_headed_capuchin
Predicting image 250 out of 272
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: white_headed_capuchin --> answer: white_headed_capuchin
prediction: white_headed_capuchin --> answer: white_headed_capuchin
prediction: white_headed_capuchin --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: japanese_macaque --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: pygmy_marmoset --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: white_headed_capuchin --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
prediction: common_squirrel_monkey --> answer: white_headed_capuchin
total correct: 41/272 - 15%

A: So, as it turns out, I was using the wrong channel input mode. The pre-trained network I was using is called resnet50 from the keras library, and it uses the caffec style input.
The solution is to import preprocess_image() from keras, then run
img = preprocess_image(img)
Another factor was me loading images with cv2.imread. I'm uncertain but this may use the wrong channel format that resnet50 requires. The alternative is to use keras' load_img() function.
Conclusion: val_acc is generally correct during training. If your prediction accuracy is poor it is likely a data input problem!


text:
Q: How to retrieve the value of a dropdown with multiple values? I have a dropdown which can select multiple values.I know that if the dropdown stores values comma separated its possible to split the string and retrieve the values. However I have a dropdown which on selection of multiple values stores them as a list with each value as a list element. I tried to retreive the values in the same way but I am only getting the first value! Can anyone suggest a way to retrieve all the values using JS?
The selected values from the dropdown basically fill a list dynamically. I need to know how to retrieve the values of the list.
The code of the list is:
The Javascript and HTML code is:
 var ul = document.getElementById("foo");
 var items = ul.getElementsByTagName("li");
 for (var i = 0; i < items.length; ++i)
 {
     var it = items[i].getElementsByTagName("span");
     alert(it.innerHTML);

 }

 Afghanistan

 Afghanistan2

 Afghanistan3

A: Is it compulsory to use raw JS?
In jQuery you can do this way:
$( "ul > li" ).each(function( index ) {
  console.log( index + ": " + $( this ).text() );
});

P.S. I'm using in this example ul > li selector, but i'm not sure that it's best solution in your case, because I can't see full markup of your page. According to the subject of your question I suppose you need to use some extra jQuery selector value to detect selected options. Something like that:
 if ($(this).is(':selected') {
//then process this value
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why isnt input function reading all lines from input txt file? Python So I have a project, where my program reads a txt file and then converts the txt into a tab txt file ( basically it reads the input, and with the dicionary, when it finds a special character it inserts a tab '\t'). The program works fine (so far) but it only reads the first line until it finds a newline '\n', and I just cant understand what is wrong in my code for that to happen. Can someone indicate me where is my code failing?
Code:
from Tkinter import *
import Tkinter as tk
import codecs
from string import *

u'\xe1'.encode('utf-8')

root = tk.Tk()
root.title('Tentative 1')

file = open('Data Path', 'r+')

#sentence = file.read()
#sentence = sentence.decode('cp1252', 'strict')

with codecs.open('Data path', encoding='latin1') as f:
sentence = f.readline()

if u'\xe1' in sentence:
 print sentence

else:
 pass
#sentence = sentence.replace("u'\xe1'", "-")

def task():
 print '\n', sentence

def replace_all(text, dic):
 for i, j in dic.iteritems():
    text = text.replace(i, j)
 return text
reps = {'^^':'\t', '(':'\t', ')':'\t', 'ISBN:':'\t', '--':'\t', '"':'\t', '.:':'\t', '|':'\t', 'p.':'\t', ',':' '}
txt = replace_all(sentence, reps)

def txt_conversor():
 txt = replace_all(sentence, reps)
 print '\n', txt

results = tk.Button(root, text='Results', width=25, command=task)
results.pack()
txt = tk.Button(root, text='Convert results', width=25, command=txt_conversor)
txt.pack()

root.mainloop()

I did tried to change f.readline() to f.readlines() but it gives an error:
Traceback (most recent call last):
File "C:\Python27\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 323, in RunScript
debugger.run(codeObject, __main__.__dict__, start_stepping=0)
File "C:\Python27\Lib\site-packages\Pythonwin\pywin\debugger\__init__.py", line 60, in run
_GetCurrentDebugger().run(cmd, globals,locals, start_stepping)
File "C:\Python27\Lib\site-packages\Pythonwin\pywin\debugger\debugger.py", line 654, in run
exec cmd in globals, locals
File "C:\Users\Joao\Desktop\Script (Console Bug with conversor).py", line 6, in <module>
import sys
File "C:\Users\Joao\Desktop\Script (Console Bug with conversor).py", line 233, in replace_all
text = text.replace(i, j)
AttributeError: 'list' object has no attribute 'replace'

So how do i read multiple lines from the txt file?
Input:
Correia, Teresa Pinto; Henriques, Virgínia; Julião, Rui Pedro^^ (2013)), IX Congresso da      Geografia Portuguesa – Geografia: Espaço, Natureza, Sociedade e Ciência--, ISBN: 978-972-99436-6-9, |Lisboa: Associação Portuguesa de Geógrafos. p. 977 e-Book

Dominguez, L.; Aliste, J; Ibáñez Martinez; Natário, M.; Fernandes, Gonçalo Poeta (2013) – Estudio Socioeconomico de la Frontera entre Portugal y España, Edita Riet, Salamanca. (ISBN: 978-84-7797-403-1)

Output:
 Correia  Teresa Pinto; Henriques  Virgínia; Julião  Rui Pedro      2013          IX Congresso da Geografia Portuguesa  Geografia: Espaço  Natureza  Sociedade e Ciência        978-972-99436-6-9      Lisboa: Associação Portuguesa de Geógrafos.      977 e-Book

A: f.readline() returns just the next line of the file up to and including the newline character, hence it it correctly stops after processing your first line.
f.readlines() returns a list of strings where each string corresponds to a line from the file. The problem in your case is that you are using a string method on a list object (sentence).
For fixing you can either use read(), which returns the whole content of the file as a string (and it's probably the most pythonic solution) or make sure to pass a list to your replace_all function (process list items one by one, use .join(), ect.).
Here you can find a nice explanation of the different file methods: http://interactivepython.org/runestone/static/thinkcspy/Files/files.html#filemethods2a

A: Use f.read() to get all text as one string (with all '\n' inside).
sentence = f.read()

A: The best way to read a file.
with open(filename, "r") as file:
    for i in file.readlines():
        print(i)
# end with (closes the file)


text:
Q: refactoring sample Python to-do list into web services, TypeError: the JSON object must be str, not 'bytes' Here is sample.py:
from flask import Flask, render_template, jsonify
import urllib.request
import sqlite3
import json

app = Flask(__name__)
app.config.from_object(__name__)

@app.route("/")
def show_list():
    with urllib.request.urlopen('http://localhost:6000/api/items') as response:
        resp = response.read()
    resp = json.loads(resp)
    return render_template('index.html', todolist=resp)

if __name__ == "__main__":
    app.debug = True
    app.run(port=5000)

Here is sampleapi.py
from flask import Flask, render_template, redirect, g, request, url_for, jsonify
import sqlite3
import urllib.request

DATABASE = 'todolist.db'

app = Flask(__name__)
app.config.from_object(__name__)

@app.route("/api/items")
def get_items():
    db = get_db()
    cur = db.execute('SELECT what_to_do, due_date, status FROM entries')
    entries = cur.fetchall()
    tdlist = [dict(what_to_do=row[0], due_date=row[1], status=row[2])
              for row in entries]
    return jsonify(tdlist)

def get_db():
    """open new db connection.
    """
    if not hasattr(g, 'sqlite_db'):
        g.sqlite_db = sqlite3.connect(app.config['DATABASE'])
    return g.sqlite_db

@app.teardown_appcontext
def close_db(error):
    """Close db at the end of the request."""
    if hasattr(g, 'sqlite_db'):
        g.sqlite_db.close()

if __name__ == "__main__":
    app.run("0.0.0.0", port=6000)

This is the error I get:
File "sample.py", line 14, in show_list
TypeError: the JSON object must be str, not 'bytes'

So I believe I have to change urllib.request.urlopen('http://localhost:6000/api/items') as response:
as we can't use urllib library to send POST requests, as it sends the data in bytes instead of JSON. So how do I use the requests library, which can send data over http protocol as json?

A: Your problem can definitely be solved without requests, but it's much easier to use than urllib anyway so I recommend it. Here is what you would do:
import requests

resp = requests.get('http://localhost:6000/api/items').json()


text:
Q: grey strikes strokes through folders in eclipse I've been working with this project for some time.
Today grey strikes appeared through the folders of one project (PhoneStreamingActivity).
Why?
I was wiring up the jni component of my project and moving some files between packages when it happened.

A: From this website grey bars mean method is deprecated. Perhaps something in the folder is deprecated.
http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.jdt.doc.user/reference/ref-icons.htm


text:
Q: Using a variable to call an array from an xml file I had some trouble wording the question, but I think I can explain it better once I show the code:
This is my xml file (test.xml)
<?xml version="1.0" encoding="utf-8"?>
<root>
<entry id="1">
  <post>05/12/2014 12:00:00</post>
  <page>1</page>
  <part>1</part>
  BODY TEXT 1
</entry>
<entry id="2">
  <post>05/14/2014 12:00:00</post>
  <part>1</part>
  <page>2</page>
  BODY TEXT 2
</entry>
</root>

This is my PHP code (call.php)
<?php

if(isset($_GET['p']))
{
$p=$_GET['p'];
echo $p . "
";
$xml=simplexml_load_file("test.xml");
$day=$xml->entry[$p]->post;//<-----------PROBLEM AREA
$post=strtotime("$day");
echo $post . "
";
echo time() . "
";
if(time() >= $post)
{
    echo $xml->entry[$_GET['p']]->page . "
";
    echo $xml->entry[$_GET['p']]->part . "
";
}
}else{
    echo "
Main Page Stuff
";
}
?>

The problem I am having is with the $day variable. If I replace [$p] with [1] or [0], it runs perfectly, but I need to have it called with a variable so I can change what part of the XML file is loaded depending on the query string, currently '?p=1'.
The echo $p results prints out 1 or 0 depending on what I put into the URL, so the $_GET is working properly, but if I put either $p or $_GET into entry[] it gives the error
Notice: Trying to get property of non-object in C:\wamp\www\xmltest\call.php on line 20

(line 20 is the one marked 'PROBLEM AREA')
is there any way to fix this problem so I can call either the first  or the second depending on the query string?

A: I could not find a way to make the solution I was hoping for work, so I worked around it by making a new xml file for each entry instead of having each entry in one xml file.
Code used to load the xml file:
p="docs/".$_GET['p'].".xml";
if(file_exists($p))
{
  $xml=simplexml_load_file($p);
  $day=$xml->entry->post;
  $value = $xml->entry->body;
  echo "Part ".$xml->entry->part;
  echo "Page ".$xml->entry->page;
}


text:
Q: How to implement Retry logic in RabbitMQ? In my project I'm setting SimpleRetryPolicy to add custom exception and RetryOperationsInterceptor which is consuming this policy.
@Bean
    public SimpleRetryPolicy rejectionRetryPolicy() {
        Map<Class<? extends Throwable>, Boolean> exceptionsMap = new HashMap<Class<? extends Throwable>, Boolean>();
        exceptionsMap.put(DoNotRetryException.class, false);//not retriable
        exceptionsMap.put(RetryException.class, true); //retriable
        return new SimpleRetryPolicy(3, exceptionsMap, true);
    }

    @Bean
    RetryOperationsInterceptor interceptor() {
        return RetryInterceptorBuilder.stateless()
                .retryPolicy(rejectionRetryPolicy())
                .backOffOptions(2000L, 2, 3000L)
                .recoverer(
                        new RepublishMessageRecoverer(rabbitTemplate(), "dlExchange", "dlRoutingKey"))
                .build();
    }

But with these configurations retry is not working for both RetryException and DoNotRetryException, where I want RetryException to be retried finite number of time and DoNotRetryException to send to DLQ
Please help with the issue, I'm attaching repo link if in case of need.
https://github.com/aviralnimbekar/RabbitMQ/tree/main/src

A: Your GlobalErrorHandler does its logic before the retry happens and you override there an exception with the AmqpRejectAndDontRequeueException. And looks like you do there a publish to DLX. Consider to move your GlobalErrorHandler logic to a more general ErrorHandler for the factory.setErrorHandler(); instead.
See more info in docs: https://docs.spring.io/spring-amqp/reference/html/#exception-handling
UPDATE
After removing errorHandler = "globalErrorHandler" from your @RabbitListener, I got this in logs:
2022-08-03 16:02:08.093  INFO 16896 --- [nio-8080-exec-4] c.t.r.producer.RabbitMQProducer          : Message sent -> retry
2022-08-03 16:02:08.095  INFO 16896 --- [ntContainer#0-1] c.t.r.consumer.RabbitMQConsumer          : Retrying message...
2022-08-03 16:02:10.096  INFO 16896 --- [ntContainer#0-1] c.t.r.consumer.RabbitMQConsumer          : Retrying message...
2022-08-03 16:02:13.099  INFO 16896 --- [ntContainer#0-1] c.t.r.consumer.RabbitMQConsumer          : Retrying message...
2022-08-03 16:02:13.100  WARN 16896 --- [ntContainer#0-1] o.s.a.r.retry.RepublishMessageRecoverer  : Republishing failed message to exchange 'dlExchange' with routing key dlRoutingKey
2022-08-03 16:02:17.736  INFO 16896 --- [nio-8080-exec-5] c.t.r.producer.RabbitMQProducer          : Message sent -> 1231231
2022-08-03 16:02:17.738  INFO 16896 --- [ntContainer#0-1] c.t.r.consumer.RabbitMQConsumer          : sending into dlq...
2022-08-03 16:02:17.739  WARN 16896 --- [ntContainer#0-1] o.s.a.r.retry.RepublishMessageRecoverer  : Republishing failed message to exchange 'dlExchange' with routing key dlRoutingKey

Which definitely reflects your original requirements.


text:
Q: SQL - 'Where exists' clause without equality check Can someone explain what this syntax is doing:
where exists(select * from table(source.sources))

I dont understand how the comparison takes place. The syntax i am used to is
Select x
from y
where exists (select 1 from z where z.id = y.id)

In the first exists statement, where does the y.id = x.id comparison take place? Can i see an example of how the first syntax can be used?
Thanks

A: It looks like sources is a nested table in the source table. Here's an example:
create type sources_type as table of number
/

create table source (id number, sources sources_type)
nested table sources store as sources_tab;

insert into source (id, sources) values (1, null);
insert into source (id, sources) values (2, sources_type());
insert into source (id, sources) values (3, sources_type(1, 2, 3));

The three rows are the three possible states of sources; null, an empty table (which is not the same thing), and a populated table. If you want to select rows where the table is not empty, you can't check if it's null as that is only half the story.
select * from source
where sources is null;

        ID SOURCES
---------- ----------------------------------------
         1

select * from source
where sources is not null;

        ID SOURCES
---------- ----------------------------------------
         2 STACKOVERFLOW.SOURCES_TYPE()
         3 STACKOVERFLOW.SOURCES_TYPE(1,2,3)

You might not want the row with id=2 included. So you can look at the nested table contents instead:
select * from source
where not exists (select * from table(sources));

        ID SOURCES
---------- ----------------------------------------
         1
         2 STACKOVERFLOW.SOURCES_TYPE()

select * from source
where exists (select * from table(sources));

        ID SOURCES
---------- ----------------------------------------
         3 STACKOVERFLOW.SOURCES_TYPE(1,2,3)

So that final query is ignoring empty nested tables, as well as nulls.
In your second example you're doing a correlated subquery (or at least I assume you would be if the pseudocode wan't a bit mangled), looking for matching data in a table which is not part of the main query, and which does (usually) need the equality test; in the first example you're checking for the existence of data within the same table, so there is nothing to compare against.
You can also check for specific values in the nested table as well - I'm not sure if that clarifies or confuses the issue:
select * from source
where exists (select * from table(sources) where column_value = 2);


text:
Q: SQL - Adding each value to every other value in a table I have a sample table
table
2
4
6

I want to add each value to every other value in this manner:
table
(2+2)
(2+4)
(2+6)
(4+2)
(4+4)
(4+6)
(6+2)
(6+4)
(6+6)

The end result should look like:
table
4
6
8
6
8
10
8
10
12

But I have no idea on how to calculate all the values in this manner.

A: Do a self CROSS JOIN to get a cross product:
select t1.c + t2.c
from tablename t1 cross join tablename t2

Add ORDER BY if you need to guarantee that specific order:
ORDER BY t1.c, t2.c


text:
Q: Unauthorized curl for parse.com on mac I am working on a java project that communicates to a parse database that is online.
But the problem is following curl command:
curl -X GET \
-H "X-Parse-Application-Id: ApplicationID" \
-H "X-Parse-Master-Key: MasterKey" \
http://0.0.0.0:1337/parse/classes/testClass

When i execute this command from my windows pc i get all the rows from my test class. But when i execute it from my macbook i get:
{"error":"unauthorized"}

I am using the same code on my windows and mac and i am connecting to the same parse server.
This is also the exact same curl command I get when i go to my parse dashboard and click on Export to Curl in the API Console. When i execute it from my dashboard it also works.
When i try to execute the curl command through my terminal I am able to get the row's.
But i use the same curl in my code:
String curl = "curl -X GET \\\n" +
                "-H \"X-Parse-Application-Id: ApplicationID\" \\\n" +
                "-H \"X-Parse-Master-Key: MasterKey\" \\\n" +
                "http://0.0.0.0:1337/parse/classes/testClass";

        Process curlProc;
        String outputString = null;
        try {
            curlProc = Runtime.getRuntime().exec(curl);

            DataInputStream curlIn = new DataInputStream(
                    curlProc.getInputStream());

            String retrievedJson = "";

            while ((outputString = curlIn.readLine()) != null) {
                retrievedJson = outputString;
                System.out.print("RETRIEVED JSON: "+outputString+" \n");
            }


text:
Q: Postgres: update specific json object in array having some troubles with POSTGRES queries.
I have a column jsonb called venue_menu which has an array of objects that looks like this:
[
    { "menu_id":"0", "menu_name":"name 1"},
    { "menu_id":"1", "menu_name":"name 2"},
    { "menu_id":"2", "menu_name":"name 3"}
]

I want to make an update, for instance at the object where menu_id is 2 for a particular row which is selected by the column client_id (the WHERE clause). I have the following query so far
UPDATE client SET venue_menu = jsonb_set(venue_menu, '{}', { "menu_id":"2", "menu_name":"name updated"}) WHERE client_id = "1";

I can't seem to figure out where to do the query that specifies the key name of the object I want to update, any ideas?
Thank you.

A: Use jsonb_set
update "t" set "col"= jsonb_set("cols":: JSONB,('{'|| elem_index || ',"' ||'menu_name"}')::text[],'"name updated"'::jsonb,false)
from (select pos- 1 as elem_index,"col" as "cols","client_id" as "colId"
from  "t",jsonb_array_elements("t"."col" :: JSONB) with ordinality arr(elem, pos) where elem->>'menu_id' = '2') as "tble"
where  client_id =1

DEMO

A: You can use:

*

*jsonb_to_recordset to split the array into rows

*jsonb_build_object to build each element using the splited rows

*jsonb_agg to join each element into a new array

Here is the example:
select jsonb_agg(jsonb_build_object(
    'menu_id', menu_id,
    'menu_name', case when menu_id='2' then 'name changed' else menu_name end
  ))
  from jsonb_to_recordset('[
    { "menu_id":"0", "menu_name":"name 1"},
    { "menu_id":"1", "menu_name":"name 2"},
    { "menu_id":"2", "menu_name":"name 3"}
]') as menu_t(menu_id text, menu_name text);

You can see a running example at: https://dbfiddle.uk/?rdbms=postgres_10&fiddle=147c0de2abd5d0df786ed636793f1cc8


text:
Q: xml parsing in php - getting specific values New to parsing XML and XML in general... I am working off an example, but there are a few things I cannot figure out :
I am currently using something such as this for values :
$order->reference = $doc->getElementsByTagName("reference")->item(0)->nodeValue;

which I realize is getting the value of the 1st occurrence of x and it works fine.
Now, since customer and purchaser have the same values within them how can I target one or the other?  There will only be a max of one instance for each.
Also, I expect multiple <orderItem> within <orderItems>... how can I iterate through these... preferably creating something like an array as I will have no idea how many there will be.
example xml :
<order>
  <reference/>
  <status>open | request | requested | acceptance | accepted | fulfillment | fulfilled | completion | completed | canceled | failed</status>
  <statusChanged>2010-08-15T00:00:00.000Z</statusChanged>
  <test>true | false</test>
  <due>2010-08-15T00:00:00.000Z</due>
  <returnStatus>none | partial | full</returnStatus>
  <currency/>
  <referrer/>
  <originIp/>
  <total>0.0</total>
  <tax>0.0</tax>
  <shipping>0.0</shipping>
  <sourceName/>
  <sourceKey/>
  <sourceCampaign/>
  <customer>
    <firstName/>
    <lastName/>
    <company/>
    <email/>
    <phoneNumber/>
  </customer>
  <purchaser>
    <firstName/>
    <lastName/>
    <company/>
    <email/>
    <phoneNumber/>
  </purchaser>
  <address>
    <addressLine1/>
    <addressLine2/>
    <city/>
    <region/>
    <regionCustom/>
    <postalCode/>
    <country/>
  </address>
  <orderItems>
    <orderItem>
      <productDisplay/>
      <productName/>
      <quantity>0</quantity>
      <subscriptionReference/>
    </orderItem>
  </orderItems>
  <payments>
    <payment>
      <status>open | request | requested | acceptance | accepted | fulfillment | fulfilled | completion | completed | canceled | failed</status>
      <statusChanged>2010-08-15T00:00:00.000Z</statusChanged>
      <methodType>paypal | creditcard | test | bank | check | purchase-order | free</methodType>
      <declinedReason>internal-error | unsupported-country | expired-card | declined | risk | processor-risk | connection | unknown | cc-address-verification | cc-cvv | voice-auth</declinedReason>
      <currency/>
      <total>0.0</total>
    </payment>
  </payments>
</order>

EDIT :
Getting no errors yet no values for customer / purchaser.
private function parseFsprgOrder($doc) {
    //show values coming in
    echo '<pre>',print_r($doc, 1),'</pre>';

    $order = new FsprgOrder();

    $order->reference = $doc->getElementsByTagName("reference")->item(0)->nodeValue;
    $order->status = $doc->getElementsByTagName("status")->item(0)->nodeValue;
    $order->statusChanged = strtotime($doc->getElementsByTagName("statusChanged")->item(0)->nodeValue);
    $order->test = $doc->getElementsByTagName("test")->item(0)->nodeValue;
    $order->due = strtotime($doc->getElementsByTagName("due")->item(0)->nodeValue);
    $order->returnStatus = $doc->getElementsByTagName("returnStatus")->item(0)->nodeValue;
    $order->currency = $doc->getElementsByTagName("currency")->item(0)->nodeValue;
    $order->referrer = $doc->getElementsByTagName("referrer")->item(0)->nodeValue;
    $order->originIp = $doc->getElementsByTagName("originIp")->item(0)->nodeValue;
    $order->total = $doc->getElementsByTagName("total")->item(0)->nodeValue;
    $order->tax = $doc->getElementsByTagName("tax")->item(0)->nodeValue;
    $order->shipping = $doc->getElementsByTagName("shipping")->item(0)->nodeValue;
    $order->sourceName = $doc->getElementsByTagName("sourceName")->item(0)->nodeValue;
    $order->sourceKey = $doc->getElementsByTagName("sourceKey")->item(0)->nodeValue;
    $order->sourceCampaign = $doc->getElementsByTagName("sourceCampaign")->item(0)->nodeValue;

    //customer info
    $customerNodes = $doc->getElementsByTagName("customer")->item(0);

    if($customerNodes->length > 0)
    {
        $customer = new FsprgCustomer();

        $customer->firstName = $customerNodes->getElementsByTagName("firstName")->item(0)->nodeValue;
        $customer->lastName = $customerNodes->getElementsByTagName("lastName")->item(0)->nodeValue;
        $customer->company = $customerNodes->getElementsByTagName("company")->item(0)->nodeValue;
        $customer->email = $customerNodes->getElementsByTagName("email")->item(0)->nodeValue;
        $customer->phoneNumber = $customerNodes->getElementsByTagName("phoneNumber")->item(0)->nodeValue;

        $order->customer = $customer;
    }

    //purchaser info
    $purchaserNodes = $doc->getElementsByTagName("purchaser")->item(0);

    if($purchaserNodes->length > 0)
    {
        $purchaser = new FsprgPurchaser();

        $purchaser->firstName = $purchaserNodes->getElementsByTagName("firstName")->item(0)->nodeValue;
        $purchaser->lastName = $purchaserNodes->getElementsByTagName("lastName")->item(0)->nodeValue;
        $purchaser->company = $purchaserNodes->getElementsByTagName("company")->item(0)->nodeValue;
        $purchaser->email = $purchaserNodes->getElementsByTagName("email")->item(0)->nodeValue;
        $purchaser->phoneNumber = $purchaserNodes->getElementsByTagName("phoneNumber")->item(0)->nodeValue;

        $order->purchaser = $purchaser;
    }

    return $order;
}

class FsprgCustomer {
    public $firstName;
    public $lastName;
    public $company;
    public $email;
    public $phoneNumber;
}

class FsprgPurchaser {
    public $firstName;
    public $lastName;
    public $company;
    public $email;
    public $phoneNumber;
}

class FsprgOrder {
    public $reference;
    public $status;
    public $statusChanged;
    public $test;
    public $due;
    public $returnStatus;
    public $currency;
    public $referrer;
    public $originIp;
    public $total;
    public $tax;
    public $shipping;
    public $sourceName;
    public $sourceKey;
    public $sourceCampaign;
}

A: $customerNodes=order->getElemensByTagName('customer');
if($customerNodes->length>0)
    $customer=$customerNodes->item(0);
$purchaseNodes=order->getElemensByTagName('purchase');
if($purchaseNodes->length>0)
    $purchase=$purchaseNodes->item(0);
$orderItemNodes=order->getElemensByTagName('orderItem');
if($orderItemNodes->length>0)
    foreach($orderItemNodes as $orderItemNode){
        //process $orderItemNode
    }

A: Check DOMXPath::evaluate(). This allows you to fetch values from a DOM using XPath expressions.
Fetching a list of nodes:
$xpath - new DOMXPath($domDocument);
$nodeList = $xpath->evaluate('/order');

Or a scalar value:
$xpath - new DOMXPath($domDocument);
$string = $xpath->evaluate('string(/order/customer/firstName)');

A: //customer info
$customerNodes = $doc->getElementsByTagName("customer");

if($customerNodes->length > 0)
{
    $customer = new FsprgCustomer();

    $customer->firstName = $customerNodes->item(0)->getElementsByTagName("firstName")->item(0)->nodeValue;
    $customer->lastName = $customerNodes->item(0)->getElementsByTagName("lastName")->item(0)->nodeValue;
    $customer->company = $customerNodes->item(0)->getElementsByTagName("company")->item(0)->nodeValue;
    $customer->email = $customerNodes->item(0)->getElementsByTagName("email")->item(0)->nodeValue;
    $customer->phoneNumber = $customerNodes->item(0)->getElementsByTagName("phoneNumber")->item(0)->nodeValue;

    $order->customer = $customer;
}


text:
Q: Rails API: Cannot whitelist JSON field attribute I'm building a rails API with a model containing an attribute data of JSON type. (PSQL)
But when I try to post something like this
{ model: { name: 'Hello', data: { a: 1, b: 2 } } }

Rails thinks a and b are the attributes of a nested data association... It considers then they are unpermitted params.
The thing is, { a: 1, b: 2 } is the value of my field data.
How to provide JSON value to an attribute ?
-
Edit:
The error displayed is:
Unpermitted parameters: name, provider, confidence, location_type, formatted_address, place_id, types, locality, ...

The value of the data attribute is { name: 'Name', provider: 'Provider', ... }
Like I said Rails thinks they are the attributes of a nested data association.
-
Log:
Pastebin

A: if the keys are unknown in advance this could be a workaround:
def model_params
   data_keys = params[:model].try(:fetch, :data, {}).keys
   params.require(:model).permit(data: data_keys)
end

Credit goes to aliibrahim, read the discussion https://github.com/rails/rails/issues/9454 (P.S seems like strong parameters will support this use case in Rails 5.1)

A: When you post something, you have to make sure that your json have the same parameters that your controller.
Example rails api:
def example
 @model = Model.new(params)
 @model.save
 render(json: model.to_json, status: :ok)
end

def params
 params.permit(:name, :provider, {:data => [:a, :b]})
end

Example front-end json for post:
var body = {
 name: 'myName',
 provider: 'provider',
 data: {
  a: 'something',
  b: 'otherthing',
 }
};

For some reason rails doesnt recognize a nested json, so you need to write into params.permit that data will be a json with that syntax, if where a array, the [] should be empty.


text:
Q: How do I add an URL field to the iOS Settings app (Like in Nike+) There are several questions about this on StackOverflow, but they all claim this isn't possible, that you can only do this by showing a custom Settings page in your app. However, the Nike+ app does exactly what I want, as seen here:

So, again, does anyone know how to achieve this?

A: That's not possible with the current Settings.bundle for 3rd party apps. Checkout Apple docs Settings Application Schema Reference for all available element types.


text:
Q: Java lists filter and find first/find last I have a java list of objects. The object attributes are:
public class CheckPoint {
    private String message;
    private String tag;
}

Now, I want to find the filter the list based on tag and get first/last element.
For eg: Possible tag values: A, B, C. For tags with value A - I want the last element, and B - I want first element, C - first element
Current Solution:
CheckPoint inTransitCheckPoint = checkPointsList.stream().filter(c -> c.getTag().equals("A")).reduce((first, second) -> second).orElse(null);

CheckPoint useCheckPoint = checkPointsList.stream().filter(c -> c.getTag().equals("B")).findFirst.orElse(null);

CheckPoint typeCheckPoint = checkPointsList.stream().filter(c -> c.getTag().equals("C")).findFirst.orElse(null);

However, I do understand this is an inefficient solution since we are looping thrice. Can someone help me solve it in a more performant way?
Any help will be appreciated, thanks :)

A: You could first collect to a Map for example:
Map<String, List<CheckPoint>> map =
       checkPointsList.stream()
                      .collect(Collectors.groupingBy(CheckPoint::getTag));

Optional.ofNullable(map.get("A"))
        .orElse(Collection.emptyList())
        .reduce((left, right) -> right)
        .orElse(null);
// same for "B" and "C"

A: I suggest grouping the checkPointList by tag into a Map<String, LinkedList<CheckPoint>>:
Map<String, LinkedList<CheckPoint>> map = new HashMap<>();
map.put("A", new LinkedList<>());
map.put("B", new LinkedList<>());
map.put("C", new LinkedList<>());

for(CheckPoint c : checkPointList) {
    map.computeIfAbsent(c.getTag(), ignored -> new LinkedList<>()).add(c);
}

The linked list is a handy helper because it allows you to directly get the first or last element (and if absent returns null):
CheckPoint A = map.get("A").pollLast();
CheckPoint B = map.get("B").pollFirst();
CheckPoint C = map.get("C").pollFirst();

Or you can just use this even easier for-loop:
CheckPoint a = null, b = null, c = null;
for (CheckPoint checkPoint : checkPointList) {
    String tag = checkPoint.getTag();
    if ("A".equals(tag) && a == null) {
        a = checkPoint;
    } else if("B".equals(tag)){
        b = checkPoint;
    } else if("C".equals(tag)){
        c = checkPoint;
    }
}

The variables for "B" and "C" are always overwritten with the last value, whereas for a only the first "A" checkpoint will be chosen.


text:
Q: React - trying to save fetched data in a variable but the variable returns empty I fetched json data with async await and i wanted to save the fetched data in a variable in order to be able to use it with a map in my component,
the data comes in properly inside the function - i checked with an alert , and also in the variable inside the function it does display all the data , but somehow the variable outside the function returns empty .
here is some code:
both alerts in the following code return the right data.
export let fetchPosts = [];
export async function FetchPosts() {
    await axios.get('https://jsonplaceholder.typicode.com/posts').then(
        res => {
            alert(JSON.stringify(res.data))
            fetchPosts = JSON.stringify(res.data);
            alert(fetchPosts)
        }
    ).catch(err => {
        alert('err');
    })
}

import { fetchPosts } from '../services/post';
import { FetchPosts } from '../services/post';

export default function Posts() {
    function clickme() {
        FetchPosts()
    }
    return (<>
        <button onClick={clickme}>Click me</button>
        {fetchPosts.map((post, index) => (

{post.title}

{post.body}

        ))}
    </>)
}

A: State is the issue
React doesn't automatically reload on your singleton fetchPosts.
Instead, try...
export function FetchPosts() {
    return axios.get('https://jsonplaceholder.typicode.com/posts');
}

then
import { useState } from 'react';
import { FetchPosts } from '../services/post';

export default function Posts() {
    const [posts, setPosts] = useState([]);
    function clickme() {
        FetchPosts().then(res => {
          setPosts(res.data);
        });
    }
    return (<>
        <button onClick={clickme}>Click me</button>
        {posts.map((post, index) => (

{post.title}

{post.body}

        ))}
    </>)
}

https://codesandbox.io/s/jolly-almeida-q4331?fontsize=14&hidenavigation=1&theme=dark
If you want global state, that's another topic you should dive into entirely but you can do it with a singleton, you just need to incorporate it with hooks and an event emitter.  I have a bit of a hacked version of this here https://codesandbox.io/s/react-typescript-playground-forked-h8rpu but you should probably stick to redux or mobx or AppContext which is more of a popular pattern.


text:
Q: Handle component's mount and unmount order caused by react-router animations I used CSS transitions from react-transition-group in order to make transitions between different routes animated.
Below is how the code roughly looks like:
<BrowserRouter>
  <TransitionGroup>
    <CSSTransition
      timeout={350}
      classNames="page"
      key={location.key} //location is object returned by useLocation() hook
      unmountOnExit
    >
      <Switch location={location}>
        <Route path="/" component={HomeComponent} />
        <Route path="/login" component={LoginComponent} />
      </Switch>
    </CSSTransition>
  </TransitionGroup>
</BrowserRouter>

Animations work fine, but what I found is that the order in which components are being mounted and unmounted is not the way I want it to be. The thing is that If I use the same code without animations, when I go from route "/" to route "/login", firstly HomeComponent gets unmounted and only then react mounts LoginComponent. However, using animations, when the same change of route happens, firstly LoginComponent is being mounted and afterward HomeComponent is being unmounted. In my opinion, this behaviour is not obviously expected.
So the question is: is it possible to remain animated routes in my app and change this odd order in which components are being mounted and unmounted? If no, how can I know, being inside my LoginComponent, that HomeComponent is now unmounted without manipulating any global state?


text:
Q: What is the most stable modal dialog implementation across browsers to use from javascript for a web app? I'm using a lot of JQuery in a web application that I am building for a client and I want to find an javascript implementation of a modal dialog that is reasonably stable across the following browser set.
IE 7+
FF 2+
Chrome and Safari
I've tried a couple of jQuery plugins but there always seems to be artifacts in one of these browsers.
--- Edit
jqModal seems to be more stable but I have an issue in IE7 where the dialog immediately disappears after popping up. I suspect a js event isn't being canceled or something. I'll have a bit more of a play.

A: I used jqModal few times and I'm very satisfied. It is pretty configurable yet very light weight.

A: Have you tried YUI? I'm not sure what the support is for Chrome but I've had good luck with it for IE and Firefox and allegedly it works with Safari.

A: We currently use BlockUI. It's awesome, in word. Can be styled via css (of course), blocks any element and seems stable, certainly in block IE and Firefox....
If you need a hand with it, post and I'll lend a hand...
http://www.malsup.com/jquery/block/

A: I went through a similar exercise, tried most of the plugins I could find. I used YUI for quite a while with good results; the only issue I ran into was resizing centered modals, which is quite an obscure use case.
I ended up with http://dev.iceburg.net/jquery/jqModal/ , I'm pretty happy with it.


text:
Q: Some questions about OOP I have an object called clock.
I have a method of said object called time.
If I used this.propertyName inside my time method, this will give the property to my clock object, right? But what if there is an if/else statement (within the time method itself), for example, which needs to run before
the value of the property can be assigned?
if(t.getHours() >= 12){
        this.ap = "AM";
    }else{
        this.ap = "PM";
    }

So, if I used a simple value like this.ap = "hi", this works fine. It gives the property to my object. If I have a statement like shown above, the property is undefined. What is the best way around this?
Also, another quick question since I'm only just starting to use my own objects. If I have an object with 3 separate methods, and I want to use a value in ALL methods that's been declared within 1 method, assigning it as a property of my object allows me to do this. Am I right?
So If I used var property = "" in one method, the only way to access this in my other methods is to return it. But setting the property to the object solves this? I realize I can experiment around with this but I'd rather just know the proper way.
Edit: Here's an example. Obviously I'm misunderstanding something. I can't seem to define properties from within a method.
var clock = {};

clock.test1 = "test 1.";

clock.time = function(){

    clock.test = "test 2.";

    if(t.getHours() >= 12){
        clock.ap = "PM";
    }else{
        clock.ap = "AM";
    }

}

alert(clock.test1);  //success
alert(clock.test); //returns undefined
    alert(clock.ap);  //returns undefined

A: The usual way to avoid problems with binding this is to do something like this:
var MyObject = function() {
    var self = this;
    self.someProperty = "foo";

    self.someMethod() {
        self.someProperty = "bar";
    }
}

var anInstance = new MyObject();
console.log(anInstance.someProperty);      // foo
anInstance.someMethod();
console.log(anInstance.someProperty);      // bar

This avoids problems with this being something other than what you expected it to be, which can happen depending on how you call methods (using a method as a handler for some DOM event for example).
This example works by exploiting closure, which is a very important concept in Javascript that you should read up on (Google it).


text:
Q: Swap key and value in a map in fsharp How to create a new map that is similar to the original one, but with swapped keys and values in Fsharp?
For example, I have this
let map1 =
[("A", "1"); ("B", "2"); ("C", "3");]
|> Map.ofList

and want to get this:
let map2 =
[("1", "A"); ("2", "B"); ("3", "C");]
|> Map.ofList

Thank you for your help!

A: Perhaps you will approach this decision:
let map1 = Map.ofList [("A", "1"); ("B", "2"); ("C", "3")]

map1 |> printfn "%A"

let rev map: Map<string,string> =
      Map.fold (fun m key value -> m.Add(value,key)) Map.empty map

rev map1 |> printfn "%A"

Print:
map [("A", "1"); ("B", "2"); ("C", "3")]
map [("1", "A"); ("2", "B"); ("3", "C")]

Link: http://ideone.com/cfN2yH

A: You could convert it to a list and back, calling a function to swap in the middle.
let swap (x, y) = y, x
let swapAll tuples = List.map swap tuples
let invert map = map |> Map.toList |> swapAll |> Map.ofList

This method somewhat highlights what's nice about functional programming--you can build up complex behavior just by combining small building blocks.


text:
Q: XML After Effect File (*.aepx) -> Understand binary number format to edit xml file I'm trying to understand number format for aepx file for After Effect CS6 and CC
Coordinates are coded in cdat hexadecimal data. Coordinates is two number. I have made a list of number with the encoded hexadecimal value to help to understand format :
-100;-100   -> <cdat bdata="bfaaaaaaaaaaaaabbfb7b425ed097b420000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"/>

100;100     -> <cdat bdata="3faaaaaaaaaaaaab3fb7b425ed097b420000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"/>

100;200     -> <cdat bdata="3faaaaaaaaaaaaab3fc7b425ed097b420000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"/>

200;100     -> <cdat bdata="3fbaaaaaaaaaaaab3fb7b425ed097b420000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"/>

200;200     -> <cdat bdata="3fbaaaaaaaaaaaab3fc7b425ed097b420000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"/>

300;300     -> <cdat bdata="3fc40000000000003fd1c71c71c71c720000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"/>

800;200     -> <cdat bdata="3fdaaaaaaaaaaaab3fc7b425ed097b420000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"/>

800;400     -> <cdat bdata="3fdaaaaaaaaaaaab3fd7b425ed097b420000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"/>

800,5;400   -> <cdat bdata="3fdaaeeeeeeeeeef3fd7b425ed097b420000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"/>

800,5;400,5 -> <cdat bdata="3fdaaeeeeeeeeeef3fd7bbbbbbbbbbbc0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"/>

0;400,5     -> <cdat bdata="00000000000000003fd7bbbbbbbbbbbc0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"/>

800,5;0     -> <cdat bdata="3fdaaeeeeeeeeeef00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"/>

400,5;800,5 -> <cdat bdata="3fcab333333333333fe7b7f0d4629b7f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"/>

Someone has an idea of this number format ?

A: Not sure if it's still relevant, however I figured out that it's a double representation (big endian)
-100;-100   -> -0.0520833333333333 -0.0925925925925926
100;100     ->  0.0520833333333333  0.0925925925925926
200;100     ->  0.104166666666667   0.0925925925925926
200;200     ->  0.104166666666667   0.185185185185185
800;200     ->  0.416666666666667   0.185185185185185
800;400     ->  0.416666666666667   0.37037037037037
800,5;400   ->  0.416927083333333   0.37037037037037
0;400,5     ->  0.000000000000000   0.370833333333333
400,5;800,5 ->  0.20859375          0.741203703703704

However, those values are not exact pixels, as you might expect, they represent a coefficient. Each of them should be multiplied by your composition width and height respectively.
As far as i can tell your had 1920x1080 resolution:
0.416927083333333 * 1920 = 800.4999999999993

P.S. I'm working on aepx format research, in case you would like to contribute: https://github.com/inlife/aftereffects-project-research


text:
Q: is it possible? pdf - exacttarget Came across this link-How to Use Custom Subscriber Attributes in a Triggered Email
Based on above i wonder is it possible to do ??:

*

*Landing page to display list of subscibers in the list.

*A button on LP to generate a PDF, and option to either download it, view it, or email it to someone else.

A: You will have to build the PDF document itself (browser pdf viewing plugin will allow download). This is most simply done with a 3rd party library. Since it's on a landing page you will not have access to server-side processing other than SSJS so JS is your best bet.
Try: http://parall.ax/products/jspdf
Check the HTML Renderer functionality -- if the list is styled in any way this should make things easy (will just accept the list's container and parse that)
In terms of emailing it to someone else... This is much trickier. Basically you would need to first save the file to the server and then create a link with a mailto: address as the href which contains an &attachment="\myhost\my_folder\my_file.pdf" at the end. This is probably possible but not at all simple.


text:
Q: Use toDataUrl 4 times or more, window.print causes a freezing tab in Chrome I want to print charts from chartJs. For this purpose, I use the function document.getElementById('myChart').toDataURL();. The element of the id is my canvas, that is created by chartJs. Then, I build the content that I want to print. Later on, I print them using the function window.open().print().
At the beginning, it was working fine using one or two charts. But as soon as I add to the content a 4th chart, my Tab is freezing in Chrome. So I cant act in the form anymore and I have to close the Tab.
I created a jsFiddle to demonstrate it. To see the problem, you have to click on the "please print me" button.
Here is a running version, where I just print 3 Charts. You can print it as often as you want and you can use the select next to it: https://jsfiddle.net/u49e7qmL/2/
Here is a not running version, where I just print 4 Charts. As soon as you click on print, the tab makes a problem. You cannot print a 2nd time. Additionally you cannot use the select next to it. In my application, the whole tab freezes: https://jsfiddle.net/u49e7qmL/3/
What do I have to do that I can keep using the tab like when I print with just 3 elements?


text:
Q: AngularJS $http undefined I get TypeError: Cannot call method 'get' of undefined when running this module:
angular.module('EventList', [])

.config([ '$routeProvider', function config($routeProvider){
    $routeProvider.when(Urls.EVENT_LIST_PAGE, {
        templateUrl: 'app/EventList/event-list.html',
        controller: 'EventListCtrl'
      });
 }])

.controller('EventListCtrl', ['$scope', '$http', function EventListController($scope, $location, $http) {
  $scope.events = [];
  $http.get('http://localhost:8000/event').
    success(function (data, status) {
      $scope.events = data;
      for (var i = 0; i < $scope.events.length; i++) {
        $scope.events[i].event_url = ('#' + Urls.EVENT_PAGE + '/' + $scope.events[i]._id);
      }
    }).
    error(function (data, status) {
      $scope.data = data || "Request failed";
    }
  );

}]);

What am I doing wrong here and how can I fix it?

A: When using the bracket notation the dependency list before the function needs to match the services being injected into the function.
You have an extra $location service in your EventsListController function so change this:
.controller('EventListCtrl', ['$scope', '$http', function EventListController($scope, $location, $http) {
// controller code goes here
}]);

to this:
.controller('EventListCtrl', ['$scope', '$http', function EventListController($scope, $http) {
// controller code goes here
}]);

The key change being: function EventListController($scope, $http) instead of function EventListController($scope, $location, $http)


text:
Q: Update accounts.name when accounts.id is modified I have a database where in the accounts table the "username" is the "id".
Now I need to add to the table the field "name" which will work as the "id", so if I create a new account, I need the "id" field to also copy it's value at "name" field.
There's any way to automate that without modifying the account creation process? So "name" will always copy the "id" value.
I'm running PhpMyAdmin in Windows (MySQL).
I need this because I have to work with 2 apps in the same database and I don't have the code neither can get any updates. One of them is using "id" field to verify users "usernames" and the other one is using the "name" field to verify users.
I know this is not a good thing, I didn't develop it. But the only thing I can do is modify the database.

A: Use a trigger on insert
CREATE TRIGGER insert_name AFTER INSERT ON accounts
   FOR EACH ROW SET name = NEW.id
Of course if the id column can be updated you will also need an update trigger

A: You can do it before storing it in the Database.
Free advice:
You have to change the design of the Database because it will produce anomalies.


text:
Q: Add all folder in subfolder of assets in pubspec.yaml at once? I have some folder in assets/images such as :
flutter:
  assets:
    - assets/images/
    - assets/images/home/
    - assets/images/shop/
    - assets/images/profile/
    - assets/images/etc/

is there any way to add all subfolder at once? seems like assets/images/* or something?
many thanks in advance!

A: Only files located directly in the directory are included unless there are files with the same name inside a subdirectory (see Asset Variants). To add files located in subdirectories, create an entry per directory.
see more


text:
Q: How do I set a nullable realm object I added migration to my project. After a lot of work I got it to work standalone. When trying to update I get the error
@PrimaryKey field 'id' does not support null values in the existing Realm file. Migrate using RealmObjectSchema.setNullable(), or mark the field as @Required

This is not for a value feature in the objects I am adding. Can anyone elaborate on this or link to documentation on how to do this? I can't find anything
This is the variable
   @PrimaryKey
private String id;

EDIT: May have solved it by doing
schema.get("Log").setNullable("id", true);

A: Well if you've updated an older code-base, then you're running into breaking change from 0.89.0 where @PrimaryKey annotated fields became nullable (and null can be used as a primary key for 1 element).
So if you don't want your @PrimaryKey annotated field to be nullable, you should just add @Required annotation too.
Otherwise, you should add to your migration:
RealmObjectSchema yourClassSchema = schema.get("YourClass");
yourClassSchema.setNullable("id", true);


text:
Q: How many legal positions are there on a Rubik's cube with two pieces glued together? Legal here means reachable from the solved state without separating the two glued pieces. Answer depends on the type of pieces glued together (egde+corner or edge+center). Is it just all normally legal positions where the two pieces are adjacent?

A: It indeed turns out that bandaging just two pieces together does not inhibit the amount of mixing the other pieces can get, so the number of positions of this bandaged cube is indeed the simply the number of cube positions with those two pieces adjacent.
In fact, if you take three faces adjacent to a corner, and mix the cube using only moves of those three faces, then the moving pieces can be fully mixed. That is to say, you can bandage a whole 2x2x2 block, and the resulting puzzle has the same number of positions as a normal cube with that block solved. To put it another way, if you solve the whole cube by first solving a 2x2x2 block, then you won't need to temporarily break that block when solving the remainder. This does not happen if you choose three faces, two of which are opposite. With turns of three such faces you cannot flip any edge pieces.
To prove this kind of thing you can either explicitly work out a solving method (usually be placing the bandaged piece correctly first), or you can use a program such as GAP to model the group and calculate its size. To model the group you will have to consider the bandaged piece as being fixed, and all the other pieces including face centres as moving pieces. That group is generated by moves of any face layer and middle layer that does not affect the bandaged piece.
Things get very complicated when you have several groups of bandaged pieces. When they move around in different arrangements, some moves get blocked. The puzzle can no longer be modelled as a group generated by single moves of the layers. Even working out the number of positions an unstickered bandaged cube has becomes tricky, and generally boils down to trying all possibilities (e.g. by computer search).


text:
Q: Change Tracking cleanup Is there a way to know when cleanup of change tracking tables occurs? How to check the last occurrence of a cleanup process?
BACKGROUND:
I have Change Tracking on database with retention set to 1 minute:
ALTER DATABASE [test] SET CHANGE_TRACKING = ON (CHANGE_RETENTION = 1 MINUTES)

I do some updates in my test table and then wait a bit longer than the retention period (lets say 3 minutes). As the cleanup process is asynchronous, I do understand that there NO guarantee that Change Tracking tables will be cleaned up after 1 minute. It can happen at any time that is > 1 min.
I found this procedure to call the cleanup process manually:
EXEC sp_flush_commit_table_on_demand 100000

But it does not work as expected.. (Change Tracking rows are still in place after retention period)

A: I reproduced this using the code below, and essentially, yes, if you wait long enough, and auto cleanup is on, it will clean itself out. It appears to be bound the a minimum - that is, the change_retention setting is more of a suggestion than a command.
Admittedly, I haven't tested with real-world table activity, etc., but the links below contain more information about what the job does - it's more of a black box, really, than anything.
Links:
MS Change Tracking
Kendra Little on Change Tracking
Song Lyrics - Courtesy of Disney
Here's what I came up with.
use master;
go

drop database cttest;
go

create database cttest;
go

use cttest;
go

create table dbo.t
(id int identity(1,1) primary key--can't track without it
, c1 int
, c2 varchar(100));
go

-- pre ct
insert t values (123, 'Yo ho, yo ho')
insert t values (234, 'We pillage, we plunder, we rifle and loot.')
insert t values (345, 'Drink up me ''earties, yo ho.')
insert t values (456, 'We kidnap and ravage and don''t give a hoot.')
insert t values (567, 'Drink up me ''earties, yo ho.')
go

-- check the table
select * from t;
go

-- enable change tracking for this DB
alter database cttest set change_tracking = on (change_retention = 1 minutes)
go

alter table dbo.t enable change_tracking with (track_columns_updated=off);
go

-- this should be a tracked change
insert t values (678, 'Yo ho, yo ho, a pirate''s life for me.');
go

-- show the change tracking record
-- so i waited 10 minutes, and then...
select * from changetable(changes dbo.t, NULL) as ct;
go

-- is this table even tracked ?
SELECT object_name(object_id),* FROM sys.change_tracking_tables

-- make another change
update t set c2 = 'Yo ho, yo ho, a pirate''s life for me.' where c1 = 123;
go

-- show the change tracking record
select * from changetable(changes dbo.t, NULL) as ct;
go

-- make more changes
insert t values (789, 'We extort and pilfer, we filch and sack.')
insert t values (8910, 'Drink up me ''earties, yo ho.')
insert t values (91011, 'Maraud and embezzle and even highjack.')
insert t values (101112, 'Drink up me ''earties, yo ho.')
go

-- show the change tracking record
select * from changetable(changes dbo.t, NULL) as ct;
go

-- make another change
update t set c2 = 'Yo ho, yo ho, a pirate''s life for me.' where c1 = 123;
go 15

-- show the tracked items
select * from changetable(changes dbo.t, NULL) as ct;
go

-- force a <ahem> flush
EXEC sp_flush_commit_table_on_demand 100000;
go

/*
Received message
(0 row(s) affected)
The Change Tracking manual cleanup procedure for database cttest has been executed
*/

-- show the tracked items
-- still there !
select * from changetable(changes dbo.t, NULL) as ct;
go

-- ok then, we'll turn it off !
alter database cttest set change_tracking (auto_cleanup=off);
go

-- force a <ahem> flush
EXEC sp_flush_commit_table_on_demand 100000;
go

-- show the tracked items
-- still there !
select * from changetable(changes dbo.t, NULL) as ct;
go

-- ok then, we'll turn it back on, and wait
alter database cttest set change_tracking (change_retention = 1 minutes, auto_cleanup = on)
go

A: sp_flush_commit_table_on_demand clears only the syscommittab and not the change tracking side tables.
Executing the sp_flush_commit_table_on_demand has nothing to do with clearing the change tracking side tables.  CHANGETABLE function relies on both syscommittab and change tracking side tables.
select * from changetable(changes dbo.t, NULL) as ct - This will return all changes to dbo.t table since the first version since we pass NULL as the last synced version.


text:
Q: C++: static instance of inner class in outer class I have written some piece of code as below.
Here there is an outer class and an inner class.
I want a functionality similar to inner static class of java.
So I declare the inner class object as static.
The output comes fine:
#include <iostream>

using namespace std;

class X {

    private:
    X() {}
    public:

        class Y {
            public:
                virtual void f() = 0;
        };
        class Z:public Y {
            public:
                Z(X& val) : x(val) {}
                void f() {
                    cout << "Programming";
                    x.i = 5;
                }
            private:
                X& x;
        };
        static Z getZ() {
            return z;
        }
    private:
        static Z z;
        int i;
};

X::Z  X::z = X::getZ();

int main()
{
    X::getZ().f();
    return 0;
}

I am not able to understand this statement though. How does it work?
X::Z  X::z = X::getZ();

Edit: How do I initialize an instance of inner class then?
Also I get a segmentation fault when I assign below which may be because of self assignment.
 x.i = 5;

A: Since z is a static member variable, it requires a definition. The line of code you are looking at is that definition.
X::Z  X::z = X::getZ();

X::Z (note the uppercase Z) is the type, X::z (note the lowercase z) is the variable, and it is initialized by the return value of the X::getZ() static member function.
It turns out X::getZ() is simply returning X::z. Although it appears redundant, it suppresses the execution of the default constructor for X::z, and uses the copy constructor instead.
Static objects are zero initialized before the static initializations are performed. If the object is correctly initialized by zero initialization, the copy constructor on self does not do any particular harm. However, in this case X::Z has a reference member variable x which is left zero initialized. Accessing x would lead to undefined behavior.

You added an additional question regarding the proper initialization of the static member z.
Since you are providing an accessor method for z in the form of X::getZ(), a better solution is to avoid the static member variable, and place a static instance inside the X::getZ() function itself. Since z will require an instance of X to be initialized properly, one should be provided.
class X {
//...
public:
    static Z & getZ() {
        static X x;
        static Z z(x);
        return z;
    }
private:
    int i;
};

The return type for X::getZ() is changed to be a reference to the static instance, so that the instance can be manipulated.

A:
I am not able to understand this statement though.

This is a definition of a static variable declared inside class X. Here is what each part of it means:

*

*X::Z says that the type of the static data member being defined is Z, which is defined inside class X.

*X::z means that we are defining a static member called z declared inside class X

*= X::getZ() means that z is to be initialized to the value returned from getZ() member function.

However, this is not a good code, because getZ uses the very z that it initializes, before the variable gets a chance to be initialized.

A: This is the definition of the static variable X::z. Some static data members require a namespace-scope definition if they are later used in a context that requires the data member to exist in physical memory.
The definition has the format of a normal variable declaration, except its name is qualified to denote that it is a static member:
X::Z is the type of the member, and X::z is a qualified-id designating its name. This statement initializes its value to the return value of the static member function X::getZ(), which is itself.
Note that this undefined behavior since X::getZ() returns z in its uninitialized state.


text:
Q: What's amiss in this Fourier convergence analysis? I worked out this solution to this basic PDE Fourier series convergence problem, but I suspect the result is "too easy to be correct," because all the answers point to no restriction on either $m$ and $b$:

Given this piecewise function:
  $$f(x) =
\begin{cases}
e^x, &-1 \leq x \leq 0,\\
mx + b, &0 \leq x \leq 1.
\end{cases}$$
  Without computing out any Fourier coefficients, find out the followings:
  (a) for waht values of $m$ and $b$, if there is any, will the full Fourier series of $f(x)$ converge pointwise on $-1 \leq x \leq 1$?
  (b) Same as the above, for converge uniformly?
  (c) For converge in the $L^2$ sense?

Here are my answers on each of them:

(a) My text says that if $f(x)$ is piecewise smooth on an interval, then its Fourier series converges pointwise on the interval. Piecewise smooth means both $f(x)$ and $f'(x)$ are piecewise continuous. Here, it is easy to see that $f(x)$ and $f'(x)$ are piecewise continuous for all real $m$'s and $b$'s. Thus there is no restriction on $m$ and $b$.
So far so good!

(b) My text also says uniform convergence demands more stringent conditions: $f(x)$ has to have a continuous periodic extension, besides that $f'(x)$ has to be piecewise continuous on the interval. Here, I wrote that $f(x) = e^x$ has a continuous even function in $e^{-x}$ and $f(x) = mx + b$ also has continuous shift function, thus there is no restriction again for both $m, b$ in part (b).
Now I am beginning to doubt myself: Did I miss anything here?

(c) Finally my text says that $f(x)$ converges in the $L^2$ sense if and only if $\int_{-l}^{l} | f(x) |^2 dx < \infty$. From here, we can see that both $\int_{-1}^{1} | e^x |^2 dx$ and $\int_{-1}^{1} | mx + b |^2 dx$ are finite. Thus again there is no restriction on both $m$ and $b$.
Now I am beginning to seriously second-guess myself: Is anything amiss here too?

Thank you for your time and help.

A: You are right about $L^2$ convergence. For pointwise convergence, you need $b=1$ otherwise is not continuos in $0\  (\diamond)$. For uniform convergence, you need to make sure that the function $f$ can be made periodically continuos; that is, you have to connect the function at its extremes. Since $f(1) = m + b = m + 1$, and $f(-1) = e^{-1}$,  you need $e^{-1} = m + 1 \implies m = e^{-1} - 1$
$\ \ \ \ \ (\diamond)$  In general, if your function is piecewise smooth, then the fourier series converges to $$\frac{f(x_0^+) + f(x_0^-)}2$$
$\ \ \ \ \ \ \ $So if you have a piecewise smooth function and you want pointwise convergence everywhere,$\ \ \ \ \ \ \ $ you need to make your function continuos

A: Observe that the function is not periodic. To make it periodic, I suggest change the value at the end point, i.e., define $f$ as

$f(x) = \left\{ \begin{array}{l}
{e^x}{\rm{ ,  }} - 1 \le x \le 0,\\
mx + b,{\rm{ }}0 \le x < 1\\
{e^{ - 1}},{\rm{  }}x = 1.
\end{array} \right .$
and extend by periodicity. Its period is of course 2.
Note that the function is plainly square integrable.
Therefore, its Fourier series converges to $f$ in the L2 norm.
Observe also that the function is of bounded variation. Therefore, its Fourier series converges everywhere.  It converges to  f(x) where f(x) is continuous, i.e., when x is not equal to $0$ or $-1$ or $1$. It converges to $(1+b)/2$  when $x = 0$; it converges to (e-1+m+b)/2 when $x$ = 1 or -1.
If $b = 1 $ and e-1 = $m+b$, then $f$ is a continuous function of bounded variation and so its Fourier series converges uniformly to $f$.
If $b$ is not equal to $1$ and e-1 is not equal to $m+b$, then its Fourier series converges uniformly in any closed subinterval not containing {0, -1, 1}  . To decide that it does not converge uniformly in the whole interval, one has to examine the local behaviour of $f$ at and near these three points.
If the Fourier series converges uniformly in $[-1, 1]$ to a function, then the function must be continuous in $[-1, 1]$. So in our case if $b$ is not equal to 1 or e-1 is not equal to $m+b$, $f$ is not continuous at $0$ or at $-1$ or at $1$ and so the Fourier series cannot converge uniformly in $[-1, 1]$ .
See THeorem 23 to Theorem 29 in my article
https://037598a680dc5e00a4d1feafd699642badaa7a8c.googledrive.com/host/0B4HffVs7117IbmZ2OTdKSVBZLVk/Fourier%20Series/Convergence%20of%20Fourier%20Series.pdf


text:
Q: Remove pointer object whose reference is maintained in three different lists I am not sure how to approach this problem:
'Player' class maintains a list of Bullet* objects:
class Player
{
protected:
    std::list< Bullet* > m_pBullet_list;
}

When the player fires a Bullet, it is added to this list. Also, inside the constructor of bullet, a reference of the same object is updated in CollisionMgr, where CollisionMgr also mantains a list of Bullet*.
Bullet::Bullet(GameGL*a_pGameGL, Player*a_pPlayer)
: GameObject( a_pGameGL )
{
    m_pPlayer = a_pPlayer;

    m_pGameGL->GetCollisionMgr()->AddBullet(this);
}

class CollisionMgr
{

void AddBullet(Bullet* a_pBullet);

protected:
std::list< Bullet*> m_BulletPList;
}

In CollisionMgr.Update(); based on some conditions, I populate class Cell which again contain a list of Bullet*. Finally, certain conditions qualify a Bullet to be deleted. Now, these conditions are tested upon while iterating through a Cell's list. So, if I have to delete the Bullet object, from all these places, how should I do it so that there are no more dangling references to it?
std::list< Bullet*>::iterator bullet_it;

    for( bullet_it = (a_pCell->m_BulletPList).begin(); bullet_it != (a_pCell->m_BulletPList).end(); bullet_it++) {

        bool l_Bullet_trash = false;
        Bullet* bullet1 = *bullet_it;

        // conditions would set this to true

        if ( l_Bullet_Trash )
            // TrashBullet( bullet1 );
            continue;
        }

Also, I was reading about list::remove, and it mentions that it calls the destructor of the object we are trying to delete. Given this info, if I delete from one list, the object does not exist, but the list would still contain a reference to it..How do I handle all these problems?

A: One option is to use reference counting with weak references (Boost supports this). You have one "authoritative" container that owns the strong reference, and hence deletes any Bullet removed from it. All other containers use weak references, and remove Bullets when they find that the weak reference has become invalid.
This does complicate things slightly in several places, but it is logically much cleaner and safer than other mechanisms.

A: Interesting observation or maybe this is just a part of the 'undefined behavior'. So, this is how I am trashing a bullet and its not giving me an error..as of now:
void CollisionMgr::TrashBullet(Bullet* a_pBullet, Cell* a_pCell)
{

    a_pBullet->Owner()->TrashBullet( a_pBullet );
    m_BulletPList.remove( a_pBullet );
    //a_pCell->m_BulletPList.remove( a_pBullet );

    delete a_pBullet;
}

So, Once I "remove" references to Bullet from lists, I then manually delete it. What confuses me is, from the description of 'list::remove' :

void remove ( const T& value );
  Remove elements with specific value.
  Removes from the list all the elements
  with a specific value. This calls the
  destructor of these objects and
  reduces the list size by the amount of
  elements removed.

Thus, when I call the remove on bullet from the list, the destructor for that bullet object should be called. But, that aint happening here...
So, is this just a part of the undefined behavior and my compiler's quirk or am I missing something trivial here ?

A: You are not storing bullets in these lists, but pointers to bullets, so no destructor will be called. The objects can be safely removed from all lists, but you will need to call delete yourself.


text:
Q: Get dimensions of an image after render finishes, in Angular I am trying to get the rendered size of an image in a component. Using the (load) event, I am getting the size of the image as it is displayed at that moment (pic1) and the "final" size after the page fully renders. I guess I can use ngAfterViewChecked but that would mean I am constantly calculating that size when the only meaningful instance for that is when the window opens or resizes

A: *

*An alternate approach that you can use is, subscribe to changes in Window: resize event using the HostListener in order to calculate image dimensions, as shown in the following code snippet.

import { HostListener } from '@angular/core';

@HostListener('window:resize', ['$event'])
  // Invoke function to compute the image dimensions here
}

Note: You can also invoke the function to compute the dimensions of the said image inside AfterViewInit lifecycle hook rather than on load event.

*

*Another approach is to calculate image dimensions by listening to changes in the Window: resize event using the fromEvent, as shown in the code snippet below.

import { fromEvent } from 'rxjs';

changeSubscription$: Subscription

ngOnInit() {
  this.windowResizeEventChanges$ = fromEvent(window, 'resize').subscribe(event => {
    // Invoke function to compute the image dimensions here
  });
}

ngOnDestroy() {
  this.windowResizeEventChangesn$.unsubscribe() // Unsubscribe to stop listening the changes in Window: resize
}

Read more about fromEvent here.

A: I ended up using a Mutation Observer, watching for attribute changes, attached to the item that contains the image. In my case there is a need for some management because it doesn't just run once, but it solves the issue
ngAfterViewInit() {
  this.refElement = this.appsContainer.nativeElement.querySelector('item') as HTMLElement;
  const config = { attributes: true };
  this.mutationObserver = new MutationObserver((mutation) => {
    const target = mutation[0].target as HTMLElement;
    //some code here to execute based on some conditions and to remove the observer
   }
  });
this.mutationObserver.observe(this.refElement, config);}


text:
Q: What are good ways to improve physical hardware reuse? How can I select generically re-usable parts for the unique things I build?
What are good approaches for building unique devices, so that when I no longer need them,
it's relatively easy to disassemble them into parts I can re-use on the next project?
This question focuses on when I build one or a few physical objects.
The "design for disassembly" techniques used in some sustainable designs may also be related, although that focuses more on physical objects built in larger quantities -- is there another question that focuses on that?
Reusing abstract designs for hardware is already covered in another question.
There are lots of items I build exactly one of:
the first (or the 17th) breadboarded prototype of the electronics of a product;
various unique templates and jigs used in production;
test jigs, etc.
When they reach the end of their useful life, they get tossed in the scrap box.
I build them out of
(a) random scrap still hanging around from previous projects, and
(b) new stuff we got with (perhaps shortsighted) focus on this particular project.
I can't help but notice that the shiny new stuff ends up in 3 categories:

*

*a Some things -- solderless breadboards, soldering iron, 1/2 inch (12 mm) socket wrench, pin headers on 1/10 inch centers, alligator clips, velcro cable-ties, etc. -- get re-used over and over again.

*b Some things that at first glance appear very similar -- 15/16 inch socket wrench, etc. -- only get used for one job, and are never used again. While those things were necessary for that one job, and so perhaps I should think of them as a "sunk cost" that I've already made back the return on their investment. Since they are still functional, it seems wasteful to simply throw them away. So they end up taking up space and collecting dust indefinitely.

*c Some things can only be used once -- zip ties, solder, etc. Sometimes it seems a little wasteful, but (if I maintain a short-sighted focus on this particular project) these disposable items are the cheapest way to get things done, and at least they don't tend to accumulate and take up space.

Category (b) is the worst.
If I knew at the time I was buying that part what I know now after watching that part collect dust for years, I would have either saved a little money and bought some disposable category (c) part instead, or else spend a little more money and bought some more generally useful category (a) part instead.
(Or perhaps not. Sometimes I absolutely need some super-specialized part for some project).
Do you have any tips for recognizing ahead of time that a part I am about to buy is highly likely to end up gathering dust as type (b), so that I can try to substitute something that is more likely to be type (a) or type (c)?
Any other tips for making it more likely that parts and tools I hope to re-use actually are re-used later?
Rather than make one all-singing, all-dancing do-everything hyper-specialized PCB that I'll only use this one time and then toss the whole thing, are there good ways to partition the design so that at least part of it is re-usable later?
What are good ways to improve physical hardware reuse?

A: Forget category c: some things are truly disposable and can't be reused in their current state unless you want to start a recycling company.
Category B is the most interesting. For tools, there's eBay: just resell stuff you don't need. Even then, a lot of what we do is specialty stuff: I have 6805J programmers that no one wants even for the cost of shipping. They've simply outlasted their usefulness.
The problem with reusing hardware is the documentation has to be perfect, or the time spent trying to reuse a board or other hardware becomes more costly than simply starting from scratch again. I find that for the things I build for other people, I'm pretty good at keeping good documents. But for stuff I build intending to use for few days and then forget about, documentation is pretty much none existent, so boards end up permanently consigned to the junk bin.

A: Services like Tgimboej(The Great Internet Migratory Box Of Electronics Junk) are great for trading and getting rid of extra parts. junk exchange is another place, but its more like a classified ads. Personally I keep things till some one needs it, or I finally found a use for that part, dust and all.
as for one offs on PCBs or perfboards, I Use IC sockets so chips can be re used on other boards, Try to make the power supply on a separate board if possible. leave leads as long as possible when soldering components to boards. I think making things modular is the best way to get the best results for re-usability.