Q:

Yet another Python text editor

Here's what I managed to do. It is rather limited and I had to get help from the internet in some places.
Can you review it, give me some tips on making the code better, cleaner, faster etc.?
editor.py
import tkinter
import tkinter.ttk
import tkinter.filedialog
import tkinter.messagebox
import os

try:
    import config
    import menu
    import syntaxhl
    import findtool

except ImportError as e:
    import sys
    sys.exit("Import error.\nRaw: {}".format(e))

class Editor(object):

    def editor(self):
        self.root = tkinter.Tk()

        self.config = config.config()
        self.syntaxcolor = config.syntaxHighligh()

        self.root.wm_title(self.config.editor_title)
        self.root.attributes("-alpha", self.config.transparency)

        # Scrollbar
        self.scrollbar = tkinter.Scrollbar(self.root)
        self.scrollbar.pack(side = tkinter.RIGHT, fill = tkinter.Y)

        # Editor.
        self.editor_space = tkinter.Text(self.root)
        self.editor_space.config(undo = self.config.undo, width = self.config.width,
                                 height = self.config.height, fg = self.config.foreground,
                                 bg = self.config.background, insertbackground = self.config.cursorColor,
                                 yscrollcommand = self.scrollbar.set,
                                 font = (self.config.font, self.config.font_size))

        self.editor_space.pack(fill = tkinter.X)
        self.scrollbar.config(command = self.editor_space.yview)

        # Find tool
        find = findtool.Find(self.editor_space)

        # Menu.
        # Note: The order of the instances is the order in witch the menus will appear.
        self.mn = tkinter.Menu(self.root)
        self.filemenu = menu.FileMenu(self.mn, self.openFile,
                                      self.saveFile, self.destroy,
                                      self.root)

        self.toolmenu = menu.ToolsMenu(self.mn, self.clear,
                                       self.syntaxHighlight,
                                       find.find)

        self.prefmenu = menu.Settings(self.mn, self.openConfigFile)
        self.helpmenu = menu.HelpMenu(self.mn, self.about)

        # Close event.
        if self.config.askokcancel:
            self.root.protocol("WM_DELETE_WINDOW", self.destroy)

        self.root.config(menu = self.mn)

        self.root.mainloop()

    def openConfigFile(self):
        try:
            with open("config.py") as file:
                for line in file.readlines():
                    self.editor_space.insert(tkinter.END, line)

        except IOError as e:
            tkinter.messagebox.showerror("Error", "Couldn't open file.")

        except Exception as e:
            tkinter.messagebox.showerror("Error", "Error.\n{}".format(repr(e)))

    def destroy(self):
        ako = tkinter.messagebox.askokcancel("Quit", "Are you sure you want to exit?")
        if ako:
            self.root.quit()

    def clear(self):
        self.editor_space.delete("1.0", tkinter.END)

    def saveFile(self):
        path = tkinter.filedialog.asksaveasfilename(defaultextension = self.config.defext)
        filename = os.path.basename(path)

        try:
            with open(filename, "w") as wf:
                wf.write(self.editor_space.get("0.0", tkinter.END))

            tkinter.messagebox.showinfo(None, "File saved.")

        except IOError as e:
            tkinter.messagebox.showerror("Error", "Couldn't open file.")

        except Exception as e:
            tkinter.messagebox.showerror("Error", "Error.\n{}".format(repr(e)))

    def openFile(self):
        self.clear()
        file = tkinter.filedialog.askopenfile()
        try:
            for line in file.readlines():
                self.editor_space.insert(tkinter.END, line)

            self.syntaxHighlight()

        except IOError as e:
            tkinter.messagebox.showerror("Error", "Couldn't open file.")

        except Exception as e:
            tkinter.messagebox.showerror("Error", "Error.\n{}".format(repr(e)))

    def syntaxHighlight(self):
        for keyw, color in getattr(self.syntaxcolor, "colors").items():
            syntaxhl.highlight(self.editor_space, keyw, color)

    def about(self):
        pass

config.py
class config(object):
    editor_title = "TEdit"
    undo = 1 # 1 - Enable

    # The default extension used when saving a file.
    defext = ".txt"

    # Size of the editor window.
    width = 150
    height = 50

    askokcancel = False
    matchColor = "blue"

    # Theme
    transparency = 1
    background = "black"
    foreground = "white"
    font = "Arial"
    font_size = 18
    cursorColor = "green"

class syntaxHighligh(object):
    colors = {"import" : "red",
              "def" : "red",
              "format" : "red",
              "if" : "red",
              "class" : "red",
              "else" : "red",
              "elif" : "red",
              "=" : "red",
              "try" : "red",
              "except" : "red",
              "finally" : "red",
              "yield" : "red",
              "return" : "red",
              "not" : "red",
              "pass" : "red",
              "for": "red",
              "pass": "red",
              "in" : "red",
              "print" : "red",
              "lambda" : "red",
              }

findtool.py
import tkinter
import tkinter.ttk
import config

class Find(object):

    def __init__(self, es):
        self.editor_space = es
        self.config = config.config()

    def find(self):
        # Find window and stuff.
        root = tkinter.Tk()
        tkinter.Label(root, text = "Seach for: ").grid(row = 1, column = 0)

        input_ = tkinter.ttk.Entry(root, width = 20)
        input_.grid(row = 1, column = 1)

        self.editor_space.tag_configure("search", background = self.config.matchColor)

        # Search button.
        tkinter.ttk.Button(root, text = "Search", command=lambda: self.search_editor_space(input_.get())).grid(row = 2, column = 1,
                                                                                columnspan = 2)

        # On close.
        root.protocol("WM_DELETE_WINDOW", lambda: self.destroy_find_window(root))

    def destroy_find_window(self, root):
        self.editor_space.tag_remove("found", "1.0", tkinter.END)
        root.destroy()

    def search_editor_space(self, searchfor):
        # Actual search.
        # Got from(with small modifications): http://www.java2s.com/Code/Python/GUI-Tk/SearchstringinText.html
        # Thanks.

        self.editor_space.tag_config("found", foreground = self.config.matchColor)
        countVar = tkinter.IntVar()

        item = "1.0"

        while True:
            item = self.editor_space.search(searchfor, item, tkinter.END, count = countVar)

            if not item:
                break

            lastindex = "{} + {}c".format(item, countVar.get())

            self.editor_space.tag_add("found", item, lastindex)

            item = lastindex

menu.py
import tkinter
import tkinter.ttk

class FileMenu(object):

    def __init__(self, menubar, openFunc, saveFunc, closeFunc, root):
        self.of = openFunc
        self.sf = saveFunc
        self.cf = closeFunc

        self.menu = tkinter.Menu(menubar)

        filemenu = tkinter.Menu(self.menu)
        filemenu.add_command(label = "Open", command = self.of)
        filemenu.add_command(label = "Save", command = self.sf)
        filemenu.add_separator()
        filemenu.add_command(label = "Exit", command = self.cf)

        menubar.add_cascade(label = "File", menu = filemenu)

class HelpMenu(object):

    def __init__(self, menubar, aboutFunc):
        self.helpmenu = tkinter.Menu(menubar)

        self.helpmenu.add_command(label = "About", command = aboutFunc)

        menubar.add_cascade(label = "Help", menu = self.helpmenu)

class ToolsMenu(object):

    def __init__(self, menubar, clearFunc, syntaxHighL, find):
        self.cf = clearFunc
        self.fd = find
        self.sh = syntaxHighL
        self.toolsmenu = tkinter.Menu(menubar)

        self.toolsmenu.add_command(label = "Clear", command = self.cf)
        self.toolsmenu.add_command(label = "Find", command = self.fd)
        self.toolsmenu.add_command(label = "Syntax highlighting", command = self.sh)

        menubar.add_cascade(label = "Tools", menu = self.toolsmenu)

class Settings(object):

    def __init__(self, menubar, configFile):
        self.prefmenu = tkinter.Menu(menubar)

        self.prefmenu.add_command(label = "Settings", command = configFile)

        menubar.add_cascade(label = "Preferences", menu = self.prefmenu)

syntaxhl.py
import tkinter

def highlight(editor_space, searchfor, color):
    countVar = tkinter.StringVar()

    pos = "1.0"

    while True:
        pos = editor_space.search(searchfor, pos, tkinter.END, count = countVar)

        if not pos:
            break

        lastindex = "{} + {}c".format(pos, countVar.get())

        editor_space.tag_add("keyword", pos, lastindex)

        pos = lastindex

    editor_space.tag_configure("keyword", foreground = color)

main.py
try:
    import editor

except ImportError as e:
    import sys
    sys.exit("editor.py module missing.")

if __name__ == '__main__':
    edit = editor.Editor()
    edit.editor()

A:

As mentioned by @L3viathan, the config class should be a dictionary, not a static class of attributes. When you ever need to store values in such a way, that a grouped together under a category, use a dictionary, like this:
CONFIG = {
    "config-attribute": "config-attribute-value"
    ...
}

Secondly, your naming is off. Functions and variables should be in lower_snake_case, and classes should be in PascalCase. If the variable is constant, it should be in UPPERCASE_SNAKE_CASE.
I'm not sure if you're using Python 3.x, or Python 2.x, but if you're using Python 3.x, you don't need to explicitly inherit all your classes from object. You can just write them like this: class MyClass:. If you're using Python 2.x though, you should continue explicitly inheriting from object.
You're mixing use of single quotes, '', and double quotes, "". Preferably, you should choose one, and stick with that.
You need two blank spaces in between your top level functions/classes. This is part of the official style guide.
Finally, add some comments. Your code is fairly readable, but it could definitely use some comments. First off, add some docstrings, """ ... """, to describe what your functions and classes do. To describe blocks of code, just use online comments, # ....


Q:

Prove by induction: $2!\cdot 4!\cdot 6!\cdot\cdot\cdot (2n)!\ge ((n+1)!)^n$

