问:
Installing rpy2 to work with R 3.4.0 on OSX
I would like to use some R packages requiring R version 3.4 and above. I want to access these packages in python (3.6.1) through rpy2 (2.8).

I have R version 3.4 installed, and it is located in /Library/Frameworks/R.framework/Resources However, when I use pip3 install rpy2 to install and use the python 3.6.1 in /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6) as my interpreter, I get the error:

Traceback (most recent call last):
    File "/Users/vincentliu/PycharmProjects/magic/rpy2tester.py", line 1, in
      from rpy2 import robjects
    File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/rpy2/robjects/init.py", line 16, in
      import rpy2.rinterface as rinterface
    File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/rpy2/rinterface/init.py", line 92, in
      from rpy2.rinterface._rinterface import (baseenv,
  ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/rpy2/rinterface/_rinterface.cpython-36m-darwin.so, 2): Library not loaded: @rpath/libiconv.2.dylib
    Referenced from: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/rpy2/rinterface/_rinterface.cpython-36m-darwin.so
    Reason: Incompatible library version: _rinterface.cpython-36m-darwin.so requires version 8.0.0 or later, but libiconv.2.dylib provides version 7.0.0

Which first seemed like a problem caused by Anaconda, and so I remove all Anaconda-related files but the problem persists.

I then uninstalled rpy2, reinstalled Anaconda and used conda install rpy2 to install, which also installs R version 3.3.2 through Anaconda. I can then change the interpreter to /anaconda/bin/python and can use rpy2 fine, but I couldn't use the R packages I care about because they need R version 3.4 and higher. Apparently, the oldest version Anaconda can install is 3.3.2, so is there any way I can use rpy2 with R version 3.4?

I can see two general solutions to this problem. One is to install rpy2 through conda and then somehow change its depending R to the 3.4 one in the system. Another solution is to resolve the error

Incompatible library version: _rinterface.cpython-36m-darwin.so requires version 8.0.0 or later, but libiconv.2.dylib provides version 7.0.0

After much struggling, I've found no good result with either.

答:
I uninstalled rpy2 and reinstalled with --verborse. I then found

ld: warning: ignoring file /opt/local/lib/libpcre.dylib, file was built for x86_64 which is not the architecture being linked (i386): /opt/local/lib/libpcre.dylib
      ld: warning: ignoring file /opt/local/lib/liblzma.dylib, file was built for x86_64 which is not the architecture being linked (i386): /opt/local/lib/liblzma.dylib
      ld: warning: ignoring file /opt/local/lib/libbz2.dylib, file was built for x86_64 which is not the architecture being linked (i386): /opt/local/lib/libbz2.dylib
      ld: warning: ignoring file /opt/local/lib/libz.dylib, file was built for x86_64 which is not the architecture being linked (i386): /opt/local/lib/libz.dylib
      ld: warning: ignoring file /opt/local/lib/libiconv.dylib, file was built for x86_64 which is not the architecture being linked (i386): /opt/local/lib/libiconv.dylib
      ld: warning: ignoring file /opt/local/lib/libicuuc.dylib, file was built for x86_64 which is not the architecture being linked (i386): /opt/local/lib/libicuuc.dylib
      ld: warning: ignoring file /opt/local/lib/libicui18n.dylib, file was built for x86_64 which is not the architecture being linked (i386): /opt/local/lib/libicui18n.dylib
      ld: warning: ignoring file /opt/local/Library/Frameworks/R.framework/R, file was built for x86_64 which is not the architecture being linked (i386): /opt/local/Library/Frameworks/R.framework/R

So I supposed the reason is the architecture incompatibility of the libiconv in opt/local, causing make to fall back onto the outdate libiconv in usr/lib. This is strange because my machine should be running on x86_64 not i386. I then tried export ARCHFLAGS="-arch x86_64" and reinstalled libiconv using port. This resolved the problem.


来源: stackexchange

问:
JTextPane / HTMLEditorKit memory leak
I have the following issue with an app of mine, a basic IRC tool, which adds messages to a "JTextPane" with using "HTMLEditorKit" as an output GUI. I noticed, that randomly but over time, my app was using more and more memory, easily blowing up in crowded channels to already 300MB after just about 20 minutes of usage. I think the problem is somehow related to "JTextPane", because I can reproduce the issue with this code:

```<code>package javaapplication26;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultCaret;
import javax.swing.text.Element;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;

public class NewJFrame extends javax.swing.JFrame {

    private long globalCount = 0;

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {

        initComponents();

        this.setSize(500, 200);
        this.setLocationRelativeTo(null);

        this.jTextPane1.setEditorKit(new HTMLEditorKit());
        this.jTextPane1.setContentType("text/html");

        this.jTextPane1.setText("<html><body><div id=\"GLOBALDIV\"></div></body></html>");

        this.jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        this.jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

        DefaultCaret caret = (DefaultCaret) this.jTextPane1.getCaret();
        caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);

        this.jScrollPane1.setAutoscrolls(false);
        this.jTextPane1.setAutoscrolls(false);

        Thread fillThread = new Thread() {

            @Override
            public void run() {

                while (!interrupted()) {

                    try {

                        removeFromPane(jTextPane1);
                        insertHTMLToPane(jTextPane1, "<div>"+globalCount+"</div>");
                        Thread.sleep(1);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                        break;
                    }
                }
            }
        };

        fillThread.start();
    }

    private void removeFromPane(JTextPane pane) {

        HTMLDocument doc = (HTMLDocument) pane.getDocument();
        Element element = doc.getElement("ID" + (this.globalCount - 10));

        if (element != null) {
            doc.removeElement(element);
        }
    }

    private void insertHTMLToPane(JTextPane pane, String htmlCode) {

        this.globalCount++;

        HTMLDocument doc = (HTMLDocument) pane.getDocument();

        Element element = doc.getElement("GLOBALDIV");

        if (element != null) {

            try {
                doc.insertBeforeEnd(element, "<div id=\"ID"+this.globalCount+"\">" + htmlCode + "</div>");
            } catch (BadLocationException | IOException ex) {
                Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setLayout(new java.awt.BorderLayout());

        jScrollPane1.setViewportView(jTextPane1);

        jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration
}
</code>```

The weird thing is, it doesnt happen with 100% chance when letting it run in Netbeans. Sometimes it stays around 70MB and never grows, but then running another time, it randomly explodes, and already grows to about 200-250MB after a minute or two.

I dont really know whats the data in memory growing more and more. It seems removing a line via "doc.removeElement(element)" doesnt always flags the object behind it to be cleared with next GC routine.

Letting it run in Netbeans with the profiler, I get something like this:

It seems there is some kind of "undo mechanism" keeping reference to all inserted lines? I am no expert in using the profiler though because I am not getting some logic out of it, where things like char[] and some other growing into the thousands, even if nothing happens in the program.

This though seems to hint, that whatever reason for, the JTextPane creates for each insert a new StyleSheet and keeps it forever in a HashTable:

I would welcome any help to find out why this is happening, or how to fix the issue. I am using latest 64bit JDK of course under Windows 10. Thank you very much

答:
Your fillThread is really scary and non-sense, for event sake, please do not go that way.

This thread is kind of lets eat resources, and beside java itself is heavy enough, it could make a great mess in system indeed.

You may invoke you business(remove last message and add new one) based on an event, here you may rely on a button click or enter key over the textbox.

Even if you are working with a stateless stuff(like http), you may increase the sleep time to something more senseful, maybe 1 second, or even more.

One possible issue(as I experienced too) could be over-lazy GC. I cannot say it 100%, but since your thread is eating(heavy work), GC could not find a time to go for memory.

Even beside JVM indicates it has threaded-GC, but it may not work over the memory and release the data sometimes(as you experienced too) parallel.

You may also check the hashmap you stated, and make sure all data need to be added and removed are done as expected.

Also your globalCount is not thread safe, you may use AtomicInteger instead.

ContentLicense: CC BY-SA 3.0

Title: JTextPane / HTMLEditorKit memory leak

Body:
I have the following issue with an app of mine, a basic IRC tool, which adds messages to a "JTextPane" with using "HTMLEditorKit" as an output GUI. I noticed, that randomly but over time, my app was using more and more memory, easily blowing up in crowded channels to already 300MB after just about 20 minutes of usage. I think the problem is somehow related to "JTextPane", because I can reproduce the issue with this code:

package javaapplication26;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultCaret;
import javax.swing.text.Element;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;

public class NewJFrame extends javax.swing.JFrame {