Prove by induction: $2!\cdot 4!\cdot 6!\cdot\cdot\cdot (2n)!\ge ((n+1)!)^n$
For $n=1$ inequality holds.
$(*)$For $n=k$
$2!\cdot\cdot\cdot (2k)!\ge ((k+1)!)^k$
Multiplying LHS and RHS with $(2k+2)!$ gives
$$2!\cdot\cdot\cdot (2k)!(2k+2)!\ge ((k+1)!)^k(2k+2)!$$
Assume (by contradiction)$$2!\cdot\cdot\cdot (2k)!(2k+2)!< ((k+1)!)^k(2k+2)!$$
$$2!\cdot\cdot\cdot (2k)!(2k+2)!-((k+1)!)^k(2k+2)!<0$$
$$(2k+2)!(2!\cdot\cdot\cdot (2k)!-((k+1)!)^k)<0$$
$(2!\cdot\cdot\cdot (2k)!-((k+1)!)^k)\ge 0$ by $(*)$, thus inequality holds $\forall n\in\mathbb{N}$
Is this proof correct?

A:

First, show that this is true for $n=1$:
$\prod\limits_{k=1}^{1}(2k)!\geq(1+1)!^{1}$
Second, assume that this is true for $n$:
$\prod\limits_{k=1}^{n}(2k)!\geq(n+1)!^{n}$
Third, prove that this is true for $n+1$:
$\prod\limits_{k=1}^{n+1}(2k)!=$
$\color\red{\prod\limits_{k=1}^{n}(2k)!}\cdot(2(n+1))!\geq$
$\color\red{(n+1)!^{n}}\cdot(2(n+1))!=$
$(n+1)!^{n}\cdot(2n+2)!=$
$(n+1)!^{n}\cdot(n+1)!\cdot\dfrac{(2n+2)!}{(n+1)!}=$
$(n+1)!^{n+1}\cdot\dfrac{(2n+2)!}{(n+1)!}=$
$(n+1)!^{n+1}\cdot\underbrace{(n+2)\cdot(n+3)\cdot\ldots\cdot(2n+2)}_{n+1\text{ times}}\geq$
$(n+1)!^{n+1}\cdot\underbrace{(n+2)\cdot(n+2)\cdot\ldots\cdot(n+2)}_{n+1\text{ times}}=$
$(n+1)!^{n+1}\cdot(n+2)^{n+1}=$
$(n+2)!^{n+1}$

Please note that the assumption is used only in the part marked red.


Q:

Preserve key:value values in text while regex replacing non-word characters in keys (Notepad++)

Trying without luck in Notepad++ to replace any non-word characters \W with underscore _ from a block of multi-line text, with exception to (and right of) a colon : (which doesn't occur on every line- something of space-delineated hierarchy, terminating in a key-value pair). A python solution could be of use as well, as I'm trying to do other things with it once reformatted. Example:
This 100% isn't what I want
  Yet, it's-what-I've got currently: D@rnit :(
This_100_is_what_I_d_like: See?
  Indentation_isn_t_necessary
    _to_maintain_but_would_be_nice: :)<-preserved!
  I_m_Mr_Conformist_over_here: |Whereas, I'm like whatever's clever.|
If_you_can_help: Thanks 100.1%!

A:

I admit that I'm answering an off-topic question I just liked the problem. Hold CTRL+H,  enable Regular Expressions in N++ then search for:
(:[^\r\n]*|^\s+)|\W(?<![\r\n])

And replace with:
(?1\1:_)

Regex has two main parts. First side of outer alternation which matches leading spaces of a line (indentation) or every thing after first occurrence of a colon, and second side which matches a non-word character except a carriage return \r or newline \n character (in negative lookbehind) to preserve linebreaks. Replacement string is a conditional block which says if first capturing group is matched replace it with itself and if not replace it with a _.


Q:

Unordered Map with Multiple Value and it's lookup

I am working on an assignment where I have been given a large tab separated value txt file and I have to search through it using a good data structure. Now the problem I am facing is that I don't know if I am inserting the values correctly in this unordered_map with the key being a string and the values being a vector of struct.
Secondly if I want to search how will it do it? For example if i enter the first ID how can i print out or access the other elements present in the struct?
Below is the sample data & code
id    effectiveTime    active    moduleId    definitionStatusId
100005    20020131    0    900000000000207008    900000000000074008
101009    20020131    1    900000000000207008    900000000000074008
102002    20020131    1    900000000000207008    900000000000074008
103007    20020131    1    900000000000207008    900000000000074008
104001    20020131    1    900000000000207008    900000000000073002
105000    20040731    0    900000000000207008    900000000000074008
106004    20020131    1    900000000000207008    900000000000074008
107008    20020131    1    900000000000207008    900000000000074008
108003    20020131    1    900000000000207008    900000000000074008
109006    20020131    1    900000000000207008    900000000000074008
110001    20020131    1    900000000000207008    900000000000074008
111002    20020131    1    900000000000207008    900000000000074008
112009    20020131    1    900000000000207008    900000000000074008
113004    20020131    1    900000000000207008    900000000000074008
114005    20020131    1    900000000000207008    900000000000074008
115006    20020131    1    900000000000207008    900000000000074008
116007    20020131    1    900000000000207008    900000000000074008
117003    20020131    1    900000000000207008    900000000000074008
118008    20020131    1    900000000000207008    900000000000074008
119000    20020731    1    900000000000207008    900000000000073002
120006    20020131    1    900000000000207008    900000000000074008
121005    20020131    1    900000000000207008    900000000000074008

And here is the code
#include <iostream>
#include <vector>
#include <fstream>
#include <unordered_map>

using namespace std;

struct concept
{
    string id,effectiveTime,active,moduleId,definitionStatusId;
};

int main ()
{
    unordered_map<string,vector<concept>> concepts;
    ifstream conceptStream("concept.txt");
    if (!conceptStream.is_open())
    {
        cout << "Failed to open\n";
        return 0;
    }
    string id,effectiveTime,active,moduleId,definitionStatusId;
    string conceptLine;
    getline(conceptStream, conceptLine);
    while (!conceptStream.eof())
    {
        getline(conceptStream, id, '\t');
        getline(conceptStream, effectiveTime, '\t');
        getline(conceptStream, active, '\t');
        getline(conceptStream, moduleId, '\t');
        getline(conceptStream, definitionStatusId, '\n');
        concepts[id] = {{id,effectiveTime,active,moduleId,definitionStatusId}};
    }

  return 0;
}

A:

You search for a value by using find. You have a value if the iterator returned isn't equal to end().
unordered_map<string,vector<concept>>::const_iterator it = concepts.find(id);
if (it != concepts.end()) {} //You have a value

The vector you have inserted will always have one entry, so you could do away with that, but as you have it you need to get the first element of the vector.
if (it != concepts.end())
  cout << it->second[0].id << it->second[0].effectiveTime; //etc

Of course maybe you intend to see if the ID already exists and add it to the vector if it does. That will work, but maybe you should consider std::unordered_multimap as Shawn suggested, and if not, change the key type to concept as there will only ever be one element in the vector.
If you do remove the vector the access code becomes simpler:
if (it != concepts.end())
  cout << it->second.id << it->second.effectiveTime; //etc


Q:

Generating a slug after Active Record object creation in rails

I'm trying to generate a unique slug for an object after the object is created using the after_commit callback.
after_commit :create_slug, on: :create

def create_slug
    self.slug = generate_slug
    self.save
end

When I try to save the object I get a "stack level too deep" error.  I'm assuming because I'm saving the object and it's called the after_commit callback again and again.
What's the best way to generate and save the unique slug in this situation?

A:

I recommend using the after_validation callback on create rather than the after_commit.  You will be calling multiple transactions, which is not the intention of this callback.  What I would do is this:
after_validation(on: :create) do
  self.slug = generate_slug
end

Also make sure there are no save actions going on inside the generate_slug.  That method should simply be returning a value to insert into the slug attribute.


Q:

Convert Base64 into PDF without converting it into an Image in JAVA

I've done converting PNG to PDF using itext.
How can i convert BASE64 into a PDF File, how can i achieve this.
//b64Image contains base64code from html2canvas, this code is for converting
 base64 to png
String b64Image=request.getParameter("img_val");

b64Image = b64Image.replace("data:image/png;base64,", "");
b64Image = b64Image.replace(" ", "+");

byte[] imageByte;
String path = "C:\\Users\\P.Balraj\\Desktop\\Screenshot.png";
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(b64Image);
File outputfile = new File(path);
    BufferedOutputStream stream = new BufferedOutputStream(
        new FileOutputStream(outputfile));
stream.write(imageByte, 0, imageByte.length);
stream.flush();
stream.close();

Thank you

A:

You can add b64 image to pdf like this:
import java.io.FileOutputStream;

//com.lowagie...   old version
//com.itextpdf...  recent version
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Image;
import org.apache.commons.codec.binary.Base64;

public class Image64ToPDF {
    public static void main(String ... args) {
        Document document = new Document();
        //
        String b64Image = "iVBORw0KGgoAAAANSUhEUgAAAJcAAACXCAMAAAAvQTlLAAABF1BMVEX////qQzU0qFNChfT7vAU8gvTz9/5pm/bh6f3m7f4edvMhePPqPi/7tgD7uAD7ugAyfvPpOCjpNCIopUv0+vb62NYAnjf97ezU6tnrTkKv2LhCrF7whX4YokLpLRnC4cn+9/bymZPoHgDt8v4zqkHo9Ov0qqX2vrrpOzb8wgB1vob+7s+ExZNUsmv/+e9XkPXT4PzsX1WZzqX4ycbudW374+JiuHdKqU7btQPsuxaTtfj8w0U8lrSux/prrEQDpljF1vsmf+Gmz8SRsD40pGf/4Kj86cGmsjY3oH85maKAqfc/jtQ/k8Q5nZL3qBT81oTtXC/xfCb1lxvvbyHNtyb8y2MAaPK1syznAhj2nzjuZirzjSD80nX4U1R1AAAFc0lEQVR4nO2YC1faSBiGQwCtEAzJxBgICSGFoMilQERbWy+tdXfb3bXdrXvt//8dO1wOEDIZkkmGePbMo+eoR8DHb9755hs4jsFgMBgMBoPBYDAYDMYzxDo+HzsN1x1C3FqjPT62rNSdjpza0LRNU5aEGZJs2rbkNtpHKUqN3UoGCmV8CLKcqTSOrDSsxg3BRjmt3Oyhc75rq/ZQkIOdlmoZd5dmljO0MZVaR7LdnSVtPJRDWs3MBNfahdWRG7ZWSzPJoa/lCFI0qykm7ZidD83oVtOS2W2aWuMKQbHmyDV6Wk7UZK1juseUtGrbOxYOqWLRsLJcsmitvDJUwu8SR2uOUKHRYC033iLCalGJV8xsUaoW14idLSrVam+rliBJ8hQJjoe7q9aRjZWSzQqcn502BM7Tw4y5uUMoVcsa4sY/W2qMz63Vo+G079rm+jOEDJ1RB5N5OVND/k3HXZlRqhY3Dsy8YNeCWqXVrph0q3VcCSwWfnpxMhLFanFOwCoK9rZp7xyWjFa1uOOAvSgPQ5x2DZtWtbga+lg0h6H+oEPr0nH2+wlSi+KUF4rH3L8IMdNNWatfyp3+mtk0k3Zz88LweJiDYl+8YoJJK8xh6V+JOcjpV4+YlOJ7NXMeZlpQ7LeTlZncSFuL+36YW4it1lLIpG3F9RflmoqJ/yzEZKo31FA8lHIrTucNQ0i7RXBry7gI2bRh2OO0rTjuSsx5xMQvJ0IlbSl4BuV8fP0r/XQtu8R6yf7GTRF7kSD2+njo8xK/Yx5/MNiPArHYo9/r8CPOq5CPQOElqdeTfx1LfaxXNgLFV4Ra/dcIL9wTonmV35F6IeJ1laDXG1Kvks/rEBf7iF75Twl64WIf1Wuf0OvM71VK0muQoNcD8/pfeD2HfKH24+Pz9BKfnoPXoe8cEnMJepH2r/4V1XObuN8j54mzxLyIz0fk/IUL/o7mCeS8+qRgvP4oFosF+DH/LEx/mn9XKPu9iOcv7sGvJV5rmCe8COLgjV+MfF71BV/8dmGMiF7qE6Jg5BcPr5eY+5PneYPolYo+qzz5vcMbMDF3fTP1IinYK/+OIN+O3o4vXs60eL7Xiv5CiHiRb0eOs1YLKX6bWxEV7GCA6BMvyL2WCymKH/glauSCvUOknvR0nLF4h0J8fX2z8gITTA9D4k99rHhxix0pXvIeQMSVRKQrWyDuqjMeSnANf7jxevFqPcpr3CK08gPyLjEDtocPm1qwYriuv0k2n/gywuRfXvi1YMVCi+3tI7Sy2XjLCFvYBcIKoofdlPuIVSSfCVdUDbRYuIztIbXipn6KoqO9eNDd/uSXA6QW8Wi/Th0EiBn6lpAp7++QWtnybQJe3CRIDIARrsNqHfUeKZZIueC/HeQFzdRRQP6V+kQFPGi+Lfu3YzHO0bhGUPRni8l3EBugNZoY8/+m+ZOvYmXii9AmXYwYDwxjUtVaremSKkqrpdW7QF2VuHl/t1GxAfEAvYmiBy/lQk3vTTqQSU83DO+Dwf1nz7lduE1KC65LULPwCECQv2i+XTuKYp9AHjQ1hFggzR+X6Y99YG8Q2MVCAfTP8/jnY9yCAsRiVQyAn8vJdVQP1VgV45u/5PM0tOJWDIbsrhjjDoRB29IutmAY8acINC0d12C3APgoQ240FGznx2v1ot6iIlEN6J3brFTs6JEASuDYg8HoRbpBkVHnIy4mMLqUizVHqfIRagbAhOCdFjJaVRCymQG1Q28bIlDqvaDxYb1UemdntVqijXQVkzSgGp3qTnLlQ9FGPZ03NusGABwNe516OlILWvVqd6IbqqoakOkXfdId1XcaqiAUONdrWh2iaS34Q9o+DAaDwWAwGAwGg8FgMJD8B0Y0n3erXn7HAAAAAElFTkSuQmCC"; // .gif and .jpg are ok too!
        String output = "c:/output.pdf";
        try {
            PdfWriter.getInstance(document, new FileOutputStream(output));
            document.open();
            byte[] decoded = Base64.decodeBase64(b64Image.getBytes());
            document.add(Image.getInstance(decoded));
            document.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Q:

Is it possible to power a microcontroller via inductance from an AC power line?

I have an AC mains wire powering a pump running at 220V at 5-10A. Is it possible to wind a secondary wire around the outside of the insulation of one of the two "hot" wires (single-phase) to get low-voltage AC that could be rectified to DC and used to power a microcontroller?
The goal is to monitor current while the pump is in use, using a separate split-core transformer as an analog input, and report usage via Wifi or Zigbee without requiring a separate DC power supply.

A:

No, the wire will not radiate a magnetic field along the lengt of the wire but straight out of the wire. To make a transformer and extract energy you need an magnetic field that alternates. As you will have a split core to measure the current the best idea would be to use it to both measure the current and extract power to your circuit. This only works with a real current transformer and not with a modern Hall effect variant, if you need the Hall effect model for accuracy in your measurements you will need a separate split core current transformer to power your circuit.
The resultant circuit is much like an transformer with only one turn of primary winding, the current in the secondary winding will be the current in the AC wire divided by the number of turns in the current transformers winding. Note that the circuit outputs a current and if the load is not sufficient the voltage can be quite high, therefor you need to be sure to load the current transformer and to have a over voltage protection that can handle the excess power, especially in events of high current on the AC line, like starting currents of an electrical motor.
If you then put a resistor or other current sensing element in series of the output of your current transformer that measures the total current you can know the current trough the AC line at the same time as you uses it to power your current sensing circuit.


Q:

Changing a programs process name in task manager?

Okay so I've been looking around and I can't find an answer anywhere.
What I want my program to do is every time I run it, the name that shows up in the task manager is randomized.
There is a program called 'Liberation' that when you run it, it will change the process name to some random characters like AeB4B3wf52.tmp or something. I'm not sure what it is coded in though, so that might be the issue.
Is this possible in C#?
Edit:
I made a sloppy work around, I created a separate program that will check if there is a file named 'pb.dat', it will copy it to the temp folder, rename it to a 'randomchars.tmp' and run it.
Code if anyone was interested:
private void Form1_Load(object sender, EventArgs e)
{
    try
    {
        if (!Directory.Exists(Environment.CurrentDirectory + @"\temp")) // Create a temp directory.
            Directory.CreateDirectory(Environment.CurrentDirectory + @"\temp");

        DirectoryInfo di = new DirectoryInfo(Environment.CurrentDirectory + @"\temp");

        foreach (FileInfo f in di.GetFiles()) // Cleaning old .tmp files
        {
            if (f.Name.EndsWith(".tmp"))
                        f.Delete();
        }

        string charList = "abcdefghijklmnopqrstuvwxyz1234567890";
        char[] trueList = charList.ToCharArray();
        string newProcName = "";

        for (int i = 0; i < 8; i++) // Build the random name
            newProcName += trueList[r.Next(0, charList.Length)];

        newProcName += ".tmp";

        if (File.Exists(Environment.CurrentDirectory + @"\pb.dat")) // Just renaming and running.
        {
            File.Copy(Environment.CurrentDirectory + @"\pb.dat", Environment.CurrentDirectory + @"\temp\" + newProcName);
            ProcessStartInfo p = new ProcessStartInfo();
            p.FileName = Environment.CurrentDirectory + @"\temp\" + newProcName;
            p.UseShellExecute = false;
            Process.Start(p);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("I caught an exception! This is a bad thing...\n\n" + ex.ToString(), "Exception caught!");
    }

    Environment.Exit(-1); // Close this program anyway.
}

A:

I would implement a host application to do this that simply runs and monitors a sub process (other executable). You may rename a file as such:
System.IO.File.Move("oldfilename", "newfilename");

and start the process like this:
Process.Start("newfilename");

This would mean that instead of one process you would have two, but the owner process only needs to be alive under startup - in order to change the name.


Q:

Solve linear congruence: $ax + b = y \; (mod \; m)$

I am trying to solve $ax + b = y \; (mod \; m)$ for x, where $a,b,y,m$ are known values. This corresponds to running a linear congruential generator in reverse for one iteration.
I am happy to assume that $gcd(a,m) = 1$, which according to this page, means there is a single solution for $x$. I am looking for a nice algebraric manipulation of the equation that will produce this value for $x$.
I begin like this: first subtract $b$ from both sides
$$ax = y - b = u \; (mod \; m)$$
Next, compute $n$, the multiplicative inverse of $u$, to arrive at
$$axn = un = 1 \; (mod \; m)$$
How do I continue and find $x$?

A:

Once you have $ax = u \pmod{m}$, just multiply by $a$'s inverse in $\Bbb Z/m\Bbb Z$ (i.e. the only solution to $a a' = 1 \pmod{m}$ since you assume $\gcd(a,m)=1$):
$$x = a^{-1} ax = a^{-1}u \pmod{m}$$
There's a lot of info (including computation methods) on modular inverse on Wikipedia.


Q:

Kotlin: Can I access a nested array from inside another array?

This may be a dumb question, but I have an array:
var testarray = arrayOf(0,0,arrayOf(7,5,2))

So I tried to access the second array by typing testarray[2][1]. However, this throws an error:
error: unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
@InlineOnly public inline operator fun <@OnlyInputTypes K, V> Map<out Int, ???>.get(key: Int): ??? defined in kotlin.collections
testarray[2][1]
^
error: no get method providing array access
testarray[2][1]

Is there a way to access the nested array?

A:

Your outer array contains Ints, and an array. So its actual declared type (that you could specify, or could let the IDE specify for you), is Array<Serializable>.
A Serializable could be anything. The compiler doesn't know that the element at index 2 happens to be an array. So it can't let you use the [] operator on it. You need to cast the element to an array to be able to do that:
println((testarray[2] as Array<Int>)[1])

That would fix the compilation issue, but not the design issue. Using arrays in general is already a smell, but using arrays containing mixed types is an even bigger smell. You should reconsider your design.


Q:

Between *variable sharing* and *command substitution*, which method is better for returning a value from another bash script

Suppose I have

a bash script A.bash, which calls another script B.bash.
B.bash calculates a variable VAR.
Now I would like B.bash to return VAR to the calling script.

I can export VAR in B.bash and source B.bash in A.bash. Another solution is to echo VAR in B.bash, execute B.bash in A.bash and get the the return value as R=$(B.bash).
Does it make sense? Which option is better? Are there any alternatives?

A:

Little introduction
Tracking forks (like $())  as they consume lot more ressource than normal (sequential) execution, if you know which variable has to be modified in advance, you'll better to use local definition around your whole script and use function instead of having to make file access between commands:
#!/bin/bash
# There is the `A` script

local VAR

function B() {
    read -a VAR </proc/uptime
}

B
echo $VAR
sleep 1
B
echo $VAR

could output something like:
1610291.39
1610292.39

with time to access /bin/sleep could be less than 1/100th of second.
A little demonstration:
local V1
B1() {
    read -a V1 </proc/uptime
}
B1 ;echo $V1 ;for i in {0..10000} ;do B1 ;done ;echo $V1
1610843.78
1610844.38
printf "%d 1/100th of sec\n" $((161084438-161084378))
60 1/100th of sec

I could set 10000x my variable in 60/100 seconds, while
B2() {
    local var
    read -a var </proc/uptime
    echo $var
}
V2=$(B2);echo $V2;for i in {0..10000};do V2=$(B2);done;echo $V2
1611121.33
1611168.01
printf "%d 1/100th of sec\n" $((161116801-161112133))
4668 1/100th of sec

May take more time!
If you really wanna keep all in separated file, as @alok suggested, you could source them, as this will not fork:
echo >/dev/shm/B3 'read -a V3 </proc/uptime'
. /dev/shm/B3 ;echo $V3 ; for i in {0..10000};do . /dev/shm/B3;done;echo $V3
1612187.89
1612188.79
printf "%d 1/100th of sec\n" $((161218879-161218789))
90 1/100th of sec

This is lot quicker than having to fork for each loop, but accessing to function via filesystem (even RAM pseudo filesystem, without access time) take some time.
My answer

Yes, it make sense, while $(...) or ... stay usefull for returning result of a binary command or other strong script with a lot of bariables you won't inherit.
Depending on your need and who wrote each parts... paralelism... other factors...
Other alternatives, for dynamic command, not really, but don't miss to use built-ins like mapfile or read -a when you can.

Disclaimer
This concern bash only! If you want your script to be portable (even if bash is already ported on most significant os), you have to not use array variables and try your script with zsh or dash.


Q:

Dragula on drag the nested image doesn't stay styled

Codepen here:
http://codepen.io/jasonsawtelle/pen/jqbeXd
//HTML

//SCSS
//Dragula
.gu-mirror{position:fixed!important;margin:0!important;z-index:9999!important;opacity:.8;-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=80)";filter:alpha(opacity=80)}.gu-hide{display:none!important}.gu-unselectable{-webkit-user-select:none!important;-moz-user-select:none!important;-ms-user-select:none!important;user-select:none!important}.gu-transit{opacity:.2;-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=20)";filter:alpha(opacity=20)}

// Example
#drag_container{
    display: flex;
    div{
        img{
            height: 100px;
        }
    }
}

//JS
dragula([document.querySelector('#drag_container')])

It's a basic setup and Dragula is working, but when I drag a div, the contained, css resized image is popping to full-size during the drag event.

A:

You should set .gu-mirror img to width: 100px; to achieve what you want. See the CodePen for the result.
.gu-mirror is the div added by the Dragula plugin to mirror the selected element to drag somewhere else.


Q:

Using JavaSounds from tomcat

I'm trying to write a Java EE application that records sound from the input on the server.
My code works fine when debuging, and running on the server as myself (both ubuntu) however when it's running from the web sever I get an exception:
javax.sound.sampled.LineUnavailableException
at org.classpath.icedtea.pulseaudio.PulseAudioMixer.openImpl(PulseAudioMixer.java:714)
at org.classpath.icedtea.pulseaudio.PulseAudioMixer.openLocal(PulseAudioMixer.java:588)
at org.classpath.icedtea.pulseaudio.PulseAudioMixer.openLocal(PulseAudioMixer.java:584)
at org.classpath.icedtea.pulseaudio.PulseAudioMixer.open(PulseAudioMixer.java:579)
at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:95)
at org.classpath.icedtea.pulseaudio.PulseAudioTargetDataLine.open(PulseAudioTargetDataLine.java:111)
at org.classpath.icedtea.pulseaudio.PulseAudioTargetDataLine.open(PulseAudioTargetDataLine.java:130)

I've tried to add the tomcat user to the audio group (which some documentation suggested) but it's still throwing the exception. I think the only difference must be the environment, but I'm at a loss for where the problem might be.

A:

I've managed to get this working now - but thank for the help.
In the end it was a OS level issue, under ubuntu only users in the audio group can access sound resources when not logged in (https://wiki.ubuntu.com/Audio/TheAudioGroup) and to connect to pulse audio it looks like you need X11 auth of some kind. After those changes it require a restart so tomcat could grab the sound device before anything else did.


Q:

Boost spirit: Invalidate parser from member function

this article (boost spirit semantic action parameters) explains how to invalidate a match from a plain function with the signature
void f(int attribute, const boost::fusion::unused_type& it, bool& mFlag)

I would like to invalidate a match from a member function of the grammar:
#include <boost/spirit/home/qi.hpp>
#include <boost/spirit/home/phoenix.hpp>

#include <iostream>
#include <string>

namespace qi  = boost::spirit::qi;
namespace phoenix = boost::phoenix;

class moduleAccessManager
{
public:
    bool getModule(const std::string name)
    {
        if(name == "cat" || name == "dog")
            return true;
        else
            return false;
    }
};

void globalIsModule(std::string moduleName, const boost::spirit::unused_type&, bool& mFlag)
{
        moduleAccessManager acm; /* Dirty workaround for this example */
        if(acm.getModule(moduleName))
            std::cout << "[isModule] Info: Found module with name >"  << moduleName << "<" << std::endl;
        else
        {
            std::cout << "[isModule] Error: No module with name >" << moduleName << "<" << std::endl;
            mFlag = false; // No valid module name
        }
}

template <typename Iterator, typename Skipper>
class moduleCommandParser : public qi::grammar<Iterator, Skipper>
{
private:
    moduleAccessManager* m_acm;

    qi::rule<Iterator, Skipper> start, module;

public:
    std::string m_moduleName;

    moduleCommandParser(moduleAccessManager* acm)
        : moduleCommandParser::base_type(start)
        , m_acm(acm)
        , m_moduleName("<empty>")
    {
        module  =   qi::as_string[qi::lexeme[+(~qi::char_(' '))]]
            [&globalIsModule] // This works fine
//          [phoenix::bind(&moduleCommandParser::isModule, this)] // Compile error
            ;
        start    =  module >> qi::as_string[+(~qi::char_('\n'))];
    };

    void isModule(std::string moduleName, const boost::spirit::unused_type&, bool& mFlag)
    {
        // Check if a module with moduleName exists
        if(m_acm->getModule(moduleName))
            std::cout << "[isModule] Info: Found module with name >"  << moduleName << "<" << std::endl;
        else
        {
            std::cout << "[isModule] Error: No module with name >" << moduleName << "<" << std::endl;
            mFlag = false; // No valid module name
        }
    };

};

int main()
{
    moduleAccessManager acm;
    moduleCommandParser<std::string::const_iterator, qi::space_type> commandGrammar(&acm);

    std::string str;
    std::string::const_iterator first;
    std::string::const_iterator last;

    str = "cat run";
    first = str.begin();
    last = str.end();
    qi::phrase_parse(first, last, commandGrammar, qi::space);

    str = "bird fly";
    first = str.begin();
    last = str.end();
    qi::phrase_parse(first, last, commandGrammar, qi::space);
}

Code on Coliru: http://coliru.stacked-crooked.com/a/4319b38a6d36c362
The important part is these two lines:
            [&globalIsModule] // This works fine
//          [phoenix::bind(&moduleCommandParser::isModule, this)] // Compile error

Using the global function works fine, but that's not an option for me because I need access to the m_acm object which is specific to the parser.
How can I bind a member function to a semantic action and at the same time be able to invalidate the match from that member function (using the 3 argument function signature mentioned above)?

A:

There are two ways:

you can assign to qi::_val using Phoenix actors
you can assign to the third parameter (bool&) inside a "raw" semantic action function

An example is here:

Constraining the existing Boost.Spirit real_parser (with a policy) (using _val)

The anatomy of a semantic action function (with the third argument):

boost spirit semantic action parameters

In your case you have a member function with roughly the "raw semantic action function" signature. Of course, you'll have to bind for the this parameter (because it's a non-static member function).
Note that in this particular case, phoenix::bind is not the right bind to use, as Phoenix Actors will be considered to be "cooked" (not raw) semantic actions, and they will get executed in the Spirit context.
You could either

use boost::bind (or even std::bind) to bind into a function that preserves the arity (!) of the member function:
[boost::bind(&moduleCommandParser::isModule, this, ::_1, ::_2, ::_3)]

This works: Live On Coliru
instead use a "cooked" semantic action, directly assigning to the _pass context placeholder:
[qi::_pass = phoenix::bind(&moduleAccessManager::getModule, m_acm, qi::_1)]

This works too: Live On Coliru

The latter example, for future reference:
#define BOOST_SPIRIT_USE_PHOENIX_V3
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

#include <iostream>
#include <string>

namespace qi      = boost::spirit::qi;
namespace phoenix = boost::phoenix;

class moduleAccessManager {
public:
    bool getModule(const std::string name) {
        return name == "cat" || name == "dog";
    }
};

void globalIsModule(std::string moduleName, const boost::spirit::unused_type&, bool& mFlag)
{
        moduleAccessManager acm; /* Dirty workaround for this example */
        if(acm.getModule(moduleName))
            std::cout << "[isModule] Info: Found module with name >"  << moduleName << "<" << std::endl;
        else
        {
            std::cout << "[isModule] Error: No module with name >" << moduleName << "<" << std::endl;
            mFlag = false; // No valid module name
        }
}

template <typename Iterator, typename Skipper>
class moduleCommandParser : public qi::grammar<Iterator, Skipper>
{
private:
    moduleAccessManager* m_acm;

    qi::rule<Iterator, Skipper> start, module;

public:
    std::string m_moduleName;

    moduleCommandParser(moduleAccessManager* acm)
        : moduleCommandParser::base_type(start)
        , m_acm(acm)
        , m_moduleName("<empty>")
    {
        using namespace phoenix::arg_names;
        module  =   qi::as_string[qi::lexeme[+(~qi::char_(' '))]]
                        [qi::_pass = phoenix::bind(&moduleAccessManager::getModule, m_acm, qi::_1)]
                    ;
        start   =  module >> qi::as_string[+(~qi::char_('\n'))];
    };

};

int main()
{
    moduleAccessManager acm;
    moduleCommandParser<std::string::const_iterator, qi::space_type> commandGrammar(&acm);

    std::string str;
    std::string::const_iterator first;
    std::string::const_iterator last;

    str = "cat run";
    first = str.begin();
    last = str.end();
    std::cout << str << std::boolalpha
              << qi::phrase_parse(first, last, commandGrammar, qi::space)
              << "\n";

    str = "bird fly";
    first = str.begin();
    last = str.end();
    std::cout << str << std::boolalpha
              << qi::phrase_parse(first, last, commandGrammar, qi::space)
              << "\n";
}


Q:

R function to allocated a fixed resource based on a unit value

I am trying to create a function in R to allocate a fixed amount of units based on the value those units provide.  I set up the below sample dataframe.
fruit <- c("apple","orange","bannana","cherry")
units_of_mass <- c(9, 11, 16, 7)
health_pts <- c(5, 3, 6, 1)
diet_plan <- data.frame(fruit, units_of_mass, health_pts)
total_units_desired <- 32

So what I would like to do is to allocate the total units desired based on the health points assigned to each fruit, starting with the highest health points.
I tried using dplyr but got stuck
fruit_detail <- diet_plan %>%

arrange(fruit, health_pts) %>%

mutate(
  cum_units = cumsum(units_of_mass) - units_of_mass,
  can_allocate = total_units_desired - cum_units,
  allocated = ifelse(can_allocate <= 0, 0, ifelse(can_allocate >=
  cum_units, cum_units))
 )

The simple way to do this would be to arrange by health points and subtract units until you run out of total_units_desired, which would look something like the below:
## iterate on allocations
diet_plan <- setDT(diet_plan)

max <- max(diet_plan$health_pts)

allocation_1 <- subset(diet_plan, health_pts == max)
allocation_1[, units_allocated := ifelse(total_units_desired >
               units_of_mass, units_of_mass, total_units_desired)]

remaining_units <- ifelse(total_units_desired - allocation_1$units_allocated
                   > 0, total_units_desired - allocation_1$units_allocated,
                   0)

diet_plan <- subset(diet_plan, health_pts < max)
max <- max(diet_plan$health_pts)

allocation_2 <- subset(diet_plan, health_pts == max)
allocation_2[, units_allocated := ifelse(remaining_units > units_of_mass,
                                  units_of_mass, remaining_units)]

remaining_units <- ifelse(remaining_units - allocation_2$units_allocated >
                   0, remaining_units - allocation_2$units_allocated, 0)

diet_plan <- subset(diet_plan, health_pts < max)
max <- max(diet_plan$health_pts)

allocation_3 <- subset(diet_plan, health_pts == max)
allocation_3[, units_allocated := ifelse(remaining_units > units_of_mass,
                                  units_of_mass, remaining_units)]

remaining_units <- ifelse(remaining_units - allocation_3$units_allocated >
                   0, remaining_units - allocation_3$units_allocated, 0)

diet_plan <- subset(diet_plan, health_pts < max)
max <- max(diet_plan$health_pts)

allocation_4 <- subset(diet_plan, health_pts == max)
allocation_4[, units_allocated := ifelse(remaining_units > units_of_mass,
units_of_mass, remaining_units)]

result <- rbind(allocation_1, allocation_2, allocation_3, allocation_4)

 fruit units_of_mass health_pts units_allocated
bannana        16          6              16
apple           9          5               9
orange         11          3               7
cherry          7          1               0

A:

The way you presented your problem, we can just sort by health_pts, then find the cumulative sum of units_of_mass, which is the total units_allocated if we take that item and all items above it. Then we can just filter the items where taking them wouldn't put us over the limit of total_units_desired.
The remaining rows, then, can have the maximum amount of units allocated:
diet_plan_sum %>%
    arrange(desc(health_pts)) %>%                # Sort by health_pts
    mutate(cum_sum = cumsum(units_of_mass)) %>%  # Calculate total cumulative units
    filter(cum_sum < total_units_desired) %>%    # Drop items over allocation limit
    mutate(units_allocated = units_of_mass) %>%  # For remaining rows, allocate max
    select(-cum_sum)                             # Drop cum_sum variable

    fruit units_of_mass health_pts units_allocated
1 bannana            16          6              16
2   apple             9          5               9

If you want to allocate the remaining units, we can then make a few changes to the above:
First, we find the first row where we go over the threshold: this is the only row with partial values. We can then set its units_allocated value to total - the proceeding row's value, which is the remainder.
For every other row, we check if the cumulative sum is greater than the threshold: if so, set units_allocated to 0, if not, set units_allocated to the units_of_mass:
diet_plan_sum %>%
    arrange(desc(health_pts)) %>%
    mutate(cum_sum = cumsum(units_of_mass),
           # Find the first row where we go over the threshold, set it to remainder
           units_allocated = if_else(cum_sum > total_units_desired & lag(cum_sum) < total_units_desired,
                                     total_units_desired - lag(cum_sum),
                                     if_else(cum_sum > total_units_desired,
                                             0,
                                             units_of_mass))) %>%
    select(-cum_sum) # Drop cum_sum variable

    fruit units_of_mass health_pts units_allocated
1 bannana            16          6              16
2   apple             9          5               9
3  orange            11          3               7
4  cherry             7          1               0


Q:

jQuery: replacing HTML with dynamic HTML instead of appending

So far, I've got this code:
$("
", {
    "id": "myId",
    "class": "myClass",
    "html": "Hello world!"
}).appendTo("#myContainer");

This appends

Hello world!

to #myContainer, as one would expect.
But instead of appending, I would like to have it replace the contents.
I'm imagining something like this:
$("#myContainer").html("
", {
    "id": "myId",
    "class": "myClass",
    "html": "Hello world!"
});