    private long globalCount = 0;

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {

        initComponents();

        this.setSize(500, 200);
        this.setLocationRelativeTo(null);

        this.jTextPane1.setEditorKit(new HTMLEditorKit());
        this.jTextPane1.setContentType("text/html");

        this.jTextPane1.setText("

");

        this.jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        this.jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

        DefaultCaret caret = (DefaultCaret) this.jTextPane1.getCaret();
        caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);

        this.jScrollPane1.setAutoscrolls(false);
        this.jTextPane1.setAutoscrolls(false);

        Thread fillThread = new Thread() {

            @Override
            public void run() {

                while (!interrupted()) {

                    try {

                        removeFromPane(jTextPane1);
                        insertHTMLToPane(jTextPane1, "
"+globalCount+"
");
                        Thread.sleep(1);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                        break;
                    }
                }
            }
        };

        fillThread.start();
    }

    private void removeFromPane(JTextPane pane) {

        HTMLDocument doc = (HTMLDocument) pane.getDocument();
        Element element = doc.getElement("ID" + (this.globalCount - 10));

        if (element != null) {
            doc.removeElement(element);
        }
    }

    private void insertHTMLToPane(JTextPane pane, String htmlCode) {

        this.globalCount++;

        HTMLDocument doc = (HTMLDocument) pane.getDocument();

        Element element = doc.getElement("GLOBALDIV");

        if (element != null) {

            try {
                doc.insertBeforeEnd(element, "
" + htmlCode + "
");
            } catch (BadLocationException | IOException ex) {
                Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setLayout(new java.awt.BorderLayout());

        jScrollPane1.setViewportView(jTextPane1);

        jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration
}

The weird thing is, it doesnt happen with 100% chance when letting it run in Netbeans. Sometimes it stays around 70MB and never grows, but then running another time, it randomly explodes, and already grows to about 200-250MB after a minute or two.

I dont really know whats the data in memory growing more and more. It seems removing a line via "doc.removeElement(element)" doesnt always flags the object behind it to be cleared with next GC routine.

Letting it run in Netbeans with the profiler, I get something like this:

It seems there is some kind of "undo mechanism" keeping reference to all inserted lines? I am no expert in using the profiler though because I am not getting some logic out of it, where things like char[] and some other growing into the thousands, even if nothing happens in the program.

This though seems to hint, that whatever reason for, the JTextPane creates for each insert a new StyleSheet and keeps it forever in a HashTable:

I would welcome any help to find out why this is happening, or how to fix the issue. I am using latest 64bit JDK of course under Windows 10. Thank you very much


问:
TinyMCE: get values from a listbox in a modal window
I'm creating a TinyMCE Plugin for Wordpress. It has a textbox and a listbox field, both staying in a modal window.
Code below:

```<code>(function () {
    tinymce.create('tinymce.plugins.windowdata', {
        init : function(ed, url) {
            ed.addButton('showModal', {
                title: 'Show Modal',
                image: url + '/img/button.png',
                onclick: function () {
                    ed.windowManager.open({
                        title: 'Minestra',
                        body: [
                            {type: 'textbox', name: 'Field', label: 'Number', value: '', tooltip: 'Tooltip', maxLength: 3, classes: 'i1n'}, //textbox
                            {type: 'listbox', label: 'Listbox', classes: 'i1lb', values: [
                                {text: '', value: ''},
                                {text: 'Number', value: 'lone_number'},
                                {text: 'Bar', value: 'bar'},
                            ]}, //listbox
                        ],
                        onsubmit: function () {
                            var n1 = document.getElementsByClassName('mce-i1n')[0].value; //textbox value
                            var t1 = document.getElementsByClassName('mce-i1lb')[0].getElementsByTagName('button')[0].getElementsByClassName('mce-txt')[0].innerHTML; //listbox value

                            ed.execCommand('mceInsertContent', 0, n1+' is of type '+t1) //write contents
                        }
                    })
                }
            });
    }
)
</code>```

My question is about how to get the field values. What i did works very well with the textbox (the n1 var inside the onsubmit() method), but the listbox gets the same text that is shown to TinyMCE user (the text var in each listbox item).

What i want is a way to get the value instead; plus, i suppose i didn't get the right way to do it, not even with textbox. Anyone can help me? Thank you.

答:
I solved by my own: i had to give a name to all of my fields:

```<code>    {type: 'textbox', name: 'Field', label: 'Number', value: '', tooltip: 'Tooltip', maxLength: 3, classes: 'i1n'}, //textbox
    {type: 'listbox', name: 'Listbox', label: 'Listbox', classes: 'i1lb', values: [
        {text: '', value: ''},
        {text: 'Number', value: 'lone_number'},
        {text: 'Bar', value: 'bar'},
    ]
</code>```

At this point, to generate my content i got values this way:

```<code>onsubmit: function (e) {
    e.data.Field;
    e.data.Listbox;
}
</code>```

and used this to write in TinyMCE textarea. To get values back i had to modify textbox field this way:

```<code>{type: 'textbox', name: 'Field', label: 'Number', value: '', tooltip: 'Tooltip', maxLength: 3, classes: 'i1n', value: ed.selection.getContent()}
</code>```

Similarly with listbox

Body:
I'm creating a TinyMCE Plugin for Wordpress. It has a textbox and a listbox field, both staying in a modal window.
Code below:

(function () {
    tinymce.create('tinymce.plugins.windowdata', {
        init : function(ed, url) {
            ed.addButton('showModal', {
                title: 'Show Modal',
                image: url + '/img/button.png',
                onclick: function () {
                    ed.windowManager.open({
                        title: 'Minestra',
                        body: [
                            {type: 'textbox', name: 'Field', label: 'Number', value: '', tooltip: 'Tooltip', maxLength: 3, classes: 'i1n'}, //textbox
                            {type: 'listbox', label: 'Listbox', classes: 'i1lb', values: [
                                {text: '', value: ''},
                                {text: 'Number', value: 'lone_number'},
                                {text: 'Bar', value: 'bar'},
                            ]}, //listbox
                        ],
                        onsubmit: function () {
                            var n1 = document.getElementsByClassName('mce-i1n')[0].value; //textbox value
                            var t1 = document.getElementsByClassName('mce-i1lb')[0].getElementsByTagName('button')[0].getElementsByClassName('mce-txt')[0].innerHTML; //listbox value

                            ed.execCommand('mceInsertContent', 0, n1+' is of type '+t1) //write contents
                        }
                    })
                }
            });
    }
)

My question is about how to get the field values. What i did works very well with the textbox (the n1 var inside the onsubmit() method), but the listbox gets the same text that is shown to TinyMCE user (the text var in each listbox item).

What i want is a way to get the value instead; plus, i suppose i didn't get the right way to do it, not even with textbox. Anyone can help me? Thank you.

Body:
I solved by my own: i had to give a name to all of my fields:

    {type: 'textbox', name: 'Field', label: 'Number', value: '', tooltip: 'Tooltip', maxLength: 3, classes: 'i1n'}, //textbox
    {type: 'listbox', name: 'Listbox', label: 'Listbox', classes: 'i1lb', values: [
        {text: '', value: ''},
        {text: 'Number', value: 'lone_number'},
        {text: 'Bar', value: 'bar'},
    ]

At this point, to generate my content i got values this way:

onsubmit: function (e) {
    e.data.Field;
    e.data.Listbox;
}

and used this to write in TinyMCE textarea. To get values back i had to modify textbox field this way:

{type: 'textbox', name: 'Field', label: 'Number', value: '', tooltip: 'Tooltip', maxLength: 3, classes: 'i1n', value: ed.selection.getContent()}

Similarly with listbox


问:
How can I use the Keras OCR example?
I found examples/image_ocr.py which seems to for OCR. Hence it should be possible to give the model an image and receive text. However, I have no idea how to do so. How do I feed the model with a new image? Which kind of preprocessing is necessary?

What I did

Installing the depencencies:

Install cairocffi: sudo apt-get install python-cairocffi

Install editdistance: sudo -H pip install editdistance

Change train to return the model and save the trained model.

Run the script to train the model.

Now I have a model.h5. What's next?

See https://github.com/MartinThoma/algorithms/tree/master/ML/ocr/keras for my current code. I know how to load the model (see below) and this seems to work. The problem is that I don't know how to feed new scans of images with text to the model.

Related side questions

What is CTC? Connectionist Temporal Classification?

Are there algorithms which reliably detect the rotation of a document?

Are there algorithms which reliably detect lines / text blocks / tables / images (hence make a reasonable segmentation)? I guess edge detection with smoothing and line-wise histograms already works reasonably well for that?

What I tried

```<code>#!/usr/bin/env python

from keras import backend as K
import keras
from keras.models import load_model
import os

from image_ocr import ctc_lambda_func, create_model, TextImageGenerator
from keras.layers import Lambda
from keras.utils.data_utils import get_file
import scipy.ndimage
import numpy

img_h = 64
img_w = 512
pool_size = 2
words_per_epoch = 16000
val_split = 0.2
val_words = int(words_per_epoch * (val_split))
if K.image_data_format() == 'channels_first':
    input_shape = (1, img_w, img_h)
else:
    input_shape = (img_w, img_h, 1)

fdir = os.path.dirname(get_file('wordlists.tgz',
                                origin='http://www.mythic-ai.com/datasets/wordlists.tgz', untar=True))

img_gen = TextImageGenerator(monogram_file=os.path.join(fdir, 'wordlist_mono_clean.txt'),
                             bigram_file=os.path.join(fdir, 'wordlist_bi_clean.txt'),
                             minibatch_size=32,
                             img_w=img_w,
                             img_h=img_h,
                             downsample_factor=(pool_size ** 2),
                             val_split=words_per_epoch - val_words
                             )
print("Input shape: {}".format(input_shape))
model, _, _ = create_model(input_shape, img_gen, pool_size, img_w, img_h)

model.load_weights("my_model.h5")

x = scipy.ndimage.imread('example.png', mode='L').transpose()
x = x.reshape(x.shape + (1,))

# Does not work
print(model.predict(x))
</code>```

this gives

```<code>2017-07-05 22:07:58.695665: I tensorflow/core/common_runtime/gpu/gpu_device.cc:996] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX TITAN Black, pci bus id: 0000:01:00.0)
Traceback (most recent call last):
  File "eval_example.py", line 45, in <module>
    print(model.predict(x))
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1567, in predict
    check_batch_axis=False)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 106, in _standardize_input_data
    'Found: array with shape ' + str(data.shape))
ValueError: The model expects 4 arrays, but only received one array. Found: array with shape (512, 64, 1)
</code>```

答:
Now I have a model.h5. What's next?

First I should comment that the model.h5 contains the weights of your network, if you wish to save the architecture of your network as well you should save it as a json like this example:

```<code>model_json = model_json = model.to_json()
with open("model_arch.json", "w") as json_file:
    json_file.write(model_json)
</code>```

Now, once you have your model and its weights you can load them on demand by doing the following:

```<code>json_file = open('model_arch.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
# if you already have a loaded model and dont need to save start from here
loaded_model.load_weights("model.h5")
# compile loaded model with certain specifications
sgd = SGD(lr=0.01)
loaded_model.compile(loss="binary_crossentropy", optimizer=sgd, metrics=["accuracy"])
</code>```

Then, with that loaded_module you can proceed to predict the classification of certain input like this:

```<code>prediction = loaded_model.predict(some_input, batch_size=20, verbose=0)
</code>```

Which will return the classification of that input.

About the Side Questions:

CTC seems to be a term they are defining in the paper you refered, extracting from it says:

In what follows, we refer to the task of labelling un-
  segmented data sequences as
  temporal classification
  (Kadous, 2002), and to our use of RNNs for this pur-
  pose as
  connectionist temporal classification
  (CTC).

To compensate the rotation of a document, images, or similar you could either generate more data from your current one by applying such transformations (take a look at this blog post that explains a way to do that ), or you could use a Convolutional Neural Network approach, which also is actually what that Keras example you are using does, as we can see from that git:

This example uses a convolutional stack followed by a recurrent stack
  and a CTC logloss function to perform optical character recognition
  of generated text images.

You can check this tutorial that is related to what you are doing and where they also explain more about Convolutional Neural Networks.

Well this one is a broad question but to detect lines you could use the Hough Line Transform, or also Canny Edge Detection could be good options.

Edit: The error you are getting is because it is expected more parameters instead of 1, from the keras docs we can see:

```<code>predict(self, x, batch_size=32, verbose=0)
</code>```

Raises ValueError: In case of mismatch between the provided input data and the model's expectations, or in case a stateful model receives a number of samples that is not a multiple of the batch size.

Title: How can I use the Keras OCR example?

Body:
I found examples/image_ocr.py which seems to for OCR. Hence it should be possible to give the model an image and receive text. However, I have no idea how to do so. How do I feed the model with a new image? Which kind of preprocessing is necessary?

What I did

Installing the depencencies:

Install cairocffi: sudo apt-get install python-cairocffi

Install editdistance: sudo -H pip install editdistance

Change train to return the model and save the trained model.

Run the script to train the model.

Now I have a model.h5. What's next?

See https://github.com/MartinThoma/algorithms/tree/master/ML/ocr/keras for my current code. I know how to load the model (see below) and this seems to work. The problem is that I don't know how to feed new scans of images with text to the model.

Related side questions

What is CTC? Connectionist Temporal Classification?

Are there algorithms which reliably detect the rotation of a document?

Are there algorithms which reliably detect lines / text blocks / tables / images (hence make a reasonable segmentation)? I guess edge detection with smoothing and line-wise histograms already works reasonably well for that?

What I tried

#!/usr/bin/env python

from keras import backend as K
import keras
from keras.models import load_model
import os

from image_ocr import ctc_lambda_func, create_model, TextImageGenerator
from keras.layers import Lambda
from keras.utils.data_utils import get_file
import scipy.ndimage
import numpy

img_h = 64
img_w = 512
pool_size = 2
words_per_epoch = 16000
val_split = 0.2
val_words = int(words_per_epoch * (val_split))
if K.image_data_format() == 'channels_first':
    input_shape = (1, img_w, img_h)
else:
    input_shape = (img_w, img_h, 1)

fdir = os.path.dirname(get_file('wordlists.tgz',
                                origin='http://www.mythic-ai.com/datasets/wordlists.tgz', untar=True))

img_gen = TextImageGenerator(monogram_file=os.path.join(fdir, 'wordlist_mono_clean.txt'),
                             bigram_file=os.path.join(fdir, 'wordlist_bi_clean.txt'),
                             minibatch_size=32,
                             img_w=img_w,
                             img_h=img_h,
                             downsample_factor=(pool_size ** 2),
                             val_split=words_per_epoch - val_words
                             )
print("Input shape: {}".format(input_shape))
model, _, _ = create_model(input_shape, img_gen, pool_size, img_w, img_h)

model.load_weights("my_model.h5")

x = scipy.ndimage.imread('example.png', mode='L').transpose()
x = x.reshape(x.shape + (1,))

# Does not work
print(model.predict(x))

this gives

2017-07-05 22:07:58.695665: I tensorflow/core/common_runtime/gpu/gpu_device.cc:996] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX TITAN Black, pci bus id: 0000:01:00.0)
Traceback (most recent call last):
  File "eval_example.py", line 45, in <module>
    print(model.predict(x))
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1567, in predict
    check_batch_axis=False)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 106, in _standardize_input_data
    'Found: array with shape ' + str(data.shape))
ValueError: The model expects 4 arrays, but only received one array. Found: array with shape (512, 64, 1)

Body:
Now I have a model.h5. What's next?

First I should comment that the model.h5 contains the weights of your network, if you wish to save the architecture of your network as well you should save it as a json like this example:

model_json = model_json = model.to_json()
with open("model_arch.json", "w") as json_file:
    json_file.write(model_json)

Now, once you have your model and its weights you can load them on demand by doing the following:

json_file = open('model_arch.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
# if you already have a loaded model and dont need to save start from here
loaded_model.load_weights("model.h5")
# compile loaded model with certain specifications
sgd = SGD(lr=0.01)
loaded_model.compile(loss="binary_crossentropy", optimizer=sgd, metrics=["accuracy"])

Then, with that loaded_module you can proceed to predict the classification of certain input like this:

prediction = loaded_model.predict(some_input, batch_size=20, verbose=0)

Which will return the classification of that input.

About the Side Questions:

CTC seems to be a term they are defining in the paper you refered, extracting from it says:

In what follows, we refer to the task of labelling un-
  segmented data sequences as
  temporal classification
  (Kadous, 2002), and to our use of RNNs for this pur-
  pose as
  connectionist temporal classification
  (CTC).

To compensate the rotation of a document, images, or similar you could either generate more data from your current one by applying such transformations (take a look at this blog post that explains a way to do that ), or you could use a Convolutional Neural Network approach, which also is actually what that Keras example you are using does, as we can see from that git:

This example uses a convolutional stack followed by a recurrent stack
  and a CTC logloss function to perform optical character recognition
  of generated text images.

You can check this tutorial that is related to what you are doing and where they also explain more about Convolutional Neural Networks.

Well this one is a broad question but to detect lines you could use the Hough Line Transform, or also Canny Edge Detection could be good options.

Edit: The error you are getting is because it is expected more parameters instead of 1, from the keras docs we can see:

predict(self, x, batch_size=32, verbose=0)

Raises ValueError: In case of mismatch between the provided input data and the model's expectations, or in case a stateful model receives a number of samples that is not a multiple of the batch size.


问:
Error: argument "x" is missing, with no default
I am getting an error: argument "x" is missing, with no default
Upon debugging, I found this out to be in the line :
MyData1<- MyData()[,c(col(),col()+1)]
I have tried to pass the argument as a single vector like
MyData1<- MyData()[,p=c(col(),col()+1)]

Error: Error in [.data.frame: unused argument (p = c(col(), col() +
  1))

This is just a snippet from my actual code:

```<code>TotalTS<-ts(MyData()[,Col()],start=Start(),frequency = Fre())
    InsampleTs<-window(TotalTS,start = c(Start(),1),end=c(2017,5))
    TotalTS1<-ts(MyData()[,Col()+1],start=Start(),frequency = Fre())
    InsampleTs1<-window(TotalTS1,start = c(Start(),1),end=c(2017,5))

    MyData1<- MyData()[,c(col(),col()+1)]
    MyData1$util1<-MyData1[,1]*100/MyData1[,2]
    popj<-nrow(MyData())-length(InsampleTs)

    if(input$F6==1){
      if(input$AM==1){

        forecast32<-hw(InsampleTs,h=Col1(),level = input$CI2)
        forecast32_1<-hw(InsampleTs,h=Col1(),level = input$CI2)

        c<-as.matrix(forecast32$x)
        d<-as.matrix(forecast32_1$x)

        c1<-as.matrix(forecast32$fitted)
        d1<-as.matrix(forecast32_1$fitted)
        util2<-(c1*100)/d1
        util1<-(c*100)/d
        c11 <- as.matrix(forecast32$mean[1:popj])
        d11<- as.matrix(forecast32_1$mean[1:popj])
        c12 <- as.matrix(forecast32$lower[1:popj])
        d12<- as.matrix(forecast32_1$lower[1:popj])
        c13 <- as.matrix(forecast32$upper[1:popj])
        d13<- as.matrix(forecast32_1$upper[1:popj])

        c111 <- c11*100/d11
      c112<- c12*100/d12
        c113 <- c13*100/d13
        MyData1$util2 <- util2
        MyData1 <- MyData1[,c(col(),col()+1)]

        e<-as.matrix(forecast32$mean[-c(1:popj)])
        f<-as.matrix(forecast32_1$mean[-c(1:popj)])
        e2<-as.matrix(forecast32$upper[-c(1:popj)])
        f2<-as.matrix(forecast32_1$upper[-c(1:popj)])
        e1<-as.matrix(forecast32$lower[-c(1:popj)])
        f1<-as.matrix(forecast32_1$lower[-c(1:popj)])

        e111 <- e*100/f
        e113<- e2*100/f2
        e112 <- e1*100/f1

       r<- cbind(e111,e112,e113)
       colnames(r) <- c("Predicted","lower Limit","Upper Limit")

        MyData1 <- ts(MyData1,start=c(Start(),1), end=c(2017,5), frequency=Fre())
        #r<-ts(r,start=c(2017,6),end=c((Hstar()+2),Fre()))
        r<-ts(r,start=c(2017,6),end=c(2019,6), frequency = 12)
        autoplot(ts( cbind(r,MyData1),start = c(Start(),1),frequency=Fre() ),facets = F)
        }**strong text**
</code>```

答:
Looking at your code and tracing the sequence of steps to MyData1, I identified these lines:

```<code>  1 c1<-as.matrix(forecast32$fitted)
  2 d1<-as.matrix(forecast32_1$fitted)
  3 util2<-(c1*100)/d1
  4 MyData1$util2 <- util2
  5 MyData1 <- MyData1[,c(col(),col()+1)]
</code>```

Assuming MyData is an object which already exists as a matrix or data.frame, the issue is because you are not giving the Extract operator an index specifying the rows or column you wish to extract. Instead you've passed the col function without specifying a matrix-like object for it to use.

```<code> 5 MyData1 <- MyData1[,c(col(),col()+1)]
</code>```

Should Be

```<code>5 MyData1 <- MyData1[,c(col(x),col(x)+1)]
</code>```

However, I must ask, what are you trying to accomplish with this subset operation? There maybe a more elegant and compact solution that is cleaner than using the col function to specify the columns you'd like to extract from MyData1.

Body:
I am getting an error: argument "x" is missing, with no default
Upon debugging, I found this out to be in the line :
MyData1<- MyData()[,c(col(),col()+1)]
I have tried to pass the argument as a single vector like
MyData1<- MyData()[,p=c(col(),col()+1)]

Error: Error in [.data.frame: unused argument (p = c(col(), col() +
  1))

This is just a snippet from my actual code:

TotalTS<-ts(MyData()[,Col()],start=Start(),frequency = Fre())
    InsampleTs<-window(TotalTS,start = c(Start(),1),end=c(2017,5))
    TotalTS1<-ts(MyData()[,Col()+1],start=Start(),frequency = Fre())
    InsampleTs1<-window(TotalTS1,start = c(Start(),1),end=c(2017,5))

    MyData1<- MyData()[,c(col(),col()+1)]
    MyData1$util1<-MyData1[,1]*100/MyData1[,2]
    popj<-nrow(MyData())-length(InsampleTs)

    if(input$F6==1){
      if(input$AM==1){

        forecast32<-hw(InsampleTs,h=Col1(),level = input$CI2)
        forecast32_1<-hw(InsampleTs,h=Col1(),level = input$CI2)

        c<-as.matrix(forecast32$x)
        d<-as.matrix(forecast32_1$x)

        c1<-as.matrix(forecast32$fitted)
        d1<-as.matrix(forecast32_1$fitted)
        util2<-(c1*100)/d1
        util1<-(c*100)/d
        c11 <- as.matrix(forecast32$mean[1:popj])
        d11<- as.matrix(forecast32_1$mean[1:popj])
        c12 <- as.matrix(forecast32$lower[1:popj])
        d12<- as.matrix(forecast32_1$lower[1:popj])
        c13 <- as.matrix(forecast32$upper[1:popj])
        d13<- as.matrix(forecast32_1$upper[1:popj])

        c111 <- c11*100/d11
      c112<- c12*100/d12
        c113 <- c13*100/d13
        MyData1$util2 <- util2
        MyData1 <- MyData1[,c(col(),col()+1)]

        e<-as.matrix(forecast32$mean[-c(1:popj)])
        f<-as.matrix(forecast32_1$mean[-c(1:popj)])
        e2<-as.matrix(forecast32$upper[-c(1:popj)])
        f2<-as.matrix(forecast32_1$upper[-c(1:popj)])
        e1<-as.matrix(forecast32$lower[-c(1:popj)])
        f1<-as.matrix(forecast32_1$lower[-c(1:popj)])

        e111 <- e*100/f
        e113<- e2*100/f2
        e112 <- e1*100/f1

       r<- cbind(e111,e112,e113)
       colnames(r) <- c("Predicted","lower Limit","Upper Limit")

        MyData1 <- ts(MyData1,start=c(Start(),1), end=c(2017,5), frequency=Fre())
        #r<-ts(r,start=c(2017,6),end=c((Hstar()+2),Fre()))
        r<-ts(r,start=c(2017,6),end=c(2019,6), frequency = 12)
        autoplot(ts( cbind(r,MyData1),start = c(Start(),1),frequency=Fre() ),facets = F)
        }**strong text**

Body:
Looking at your code and tracing the sequence of steps to MyData1, I identified these lines:

  1 c1<-as.matrix(forecast32$fitted)
  2 d1<-as.matrix(forecast32_1$fitted)
  3 util2<-(c1*100)/d1
  4 MyData1$util2 <- util2
  5 MyData1 <- MyData1[,c(col(),col()+1)]

Assuming MyData is an object which already exists as a matrix or data.frame, the issue is because you are not giving the Extract operator an index specifying the rows or column you wish to extract. Instead you've passed the col function without specifying a matrix-like object for it to use.

 5 MyData1 <- MyData1[,c(col(),col()+1)]

Should Be

5 MyData1 <- MyData1[,c(col(x),col(x)+1)]

However, I must ask, what are you trying to accomplish with this subset operation? There maybe a more elegant and compact solution that is cleaner than using the col function to specify the columns you'd like to extract from MyData1.


问:
Selecting tensorflow object detection API training hyper parameters
I am setting up an object detection pipeline based on recently released tensorflow object detection API. I am using the arXiv as guidance. I am looking to understand the below for training on my own dataset.

It is not clear how they selected the learning rate schedules and how that would change based on the number of GPUs available for training. How do the training rate schedule change based on number of GPU's available for training? The paper mentions 9 GPUs are used. How should I change the training rate if I only want to use 1 GPU?

The released sample training config file for Pascal VOC using Faster R-CNN has initial learning rate = 0.0001. This is 10x lower than what was published in the original Faster-RCNN paper. Is this due to an assumption on the number of GPU's available for training or due to a different reason?

When I start training from the COCO detection checkpoint, how should the training loss decrease? Looking at tensorboard, on my dataset training loss is low - between 0.8 to 1.2 per iteration (with batch size of 1). Below image shows the various losses from tensorboard. . Is this expected behavior?

答:
For questions 1 and 2: our implementation differs in a few small details compared to the original paper and internally we train all of our detectors with asynchronous SGD with ~10 GPUs.  Our learning rates are calibrated for this setting (which you will also have if you decide to train via Cloud ML Engine as in the Pets walkthrough).  If you use another setting, you will have to do a bit of hyperparameter exploration.  For a single GPU, leaving the learning rate alone probably won't hurt performance, but you may be able to get faster convergence by increasing it.

For question 3: Training losses decrease erratically and you can only see the decrease if you smooth the plots quite a bit over time.  Moreover, it's hard to explicitly say how well you are doing with respect to eval metrics just by looking at the training losses.  I recommend looking at the mAP plots over time as well as the image visualizations to really get an idea of whether your model has "lifted off".

Hope this helps.


问:
Add new rows to existing column of excel in python

I want to add new records every week to this existing file without creating a new one.

For example, Next I want to add record on date 6/13/2016

Randy->(13,23,13)

Shaw->(13,15,13)

and many such entries next two months. How do I do that? I am beginner so having trouble to put it in syntax.

I could do only this much

```<code>import xlrd

#Opening the excel file
file_location= "C:/Users/agodgh1a/Desktop/Apurva/EPSON.xlsx"
workbook= xlrd.open_workbook(file_location)
sheet=workbook.sheet_by_index(0)
</code>```

Thank you!

答:
The lib you're using looks like it only reads, not edits.  Here's an example in openpyxl:

```<code>from openpyxl import Workbook, load_workbook

# create the file
wb = Workbook()
ws = wb.active
ws.append([1, 2, 3])
wb.save("sample.xlsx")

# re-open and append
wb = load_workbook("sample.xlsx")
ws = wb.active
ws.append([4, 5, 6])
wb.save("sample.xlsx")
</code>```

Run that and you'll have a file sample.xlsx with both rows.

Body:
I want to add new records every week to this existing file without creating a new one.

For example, Next I want to add record on date 6/13/2016

Randy->(13,23,13)

Shaw->(13,15,13)

and many such entries next two months. How do I do that? I am beginner so having trouble to put it in syntax.

I could do only this much

import xlrd

#Opening the excel file
file_location= "C:/Users/agodgh1a/Desktop/Apurva/EPSON.xlsx"
workbook= xlrd.open_workbook(file_location)
sheet=workbook.sheet_by_index(0)

Thank you!

Body:
The lib you're using looks like it only reads, not edits.  Here's an example in openpyxl:

from openpyxl import Workbook, load_workbook

# create the file
wb = Workbook()
ws = wb.active
ws.append([1, 2, 3])
wb.save("sample.xlsx")

# re-open and append
wb = load_workbook("sample.xlsx")
ws = wb.active
ws.append([4, 5, 6])
wb.save("sample.xlsx")

Run that and you'll have a file sample.xlsx with both rows.


问:
Service fabric reliable collections
What is the justifications for the service fabric reliable collections. The team I am working with is replacing the stateful services with stateless and removing the state to a redis server. As far as I understood was service fabric should eliminate the unnecassary talk and be fast at solving issues. I guess the persistance state parameter in service fabric and the debugging is so hard that the team gave up on it.

How should we approach service fabric projects

PS

I still feel that SF is the way to go as It gives us the 1000 server Virtual Machine scale sets architecture.

答:
Reliable collections are fantastic if

You have data that needs to be persistent

Highly available across multiple nodes

Be as close as possible to the application code (and hence blazing fast)

Can be updated seamlessly in one node and replicated across nodes

Allows programmers the ease of programming with dictionaries and queues without them having to learn another caching mechanism

Reliable collections are a brilliant solution if all the above set of features are needed. Individual points can be achieved by other means but getting all of it together needs some heavy lifting and thought/experience.

Making all services stateless will make the individual services fast, but they still need to read and write to redis which is another executable to maintain and make highly available.

Title: Service fabric reliable collections


问:
Error while calling sqlite database query
I get the following exception when running from code. Which argument is the message talking about?

```<code>Caused by: java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range.  The statement has 0 parameters.
at android.database.sqlite.SQLiteProgram.bind(SQLiteProgram.java:212)
at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:166)
at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:200)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1345)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1284)
at su.joel.punchintime.ShowRawDB.displayDatabaseInfo(ShowRawDB.java:53)
at su.joel.punchintime.ShowRawDB.onCreate(ShowRawDB.java:19)
</code>```

at this line: Cursor cursor = db.rawQuery(queryString, whereArgs);

The activity:

```<code>package su.joel.punchintime;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class ShowRawDB extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_raw_db);
        displayDatabaseInfo();
    }
    private void displayDatabaseInfo() {
        DatabaseHelper DBHelper = new DatabaseHelper(this);
        SQLiteDatabase db = DBHelper.getReadableDatabase();
        String[] projection = {
                DBHelper.COL_ID,
                DBHelper.COL_DATE,
                DBHelper.COL_PUNCHIN
        };
        String selection = "null";
        String[] selectionArgs = { "null" };
        String sortOrder =
                DBHelper.COL_DATE + " DESC";
        String queryString =
                "SELECT * FROM punchlog";
        String[] whereArgs = new String[] {""};
        Cursor cursor = db.rawQuery(queryString, whereArgs);
        List itemIds = new ArrayList<>();
        while(cursor.moveToNext()) {
            long itemId = cursor.getLong(
                    cursor.getColumnIndexOrThrow(DBHelper.COL_ID));
            itemIds.add(itemId);
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, itemIds);
        ListView lst = (ListView) findViewById(R.id.listDB);
        lst.setAdapter(adapter);
        cursor.close();
    }
}
</code>```

And the database helper:

```<code>package su.joel.punchintime;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public final class DatabaseHelper extends SQLiteOpenHelper {
        public static final String TABLE_NAME = "punchlog";
        public static final String COL_ID = "_id";
        public static final String COL_DATE = "date";
        public static final String COL_PUNCHIN = "punchin";
        public static final String COL_PUNCHOUT = "punchout";
        public static final String COL_ONDUTY = "onduty";
        public static final String COL_FORGOTIN = "forgotin";
        public static final String COL_FORGOTOUT = "forgotout";
        public static final String COL_LATEIN = "latein";
        public static final String COL_LATEOUT = "lateout";
    String SQL_CREATE_ENTRIES =
            "CREATE TABLE " + TABLE_NAME + " (" +
                    COL_ID + " INTEGER PRIMARY KEY," +
                    COL_DATE + " TEXT," +
                    COL_PUNCHIN + " TEXT," +
                    COL_PUNCHOUT + " TEXT," +
                    COL_ONDUTY + " INTEGER," +
                    COL_FORGOTIN + " INTEGER," +
                    COL_FORGOTOUT + " INTEGER," +
                    COL_LATEIN + " INTEGER," +
                    COL_LATEOUT + " INTEGER);";
    String SQL_DELETE_ENTRIES =
            "DROP TABLE IF EXISTS " + TABLE_NAME;
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "PunchInTime.db";
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRIES);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(SQL_DELETE_ENTRIES);
        System.out.println(SQL_CREATE_ENTRIES);
        onCreate(db);
    }
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }
}
</code>```

答:
Seems to me that you are passing a single whereArg when the SQL string expects none...
try

String[] whereArgs = new String[] {};

instead.

Body:
I get the following exception when running from code. Which argument is the message talking about?

Caused by: java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range.  The statement has 0 parameters.
at android.database.sqlite.SQLiteProgram.bind(SQLiteProgram.java:212)
at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:166)
at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:200)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1345)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1284)
at su.joel.punchintime.ShowRawDB.displayDatabaseInfo(ShowRawDB.java:53)
at su.joel.punchintime.ShowRawDB.onCreate(ShowRawDB.java:19)

at this line: Cursor cursor = db.rawQuery(queryString, whereArgs);

The activity:

package su.joel.punchintime;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class ShowRawDB extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_raw_db);
        displayDatabaseInfo();
    }
    private void displayDatabaseInfo() {
        DatabaseHelper DBHelper = new DatabaseHelper(this);
        SQLiteDatabase db = DBHelper.getReadableDatabase();
        String[] projection = {
                DBHelper.COL_ID,
                DBHelper.COL_DATE,
                DBHelper.COL_PUNCHIN
        };
        String selection = "null";
        String[] selectionArgs = { "null" };
        String sortOrder =
                DBHelper.COL_DATE + " DESC";
        String queryString =
                "SELECT * FROM punchlog";
        String[] whereArgs = new String[] {""};
        Cursor cursor = db.rawQuery(queryString, whereArgs);
        List itemIds = new ArrayList<>();
        while(cursor.moveToNext()) {
            long itemId = cursor.getLong(
                    cursor.getColumnIndexOrThrow(DBHelper.COL_ID));
            itemIds.add(itemId);
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, itemIds);
        ListView lst = (ListView) findViewById(R.id.listDB);
        lst.setAdapter(adapter);
        cursor.close();
    }
}

And the database helper:

package su.joel.punchintime;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public final class DatabaseHelper extends SQLiteOpenHelper {
        public static final String TABLE_NAME = "punchlog";
        public static final String COL_ID = "_id";
        public static final String COL_DATE = "date";
        public static final String COL_PUNCHIN = "punchin";
        public static final String COL_PUNCHOUT = "punchout";
        public static final String COL_ONDUTY = "onduty";
        public static final String COL_FORGOTIN = "forgotin";
        public static final String COL_FORGOTOUT = "forgotout";
        public static final String COL_LATEIN = "latein";
        public static final String COL_LATEOUT = "lateout";
    String SQL_CREATE_ENTRIES =
            "CREATE TABLE " + TABLE_NAME + " (" +
                    COL_ID + " INTEGER PRIMARY KEY," +
                    COL_DATE + " TEXT," +
                    COL_PUNCHIN + " TEXT," +
                    COL_PUNCHOUT + " TEXT," +
                    COL_ONDUTY + " INTEGER," +
                    COL_FORGOTIN + " INTEGER," +
                    COL_FORGOTOUT + " INTEGER," +
                    COL_LATEIN + " INTEGER," +
                    COL_LATEOUT + " INTEGER);";
    String SQL_DELETE_ENTRIES =
            "DROP TABLE IF EXISTS " + TABLE_NAME;
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "PunchInTime.db";
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRIES);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(SQL_DELETE_ENTRIES);
        System.out.println(SQL_CREATE_ENTRIES);
        onCreate(db);
    }
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }
}


问:
Swift 3 pass data from one ViewController to another ViewController
I am new to IOS programming and don't really know what I'm asking but I will try and explain

I am using Firebase to auth and then I want to take the UID and pass it to a different VC the problem I am getting I cant get the var userID to print out side of the IBAction here is where I am so far, any pointer would get good cheers guys

```<code>@IBAction func creatAccountPressed(_ sender: Any) {
    if let email = emailTextField.text,
        let password = passwordTextField.text,
        let name = nameTextField.text {
        Auth.auth().createUser(withEmail: email, password: password, completion: { user, error in
            if let firebaseError = error {
                print(firebaseError.localizedDescription)
            }
            let userID            = user!.uid
            let userEmail: String = self.emailTextField.text!
            let fullName: String  = self.nameTextField.text!
            self.ref.child("users").child(userID).setValue(["Email": userEmail, "Name": fullName])
            self.userID1          = user!.uid as! String
        })
        print(self.userID1)
        presentLoggedInScreen()
    }
}

func presentLoggedInScreen() {
    let stroyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let loggedInVC: LoggedInVCViewController = stroyboard.instantiateViewController(withIdentifier: "loggedInVC") as! LoggedInVCViewController
    self.present(loggedInVC, animated: true, completion: nil)
}
</code>```

答:
One the simpler way to pass info from one VC to another is either through an initiliazer, or through a variable that you set before presenting the second VC.