A:

Actually, this is really easy to do, you just have to wrap the dynamic HTML in $() (or jquery(), if you prefer) again:
$("#myContainer").html($("
", {
    "id": "myId",
    "class": "myClass",
    "html": "Hello world!"
}));

Even though this works perfectly fine, I'm wondering if there's a more elegant/performant way of doing this.


Q:

How to solve Scanner Permissions issues

My computer previously ran Ubuntu 10.4.  After upgrading to 13.4, my Epson scanner no longer can be found by the system.  Following documentation, I find the following:
$ sane-find-scanner

  # sane-find-scanner will now attempt to detect your scanner. If the
  # result is different from what you expected, first make sure your
  # scanner is powered up and properly connected to your computer.

  # No SCSI scanners found. If you expected something different, make sure that
  # you have loaded a kernel SCSI driver for your SCSI adapter.

could not open USB device 0x046d/0x082b at 001:007: Access denied (insufficient permissions)
...
  # No USB scanners found. If you expected something different, make sure that
  # you have loaded a kernel driver for your USB host controller and have setup
  # the USB system correctly. See man sane-usb for details.
...

If I instead run sudo sane-find-scanner, I get
$ sudo sane-find-scanner

  # sane-find-scanner will now attempt to detect your scanner. If the
  # result is different from what you expected, first make sure your
  # scanner is powered up and properly connected to your computer.

  # No SCSI scanners found. If you expected something different, make sure that
  # you have loaded a kernel SCSI driver for your SCSI adapter.