Since you are new to this, try the variable approach for now, so if say, you're passing a string:

```<code>class LoggedInVCViewController : UIViewController {

    var info : String? {
       didSet {
          if let newInfo = self.info {
             //do what ever you need to do here
          }
       }
    }

    override viewDidLoad() {
       super.viewDidLoad()

    }

}

func presentLoggedInScreen(yourInfo: String) {
   let stroyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
   let loggedInVC:LoggedInVCViewController =
   storyboard.instantiateViewController(withIdentifier: "loggedInVC") as!
   LoggedInVCViewController
   loggedInVC.info = yourInfo
   self.present(loggedInVC, animated: true, completion: nil)
}
</code>```

Mind you, you can always use any other king of variable Class for info. You also would program your VC to execute some methods inside of the get bracket of the property, populate some fields based on the content of info, load a specific UI etc.

Another usefull way is to go the initialization route, but unfortunately you cannot use it with Storyboard nibs (sad i know, but this post goes over this nicely), but it still usefull whenever you will feel comfortable enough to initialize and design VC's programmatically (which I would learn ASAP if were you).

You pass a variable in a custom intializer method for your VC:

```<code>class LoggedInVCViewController : UIViewController {

    var info : Any? {
        get {
            if let this = self.info {
                return this
            } else {
                return nil
            }
        } set {
            if let new = newValue {
                //
            }
        }
    }

    init(info: Any?) {
        //This first line is key, it also calls viewDidLoad() internally, so don't re-write viewDidLoad() here!!
        super.init(nibName: nil, bundle: nil)

        if let newInfo = info {
            //here we check info for whatever you pass to it
            self.info = newInfo
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
</code>```