found USB scanner (vendor=0x04b8 [EPSON], product=0x0131 [EPSON Scanner]) at libusb:001:009
could not fetch string descriptor: Pipe error
could not fetch string descriptor: Pipe error
  # Your USB scanner was (probably) detected. It may or may not be supported by
  # SANE. Try scanimage -L and read the backend's manpage.

So what do I do?  scanimage -L does nothing for me and I don't know what the "backend's manpage" might be.  It's seems likely that this is a permissions issue since the scanner can be found as root, but I don't know how to solve it.  Can someone help?
Update:
I had also tried simple-scan and xsane.  Neither of them could find the scanner.  That was what led me to try sane-find-scanner.

A:

My scanner(Epson Perfection V-300 Photo is NOT supported). So how did it ever work with Ubuntu 10.04? "Perfection V300 Photo    USB 0x04b8/0x0131 Unsupported   supported by the epkowa backend plus non-free interpreter".  Thanks to Marc for giving me a place to look, the first step there got me this information, which brought back the memories of what I had to do to get this to work with Ubuntu 10.04.  I downloaded the drivers and everything just worked.
I would say that the error message in sane-find-scanner is less helpful than it easily might be.
Instead of just
  # Your USB scanner was (probably) detected. It may or may not be supported by
  # SANE. Try scanimage -L and read the backend's manpage.

they could have easily included a link to http://www.sane-project.org/sane-mfgs.html and saved me hours of wasted time investigating.


Q:

What would it look like inside an Alcubierre field?

For the purpose of this questions, let's assume my crew has solved all those nasty problems of survivability inside the field, not unleashing a devastating blast of particles at their destination, and energy requirements.
What would the solar system look like to someone inside the ship while the Drive was active? If they for some reason decided to look at the Sun through a window, what would they see travelling away from it? Would they even be able to see anything at all?

A:

According to wikipedia (which is more than sufficient for a layman-level discussion, hard-science or otherwise):

The Alcubierre drive [...] is a speculative idea [...] by which a spacecraft could achieve apparent faster-than-light travel [...].
Rather than exceeding the speed of light within a local reference frame, a spacecraft would traverse distances by contracting space in front of it and expanding space behind it, resulting in effective faster-than-light travel.