So you would use is as:

```<code>func presentLoggedInScreen(yourInfo: String) {
        let loggedInVC = LoggedInVCViewController(info: yourInfo)
        self.present(loggedInVC, animated: true, completion: nil)
}
</code>```

Obviously, as stated, this method cannot be used with Storyboards, but very usefull and, as I'm sure you can see, is much more compact.

I suggest you get familiar with Swift Properties of the docs, along with some blog tips such as this one. You can get pretty creative after a while.

For learning more programmatic approaches, i strongly recommend this YouTube channel: Let's Build That App, I personnaly haven't found a better reference point for programmatic approach Swift programming.

Don't hesitate to ask questions!

UPDATE

Your IBAction should look like this:

```<code>@IBAction func creatAccountPressed(_ sender: Any) {
    if let email = emailTextField.text, let password = passwordTextField.text, let name = nameTextField.text {
        Auth.auth().createUser(withEmail: email, password: password, completion: { user, error in
            if let firebaseError = error {
                print(firebaseError.localizedDescription)
                }

            let userID = user!.uid
            let userEmail: String = self.emailTextField.text!
            let fullName: String = self.nameTextField.text!

            self.ref.child("users").child(userID).setValue(["Email": userEmail, "Name": fullName])

           self.userID1 = user!.uid as! String

           print(self.userID1)

           presentLoggedInScreen(yourInfo: self.userID1)

        })

    }
}
</code>```

Body:
I am new to IOS programming and don't really know what I'm asking but I will try and explain

I am using Firebase to auth and then I want to take the UID and pass it to a different VC the problem I am getting I cant get the var userID to print out side of the IBAction here is where I am so far, any pointer would get good cheers guys

@IBAction func creatAccountPressed(_ sender: Any) {
    if let email = emailTextField.text,
        let password = passwordTextField.text,
        let name = nameTextField.text {
        Auth.auth().createUser(withEmail: email, password: password, completion: { user, error in
            if let firebaseError = error {
                print(firebaseError.localizedDescription)
            }
            let userID            = user!.uid
            let userEmail: String = self.emailTextField.text!
            let fullName: String  = self.nameTextField.text!
            self.ref.child("users").child(userID).setValue(["Email": userEmail, "Name": fullName])
            self.userID1          = user!.uid as! String
        })
        print(self.userID1)
        presentLoggedInScreen()
    }
}

func presentLoggedInScreen() {
    let stroyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let loggedInVC: LoggedInVCViewController = stroyboard.instantiateViewController(withIdentifier: "loggedInVC") as! LoggedInVCViewController
    self.present(loggedInVC, animated: true, completion: nil)
}

Body:
One the simpler way to pass info from one VC to another is either through an initiliazer, or through a variable that you set before presenting the second VC.

Since you are new to this, try the variable approach for now, so if say, you're passing a string:

class LoggedInVCViewController : UIViewController {

    var info : String? {
       didSet {
          if let newInfo = self.info {
             //do what ever you need to do here
          }
       }
    }

    override viewDidLoad() {
       super.viewDidLoad()

    }

}

func presentLoggedInScreen(yourInfo: String) {
   let stroyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
   let loggedInVC:LoggedInVCViewController =
   storyboard.instantiateViewController(withIdentifier: "loggedInVC") as!
   LoggedInVCViewController
   loggedInVC.info = yourInfo
   self.present(loggedInVC, animated: true, completion: nil)
}

Mind you, you can always use any other king of variable Class for info. You also would program your VC to execute some methods inside of the get bracket of the property, populate some fields based on the content of info, load a specific UI etc.

Another usefull way is to go the initialization route, but unfortunately you cannot use it with Storyboard nibs (sad i know, but this post goes over this nicely), but it still usefull whenever you will feel comfortable enough to initialize and design VC's programmatically (which I would learn ASAP if were you).

You pass a variable in a custom intializer method for your VC:

class LoggedInVCViewController : UIViewController {

    var info : Any? {
        get {
            if let this = self.info {
                return this
            } else {
                return nil
            }
        } set {
            if let new = newValue {
                //
            }
        }
    }

    init(info: Any?) {
        //This first line is key, it also calls viewDidLoad() internally, so don't re-write viewDidLoad() here!!
        super.init(nibName: nil, bundle: nil)

        if let newInfo = info {
            //here we check info for whatever you pass to it
            self.info = newInfo
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

So you would use is as:

func presentLoggedInScreen(yourInfo: String) {
        let loggedInVC = LoggedInVCViewController(info: yourInfo)
        self.present(loggedInVC, animated: true, completion: nil)
}

Obviously, as stated, this method cannot be used with Storyboards, but very usefull and, as I'm sure you can see, is much more compact.

I suggest you get familiar with Swift Properties of the docs, along with some blog tips such as this one. You can get pretty creative after a while.

For learning more programmatic approaches, i strongly recommend this YouTube channel: Let's Build That App, I personnaly haven't found a better reference point for programmatic approach Swift programming.

Don't hesitate to ask questions!

UPDATE

Your IBAction should look like this:

@IBAction func creatAccountPressed(_ sender: Any) {
    if let email = emailTextField.text, let password = passwordTextField.text, let name = nameTextField.text {
        Auth.auth().createUser(withEmail: email, password: password, completion: { user, error in
            if let firebaseError = error {
                print(firebaseError.localizedDescription)
                }

            let userID = user!.uid
            let userEmail: String = self.emailTextField.text!
            let fullName: String = self.nameTextField.text!

            self.ref.child("users").child(userID).setValue(["Email": userEmail, "Name": fullName])

           self.userID1 = user!.uid as! String

           print(self.userID1)

           presentLoggedInScreen(yourInfo: self.userID1)

        })

    }
}


问:
Drupal: add a link to a image free cck field & re-indent
I am working on theming the product page for drupal ubercart and can't seem to get the image to be a link also. This is what I have so far:

```<code><?php
if ($node->field_image_cache[0]['filepath']):
    print theme('imagecache', 'uc_thumbmail', $node->field_image_cache[0]['filepath']);
endif;
?>
</code>```

The link has to link to the full image which is product_full opposed to uc_thumbnail and I'm trying to make it into a light box also but I will be happy to even get the link to work.

答:
On Drupal 7, you may take advantage of the native l() function:</p>

```<code>echo l(theme_imagefield_image($node->field_image[0]), "link-destination", Array("html"=> true)) ;
</code>```

Body:
I am working on theming the product page for drupal ubercart and can't seem to get the image to be a link also. This is what I have so far:

<?php
if ($node->field_image_cache[0]['filepath']):
    print theme('imagecache', 'uc_thumbmail', $node->field_image_cache[0]['filepath']);
endif;
?>

The link has to link to the full image which is product_full opposed to uc_thumbnail and I'm trying to make it into a light box also but I will be happy to even get the link to work.

Body:
On Drupal 7, you may take advantage of the native l() function:

echo l(theme_imagefield_image($node->field_image[0]), "link-destination", Array("html"=> true)) ;


问:
Change View Background color for clicked recyclerview items
I am trying to change the background color of my recyclerview row when it is clicked. When one row is clicked, its background color is changed. If another row is clicked, then the previous row changes back to its old state and the newly clicked one changes color.

I've tried achieving this using selectors, but when i release the touch, the color just goes back to normal and none of my rows are highlighted.

Would anyone have an idea how to approach this? Thanks in advance

Here is my selector code - Desired goal (Selected row STAYS charcoal until another row is selected)

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true"
        android:state_pressed="true" android:drawable="@color/charcoal_dark" />
    <item android:state_enabled="true"
        android:state_focused="false" android:drawable="@color/charcoal_dark" />
    <item android:drawable="@color/black"/>
</selector>
</code>```

答:
Have you tried handling onClick event of the element and changing the background color property?

Here is an example code from post How to Change color of Button in Android when Clicked?

```<code>boolean check = false;
Button backward_img;
Button backward_img1;
backward_img = (Button) findViewById(R.id.bars_footer_backward);
backward_img1 = (Button) findViewById(R.id.bars_footer_backward1);
backward_img.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
        check = true;
        backward_img.setBackgroundColor(Color.BLUE);
    }
});

if (check == true) {
    backward_img1.setBackgroundColor(Color.RED);
    backward_img.setBackgroundColor(Color.BLUE);
}
</code>```

Body:
I am trying to change the background color of my recyclerview row when it is clicked. When one row is clicked, its background color is changed. If another row is clicked, then the previous row changes back to its old state and the newly clicked one changes color.

I've tried achieving this using selectors, but when i release the touch, the color just goes back to normal and none of my rows are highlighted.

Would anyone have an idea how to approach this? Thanks in advance

Here is my selector code - Desired goal (Selected row STAYS charcoal until another row is selected)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true"
        android:state_pressed="true" android:drawable="@color/charcoal_dark" />
    <item android:state_enabled="true"
        android:state_focused="false" android:drawable="@color/charcoal_dark" />
    <item android:drawable="@color/black"/>
</selector>

Body:
Have you tried handling onClick event of the element and changing the background color property?

Here is an example code from post How to Change color of Button in Android when Clicked?

boolean check = false;
Button backward_img;
Button backward_img1;
backward_img = (Button) findViewById(R.id.bars_footer_backward);
backward_img1 = (Button) findViewById(R.id.bars_footer_backward1);
backward_img.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
        check = true;
        backward_img.setBackgroundColor(Color.BLUE);
    }
});

if (check == true) {
    backward_img1.setBackgroundColor(Color.RED);
    backward_img.setBackgroundColor(Color.BLUE);
}


问:
Failed to load phpMyAdmin configuration (./config.inc.php:31): parse error
hello guys i made a fresh install of phpmyadmin in my computer. after making a new host i tried to log in but phpmyadmin throwing

#2002 - No such file or directory
The server is not responding
  (or the local server's socket is not correctly configured)

.

i searched for this error and following this example i made the proper changes, first of all, the name of the file from   config.sample.inc.php to config.inc.php and after that i changed the line of the document as the example suggests. Then when i am trying to redirect in phpmyadmin it triggers this error

Failed to load phpMyAdmin configuration (./config.inc.php:31): parse
  error

this error is triggering only when i change the line

```<code>$cfg['Servers'][$i]['host'] = 'localhost';
</code>```

to:

```<code>$cfg['Servers'][$i]['host'] = '127.0.0.1';
</code>```

my operating system is OS X el capitan 10.11.6

any ideas will be helpfull

thanks in advance

vaggelis

答: I found it guys, i havent started my database after installed mysql. it was that silly mistake. </p>

Body:
hello guys i made a fresh install of phpmyadmin in my computer. after making a new host i tried to log in but phpmyadmin throwing

#2002 - No such file or directory
The server is not responding
  (or the local server's socket is not correctly configured)

.

i searched for this error and following this example i made the proper changes, first of all, the name of the file from   config.sample.inc.php to config.inc.php and after that i changed the line of the document as the example suggests. Then when i am trying to redirect in phpmyadmin it triggers this error

Failed to load phpMyAdmin configuration (./config.inc.php:31): parse
  error

this error is triggering only when i change the line

$cfg['Servers'][$i]['host'] = 'localhost';

to:

$cfg['Servers'][$i]['host'] = '127.0.0.1';

my operating system is OS X el capitan 10.11.6

any ideas will be helpfull

thanks in advance

vaggelis


问:
create corner arc with css
How would you create such corner arc using css?

This is starter template: https://codepen.io/anon/pen/rwraXG

I was hoping that I would be able to use black outer div and red inner div, and use border radius to leave just the top left corner showing through. I messed something midway.

.bar {
  width: 100px;
  height: 20px;
  background-color: red;
}

.outer {
  height: 100%;
  width: 8px;
  background-color: black;
}

.inner {
  height: 100%;
  width: 100%;
  background-color: red;
  border: 2px solid black;
  border-radius: 15px 0px 0px 0px:
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bar">
  <div class="outer">
    <div class="inner"></div>
  </div>
</div></code>```