When I was getting my degree in physics (almost two decades ago), I wrote a paper on the visual effects of near-luminous travel.  While this isn't the same thing, there are two similar circumstances that immediately leap out at me - both dealing with changes in angles: shape and color.
First, the shape of things changes.  The more the space ahead of you contracts (and the space behind you expands), the 'smaller' things ahead of you look and the 'bigger' the things behind you appear.  Angles of objects slightly off-center ahead contract until - at some limit - they appear directly ahead; the more contraction of space, the tighter the new angle.  For instance, if you are heading straight for a very large object (a galaxy, for instance, so we don't run into it right away), and it forms a rough circle directly ahead, the more the space contracts, the smaller that circle will be as the center remains unchanged by the edges contract in.  A similar, but reversed, effect happens to objects behind you: they expand the 'cone' from you to them.  A circular galaxy directly behind you will expand as the center remains unchanged by the edges all widen.  At extremes, things directly behind you will seem to be 'swallowing' you as the angles pass 90°...
Second, the color of things changes, too.  The very wavelength of light undergoes the same contraction (ahead) and expansion (behind).  Wavelength of light affects, among other things, color - so things ahead of you will tend to "blueshift" and things behind you will tend to "redshift."  At smaller 'levels' of contraction and expansion, this would just make things look weird... but the electromagnetic spectrum is more than just the visual spectrum.  At extremes, things behind you will shift beyond red into the infrared then micro- and radio waves, and things ahead of you will shift beyond blue into the ultraviolet then into ionizing radiation.  Hopefully, your culture that has invented a working FTL drive understands that they'll need radiation shielding...
For near-luminous travel, these two effects don't start becoming really interesting until you hit something like 0.99999c, though they'll be visible to the naked eye long before that.  The question then, becomes, how much "contracting" and "expanding" of space you're doing in your drive.  (I'd provide equations, but I'd have to dig them out of a box in the basement - and while they don't require anything too nasty math-wise, they do involve four-dimensional vector matrices, which gives mathphobes nightmares.  I haven't touched this stuff in close to two decades, so I'd rather not try to wrap my head around the actual physics - just the high-level layman descriptions.)


Q:

await method causing incompatibleClassChangeError: implementing class

I'm using play-1.2.5. For async I'm using await() method in my controller. but that await() causing IncompatibleClassChangeError during my application startup. I really don't understand the reason.
when I comment await() line, that error gone away.
here is my Contoller action:
public static void loadScheduledConfigs() {
    Future<JsonObject> future = Startup.THREAD_POOL.submit(new MyCallable());
    JsonObject object = null;
    /*
    I also tried this
        Future<JsonObject> future =  new FutureTask<JsonObject>( new MyCallable());
        JsonObject object =  await(future);
    */
    try{
        object = future.get();
    }catch(Exception e) {
        log.error(e.getMessage(), e);
    }
    renderJSON(object);
}

Exception:
Oops: IncompatibleClassChangeError
An unexpected error occured caused by exception IncompatibleClassChangeError: Implementing class

play.exceptions.UnexpectedException: Unexpected Error
    at play.Invoker$Invocation.onException(Invoker.java:244) ~[play-1.2.5rc4.jar:na]
    at play.Invoker$Invocation.run(Invoker.java:286) ~[play-1.2.5rc4.jar:na]
    at Invocation.HTTP Request(Play!) ~[na:na]
Caused by: java.lang.IncompatibleClassChangeError: Implementing class
    at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.7.0_07]
    at java.lang.ClassLoader.defineClass(ClassLoader.java:791) ~[na:1.7.0_07]
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.7.0_07]
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) ~[na:1.7.0_07]
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71) ~[na:1.7.0_07]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361) ~[na:1.7.0_07]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355) ~[na:1.7.0_07]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.7.0_07]
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354) ~[na:1.7.0_07]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423) ~[na:1.7.0_07]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) ~[na:1.7.0_07]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356) ~[na:1.7.0_07]
    at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.7.0_07]
    at java.lang.ClassLoader.defineClass(ClassLoader.java:791) ~[na:1.7.0_07]
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.7.0_07]
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) ~[na:1.7.0_07]
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71) ~[na:1.7.0_07]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361) ~[na:1.7.0_07]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355) ~[na:1.7.0_07]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.7.0_07]
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354) ~[na:1.7.0_07]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423) ~[na:1.7.0_07]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) ~[na:1.7.0_07]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356) ~[na:1.7.0_07]
    at play.classloading.enhancers.ContinuationEnhancer.enhanceThisClass(ContinuationEnhancer.java:74) ~[play-1.2.5rc4.jar:na]
    at play.CorePlugin.enhance(CorePlugin.java:297) ~[play-1.2.5rc4.jar:na]
    at play.plugins.PluginCollection.enhance(PluginCollection.java:551) ~[play-1.2.5rc4.jar:na]
    at play.classloading.ApplicationClasses$ApplicationClass.enhance(ApplicationClasses.java:235) ~[play-1.2.5rc4.jar:na]
    at play.classloading.ApplicationClassloader.loadApplicationClass(ApplicationClassloader.java:167) ~[play-1.2.5rc4.jar:na]
    at play.classloading.ApplicationClassloader.getAllClasses(ApplicationClassloader.java:431) ~[play-1.2.5rc4.jar:na]
    at play.Play.start(Play.java:516) ~[play-1.2.5rc4.jar:na]
    at play.Play.detectChanges(Play.java:642) ~[play-1.2.5rc4.jar:na]
    at play.Invoker$Invocation.init(Invoker.java:198) ~[play-1.2.5rc4.jar:na]
    ... 1 common frames omitted

I don't know either problem is in the way I code, or some dependencies comflict causing this issue. (I checked my lib folder and classpath/dependencies of my project, I did not find any conflicting library)

A:

I got the solution. it's asm.jar who was creating issue. I'm using kryo for serialization. kryo and play both has asm.jar as a dependency. So i have two different version of asm.jar in my class path. one that comes with kryo and other one that comes with play framework. that was causing issue.
I removed one asm.jar and that exception gone away.


Q:

Why do we use Laplace transforms to analyse transient circuits?

I just learned transient circuits and we solved them both in the time domain and the Laplace domain and I can't understand why we would use the Laplace domain as it seems it is a lot more simple to use the time domain especially in series RLC circuits.

A:

It's easy to solve simple filter circuits in the time domain but there becomes a tipping-point where most engineers would prefer to solve problems in the frequency domain and apply (for example) a step-function. Finding the inverse Laplace is fairly straightforward because of Laplace tables.
As an example of an RLC low pass filter, engineers become accustomed to the transfer function: -
$$H(s) = \dfrac{\omega_n^2}{s^2+2\zeta\omega_n^2 s + \omega_n^2}$$
And, applying (for example) a step function is as simple as multiplying by 1/s: -
$$\dfrac{1}{s}\cdot\dfrac{\omega_n^2}{s^2+2\zeta\omega_n^2 s + \omega_n^2}$$
Engineers who are familiar with this get to recognize that this converts to a standard form and the next step is just using the tables to derive the transient response.
In addition, the term \$\omega_n\$ (the natural resonant frequency) can be is factored out a lot of the time so that solving the step-function formula for \$\omega_n=1\$ begins with: -
$$\dfrac{1}{s}\cdot\dfrac{1}{s^2+2\zeta s + 1}$$
This is rearranged to a standard form such as this (underdamped resonance): -
$$\dfrac{1}{s[(s+a)^2 + b^2]}$$
Where \$a =\zeta\$ and \$b=\sqrt{1-\zeta^2}\$
The Laplace tables give us this: -
$$H(t) = 1+\dfrac{1}{\sqrt{1-\zeta^2}}\cdot e^{-\zeta t}\cdot \sin(t\cdot\sqrt{1-\zeta^2}+\phi)$$
Where \$\phi = \arccos(\zeta)\$
But you will probably only be convinced when you are dealing with slightly more complex situations or really do need to analyse the frequency spectrum.

A:

In this context, the Laplace transform is simply a tool that we use to deal with differential equations.  I think it provides a slightly more intuitive feel for how responses change with frequency, but really, it's just a tool for dealing with differential equations.
The transform really starts to shine when you're cascading signals.  A variety of properties of the transform really become very useful then.  For example, convolutions in the time domain become simple multiplications in the frequency domain.  There are also a variety of frequency domain tools  that make control easier.
You start using the transforms for simple systems, so you're facile when you start using them for more advanced situations -- not because they're so intuitively easy.  In fact, the understanding is very quantal.  You'll be able to "do" problems successfully, but it may take many iterations, even years, before you grok the transforms.


Q:

Can clang warn about undefined behavior at compile-time?

#include <iostream>

int main()
{
    int n = -1000;
    for (int i(0); i != n; ++i)
    {
    }
}

In gcc the following error is caught at compile-time:
main.cpp:6:5: warning: iteration 2147483647u invokes undefined behavior [-Waggressive-loop-optimizations]

     for (int i(0); i != n; ++i)

Clang's -fsanitize=undefined is a run-time mechanism. What is clang's compile-time equivalent?

A:

Undefined behaviour is often described as such in the standard because it is difficult if not impossible for the compiler to check this in all situations.
You just run into one case that is handled by GCC and not Clang. If you look, you'll be able to find cases that are handled by one but not another compiler. That's because they're not the same compiler, and have different analyses that they perform.

A:

Clang can't catch this one yet, at least not as part of compiling (I haven't checked the clang static analyzer, and if it also can't, please file a bug).
GCC has decided that it's okay to emit warnings from the middle of the optimizer:
$ g++ -Waggressive-loop-optimizations a.cc
$ g++ -Waggressive-loop-optimizations a.cc -O2
a.cc: In function ‘int main()’:
a.cc:6:5: warning: iteration 2147483647u invokes undefined behavior [-Waggressive-loop-optimizations]
     for (int i(0); i != n; ++i)
     ^
a.cc:6:5: note: containing loop