答:
fiddle: https://jsfiddle.net/m8wf66u6/

HTML:

```<code><div class="outer">
<div class="inner">
</div>
</div>
</code>```

CSS:

```<code>.outer {
  height: 200px;
  width: 400px;
  background-color: black;
}

.inner {
  height: 100%;
  width: 100%;
  background-color: red;
  border-top-left-radius: 20px;
}
</code>```

Title: create corner arc with css

Body:
fiddle: https://jsfiddle.net/m8wf66u6/

HTML:

<div class="outer">
<div class="inner">
</div>
</div>

CSS:

.outer {
  height: 200px;
  width: 400px;
  background-color: black;
}

.inner {
  height: 100%;
  width: 100%;
  background-color: red;
  border-top-left-radius: 20px;
}


答:
Modified your codepen: https://codepen.io/anon/pen/dRjoow

Essentially, it was a syntax error. You had a colon (:) at the end of your border-radius property like this:

```<code>.inner{
  ...
  border-radius: 15px 0px 0px 0px:
}
</code>```

instead of a semi colon (;) like this:

```<code>.inner{
  ...
  border-radius: 15px 0px 0px 0px;
}
</code>```

so it wasn't rendering.

Title: create corner arc with css

Body:
How would you create such corner arc using css?

This is starter template: https://codepen.io/anon/pen/rwraXG

I was hoping that I would be able to use black outer div and red inner div, and use border radius to leave just the top left corner showing through. I messed something midway.

.bar {
  width: 100px;
  height: 20px;
  background-color: red;
}

.outer {
  height: 100%;
  width: 8px;
  background-color: black;
}

.inner {
  height: 100%;
  width: 100%;
  background-color: red;
  border: 2px solid black;
  border-radius: 15px 0px 0px 0px:
}

Body:
Modified your codepen: https://codepen.io/anon/pen/dRjoow

Essentially, it was a syntax error. You had a colon (:) at the end of your border-radius property like this:

.inner{
  ...
  border-radius: 15px 0px 0px 0px:
}

instead of a semi colon (;) like this:

.inner{
  ...
  border-radius: 15px 0px 0px 0px;
}

so it wasn't rendering.


问:
C++ -- Difference between "throw new BadConversion("xxx")" and "throw BadConversion("xxx")"
```<code>// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html
class BadConversion : public std::runtime_error {
 public:
   BadConversion(std::string const& s)
     : std::runtime_error(s)
     { }
 };

 inline std::string stringify(double x)
 {
   std::ostringstream o;
   if (!(o << x))
     throw BadConversion("stringify(double)");
     // throw new BadConversion("stringify(double)");
   return o.str();
 }
</code>```

[Q1] When we throw an exception in the function, what is the difference between throw new ClassName() and throw ClassName()?

[Q2] Which one is better?

Thank you

答:
Within your code base you should choose one method and stick to it for consistency.

If some of your code throws pointers and other libraries throws objects then your catch clauses may get a bit convoluted as you may need catches for both pointers and objects of the same type.

I personally prefer to throw objects rather than pointers (the main reason I choose this rather than pointers is that it mimics the standard library). Though it is quite feasible to throw pointers the question of ownership rears its ugly head. Who (if anybody) is responsible for deleting the pointer?

ContentLicense: CC BY-SA 2.5

Body:
// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html
class BadConversion : public std::runtime_error {
 public:
   BadConversion(std::string const& s)
     : std::runtime_error(s)
     { }
 };

 inline std::string stringify(double x)
 {
   std::ostringstream o;
   if (!(o << x))
     throw BadConversion("stringify(double)");
     // throw new BadConversion("stringify(double)");
   return o.str();
 }

[Q1] When we throw an exception in the function, what is the difference between throw new ClassName() and throw ClassName()?

[Q2] Which one is better?

Thank you


问:
node.js Error handling. storing error message in err instead of automatically printing it to console
in the following code, i created an error

```<code>db.collection('deals').findOne({"_id":"8976889"})
.then(function(dealsInfoResult){
    throw Error("THIS IS THE ERROR");
    return (dealsInfoResult);
})
.catch(function(err){
    console.log("ERRRR: " + err);
    res.send(err);
})
</code>```

});

after the error occurs, err does not have any error message, its empty. Rather "Error: This is the Error" is printed
In case of any error, i want the error to be stored in err so that i can handle it in my way.

答: Use err.message to see the string.</p>

Body:
in the following code, i created an error

db.collection('deals').findOne({"_id":"8976889"})
.then(function(dealsInfoResult){
    throw Error("THIS IS THE ERROR");
    return (dealsInfoResult);
})
.catch(function(err){
    console.log("ERRRR: " + err);
    res.send(err);
})

});

after the error occurs, err does not have any error message, its empty. Rather "Error: This is the Error" is printed
In case of any error, i want the error to be stored in err so that i can handle it in my way.

Body: Use err.message to see the string.


问:
Getting data in textbox
I want to do " When I write "Item Code" on textbox and click search, It will search & found that item in sql database which has that item code . And Bring it name to textbox2(ITEM NAME). How can I do it ? I can bring it on colomn/raw but Idk how can I bring that item name on textbox2

I can search data on database and bring it to dataGridview . With this code

```<code>if (textBox1.Text.Trim() == "") errorProvider1.SetError(textBox1, "Fiil in the blanks");
else errorProvider1.SetError(textBox1, "");

conn.Open();
string regs = "SELECT * from stackTable where itemCodu=@Cod";

SqlCommand cmd = new SqlCommand(regs, conn);
cmd.Parameters.AddWithValue("@cod", textBox1.Text);

SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
gridView.DataSource = dt;
conn.Close();
</code>```

---operation sequence ( Which I want to do :D )

Search on Database

If found, bring data on Textbox2

If didn't find, Error provider, message textbox

答:
So you have a datatable, all you should have to do is to check the count after the fill with a simple if statement:

```<code>if(dt.rows.count == 0)
{
    MessageBox.Show("Not Found!!");
}
else
{
    textBox2.DataBindings.Add("Text", dt, "the column you want to use for textbox2");
}
</code>```

You should also be using using statements so that all the objects are disposed of properly.

here's an example of how I would write what you have:

```<code>textbox2.DataBinding.Clear(); //clear the databinding so it can be added for the new data found.

using(SqlConnection conn = new SqlConnection("Your connection string here")
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * from stackTable where itemCodu=@Cod")
{
     da.SelectCommand.Parameters.Add("@Cod", sqlDbType.VarChar).Value = textBox1.Text; //see comment below for this change
     da.fill(dt);
     if (dt.Rows.Count == 0)
     {
         //display not found message
     }
     else
     {
         //bind to textbox (described above)
     }
 }
</code>```

Also note, instead of allowing the parameter to be implicitly typed, it is often better to specify the type of data the parameter should receive. This can be done by using Add instead of AddWithValue

```<code>cmd.Parameters.Add("@cod", SqlType.VarChar).Value = textBox1.Text;
</code>```

The last thing to note with your code is that you can use the sqlDataAdapter without the SqlCommand.

One other thing I thought I should add:

If you know you will only ever receive 1 or 0 rows from the search, and you're not interested in binding the data, you could simply just set the textbox's .Text to the column of the row in the datatable.

For example, if you wanted to display a column in your table named Item you could simply use

```<code>textBox2.Text = dt.Rows[0]["Item"].ToString();
</code>```

Title: Getting data in textbox

Body:
I want to do " When I write "Item Code" on textbox and click search, It will search & found that item in sql database which has that item code . And Bring it name to textbox2(ITEM NAME). How can I do it ? I can bring it on colomn/raw but Idk how can I bring that item name on textbox2

I can search data on database and bring it to dataGridview . With this code

if (textBox1.Text.Trim() == "") errorProvider1.SetError(textBox1, "Fiil in the blanks");
else errorProvider1.SetError(textBox1, "");

conn.Open();
string regs = "SELECT * from stackTable where itemCodu=@Cod";

SqlCommand cmd = new SqlCommand(regs, conn);
cmd.Parameters.AddWithValue("@cod", textBox1.Text);

SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
gridView.DataSource = dt;
conn.Close();

---operation sequence ( Which I want to do :D )

Search on Database

If found, bring data on Textbox2

If didn't find, Error provider, message textbox

Body:
So you have a datatable, all you should have to do is to check the count after the fill with a simple if statement:

if(dt.rows.count == 0)
{
    MessageBox.Show("Not Found!!");
}
else
{
    textBox2.DataBindings.Add("Text", dt, "the column you want to use for textbox2");
}