This is actually really tricky and potentially finicky. The clang developers believe that changing what warnings you emit based on optimization level is bad behaviour, we don't think users expect to miss warnings when building at -O0 or to discover new bugs days later when doing a release build. Secondly, the way that the optimizer is designed is such that it keeps one representation of the program around at any point in time and transforms it from saying one thing to another without keeping a history trail of what it's done versus what's in the original code. This LLVM blog article talks about the problem. Clang's warnings are built on top of clang's ASTs which have a complete representation of the original source code, including template and macro histories so we can always point to the right code and filter on properties like "was it a template argument".
It might be possible to add this to clang, I haven't figured out an efficient way to do it after only 30 seconds of thinking about it. The problem is that we're willing to spend a lot more time proving things in the optimizer than we are as part of warning generation. We don't want to pay the compile time twice. The static analyzer on the other hand, doesn't have this restriction and will happily do very expensive work to find your bugs.
Finally, the way you phrased your question makes it sound like you think that clang either does or doesn't catch all undefined behaviour at compile time. We do catch as much as we can efficiently, and provide dynamic checkers for as much of the rest as possible, but neither gcc nor clang will promise to catch all undefined behaviour either at compile time nor at run time. There's too much of it, and there is no list of what it all is (some operations are explicitly UB in the standard, some are UB simply because the standard fails to define what the behaviour is!).


Q:

PL/SQL to Select a Partition Window of Data

Working with Oracle 11g here.
I'm trying to figure out how to write a specific query against a sample table below:
 ID TYPE   PRIORITY    STATUS   DATE
 ----------------------------------------------------
 1  Q      A           NEW      01-OCT-2009
 1  Q      A           NEW      01-OCT-2009
 1  Q      A           NEW      01-OCT-2009
 1  Q      A           NEW      01-OCT-2009
 1  Q      A           NEW      01-OCT-2009
 1  Q      A           NEW      01-OCT-2009
 1  Q      A           NEW      01-OCT-2009
 1  Q      A           NEW      01-OCT-2009
 2  R      B           NEW      01-OCT-2009
 2  R      B           NEW      01-OCT-2009
 2  R      B           NEW      01-OCT-2009
 2  R      B           NEW      01-OCT-2009
 3  R      A           NEW      01-OCT-2009
 3  Q      A           NEW      01-OCT-2009
 3  Q      A           NEW      01-OCT-2009

Here is the pseudo-PL/SQL of what I want the query to do:
 SELECT ID, TYPE
 FROM DATA_TABLE
 WHERE ROWNUM = 1 AND STATUS = 'NEW'
 GROUP BY ID, TYPE
 ORDER BY PRIORITY, DATE

I want to grab the next group of ID, TYPE that has a status NEW ordered by priority and date.
In the case above the statement should return either 1 Q or 3 Q, but not both, since they have the same priority and date. If 3 Q was set to STATUS='DONE' then the query should return 1 Q.
For the second step I'm going to join this data back in to the table to grab the rows for the set I want to process (eg: 1 Q). This doesn't have to be a two-step process; if I can grab the set of rows to process without the join that would be ideal.
I hope I'm just missing something really simple, but I'm open to using analytic functions for partitioning if need be.

A:

SELECT * FROM (SELECT ID, TYPE FROM DATA_TABLE WHERE STATUS = 'NEW' ORDER BY PRIORITY, DATE) WHERE ROWNUM = 1

That ought to work. You don't want to group by ID and TYPE because you're not actually trying to perform any sort of aggregation on the rows matching a given ID and TYPE. If you only cared about one column (say DATE) you could say
SELECT ID, TYPE FROM DATA_TABLE WHERE DATE = (SELECT MIN(DATE) FROM DATA_TABLE) AND ROWNUM = 1

and avoid sorting the whole table. But I don't see how to make that work here.


Q:

How can I allocate a piece of memory from a certain physical memory in embedded arm processor?

I am using zynq device, trying to transfer data from DRAM to the peripheral of ARM by a piece of standalone program (without OS). In the example code, I found this code to statement the source address and destination address of the transaction.
volatile static u8 SrcBuffer[BUFFER_BYTESIZE] __attribute__ ((aligned (64)));
volatile static u8 DestBuffer[BUFFER_BYTESIZE] __attribute__ ((aligned (64)));

Since there's no OS, what's the value of address from? How can I change it?

A:

You need to define a section a in the linker file and then place the data in it using (for GCC):
__attribute__ (( section ( "your_section" ) ) )
In the linker file (will have other stuff in it already as well) something like:
MEMORY
{
   ....will be other stuff here
   ....
   YOUR_MEMORY_NAME : ORIGIN = 0xWhatever, Length = a_length // Creates a memory region
}

SECTIONS
{
   ...
   ...

   .something_data :
   {
      *(your_data)
   } > YOUR_MEMORY_NAME

   ...

}


Q:

PHP Undefined variable $_LIT["something"]

In my config.php, I have this array:
$_LIT = array(
    /* Адрес сайта */
    "url" => "http://learnit.loc/", // Адрес сайта
....
);

The problem is, that I cant use this array in code below:
For example, I have a mail-method and I have to put $_LIT["url"] in my special link variable.:
function testMethod($username, $email) {
$link = $_LIT["url"]."scipts/activate.php?link=".rand(0, 999999).rand(0, 999999).rand(0, 999999).rand(0, 999999).$username."activationLink";
}

And... I cant use it ($_LIT["url"]). It just put nothing, where the site url should be.
What I can also say, that I use my config.php in my ohter .php files using "require_once" "config.php". So I can get $_LIT["something"] there, but not directly in confing.php. Why?
Thanks for every help.

A:

The variables that are outside of functions scope cannot be accessed directly.
You need to use the keyword global inside function.
like  global $_LIT
$link = $_LIT["url"]."scipts/activate.php?link=".rand(0, 999999).rand(0, 999999).rand(0, 999999).rand(0, 999999).$username."activationLink";

Link to Documentation.
http://php.net/manual/en/language.variables.scope.php
---- update----
function testMethod($username, $email) {
    global $_LIT;

     $link = $_LIT["url"]."scipts/activate.php?link=".rand(0, 999999).rand(0, 999999).rand(0, 999999).rand(0, 999999).$username."activationLink";
}


Q:

Chebyshev-like polynomials with integral roots

Chebyshev polynomials have real roots and satisfy a recurrence relation. I was wondering if one can find a sequence of polynomials with integral or rational roots with similar properties. More precisely, one is looking for a sequence of polynomials $(f_n),f_n\in\mathbf{Q}[t]$ such that

$\deg f_n\to\infty$ as $n\to\infty$;
$\sum_{n=0}^\infty f_n(t) x^n$ is (the Taylor series of) a rational function $F$ in $x$ and $t$.
All roots of any $f_n$ are integer and have multiplicity 1. (A weaker version: the roots are allowed to be rational and are allowed to have multiplicity $>1$ but there should be an $a>0$ such that the number of distinct roots of $f_n$ is at least $a\deg f_n$.)

A:

I can satisfy conditions 1, 3 and almost satisfy condition 2.  Letting $f_n(t) = {t+n-1 \choose n}$ we have the well-known generating function
$\displaystyle \sum_{n \ge 0} f_n(t) x^n = \frac{1}{(1 - x)^{-t}}$
which is rational in $x$ for any fixed integer value of $t$.  I think condition 2 will end up being the hardest to satisfy because rational functions are quite rigid.

Edit 1:  My current opinion is that the conditions are not satisfiable.  Based on the analogous situation with linear homogeneous recurrences on the integers I am going to conjecture that any polynomial sequence which obeys a polynomial linear recurrence and is not essentially a geometric series has terms divisible by irreducible polynomials of arbitrarily high order.
Edit 2:  A very strong result available in the integer case is Zsigmondy's theorem, but we don't need a result this strong.  Here's a nice result in the integer case.  Suppose an integer sequence $a_n$ satisfies a linear homogeneous recurrence with integer coefficients, and let $p$ be a prime not dividing those coefficients.  Then the sequence $a_n \bmod p$ is periodic (not just eventually periodic) $\bmod p$ by Pigeonhole.  If in addition there exists $n$ such that $a_n = 0$ and $a_n$ is unbounded, then it follows that there is a nonzero term of the sequence divisible by $p$.  For example, this is true of the Fibonacci sequence; in fact we have the much stronger result that for $p > 5$, either $p | F_{p+1}$ or $p | F_{p-1}$.
My guess is that a result like this holds in the polynomial case with $p$ replaced by a monic irreducible polynomial (say, of degree $2$), although the argument above breaks down as written.

A:

Here's one thought.  For each integer k, f_n(k) satisfies a recurrence relation.  If the roots of f_n are all integers, then f_n(k) and f_n(k+1) have to be "in sync" in the sense that they never have opposite sign.  This is a strong condition!  For instance, suppose the sequences f_n(k) and f_n(k+1) each have unique largest eigenvalue:  then these eigenvalues would have to have the same argument.
Update:  Qiaochu's answer suggests that in fact working mod p would be just better than the "archimedean" picture sketched above, since it is really F_q[t], not Z[t] or Q[t], that is analogous to the integers.  Let F_n(t) be the reduction of f_n(t) to F_p[t].  If f_n(t) has all roots rational for every n, then the reduction of f_n(t) mod p has the same property.  But now we are saying something quite strong; that f_n(t) lies in a finitely generated subgroup of F_q(t)^*!  This is presumably ruled out by Mason's theorem (ABC for function fields.)  Indeed, you could probably prove in this way that not only are the roots of f_n(t) not rational, but f_n(t) has irreducible factors of arbitrarily large degree.
I don't think this approach would touch a harder question along the same lines like this one.


Q:

Spring does not use autowired constructor for loading the bean

I have autowired Address bean into the constructor of Employee bean. And expect when getting instance of Employee bean I should get an instance of Address inside it. But Spring container is using no-args constructor of Employee to return the instance. Below is my code
public class Address {
    public void print(){
        System.out.println("inside address");
    }
}

public class Employee {

    private Address address;

    @Autowired
    public Employee(Address address){
        this.address = address;
    }

    public Employee(){}

    public Address getAddress(){
        return address;
    }
}

@Configuration
@ComponentScan(basePackages={"com.spring"})
public class ApplicationConfig {

    @Bean
    public Employee employee(){
        return new Employee();
    }

    @Bean
    public Address address(){
        return new Address();
    }
}

public class Main {

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
        Employee employee = (Employee)context.getBean("employee");
        // Here add is null !!
        Address add = employee.getAddress();
    }
}

A:

The no-arg constructor is being used because that's the one that you're calling (new Employee()):
@Bean
public Employee employee() {
    return new Employee();
}