You should also be using using statements so that all the objects are disposed of properly.

here's an example of how I would write what you have:

textbox2.DataBinding.Clear(); //clear the databinding so it can be added for the new data found.

using(SqlConnection conn = new SqlConnection("Your connection string here")
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * from stackTable where itemCodu=@Cod")
{
     da.SelectCommand.Parameters.Add("@Cod", sqlDbType.VarChar).Value = textBox1.Text; //see comment below for this change
     da.fill(dt);
     if (dt.Rows.Count == 0)
     {
         //display not found message
     }
     else
     {
         //bind to textbox (described above)
     }
 }

Also note, instead of allowing the parameter to be implicitly typed, it is often better to specify the type of data the parameter should receive. This can be done by using Add instead of AddWithValue

cmd.Parameters.Add("@cod", SqlType.VarChar).Value = textBox1.Text;

The last thing to note with your code is that you can use the sqlDataAdapter without the SqlCommand.

One other thing I thought I should add:

If you know you will only ever receive 1 or 0 rows from the search, and you're not interested in binding the data, you could simply just set the textbox's .Text to the column of the row in the datatable.

For example, if you wanted to display a column in your table named Item you could simply use

textBox2.Text = dt.Rows[0]["Item"].ToString();


问:
Detect empty directory with Perl
What is an easy way to test if a folder is empty in perl? -s, and -z are not working.

Example:

```<code>#Ensure Apps directory exists on the test PC.
if ( ! -s $gAppsDir )
{
    die "\n$gAppsDir is not accessible or does not exist.\n";
}

#Ensure Apps directory exists on the test PC.
if ( ! -z $gAppsDir )
{
    die "\n$gAppsDir is not accessible or does not exist.\n";
}
</code>```

These above, do not work properly to tell me that the folder is empty. Thanks!

Thanks all! I ended up using:

```<code>sub is_folder_empty { my $dirname = shift; opendir(my $dh, $dirname) or die "Not a directory";
return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0; }
</code>```

答:
Credit to DevShed

```<code>if (scalar <directory/*>) {print qq|File Exists\n|}
</code>```

Edit

To include hidden files:

```<code>@arr = <directory/* directory/.*>;
@arr = grep {!/^directory/[.]{1,2}$/} @arr;
if (@arr) { print qq|File or Directory Exists\n| }
</code>```

Please read the comments as there have been good points made.  Despite the negative points this answer has received, it is still correct.

Title: Detect empty directory with Perl

Body:
What is an easy way to test if a folder is empty in perl? -s, and -z are not working.

Example:

#Ensure Apps directory exists on the test PC.
if ( ! -s $gAppsDir )
{
    die "\n$gAppsDir is not accessible or does not exist.\n";
}

#Ensure Apps directory exists on the test PC.
if ( ! -z $gAppsDir )
{
    die "\n$gAppsDir is not accessible or does not exist.\n";
}

These above, do not work properly to tell me that the folder is empty. Thanks!

Thanks all! I ended up using:

sub is_folder_empty { my $dirname = shift; opendir(my $dh, $dirname) or die "Not a directory";
return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0; }

Body:
Credit to DevShed

if (scalar <directory/*>) {print qq|File Exists\n|}

Edit

To include hidden files:

@arr = <directory/* directory/.*>;
@arr = grep {!/^directory/[.]{1,2}$/} @arr;
if (@arr) { print qq|File or Directory Exists\n| }

Please read the comments as there have been good points made.  Despite the negative points this answer has received, it is still correct.


问:
Rotate animation android from top right,Bottom left, Bottom right in android?
The below code helps me to rotate through left top edge of screen when swipe. can any one helps me how to rotate through remaining edges of the screen like top right edge, bottom right and left edges.
To be simple i need Rotate Page Transform as an animation for image view</p>

```<code>RotateAnimation r=new RotateAnimation(130,0,90,180);
</code>```

答:
You may use this code:</p>

```<code>RotateAnimation r=new RotateAnimation(0,90);
RotateAnimation r=new RotateAnimation(180,270);
RotateAnimation r=new RotateAnimation(270,360);
</code>```

Body:
The below code helps me to rotate through left top edge of screen when swipe. can any one helps me how to rotate through remaining edges of the screen like top right edge, bottom right and left edges.
To be simple i need Rotate Page Transform as an animation for image view

RotateAnimation r=new RotateAnimation(130,0,90,180);

Body:
You may use this code:

RotateAnimation r=new RotateAnimation(0,90);
RotateAnimation r=new RotateAnimation(180,270);
RotateAnimation r=new RotateAnimation(270,360);


答:
The only problem is the : at the end of the last line.

```<code>border-radius: 15px 0px 0px 0px;
</code>```

Note that you can also use :

```<code>border-top-left-radius: 15px;
</code>```

Title: create corner arc with css

Body:
The only problem is the : at the end of the last line.

border-radius: 15px 0px 0px 0px;

Note that you can also use :

border-top-left-radius: 15px;


问:
Mapping User table from Asp.Net Identity in AutoMapper
In Asp.Net Core I overrode the IdentityUser table to add more functionalities

```<code>public class Person : IdentityUser
    {
        public string Location {get; set; }
        public SellerType SellerType{get; set; }

    }
    public enum SellerType
    {
        PrivateSeller ,
        Dealer
    }
</code>```

I also have a ViewModel class CredentialModel which I am chaining with the Person class with AutoMapper

```<code>public class CredentialModel
  {
    public string UserName { get; set; }
    public string Password { get; set; }
    public string FirstName {get;set;}
    public string LastName {get; set; }
    public string Location {get; set; }
    public string SellerType{get; set; }
    public string[] SellerTypes {get; set; }
    public string PhoneNumber {get; set; }
  }
</code>```

And the AutoMapper Profile Class

```<code>public class UserMapProfile : Profile
    {
        public UserMapProfile(){
          CreateMap<CarAdderUser, CredentialModel>()
             .ForMember(model=> model.SellerType ,
             opt=> opt.MapFrom(vm=>((SellerType)vm.SellerType).ToString()))
             .ForMember(model=> model.SellerTypes, opt=> opt.UseValue(Enum.GetNames(typeof(SellerType)).ToArray()))
                .ReverseMap();
        }
    }
</code>```

My problem is in the Controller

Like this it works but i am returning the entity not the VM

```<code>    [HttpGet("getUser/{username}")]
     public  IActionResult GetUser(string username)
     {
         var user= _userManager.FindByNameAsync(username);
         return Ok(user);
     }
</code>```

Like this it throws me a 404 in Postman

```<code>[HttpGet("getUser/{username}")]
     public  IActionResult GetUser(string username)
     {
         var user= _userManager.FindByNameAsync(username);
         return Ok(_mapper.Map<CredentialModel>(user));
     }
</code>```

IT throws me an error

```<code> An unhandled exception has occurred: Missing type map configuration or unsupported mapping.

      Mapping types:
      Task`1 -> CredentialModel
</code>```

Not sure what to do ... Not an AutoMapper expert

答:
Solved ... the problem was that I forgot that I only need the result ...
so user.Result instead of user in the return ...
Not sure what the other things are ... They are not columns in the User table in the DB </p>

Body:
In Asp.Net Core I overrode the IdentityUser table to add more functionalities

public class Person : IdentityUser
    {
        public string Location {get; set; }
        public SellerType SellerType{get; set; }

    }
    public enum SellerType
    {
        PrivateSeller ,
        Dealer
    }

I also have a ViewModel class CredentialModel which I am chaining with the Person class with AutoMapper

public class CredentialModel
  {
    public string UserName { get; set; }
    public string Password { get; set; }
    public string FirstName {get;set;}
    public string LastName {get; set; }
    public string Location {get; set; }
    public string SellerType{get; set; }
    public string[] SellerTypes {get; set; }
    public string PhoneNumber {get; set; }
  }

And the AutoMapper Profile Class

public class UserMapProfile : Profile
    {
        public UserMapProfile(){
          CreateMap<CarAdderUser, CredentialModel>()
             .ForMember(model=> model.SellerType ,
             opt=> opt.MapFrom(vm=>((SellerType)vm.SellerType).ToString()))
             .ForMember(model=> model.SellerTypes, opt=> opt.UseValue(Enum.GetNames(typeof(SellerType)).ToArray()))
                .ReverseMap();
        }
    }

My problem is in the Controller

Like this it works but i am returning the entity not the VM

    [HttpGet("getUser/{username}")]
     public  IActionResult GetUser(string username)
     {
         var user= _userManager.FindByNameAsync(username);
         return Ok(user);
     }

Like this it throws me a 404 in Postman

[HttpGet("getUser/{username}")]
     public  IActionResult GetUser(string username)
     {
         var user= _userManager.FindByNameAsync(username);
         return Ok(_mapper.Map<CredentialModel>(user));
     }

IT throws me an error

 An unhandled exception has occurred: Missing type map configuration or unsupported mapping.

      Mapping types:
      Task`1 -> CredentialModel

Not sure what to do ... Not an AutoMapper expert


问:
Understanding macros in C
Why is the output from the following code the value 5?</p>

```<code>#include<stdio.h>

#define A -B
#define B -C
#define C 5

int main()
{
  printf("The value of A is %d\n", A);
  return 0;
}
</code>```

答:
This an excellent example how do not use the preprocessor. To avoid confusions parenthesis should be used (not only in this case)</p>

```<code>#define A (-B)
#define B (-C)
#define C (5)
</code>```

Title: Understanding macros in C

Body:
Why is the output from the following code the value 5?

#include<stdio.h>

#define A -B
#define B -C
#define C 5

int main()
{
  printf("The value of A is %d\n", A);
  return 0;
}

Body:
This an excellent example how do not use the preprocessor. To avoid confusions parenthesis should be used (not only in this case)

#define A (-B)
#define B (-C)
#define C (5)