Since you're manually creating the Employee instance, rather than having Spring create it for you, you'll also have to pass in the Address yourself:
@Bean
public Employee employee() {
    return new Employee(address());
}

Note that multiple calls to address() will in fact return the same bean, rather than multiple new instances, if that was your concern.
Otherwise, the alternative is to have Employee annotated with @Component, after which Spring will automatically create the bean for you and wire in the Address dependency. You get that for free since you have component scanning turned on (assuming that Employee is in the package that you're scanning). If you go this route, you can remove the employee() bean definition from your config class, otherwise one may end up overriding the other.


Q:

Run erlang code from browser and get response?

Hello awesome community!
I've started learning erlang recently. (It's quite mind bending) :)
I can't seem to find an answer anywhere.... but as a way to learn, I'm trying to create a mini shell in my web browser.
For example, I want to enter some actual erlang code into a text box, press enter and return what ever the result is and display it on the web page.
> Awesome = 41 + 41.
> io:format("Awesome = ~p", Awesome).
> 82

I've set up a simple erlang server on my localhost on port 8891 and can easily connect to it.
Is it possible to send it erlang code to run and output the response?
Any help would be appreciated! :)

A:

This can be achieved using erl_scan, erl_parse, erl_eval as mentioned in this link.
The problem is for Variable bindings. Need to know the variable bindings when it is used in an expression (more difficult when it is inside a fun)
1> Expr="Awesome = 41 + 41.".
"Awesome = 41 + 41."
2> {ok, Tokens, _} = erl_scan:string(Expr).
{ok,[{var,1,'Awesome'},
     {'=',1},
     {integer,1,41},
     {'+',1},
     {integer,1,41},
     {dot,1}],
    1}
3> {ok, [Form]} = erl_parse:parse_exprs(Tokens).
{ok,[{match,1,
            {var,1,'Awesome'},
            {op,1,'+',{integer,1,41},{integer,1,41}}}]}
4> {value, Value, Binding} = erl_eval:expr(Form, []).
{value,82,[{'Awesome',82}]}

When the user enters Awesome = 41 + 41. in the browser you can send back the response as 82.
You also need to maintain the state of the Expression. That is the Binding should be maintained can be used as follows
5> FunStr ="io:format(\"Awesome = ~p\", [Awesome]).".
"io:format(\"Awesome = ~p\", [Awesome])."
6> {ok, Tokens1, _} = erl_scan:string(FunStr).
{ok,[{atom,1,io},
     {':',1},
     {atom,1,format},
     {'(',1},
     {string,1,"Awesome = ~p"},
     {',',1},
     {'[',1},
     {var,1,'Awesome'},
     {']',1},
     {')',1},
     {dot,1}],
    1}
7> {ok, [Form1]} = erl_parse:parse_exprs(Tokens1).
{ok,[{call,1,
           {remote,1,{atom,1,io},{atom,1,format}},
           [{string,1,"Awesome = ~p"},
            {cons,1,{var,1,'Awesome'},{nil,1}}]}]}
8> {value, Fun1, _} = erl_eval:expr(Form, Binding).
{value,82,[{'Awesome',82}]}

9> {value, V, _} = erl_eval:expr(Form1, Binding).
Awesome = 82{value,ok,[{'Awesome',82}]}

The Binding list should grow till the end of the session.


Q:

Client doesn't get new IP when switching between subnets/locations

So here is our setup.
We have 14 locations each with its own subnet and router. The routers at these locations have DHCP relay enabled that points back to our central server that is running DHCP.
This DHCP server (Windows 2008 R2) has a Superscope and then our 14 other scopes inside of it. So far everything has been working and all the locations have been getting the appropriate IP addresses.
However, when a user goes between locations they never receive a new IP address. Their machine holds on to the same IP from the previous subnet and the DHCP does not hand them a new one. It won't even work if we do a release/renew.
I have to go into the DHCP Server and physically delete their IP entry in order for them to get a new IP at the new location.
Any Ideas?

A:

You don't want a superscope for this set up. The goal of a superscope is multiple networks on a shared physical segment. The DHCP server thinks these IPs are valid for anywhere inside the superscope.


Q:

Exporting a database to a different schema

I am creating an web application which is replacing the outdated one I currently use. The database is also outdated and horribly structured. For testing purposes I would like to export the old database and load it into the new one to have test data for the new web application. However, because of the schema changes to the database I need to manually change:

Table names
Column names

Example:
Old Database Table: part
id | date | user

New Database Table: apx_parts
id | date_created | user_id

Is there a MySQL tool or something to automate this? Would it have to be self-written in a scripting language?
Edit
Just to clarify, the reason I want it automated is because I want to use the most recent data that the old application is collecting.

A:

You're probably thinking about using mysqldump to copy the schema and data over.  Instead, think about exporting the data by itself.
Create the new database and tables as you normally would.
Export the data from the old database using SELECT...INTO.  Column names don't matter here.  If there are new columns in the new database, you can compute their values in this SELECT or just ignore them.
Import the data into the new database using LOAD DATA
Good luck.


Q:

Bootstrap tabs not changing the content when clicked more than once

I have been trying to implement tab into one of my pages. The code is as follows.

Vehicles

Battery

Charging

What I have done is, I have created two columns, one containing the links and the other containing the region where the data should be shown according to the link clicked. When run, the code actually works for once, i.e. the when the links are clicked for the first time, it shows the respective content on the right. But when I try to access another link, it does not work. It sort of works one time only. What should I do to make them work no matter how many times I want to toggle between data?

A:

You didn't add the 'nav nav-tabs' list container for your nav-tabs. Right now your all links are working as an independent internal link. Hence it works for just one click.
Here is update code

Vehicles

Battery

Charging

Let me know if it meets your requirements.


Q:

What is the Biblical basis against being able to predict the date of the end of the world?

Recently, there have been a few people (e.g. Harold Camping) who have predicted the end of the world.  Historically, the Jehovah's Witnesses (Watchtower Bible & Tract Society) have also predicted the end of the world several times.
What is the Biblical basis for the claim that no one can predict the date that the world will end?

A:

Jesus taught that we might be able to read the signs that it was near, but that no one would be able to know what day the end would come:

"From the fig tree learn its lesson: as soon as its branch becomes tender and puts forth its leaves, you know that summer is near. So also, when you see these things taking place, you know that he is near, at the very gates. Truly I tell you, this generation will not pass away until all these things have taken place. Heaven and earth will pass away, but my words will not pass away. But about that day or hour no one knows, neither the angels in heaven, nor the Son, but only the Father. Beware, keep alert; for you do not know when the time will come. It is like a man going on a journey, when he leaves home and puts his slaves in charge, each with his work, and commands the doorkeeper to be on the watch. Therefore, keep awake—for you do not know when the master of the house will come, in the evening, or at midnight, or at cockcrow, or at dawn, or else he may find you asleep when he comes suddenly. And what I say to you I say to all: Keep awake." —Mark 13:28-37

A:

What is the Biblical basis against being able to predict the date of the end of the world?
Here are a couple of more verses.

Acts 1:6-7  When they therefore were come together, they asked of him,
  saying, Lord, wilt thou at this time restore again the kingdom to
  Israel?   And he said unto them, It is not for you to know the times
  or the seasons, which the Father hath put in his own power.
1 Thessalonians 5:2-3  For yourselves know perfectly that the day of
  the Lord so cometh as a thief in the night.   For when they shall say,
  Peace and safety; then sudden destruction cometh upon them, as travail
  upon a woman with child; and they shall not escape.


Q:

Navigation in ReactNative

I want to navigation between two screen . I am try lot of code but not successul yet Here i am try this get undefined is not an object(RNGestureHandlerModule.State). Please help i am new in react native please check any help would be appreciated. If their any tuturial to proper guide please help let me know
My App.Js Look Like
 import React, {Component} from 'react';
    import {Platform, StyleSheet, Text, View} from 'react-native';
    import AppNavigator from './AppNavigator';

    type Props = {};
    export default class App extends Component<Props> {
      render() {
        return (

         <AppNavigator/>

        );
      }
    }

My appnavigation look like

    import { createStackNavigator } from 'react-navigation';
    import Home from './Home';
    import Friends from './Friends';

        const AppNavigator = createStackNavigator({
            Home: { screen: Home },
           Friends: { screen: Friends},
        });

        export default AppNavigator;

My Friend.js look Like
import React, {Component} from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';

type Props = {};
export default class Friends extends Component<Props> {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
          <Button
           title="Back to home"
          onPress={() =>
            this.props.navigation.navigate('Home')
          }
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
My HOme.js

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';

type Props = {};
export default class Home extends Component<Props> {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
          <Button
          title="Back to home"
          onPress={() =>
            this.props.navigation.navigate('Home')
          }
        />

      </View>
    );
  }
}

A:

It is not linked to Navigation library. The issue is linked to 'RNGestureHandlerModule'. I assume you are using another library, probably 'react-native-gesture-handler'. Try removing and linking it using react-native link.
Found this related post here

A:

You are using the latest reactnavigation library. It requires to install react-native-gesture-handler. But if you are using Expo, you don't need to install this library since its already included in the sdk.
After by installing the react-native-gesture-handler library, run the react-native link command to link all the native dependencies.


Q:

Dracut-Kernel update required but won't when running Yum on Centos 6.6

I'm a fair newbie when it comes to Linux, but I'm having problems updating a small Centos 6.6 box that's been working fine and updating previously.
When running yum update I get the error below. I've tried running yum -clean all as per another post on a similar issue but that hasn't helped.
--> Processing Dependency: dracut-kernel >= 004-388.el6 for package: kernel-2.6.32-573.1.1.el6.x86_64
--> Finished Dependency Resolution
Error: Package: kernel-2.6.32-573.1.1.el6.x86_64 (updates)
           Requires: dracut-kernel >= 004-388.el6
           Installed: dracut-kernel-004-256.el6.noarch (@anaconda-CentOS-201112091719.x86_64/6.2)
               dracut-kernel = 004-256.el6
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

A:

Yum clean had been tried (as detailed in my original post) but didn't help.
I eventually found a line exclude=dracut in yum.conf which is bizarre as I certainly didn't put it there and only I have access to the machine.  I presume something has automatically added it for some reason, but problem solved now anyway.