include google analytics in my js file
Would there be any drawbacks including the google analytics script in my
javascript file? Any suggestions?
HTML file:
<!DOCTYPE html>
<title>Include Analytics</title>
<script src=/js/myjsfile.js></script>
<p>No other Javascript in this document.
myjsfile.js:
window.onload = function(){
// my other functions
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new
Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-xxxxxxxx-x', 'domain.se');
ga('send', 'pageview');
}
Thursday, October 3, 2013
Wednesday, October 2, 2013
how to upload multiple files in one
how to upload multiple files in one
I have made a code that let me upload multiple files but in separate
I was trying to upload a multiple files in one input where i set my input
tag into
<input type="file" multiple="" name="file1">
I selected 3 images but only 1 image was uploaded..
here is my VIEW before changing my input:
<?php echo form_open_multipart('test'); ?>
<p>
<?php echo form_label('File 1: ', 'file1') ?>
<input type='file' name='file1' id='file1'>
</p>
<p>
<?php //echo form_label('File 2: ', 'file2') ?>
<input type='file' name='file2' id='file2'>
</p>
<p><?php echo form_submit('submit', 'Upload them files!') ?></p>
and here is my CONTROLLER
function index()
{
if (isset($_POST['submit']))
{
$this->load->library('upload');
$config['upload_path'] = './upload_documents/';
$config['allowed_types'] = 'jpg|png|gif|jpeg|JPG|PNG|GIF|JPEG';
$config['max_size'] = '0'; // 0 = no file size limit
$config['max_width'] = '0';
$config['max_height'] = '0';
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
foreach($_FILES as $field => $file)
{
// No problems with the file
if($file['error'] == 0)
{
// So lets upload
if ($this->upload->do_upload($field))
{
$data = $this->upload->data();
//alert("nice");
}
else
{
$errors = $this->upload->display_errors();
die();
}
}
else{
echo "alksjdfl";
die();
}
}
}
$this->load->view("test");
}
}
I have made a code that let me upload multiple files but in separate
I was trying to upload a multiple files in one input where i set my input
tag into
<input type="file" multiple="" name="file1">
I selected 3 images but only 1 image was uploaded..
here is my VIEW before changing my input:
<?php echo form_open_multipart('test'); ?>
<p>
<?php echo form_label('File 1: ', 'file1') ?>
<input type='file' name='file1' id='file1'>
</p>
<p>
<?php //echo form_label('File 2: ', 'file2') ?>
<input type='file' name='file2' id='file2'>
</p>
<p><?php echo form_submit('submit', 'Upload them files!') ?></p>
and here is my CONTROLLER
function index()
{
if (isset($_POST['submit']))
{
$this->load->library('upload');
$config['upload_path'] = './upload_documents/';
$config['allowed_types'] = 'jpg|png|gif|jpeg|JPG|PNG|GIF|JPEG';
$config['max_size'] = '0'; // 0 = no file size limit
$config['max_width'] = '0';
$config['max_height'] = '0';
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
foreach($_FILES as $field => $file)
{
// No problems with the file
if($file['error'] == 0)
{
// So lets upload
if ($this->upload->do_upload($field))
{
$data = $this->upload->data();
//alert("nice");
}
else
{
$errors = $this->upload->display_errors();
die();
}
}
else{
echo "alksjdfl";
die();
}
}
}
$this->load->view("test");
}
}
Probability - exactly one of A and B occurs
Probability - exactly one of A and B occurs
A and B are events that are subsets of the sample space. C is the event
that exactly one of A and B occurs.
1) Write an expression for C in terms of unions, intersections and
complements involving the events A and B
2) Let P be a probability defined on the events of the sample space. Write
an expression for P(C) in terms of P(A), P(B) and P(A¿B). Give proof of
your result.
Would I be right in saying that 1) is just
C=(AUB)-(A¿B)
Or would it be? (A¿B^c)U(A^c ¿B)
A and B are events that are subsets of the sample space. C is the event
that exactly one of A and B occurs.
1) Write an expression for C in terms of unions, intersections and
complements involving the events A and B
2) Let P be a probability defined on the events of the sample space. Write
an expression for P(C) in terms of P(A), P(B) and P(A¿B). Give proof of
your result.
Would I be right in saying that 1) is just
C=(AUB)-(A¿B)
Or would it be? (A¿B^c)U(A^c ¿B)
Java Swing repack components
Java Swing repack components
I have problem with pack function, when using Card Layout. I created 1
JFrame which include JPanel(in cardlayout) and this JPanel contains two
JPanels. ... so when I run my program the windows is resized to biggest
JPanel in program and i cant dynamicly resize it.
now screens: my background1(smaller background) class when i run program
only with this panel has width like 200 http://i41.tinypic.com/scfi88.jpg
when i run my program with added background2 the background gets width of
it so it looks for like 400 http://i41.tinypic.com/2lu742x.jpg so it gets
width of my background2 panel
code: main class:
public class main extends javax.swing.JFrame {
private JPanel mainPanel;
public main() {
mainPanel = new JPanel(new CardLayout());
add(mainPanel);
Background2 card1 = new Background2(mainPanel);
Background1 card2 = new Background1(mainPanel);
mainPanel.add(card1,"card1");
mainPanel.add(card2,"card2");
CardLayout cl = (CardLayout) (mainPanel.getLayout());
cl.show(mainPanel, "card1");
mainPanel.revalidate();
mainPanel.repaint();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new main().setVisible(true);
}
});
}
}
background1(it is big because it is few comonents generated in netbeans
design mode):
public class Background1 extends javax.swing.JPanel {
private JPanel mainPanel;
/**
* Creates new form HomePanel
*/
public Background1(JPanel panel) {
mainPanel=panel;
initComponents();
}
public JPanel getMainPanel() {
return mainPanel;
}
public void setMainPanel(JPanel mainPanel) {
this.mainPanel = mainPanel;
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
left_Panel = new javax.swing.JPanel();
zakladka1_Button = new javax.swing.JButton();
background_Panel = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
powrot_Button = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
jTable3 = new javax.swing.JTable();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
zakladka1_Button.setText("button");
zakladka1_Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zakladka1_ButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout left_PanelLayout = new
javax.swing.GroupLayout(left_Panel);
left_Panel.setLayout(left_PanelLayout);
left_PanelLayout.setHorizontalGroup(
left_PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(left_PanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(zakladka1_Button)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
left_PanelLayout.setVerticalGroup(
left_PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(left_PanelLayout.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(zakladka1_Button)
.addGap(433, 433, 433))
);
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane2.setViewportView(jTable2);
javax.swing.GroupLayout background_PanelLayout = new
javax.swing.GroupLayout(background_Panel);
background_Panel.setLayout(background_PanelLayout);
background_PanelLayout.setHorizontalGroup(
background_PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(background_PanelLayout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(jScrollPane2,
javax.swing.GroupLayout.PREFERRED_SIZE, 452,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(83, Short.MAX_VALUE))
);
background_PanelLayout.setVerticalGroup(
background_PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
background_PanelLayout.createSequentialGroup()
.addContainerGap(14, Short.MAX_VALUE)
.addComponent(jScrollPane2,
javax.swing.GroupLayout.PREFERRED_SIZE, 319,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
powrot_Button.setText("<--");
powrot_Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
powrot_ButtonActionPerformed(evt);
}
});
jLabel1.setText("jLabel1");
jTable3.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane3.setViewportView(jTable3);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING,
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(left_Panel,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(powrot_Button)))
.addGap(18, 18, 18)
.addComponent(background_Panel,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane3,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(powrot_Button,
javax.swing.GroupLayout.PREFERRED_SIZE, 43,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(left_Panel,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(background_Panel,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(115, 115, 115))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addComponent(jScrollPane3,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(42, 42, 42))))
);
}// </editor-fold>
private void powrot_ButtonActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout cl = (CardLayout) (mainPanel.getLayout());
cl.show(mainPanel, "card1");
mainPanel.revalidate();
mainPanel.repaint();
}
private void zakladka1_ButtonActionPerformed(java.awt.event.ActionEvent
evt) {
}
// Variables declaration - do not modify
private javax.swing.JPanel background_Panel;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
private javax.swing.JTable jTable3;
private javax.swing.JPanel left_Panel;
private javax.swing.JButton powrot_Button;
private javax.swing.JButton zakladka1_Button;
// End of variables declaration
}
background2(it is big because it is few comonents generated in netbeans
design mode)::
public class Background2 extends javax.swing.JPanel {
private JPanel mainPanel;
public Background2(JPanel panel) {
mainPanel=panel;
initComponents();
}
/**
* 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() {
loginFieldLabel = new javax.swing.JLabel();
zalogujButton = new javax.swing.JButton();
loginField = new javax.swing.JTextField();
passwordField = new javax.swing.JPasswordField();
logowanieLabel = new javax.swing.JLabel();
passwordFieldLabel = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
loginFieldLabel.setText("Login");
zalogujButton.setText("Zaloguj");
zalogujButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zalogujButtonActionPerformed(evt);
}
});
loginField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loginFieldActionPerformed(evt);
}
});
passwordField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
passwordFieldActionPerformed(evt);
}
});
logowanieLabel.setText("Logowanie");
passwordFieldLabel.setText("Has³o");
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new
org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(layout.createSequentialGroup()
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.add(zalogujButton)
.add(149, 149, 149))
.add(org.jdesktop.layout.GroupLayout.LEADING,
layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(org.jdesktop.layout.GroupLayout.LEADING,
layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(logowanieLabel)
.add(layout.createSequentialGroup()
.add(56, 56, 56)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(passwordFieldLabel)
.add(loginFieldLabel))
.add(26, 26, 26)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING,
false)
.add(loginField)
.add(passwordField,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
193,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))))
.add(org.jdesktop.layout.GroupLayout.LEADING,
layout.createSequentialGroup()
.add(105, 105, 105)
.add(jButton1)))
.addContainerGap(190, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(logowanieLabel)
.add(29, 29, 29)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(loginField,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(loginFieldLabel))
.add(28, 28, 28)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(passwordFieldLabel)
.add(passwordField,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(33, 33, 33)
.add(zalogujButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(jButton1)
.addContainerGap(101, Short.MAX_VALUE))
);
}// </editor-fold>
private void zalogujButtonActionPerformed(java.awt.event.ActionEvent evt) {
}
private void loginFieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void passwordFieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout cl = (CardLayout) (mainPanel.getLayout());
cl.show(mainPanel, "card2");
mainPanel.revalidate();
mainPanel.repaint();
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JTextField loginField;
private javax.swing.JLabel loginFieldLabel;
private javax.swing.JLabel logowanieLabel;
private javax.swing.JPasswordField passwordField;
private javax.swing.JLabel passwordFieldLabel;
private javax.swing.JButton zalogujButton;
// End of variables declaration
}
I have problem with pack function, when using Card Layout. I created 1
JFrame which include JPanel(in cardlayout) and this JPanel contains two
JPanels. ... so when I run my program the windows is resized to biggest
JPanel in program and i cant dynamicly resize it.
now screens: my background1(smaller background) class when i run program
only with this panel has width like 200 http://i41.tinypic.com/scfi88.jpg
when i run my program with added background2 the background gets width of
it so it looks for like 400 http://i41.tinypic.com/2lu742x.jpg so it gets
width of my background2 panel
code: main class:
public class main extends javax.swing.JFrame {
private JPanel mainPanel;
public main() {
mainPanel = new JPanel(new CardLayout());
add(mainPanel);
Background2 card1 = new Background2(mainPanel);
Background1 card2 = new Background1(mainPanel);
mainPanel.add(card1,"card1");
mainPanel.add(card2,"card2");
CardLayout cl = (CardLayout) (mainPanel.getLayout());
cl.show(mainPanel, "card1");
mainPanel.revalidate();
mainPanel.repaint();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new main().setVisible(true);
}
});
}
}
background1(it is big because it is few comonents generated in netbeans
design mode):
public class Background1 extends javax.swing.JPanel {
private JPanel mainPanel;
/**
* Creates new form HomePanel
*/
public Background1(JPanel panel) {
mainPanel=panel;
initComponents();
}
public JPanel getMainPanel() {
return mainPanel;
}
public void setMainPanel(JPanel mainPanel) {
this.mainPanel = mainPanel;
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
left_Panel = new javax.swing.JPanel();
zakladka1_Button = new javax.swing.JButton();
background_Panel = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
powrot_Button = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
jTable3 = new javax.swing.JTable();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
zakladka1_Button.setText("button");
zakladka1_Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zakladka1_ButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout left_PanelLayout = new
javax.swing.GroupLayout(left_Panel);
left_Panel.setLayout(left_PanelLayout);
left_PanelLayout.setHorizontalGroup(
left_PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(left_PanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(zakladka1_Button)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
left_PanelLayout.setVerticalGroup(
left_PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(left_PanelLayout.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(zakladka1_Button)
.addGap(433, 433, 433))
);
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane2.setViewportView(jTable2);
javax.swing.GroupLayout background_PanelLayout = new
javax.swing.GroupLayout(background_Panel);
background_Panel.setLayout(background_PanelLayout);
background_PanelLayout.setHorizontalGroup(
background_PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(background_PanelLayout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(jScrollPane2,
javax.swing.GroupLayout.PREFERRED_SIZE, 452,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(83, Short.MAX_VALUE))
);
background_PanelLayout.setVerticalGroup(
background_PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
background_PanelLayout.createSequentialGroup()
.addContainerGap(14, Short.MAX_VALUE)
.addComponent(jScrollPane2,
javax.swing.GroupLayout.PREFERRED_SIZE, 319,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
powrot_Button.setText("<--");
powrot_Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
powrot_ButtonActionPerformed(evt);
}
});
jLabel1.setText("jLabel1");
jTable3.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane3.setViewportView(jTable3);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING,
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(left_Panel,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(powrot_Button)))
.addGap(18, 18, 18)
.addComponent(background_Panel,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane3,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(powrot_Button,
javax.swing.GroupLayout.PREFERRED_SIZE, 43,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(left_Panel,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(background_Panel,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(115, 115, 115))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addComponent(jScrollPane3,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(42, 42, 42))))
);
}// </editor-fold>
private void powrot_ButtonActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout cl = (CardLayout) (mainPanel.getLayout());
cl.show(mainPanel, "card1");
mainPanel.revalidate();
mainPanel.repaint();
}
private void zakladka1_ButtonActionPerformed(java.awt.event.ActionEvent
evt) {
}
// Variables declaration - do not modify
private javax.swing.JPanel background_Panel;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
private javax.swing.JTable jTable3;
private javax.swing.JPanel left_Panel;
private javax.swing.JButton powrot_Button;
private javax.swing.JButton zakladka1_Button;
// End of variables declaration
}
background2(it is big because it is few comonents generated in netbeans
design mode)::
public class Background2 extends javax.swing.JPanel {
private JPanel mainPanel;
public Background2(JPanel panel) {
mainPanel=panel;
initComponents();
}
/**
* 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() {
loginFieldLabel = new javax.swing.JLabel();
zalogujButton = new javax.swing.JButton();
loginField = new javax.swing.JTextField();
passwordField = new javax.swing.JPasswordField();
logowanieLabel = new javax.swing.JLabel();
passwordFieldLabel = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
loginFieldLabel.setText("Login");
zalogujButton.setText("Zaloguj");
zalogujButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zalogujButtonActionPerformed(evt);
}
});
loginField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loginFieldActionPerformed(evt);
}
});
passwordField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
passwordFieldActionPerformed(evt);
}
});
logowanieLabel.setText("Logowanie");
passwordFieldLabel.setText("Has³o");
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new
org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(layout.createSequentialGroup()
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.add(zalogujButton)
.add(149, 149, 149))
.add(org.jdesktop.layout.GroupLayout.LEADING,
layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(org.jdesktop.layout.GroupLayout.LEADING,
layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(logowanieLabel)
.add(layout.createSequentialGroup()
.add(56, 56, 56)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(passwordFieldLabel)
.add(loginFieldLabel))
.add(26, 26, 26)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING,
false)
.add(loginField)
.add(passwordField,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
193,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))))
.add(org.jdesktop.layout.GroupLayout.LEADING,
layout.createSequentialGroup()
.add(105, 105, 105)
.add(jButton1)))
.addContainerGap(190, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(logowanieLabel)
.add(29, 29, 29)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(loginField,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(loginFieldLabel))
.add(28, 28, 28)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(passwordFieldLabel)
.add(passwordField,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(33, 33, 33)
.add(zalogujButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(jButton1)
.addContainerGap(101, Short.MAX_VALUE))
);
}// </editor-fold>
private void zalogujButtonActionPerformed(java.awt.event.ActionEvent evt) {
}
private void loginFieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void passwordFieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout cl = (CardLayout) (mainPanel.getLayout());
cl.show(mainPanel, "card2");
mainPanel.revalidate();
mainPanel.repaint();
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JTextField loginField;
private javax.swing.JLabel loginFieldLabel;
private javax.swing.JLabel logowanieLabel;
private javax.swing.JPasswordField passwordField;
private javax.swing.JLabel passwordFieldLabel;
private javax.swing.JButton zalogujButton;
// End of variables declaration
}
TypeError: '_csv.reader' object has no attribute '__getitem__' // getting columns?
TypeError: '_csv.reader' object has no attribute '__getitem__' // getting
columns?
I'm trying to open a .csv file and put each column in different list:
import csv
CSV = csv.reader(open("AAPL.csv","rb"))
column1 = CSV[0]
column2 = CSV[1]
column3 = CSV[2]
column4 = CSV[2]
column5 = CSV[4]
column6 = CSV[5]
Here is my AAPL.csv:
Date Open High Low Close Volume Adj Close
2013-09-27 874.82 877.52 871.31 876.39 1258800 876.39
2013-09-26 878.3 882.75 875 878.17 1259900 878.17
2013-09-25 886.55 886.55 875.6 877.23 1649000 877.23
2013-09-24 886.5 890.1 881.4 886.84 1467000 886.84
2013-09-23 896.15 901.59 885.2 886.5 1777400 886.5
2013-09-20 898.39 904.13 895.62 903.11 4345300 903.11
2013-09-19 905.99 905.99 895.4 898.39 1597900 898.39
2013-09-18 886.35 903.97 883.07 903.32 1934700 903.32
2013-09-17 887.41 888.39 881 886.11 1259400 886.11
2013-09-16 896.2 897 884.87 887.76 1336500 887.76
.............................................................
end of file:
.............................................................
2012-06-29 574.96 58013 572.20 580.07 2519500 580.07
2012-06-28 565.90 566.23 557.21 564.31 1920900 564.31
2012-06-27 567.70 573.99 566.02 569.30 1692300 569.30
2012-06-26 562.76 566.60 559.48 564.68 1350200 564.68
2012-06-25 567.33 568.09 557.35 560.70 1581600 560.70
When I run my code, it returns me the following error:
Traceback (most recent call last):
File "/home/misha/Documents/finance/prices/some_csv.py", line 3, in
<module>
column1 = CSV[0]
TypeError: '_csv.reader' object has no attribute '__getitem__'
Is there any pythonic way to open a .csv file and put each column in
different list not using attribute getitem?
Thanks.
NOTE: and also i need to skip first row.
columns?
I'm trying to open a .csv file and put each column in different list:
import csv
CSV = csv.reader(open("AAPL.csv","rb"))
column1 = CSV[0]
column2 = CSV[1]
column3 = CSV[2]
column4 = CSV[2]
column5 = CSV[4]
column6 = CSV[5]
Here is my AAPL.csv:
Date Open High Low Close Volume Adj Close
2013-09-27 874.82 877.52 871.31 876.39 1258800 876.39
2013-09-26 878.3 882.75 875 878.17 1259900 878.17
2013-09-25 886.55 886.55 875.6 877.23 1649000 877.23
2013-09-24 886.5 890.1 881.4 886.84 1467000 886.84
2013-09-23 896.15 901.59 885.2 886.5 1777400 886.5
2013-09-20 898.39 904.13 895.62 903.11 4345300 903.11
2013-09-19 905.99 905.99 895.4 898.39 1597900 898.39
2013-09-18 886.35 903.97 883.07 903.32 1934700 903.32
2013-09-17 887.41 888.39 881 886.11 1259400 886.11
2013-09-16 896.2 897 884.87 887.76 1336500 887.76
.............................................................
end of file:
.............................................................
2012-06-29 574.96 58013 572.20 580.07 2519500 580.07
2012-06-28 565.90 566.23 557.21 564.31 1920900 564.31
2012-06-27 567.70 573.99 566.02 569.30 1692300 569.30
2012-06-26 562.76 566.60 559.48 564.68 1350200 564.68
2012-06-25 567.33 568.09 557.35 560.70 1581600 560.70
When I run my code, it returns me the following error:
Traceback (most recent call last):
File "/home/misha/Documents/finance/prices/some_csv.py", line 3, in
<module>
column1 = CSV[0]
TypeError: '_csv.reader' object has no attribute '__getitem__'
Is there any pythonic way to open a .csv file and put each column in
different list not using attribute getitem?
Thanks.
NOTE: and also i need to skip first row.
Tuesday, October 1, 2013
How can I implement tf history command in C#?
How can I implement tf history command in C#?
I would like to implement the following command using TFS programming API:
tf history /stopafter:1 /version:W /recursive /format:detailed /noprompt .
I have some code, but it tries to inspect local workspace info and there
is none. So, I am back to nothing.
How is it done?
I would like to implement the following command using TFS programming API:
tf history /stopafter:1 /version:W /recursive /format:detailed /noprompt .
I have some code, but it tries to inspect local workspace info and there
is none. So, I am back to nothing.
How is it done?
Error with copy constructor
Error with copy constructor
My program keeps dyeing when trying to allocate new memory for my array.
By calling the add word function. Any help would be great!
Full code download @ http://www.johnsoncomputertechnologies.org/pgm2demo.zip
#include <iomanip> //Standard IO Manipulators Library
#include <algorithm>
#include <iostream> //Standard input/output library
#include <string> //Standard string Library
#include <cassert> //Error handeling Library
#include "pgm2.h"
using namespace std;
dictionary::dictionary()
{
wordptr = new value_type[DICTONARY_CAPACITY];
deffptr = new value_type[DICTONARY_CAPACITY];
used = 0;
}
dictionary::dictionary(dictionary& other)
{
value_type *wordptrs;
value_type *deffptrs;
wordptrs = new value_type[other.capacity];
deffptrs = new value_type[other.capacity];
used = other.used;
copy(other.wordptr, other.wordptr + used, wordptrs);
copy(other.deffptr, other.deffptr + used, deffptrs);
}
dictionary::~dictionary()
{
delete [] wordptr;
delete [] deffptr;
}
//Functions
void dictionary::reserve(size_type new_capacity)
{
value_type *larger_word;
value_type *larger_deff;
if(new_capacity == capacity)
return; //There allocated memory is already the correct size
if(new_capacity < used)
new_capacity = used;
larger_word = new value_type[new_capacity];
larger_deff = new value_type[new_capacity];
copy(wordptr, wordptr + used, larger_word);
copy(deffptr, deffptr + used, larger_deff);
delete [] wordptr;
delete [] deffptr;
wordptr = larger_word;
deffptr = larger_deff;
capacity = new_capacity;
}
void dictionary::addword(const value_type& word, const value_type& deff)
{
if(used == capacity)
reserve(used+1);
wordptr[used] = word;
deffptr[used] = deff;
++used;
}
pgm2.h
#include <iomanip> //Standard IO Manipulators Library
#include <algorithm>
#include <iostream> //Standard input/output library
#include <string> //Standard string Library
#include <cassert> //Error handeling Library
using namespace std;
class dictionary
{
public:
typedef string value_type;
typedef std::size_t size_type;
static const size_type DICTONARY_CAPACITY = 25;
//Default Constructor
dictionary();
dictionary(dictionary& other);
//Destructor
~dictionary();
//Functions
void reserve(size_type new_capacity);
void addword(const value_type& word, const value_type& deff);
void startPat (value_type patt);
void endPat(value_type patt);
void containsPat(value_type patt);
void print();
private:
value_type *wordptr;
value_type *deffptr;
size_type used;
size_type capacity;
};
My program keeps dyeing when trying to allocate new memory for my array.
By calling the add word function. Any help would be great!
Full code download @ http://www.johnsoncomputertechnologies.org/pgm2demo.zip
#include <iomanip> //Standard IO Manipulators Library
#include <algorithm>
#include <iostream> //Standard input/output library
#include <string> //Standard string Library
#include <cassert> //Error handeling Library
#include "pgm2.h"
using namespace std;
dictionary::dictionary()
{
wordptr = new value_type[DICTONARY_CAPACITY];
deffptr = new value_type[DICTONARY_CAPACITY];
used = 0;
}
dictionary::dictionary(dictionary& other)
{
value_type *wordptrs;
value_type *deffptrs;
wordptrs = new value_type[other.capacity];
deffptrs = new value_type[other.capacity];
used = other.used;
copy(other.wordptr, other.wordptr + used, wordptrs);
copy(other.deffptr, other.deffptr + used, deffptrs);
}
dictionary::~dictionary()
{
delete [] wordptr;
delete [] deffptr;
}
//Functions
void dictionary::reserve(size_type new_capacity)
{
value_type *larger_word;
value_type *larger_deff;
if(new_capacity == capacity)
return; //There allocated memory is already the correct size
if(new_capacity < used)
new_capacity = used;
larger_word = new value_type[new_capacity];
larger_deff = new value_type[new_capacity];
copy(wordptr, wordptr + used, larger_word);
copy(deffptr, deffptr + used, larger_deff);
delete [] wordptr;
delete [] deffptr;
wordptr = larger_word;
deffptr = larger_deff;
capacity = new_capacity;
}
void dictionary::addword(const value_type& word, const value_type& deff)
{
if(used == capacity)
reserve(used+1);
wordptr[used] = word;
deffptr[used] = deff;
++used;
}
pgm2.h
#include <iomanip> //Standard IO Manipulators Library
#include <algorithm>
#include <iostream> //Standard input/output library
#include <string> //Standard string Library
#include <cassert> //Error handeling Library
using namespace std;
class dictionary
{
public:
typedef string value_type;
typedef std::size_t size_type;
static const size_type DICTONARY_CAPACITY = 25;
//Default Constructor
dictionary();
dictionary(dictionary& other);
//Destructor
~dictionary();
//Functions
void reserve(size_type new_capacity);
void addword(const value_type& word, const value_type& deff);
void startPat (value_type patt);
void endPat(value_type patt);
void containsPat(value_type patt);
void print();
private:
value_type *wordptr;
value_type *deffptr;
size_type used;
size_type capacity;
};
How do I calculate roll, pitch, yaw from a unit vector?
How do I calculate roll, pitch, yaw from a unit vector?
I am provided a unit vector giving a direction in x, y, z coordinates, and
that the roll is defined as about the x axis, pitch around y, yaw around
z. I'm trying to determine how to calculate roll, pitch, and yaw given the
unit vector. I can see that the information should be there, but after
looking in to it for a bit, I've been unable to find the correct method of
doing this. How do I go about doing this?
I am provided a unit vector giving a direction in x, y, z coordinates, and
that the roll is defined as about the x axis, pitch around y, yaw around
z. I'm trying to determine how to calculate roll, pitch, and yaw given the
unit vector. I can see that the information should be there, but after
looking in to it for a bit, I've been unable to find the correct method of
doing this. How do I go about doing this?
Looking for a SF story regarding women growing things in their wombs scifi.stackexchange.com
Looking for a SF story regarding women growing things in their wombs –
scifi.stackexchange.com
I'm looking for the title and author of a short story or novelette that I
read quite some time ago. The main characters are two young women. One is
taking correspondence courses, and is constantly …
scifi.stackexchange.com
I'm looking for the title and author of a short story or novelette that I
read quite some time ago. The main characters are two young women. One is
taking correspondence courses, and is constantly …
Monday, September 30, 2013
.exe files getting downloaded when asked to install `ubuntu-restricted-extras` askubuntu.com
.exe files getting downloaded when asked to install
`ubuntu-restricted-extras` – askubuntu.com
I was trying to install Adobe flash plugin for Firefox 24.0 on Ubuntu
12.04 for which I executed sudo apt-get install ubuntu-restricted-extras
and I got the following messages: What suprises me is …
`ubuntu-restricted-extras` – askubuntu.com
I was trying to install Adobe flash plugin for Firefox 24.0 on Ubuntu
12.04 for which I executed sudo apt-get install ubuntu-restricted-extras
and I got the following messages: What suprises me is …
Qmail / Zend Mail - RFC 5322 compliant
Qmail / Zend Mail - RFC 5322 compliant
My company is getting spammed by itself, or rather by it's Qmail, we've
got a few automated processes sending out e-mails with Qmail and Zend
Mail.
I'm not a expert in either of these, (I know literally nothing about
them), and the 'spam e-mails' are Qmail telling us that a series of
e-mails being sent isn't RFC 5322 compliant.
Is there a way for me to locate what is generating these error e-mails? Or
a place where I can find out what e-mails it's trying to deliver but
can't.
This is the mail we recieve
From: MAILER-DAEMON@www.company.com
[mailto:MAILER-DAEMON@www.company.com]
Sent: 10. september 2013 15:10
To: company@www.company.com
Subject: failure notice
Hi. This is the qmail-send program at www.company.com.
I'm afraid I wasn't able to deliver your message to the following addresses.
This is a permanent error; I've given up. Sorry it didn't work out.
<user@mail.com>:
65.54.188.110 failed after I sent the message.
Remote host said: 550 5.7.0 (BAY0-MC3-F46) Message could not be delivered.
Please ensure the message is RFC 5322 compliant.
--- Below this line is a copy of the message.
Return-Path: <compnay@company.com>
Received: (qmail 25746 invoked by uid 0); 10 Sep 2013 15:10:02 +0200
Message-ID: <20130910131002.25707.qmail@www.company.com>
To: user <user@mail.com>
Subject:
From:
Date: Tue, 10 Sep 2013 15:10:02 +0200
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline
My company is getting spammed by itself, or rather by it's Qmail, we've
got a few automated processes sending out e-mails with Qmail and Zend
Mail.
I'm not a expert in either of these, (I know literally nothing about
them), and the 'spam e-mails' are Qmail telling us that a series of
e-mails being sent isn't RFC 5322 compliant.
Is there a way for me to locate what is generating these error e-mails? Or
a place where I can find out what e-mails it's trying to deliver but
can't.
This is the mail we recieve
From: MAILER-DAEMON@www.company.com
[mailto:MAILER-DAEMON@www.company.com]
Sent: 10. september 2013 15:10
To: company@www.company.com
Subject: failure notice
Hi. This is the qmail-send program at www.company.com.
I'm afraid I wasn't able to deliver your message to the following addresses.
This is a permanent error; I've given up. Sorry it didn't work out.
<user@mail.com>:
65.54.188.110 failed after I sent the message.
Remote host said: 550 5.7.0 (BAY0-MC3-F46) Message could not be delivered.
Please ensure the message is RFC 5322 compliant.
--- Below this line is a copy of the message.
Return-Path: <compnay@company.com>
Received: (qmail 25746 invoked by uid 0); 10 Sep 2013 15:10:02 +0200
Message-ID: <20130910131002.25707.qmail@www.company.com>
To: user <user@mail.com>
Subject:
From:
Date: Tue, 10 Sep 2013 15:10:02 +0200
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline
how to insert a piece of text in all headers in a document with VBA
how to insert a piece of text in all headers in a document with VBA
all the answers I can find (and all the examples elsewhere on the web) are
about very complicated insert operations (only on 1 header, or only odd
pages, or not using select, or some such). How do you insert a simple
piece of text into all headers in a word document using VBA? Thanks.
all the answers I can find (and all the examples elsewhere on the web) are
about very complicated insert operations (only on 1 header, or only odd
pages, or not using select, or some such). How do you insert a simple
piece of text into all headers in a word document using VBA? Thanks.
How do I create a pdf template using Java and PDFbox
How do I create a pdf template using Java and PDFbox
I'd like to know how would i generate a template with Java using Apache
PDFbox. The intention is to generate a pdf template, use it to print
details of n students by plugging in each student info into those place
holders. Please read carefully I do not want to create pdf's using a
template created outside, no, I want to create the template itself using
Java then use the template again in Java. thanks.
I'd like to know how would i generate a template with Java using Apache
PDFbox. The intention is to generate a pdf template, use it to print
details of n students by plugging in each student info into those place
holders. Please read carefully I do not want to create pdf's using a
template created outside, no, I want to create the template itself using
Java then use the template again in Java. thanks.
Sunday, September 29, 2013
Merge Sort in place for python (Cant find what is wrong)
Merge Sort in place for python (Cant find what is wrong)
I was reading about merge sort(In place) in my algorithm book (Intro to
algorithms 3rd edition Cormen), and I decided to implement it in Python.
The problem is that I can't find what I am doing wrong... I saw some code
in C++, but even with that I can't fix it.
Here is my code:
def MERGE(A,start,mid,end):
L=[0]*(mid - start + 1)
for i in range(len(L) - 1):
L[i] = A[start+i]
L[len(L) - 1] = 100000 # centinel, (fix)
R=[0]*(end - mid + 2)
for j in range(len(R) - 1):
R[j] = A[mid+j]
R[len(R) - 1] = 100000
i = 0
j = 0
k = start
for l in range(k,end):
if(L[i] < R[j]):
A[l] = L[i]
i = i + 1
else:
A[k] = R[j]
j = j + 1
def mergeSort(A,p,r):
if p < r:
mid = int((p+r)/2)
mergeSort(A,p,mid)
mergeSort(A,mid+1,r)
MERGE(A,p,mid,r)
A = [20, 30, 15, 21, 42, 45, 31, 0, 9]
mergeSort(A,0,len(A)]
When I run the code I have some index problems:
File "myrealmerge.py", line 9, in MERGE
R[j] = A[mid+j]
IndexError: list index out of range
I know that this my be a "dumb question" and that there is some related
post, but I tried the suggestions in there and It does not work for me...
Can anyone help me? T Thanks!
I was reading about merge sort(In place) in my algorithm book (Intro to
algorithms 3rd edition Cormen), and I decided to implement it in Python.
The problem is that I can't find what I am doing wrong... I saw some code
in C++, but even with that I can't fix it.
Here is my code:
def MERGE(A,start,mid,end):
L=[0]*(mid - start + 1)
for i in range(len(L) - 1):
L[i] = A[start+i]
L[len(L) - 1] = 100000 # centinel, (fix)
R=[0]*(end - mid + 2)
for j in range(len(R) - 1):
R[j] = A[mid+j]
R[len(R) - 1] = 100000
i = 0
j = 0
k = start
for l in range(k,end):
if(L[i] < R[j]):
A[l] = L[i]
i = i + 1
else:
A[k] = R[j]
j = j + 1
def mergeSort(A,p,r):
if p < r:
mid = int((p+r)/2)
mergeSort(A,p,mid)
mergeSort(A,mid+1,r)
MERGE(A,p,mid,r)
A = [20, 30, 15, 21, 42, 45, 31, 0, 9]
mergeSort(A,0,len(A)]
When I run the code I have some index problems:
File "myrealmerge.py", line 9, in MERGE
R[j] = A[mid+j]
IndexError: list index out of range
I know that this my be a "dumb question" and that there is some related
post, but I tried the suggestions in there and It does not work for me...
Can anyone help me? T Thanks!
How do I access the command line argument variable when making an alias in Terminal?
How do I access the command line argument variable when making an alias in
Terminal?
I'm making a few aliases to speed up my development processes.
Right now I'm trying to make a cdls which is quite obviously a cd
{arbitrary-file} && ls {arbitrary-file}
I was under the impression that alias cdls='cd $@ && ls $@ would work, but
it looks like I was mistaken about $@ carrying the argument (file path)
since this sends me back to my $HOME directory every time.
Terminal?
I'm making a few aliases to speed up my development processes.
Right now I'm trying to make a cdls which is quite obviously a cd
{arbitrary-file} && ls {arbitrary-file}
I was under the impression that alias cdls='cd $@ && ls $@ would work, but
it looks like I was mistaken about $@ carrying the argument (file path)
since this sends me back to my $HOME directory every time.
MATLAB GUI Zoom with multiple plots
MATLAB GUI Zoom with multiple plots
I have 2 plots in a MATLAB gui and i want to link them together so a zoom
on one plot zooms the other.
Unlike similar questions i have seen on linking plots neither my x data or
y data is shared by either graph, but it is related.
My data consists of the heights of land measured by a plane flying over
them over a period of 5 seconds.
Plot 1 : The height of land
y: height = [10,9,4,6,3];
x: time = [1,2,3,4,5];
Plot 2 : land coordinates
y: latitude = [10,20,30,40,50];
x: longitude = [1,2,3,4,5];
If the user zooms in the x axis on Plot 1, for example showing the first 3
seconds of flight I want to zoom the x and y-axis of Plot 2 so only the
first 3 longitude & latitude coordinates in the longitude & latitude
arrays are shown.
Is this possible?
I have 2 plots in a MATLAB gui and i want to link them together so a zoom
on one plot zooms the other.
Unlike similar questions i have seen on linking plots neither my x data or
y data is shared by either graph, but it is related.
My data consists of the heights of land measured by a plane flying over
them over a period of 5 seconds.
Plot 1 : The height of land
y: height = [10,9,4,6,3];
x: time = [1,2,3,4,5];
Plot 2 : land coordinates
y: latitude = [10,20,30,40,50];
x: longitude = [1,2,3,4,5];
If the user zooms in the x axis on Plot 1, for example showing the first 3
seconds of flight I want to zoom the x and y-axis of Plot 2 so only the
first 3 longitude & latitude coordinates in the longitude & latitude
arrays are shown.
Is this possible?
Accessing JSON string created in jsp from javascript
Accessing JSON string created in jsp from javascript
in jsp scriptlet I assign a value to string variable that matches json
syntax.
<%
String jsonString = "{jsonsyntax}";
%>
In javscript I access it like:
var json= <%=jsonString %>;
The problem with this, when, in browser I use "view page source" I see the
content of variable. how can I avoid it?
in jsp scriptlet I assign a value to string variable that matches json
syntax.
<%
String jsonString = "{jsonsyntax}";
%>
In javscript I access it like:
var json= <%=jsonString %>;
The problem with this, when, in browser I use "view page source" I see the
content of variable. how can I avoid it?
Saturday, September 28, 2013
CLR Hosting in C++ : how to use Type.InvokeMember with out Parameter
CLR Hosting in C++ : how to use Type.InvokeMember with out Parameter
I'm doing some work with CLR Hosting (with C++). I followed the sample
that microsoft provided and I can load .net runtime and load assemblies,
create some object instance and so on.
Now I have a question about using _Type.InvokeMember.
virtual HRESULT __stdcall InvokeMember (
/*[in]*/ BSTR name,
/*[in]*/ enum BindingFlags invokeAttr,
/*[in]*/ struct _Binder * Binder,
/*[in]*/ VARIANT Target,
/*[in]*/ SAFEARRAY * args,
/*[in]*/ SAFEARRAY * modifiers,
/*[in]*/ struct _CultureInfo * culture,
/*[in]*/ SAFEARRAY * namedParameters,
/*[out,retval]*/ VARIANT * pRetVal ) = 0;
I can use other overload version of it to invoke the object method
successfully. However, now I want to invoke a method with a out/ref
parameter like:
double TestOutParam(out double output);
The tricky part is the modifiers. I've tried passing a boolean array or
even creating a dotnet ParameterModifier to fill with it. All I get is
0x80131533. COR_E_SAFEARRAYTYPEMISMATCH.
Here is my sample code:
CComSafeArray<VARIANT> parameters; //The InvokeMember Args Array
parameters.Create(2L,0L);
parameters.SetAt(0,_variant_t(input)); //The first parameter
double dbResult=0;
_variant_t outParam,vtOutput;
outParam.vt= VT_R8;
outParam.dblVal=0;
parameters.SetAt(1,outParam,0);//The second parameter
CComSafeArray<VARIANT> parameterMods; //The ParameterModifier Array
parameterMods.Create(1L,0L);
auto parameterModifier=DotNetParameterModifier::Create(2); //Create a
dotnet ParameterModifier
parameterModifier->SetItem(0,false);
parameterModifier->SetItem(1,true);//Set 2nd item to true, means the 2nd
parameter is out parameter
parameterMods.SetAt(0,parameterModifier->GetVtObject(),0);//GetVtObject
return the VARIANT point the ParameterModifier
/*A wrapper of the _type.InvokeMember. The actual code is
HRESULT hr = _typePtr->InvokeMember(bstrMethodName,
static_cast<BindingFlags>(
BindingFlags_InvokeMethod | BindingFlags_Instance | BindingFlags_Public),
NULL, vtObject,parameters, parameterModifier,NULL,NULL,&vtRetValue);
*/
_variant_t
boolResult=this->InvokeMember("TestOutParam",parameters,parameterMods);
parameterMods.Destroy();
parameters.Destroy();
if(boolResult.boolVal)
return outParam.dblVal;
return 0;
Somebody have any idea?
I'm doing some work with CLR Hosting (with C++). I followed the sample
that microsoft provided and I can load .net runtime and load assemblies,
create some object instance and so on.
Now I have a question about using _Type.InvokeMember.
virtual HRESULT __stdcall InvokeMember (
/*[in]*/ BSTR name,
/*[in]*/ enum BindingFlags invokeAttr,
/*[in]*/ struct _Binder * Binder,
/*[in]*/ VARIANT Target,
/*[in]*/ SAFEARRAY * args,
/*[in]*/ SAFEARRAY * modifiers,
/*[in]*/ struct _CultureInfo * culture,
/*[in]*/ SAFEARRAY * namedParameters,
/*[out,retval]*/ VARIANT * pRetVal ) = 0;
I can use other overload version of it to invoke the object method
successfully. However, now I want to invoke a method with a out/ref
parameter like:
double TestOutParam(out double output);
The tricky part is the modifiers. I've tried passing a boolean array or
even creating a dotnet ParameterModifier to fill with it. All I get is
0x80131533. COR_E_SAFEARRAYTYPEMISMATCH.
Here is my sample code:
CComSafeArray<VARIANT> parameters; //The InvokeMember Args Array
parameters.Create(2L,0L);
parameters.SetAt(0,_variant_t(input)); //The first parameter
double dbResult=0;
_variant_t outParam,vtOutput;
outParam.vt= VT_R8;
outParam.dblVal=0;
parameters.SetAt(1,outParam,0);//The second parameter
CComSafeArray<VARIANT> parameterMods; //The ParameterModifier Array
parameterMods.Create(1L,0L);
auto parameterModifier=DotNetParameterModifier::Create(2); //Create a
dotnet ParameterModifier
parameterModifier->SetItem(0,false);
parameterModifier->SetItem(1,true);//Set 2nd item to true, means the 2nd
parameter is out parameter
parameterMods.SetAt(0,parameterModifier->GetVtObject(),0);//GetVtObject
return the VARIANT point the ParameterModifier
/*A wrapper of the _type.InvokeMember. The actual code is
HRESULT hr = _typePtr->InvokeMember(bstrMethodName,
static_cast<BindingFlags>(
BindingFlags_InvokeMethod | BindingFlags_Instance | BindingFlags_Public),
NULL, vtObject,parameters, parameterModifier,NULL,NULL,&vtRetValue);
*/
_variant_t
boolResult=this->InvokeMember("TestOutParam",parameters,parameterMods);
parameterMods.Destroy();
parameters.Destroy();
if(boolResult.boolVal)
return outParam.dblVal;
return 0;
Somebody have any idea?
Getting started with ARM or STM microcontrollers
Getting started with ARM or STM microcontrollers
I'm not too good with all this microcontrollers stuff.
I've used to handle with AVR assembler. But i'd like to get some knowledge
on ARM (or specific for STM MCUs) assembler and C.
Is there any book like 'quick guide' to ARM (or STM specific) assembler?
Thanks in advance.
Sorry for my broken English.
I'm not too good with all this microcontrollers stuff.
I've used to handle with AVR assembler. But i'd like to get some knowledge
on ARM (or specific for STM MCUs) assembler and C.
Is there any book like 'quick guide' to ARM (or STM specific) assembler?
Thanks in advance.
Sorry for my broken English.
php verification for calls to a database
php verification for calls to a database
I have set up a page on a site for collecting member information. I simply
want to key off a check box that needs to have a verification on it fail
if not checked. Also if any required field is NOT filled out. I am NOT
checking emails. I have the following $_POST['FirstName'],",".
$_Post['LastName'],",". and so on for the fields in code for the db. On
the html side (php set up)
I have set up a page on a site for collecting member information. I simply
want to key off a check box that needs to have a verification on it fail
if not checked. Also if any required field is NOT filled out. I am NOT
checking emails. I have the following $_POST['FirstName'],",".
$_Post['LastName'],",". and so on for the fields in code for the db. On
the html side (php set up)
public key denied, but ssh key accepted
public key denied, but ssh key accepted
pI'm having trouble with pushing to git (or rather, git is having trouble
with me) as when I codegit push/code I get an error: /p precodePermission
denied (publickey). fatal: The remote end hung up unexpectedly /code/pre
pI've looked at git's a
href=https://help.github.com/articles/error-permission-denied-publickey
rel=nofollowhelp page/a for this, but all of the 'tests' that they suggest
are passing, including checking to see that the correct key is being used
by running code$ ssh -vT git@github.com/code. This seems to be where most
people run aground based on the posts I've seen on SO, but it's working
for me. Here's the output in case I'm missing something. /p
precodeOpenSSH_5.2p1, OpenSSL 0.9.8r 8 Feb 2011 debug1: Reading
configuration data /etc/ssh_config debug1: Connecting to github.com
[192.30.252.130] port 22. debug1: Connection established. debug1: identity
file /Users/charliekim/.ssh/identity type -1 debug1: identity file
/Users/charliekim/.ssh/id_rsa type 1 debug1: identity file
/Users/charliekim/.ssh/id_dsa type -1 debug1: Remote protocol version 2.0,
remote software version OpenSSH_5.9p1 Debian-5ubuntu1+github5 debug1:
match: OpenSSH_5.9p1 Debian-5ubuntu1+github5 pat OpenSSH* debug1: Enabling
compatibility mode for protocol 2.0 debug1: Local version string
SSH-2.0-OpenSSH_5.2 debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT
received debug1: kex: server-gt;client aes128-ctr hmac-md5 none debug1:
kex: client-gt;server aes128-ctr hmac-md5 none debug1:
SSH2_MSG_KEX_DH_GEX_REQUEST(1024lt;1024lt;8192) sent debug1: expecting
SSH2_MSG_KEX_DH_GEX_GROUP debug1: SSH2_MSG_KEX_DH_GEX_INIT sent debug1:
expecting SSH2_MSG_KEX_DH_GEX_REPLY debug1: Host 'github.com' is known and
matches the RSA host key. debug1: Found key in
/Users/charliekim/.ssh/known_hosts:1 debug1: ssh_rsa_verify: signature
correct debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can
continue: publickey debug1: Next authentication method: publickey debug1:
Offering public key: /Users/charliekim/.ssh/id_rsa debug1: Server accepts
key: pkalg ssh-rsa blen 277 debug1: Authentication succeeded (publickey).
debug1: channel 0: new [client-session] debug1: Requesting
no-more-sessions@openssh.com debug1: Entering interactive session. debug1:
Remote: Forced command. debug1: Remote: Port forwarding disabled. debug1:
Remote: X11 forwarding disabled. debug1: Remote: Agent forwarding
disabled. debug1: Remote: Pty allocation disabled. debug1: Remote: Forced
command. debug1: Remote: Port forwarding disabled. debug1: Remote: X11
forwarding disabled. debug1: Remote: Agent forwarding disabled. debug1:
Remote: Pty allocation disabled. PTY allocation request failed on channel
0 Hi **! You've successfully authenticated, but GitHub does not provide
shell access. debug1: client_input_channel_req: channel 0 rtype
exit-status reply 0 debug1: client_input_channel_req: channel 0 rtype
eow@openssh.com reply 0 debug1: channel 0: free: client-session, nchannels
1 Connection to github.com closed. Transferred: sent 2496, received 3048
bytes, in 0.3 seconds Bytes per second: sent 9462.3, received 11554.9
debug1: Exit status 1 /code/pre
pI'm having trouble with pushing to git (or rather, git is having trouble
with me) as when I codegit push/code I get an error: /p precodePermission
denied (publickey). fatal: The remote end hung up unexpectedly /code/pre
pI've looked at git's a
href=https://help.github.com/articles/error-permission-denied-publickey
rel=nofollowhelp page/a for this, but all of the 'tests' that they suggest
are passing, including checking to see that the correct key is being used
by running code$ ssh -vT git@github.com/code. This seems to be where most
people run aground based on the posts I've seen on SO, but it's working
for me. Here's the output in case I'm missing something. /p
precodeOpenSSH_5.2p1, OpenSSL 0.9.8r 8 Feb 2011 debug1: Reading
configuration data /etc/ssh_config debug1: Connecting to github.com
[192.30.252.130] port 22. debug1: Connection established. debug1: identity
file /Users/charliekim/.ssh/identity type -1 debug1: identity file
/Users/charliekim/.ssh/id_rsa type 1 debug1: identity file
/Users/charliekim/.ssh/id_dsa type -1 debug1: Remote protocol version 2.0,
remote software version OpenSSH_5.9p1 Debian-5ubuntu1+github5 debug1:
match: OpenSSH_5.9p1 Debian-5ubuntu1+github5 pat OpenSSH* debug1: Enabling
compatibility mode for protocol 2.0 debug1: Local version string
SSH-2.0-OpenSSH_5.2 debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT
received debug1: kex: server-gt;client aes128-ctr hmac-md5 none debug1:
kex: client-gt;server aes128-ctr hmac-md5 none debug1:
SSH2_MSG_KEX_DH_GEX_REQUEST(1024lt;1024lt;8192) sent debug1: expecting
SSH2_MSG_KEX_DH_GEX_GROUP debug1: SSH2_MSG_KEX_DH_GEX_INIT sent debug1:
expecting SSH2_MSG_KEX_DH_GEX_REPLY debug1: Host 'github.com' is known and
matches the RSA host key. debug1: Found key in
/Users/charliekim/.ssh/known_hosts:1 debug1: ssh_rsa_verify: signature
correct debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can
continue: publickey debug1: Next authentication method: publickey debug1:
Offering public key: /Users/charliekim/.ssh/id_rsa debug1: Server accepts
key: pkalg ssh-rsa blen 277 debug1: Authentication succeeded (publickey).
debug1: channel 0: new [client-session] debug1: Requesting
no-more-sessions@openssh.com debug1: Entering interactive session. debug1:
Remote: Forced command. debug1: Remote: Port forwarding disabled. debug1:
Remote: X11 forwarding disabled. debug1: Remote: Agent forwarding
disabled. debug1: Remote: Pty allocation disabled. debug1: Remote: Forced
command. debug1: Remote: Port forwarding disabled. debug1: Remote: X11
forwarding disabled. debug1: Remote: Agent forwarding disabled. debug1:
Remote: Pty allocation disabled. PTY allocation request failed on channel
0 Hi **! You've successfully authenticated, but GitHub does not provide
shell access. debug1: client_input_channel_req: channel 0 rtype
exit-status reply 0 debug1: client_input_channel_req: channel 0 rtype
eow@openssh.com reply 0 debug1: channel 0: free: client-session, nchannels
1 Connection to github.com closed. Transferred: sent 2496, received 3048
bytes, in 0.3 seconds Bytes per second: sent 9462.3, received 11554.9
debug1: Exit status 1 /code/pre
Friday, September 27, 2013
Reorder table from jqueryUI sortable array
Reorder table from jqueryUI sortable array
Hello thanks for taking a look at this.
I am using jquery ui sortable on an <ul> whose id's increment from 0 - 16.
It creates an array like this when you sort.
var arr = ["1", "2", "4", "5", "6", "3", "10", "7", "8", "9", "17", "11",
"12", "13", "14", "15", "16"]
I have a method that I pass the list into to. Currently im trying to just
move the row to the new position, but I might have to repaint the table.
Here's the method.
positionColumns: function(list) {
var _this = this;
if (!list) list = this.order;
$(list).each(function(i, val) {
if (parseInt(val, 10) !== _this.order[i]) {
work(val, _this.order[i]);
console.log(list);
console.log(_this.order[i]);
} else {
return;
}
});
function work(from, to) {
var table = $('#dealbook-table');
var rows = $('tr', table);
var cols;
rows.each(function(i, row) {
cols = $(row).children('th, td');
console.log(cols);
cols.eq(from).detach().insertBefore(cols.eq(to));
});
}
},
Any help would be appreciated.
Hello thanks for taking a look at this.
I am using jquery ui sortable on an <ul> whose id's increment from 0 - 16.
It creates an array like this when you sort.
var arr = ["1", "2", "4", "5", "6", "3", "10", "7", "8", "9", "17", "11",
"12", "13", "14", "15", "16"]
I have a method that I pass the list into to. Currently im trying to just
move the row to the new position, but I might have to repaint the table.
Here's the method.
positionColumns: function(list) {
var _this = this;
if (!list) list = this.order;
$(list).each(function(i, val) {
if (parseInt(val, 10) !== _this.order[i]) {
work(val, _this.order[i]);
console.log(list);
console.log(_this.order[i]);
} else {
return;
}
});
function work(from, to) {
var table = $('#dealbook-table');
var rows = $('tr', table);
var cols;
rows.each(function(i, row) {
cols = $(row).children('th, td');
console.log(cols);
cols.eq(from).detach().insertBefore(cols.eq(to));
});
}
},
Any help would be appreciated.
Rename multiple MySQL tables by inserting an underscore
Rename multiple MySQL tables by inserting an underscore
How to rename a set of MySQL tables by inserting an underscore after a
keyword. The following example shows what I mean:
current names:
keywordcache
keywordfield
keywordmenu
etc.
expected names:
keyword_cache
keyword_field
keyword_menu
etc.
I use phpMyAdmin to access the data base. Renaming many tables one by one
is too time-consuming so I'm looking for some automatic method.
How to rename a set of MySQL tables by inserting an underscore after a
keyword. The following example shows what I mean:
current names:
keywordcache
keywordfield
keywordmenu
etc.
expected names:
keyword_cache
keyword_field
keyword_menu
etc.
I use phpMyAdmin to access the data base. Renaming many tables one by one
is too time-consuming so I'm looking for some automatic method.
Jersey File Upload Service missing dependency error
Jersey File Upload Service missing dependency error
I am attempting to make a file upload RESTful service. But it is spitting
out a dependency error.
Here is my code:
@ApiOperation(
value = "Upload File.",
notes = "Uploads and stores user files to the server." )
@ApiResponses(value = {
@ApiResponse(code = 403, message = "User not authorized to upload
files."),
@ApiResponse(code = 500, message = "Server error")})
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@ApiParam( value = "File", required = false)
@FormDataParam("file") InputStream uploadInputStream,
@ApiParam( value = "File Data", required = false)
@FormDataParam("file") FormDataContentDisposition fileDetail
){
return Response.ok("Test new endpoint").build();
}
I do have matching versions or jersey and multipart in my pom in my pom.xml
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>${jersey.version}</version>
</dependency>
<!-- jersey -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
and here is the error that is being produces
SEVERE: Missing dependency for method public javax.ws.rs.core.Response
com.lotame.ws.api.resources.FileResource.uploadFile(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition)
at parameter at index 0
SEVERE: Missing dependency for method public javax.ws.rs.core.Response
com.lotame.ws.api.resources.FileResource.uploadFile(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition)
at parameter at index 1
SEVERE: Method, public javax.ws.rs.core.Response
com.lotame.ws.api.resources.FileResource.uploadFile(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition),
annotated with POST of resource, class
com.lotame.ws.api.resources.FileResource, is not recognized as valid
resource method.
Any advice would be appreciated!
I am attempting to make a file upload RESTful service. But it is spitting
out a dependency error.
Here is my code:
@ApiOperation(
value = "Upload File.",
notes = "Uploads and stores user files to the server." )
@ApiResponses(value = {
@ApiResponse(code = 403, message = "User not authorized to upload
files."),
@ApiResponse(code = 500, message = "Server error")})
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@ApiParam( value = "File", required = false)
@FormDataParam("file") InputStream uploadInputStream,
@ApiParam( value = "File Data", required = false)
@FormDataParam("file") FormDataContentDisposition fileDetail
){
return Response.ok("Test new endpoint").build();
}
I do have matching versions or jersey and multipart in my pom in my pom.xml
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>${jersey.version}</version>
</dependency>
<!-- jersey -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
and here is the error that is being produces
SEVERE: Missing dependency for method public javax.ws.rs.core.Response
com.lotame.ws.api.resources.FileResource.uploadFile(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition)
at parameter at index 0
SEVERE: Missing dependency for method public javax.ws.rs.core.Response
com.lotame.ws.api.resources.FileResource.uploadFile(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition)
at parameter at index 1
SEVERE: Method, public javax.ws.rs.core.Response
com.lotame.ws.api.resources.FileResource.uploadFile(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition),
annotated with POST of resource, class
com.lotame.ws.api.resources.FileResource, is not recognized as valid
resource method.
Any advice would be appreciated!
What is the difference between the org.junit package and the junit.framework package?
What is the difference between the org.junit package and the
junit.framework package?
Whenever I use a Junit assert in my code, my IDE (Intellij IDEA 12)
politely offers to static-import it for me:
import static junit.framework.Assert.assertTrue;
However, it always gives me the choice of importing either the "org.junit"
version or the "junit.framework" version:
import static org.junit.Assert.assertTrue;
I can't find a clear answer online about what the difference is between
these two packages - is there a difference? If so, what is it? They both
come out of exactly the same Junit4 jar, so what's going on?
junit.framework package?
Whenever I use a Junit assert in my code, my IDE (Intellij IDEA 12)
politely offers to static-import it for me:
import static junit.framework.Assert.assertTrue;
However, it always gives me the choice of importing either the "org.junit"
version or the "junit.framework" version:
import static org.junit.Assert.assertTrue;
I can't find a clear answer online about what the difference is between
these two packages - is there a difference? If so, what is it? They both
come out of exactly the same Junit4 jar, so what's going on?
jQuery input selection - adding up totals inside a repeater
jQuery input selection - adding up totals inside a repeater
have two textboxes defined like so, which are inside a repeater:
<asp:TextBox ID="txtHours" runat="server" CssClass="text misch"
Width="50px" Text='<%# Eval("laborHours") %>'/>
<asp:TextBox ID="txtCosts" runat="server" CssClass="text misc"
Width="50px" Text='<%# Eval("totalCosts") %>'/>
i also have two boxes where i want to put totals:
<asp:TextBox ID="txtMiscH" runat="server" CssClass="text hours"
Width="200px" />
<asp:TextBox ID="txtMisc" runat="server" CssClass="text add" Width="200px" />
when the value in the repeater changes, i want to add them up and put in
the appropriate total boxes.
this is where i am now:
//add up miscaleneous mnumbers
//dollar amoungs
$("input[class~='misc']").change(function (event) {
var sum = 0;
var num = 0;
alert("X");
$("input[class~='misc']").each(function (event) {
alert("X");
num = parseInt($(this).val()) || 0;
sum = sum + num;
});
$("input[id*='txtMisc']").val(sum);
$("input[class~='add']").trigger('change');
});
//hours
$("input[class~='misch']").change(function (event) {
var sum = 0;
var num = 0;
$("input[class~='misch']").each(function (event) {
num = parseInt($(this).val()) || 0;
sum = sum + num;
});
$("input[id*='txtMiscH']").val(sum);
});
but it does not look like the first option works at all.
also i saw that there are different ways to select input
input[class~ or input[class* or input[class^
am i using the wrong one?
i guess because misc is also part of misch, it does the calculations for
hours, even when i only update the misc costs box. please hep. would
renaming class type be the easiest way to fix this?
http://jsfiddle.net/SKYDr/
have two textboxes defined like so, which are inside a repeater:
<asp:TextBox ID="txtHours" runat="server" CssClass="text misch"
Width="50px" Text='<%# Eval("laborHours") %>'/>
<asp:TextBox ID="txtCosts" runat="server" CssClass="text misc"
Width="50px" Text='<%# Eval("totalCosts") %>'/>
i also have two boxes where i want to put totals:
<asp:TextBox ID="txtMiscH" runat="server" CssClass="text hours"
Width="200px" />
<asp:TextBox ID="txtMisc" runat="server" CssClass="text add" Width="200px" />
when the value in the repeater changes, i want to add them up and put in
the appropriate total boxes.
this is where i am now:
//add up miscaleneous mnumbers
//dollar amoungs
$("input[class~='misc']").change(function (event) {
var sum = 0;
var num = 0;
alert("X");
$("input[class~='misc']").each(function (event) {
alert("X");
num = parseInt($(this).val()) || 0;
sum = sum + num;
});
$("input[id*='txtMisc']").val(sum);
$("input[class~='add']").trigger('change');
});
//hours
$("input[class~='misch']").change(function (event) {
var sum = 0;
var num = 0;
$("input[class~='misch']").each(function (event) {
num = parseInt($(this).val()) || 0;
sum = sum + num;
});
$("input[id*='txtMiscH']").val(sum);
});
but it does not look like the first option works at all.
also i saw that there are different ways to select input
input[class~ or input[class* or input[class^
am i using the wrong one?
i guess because misc is also part of misch, it does the calculations for
hours, even when i only update the misc costs box. please hep. would
renaming class type be the easiest way to fix this?
http://jsfiddle.net/SKYDr/
Google custom search is not returning proper result in magento
Google custom search is not returning proper result in magento
I have implemented custom google search in two pages. here you guys can
find it here
rituwears.in
I provide a screenshot of an image of my page after search.. You can
easily find how results are coming as search results
plz need help
I have implemented custom google search in two pages. here you guys can
find it here
rituwears.in
I provide a screenshot of an image of my page after search.. You can
easily find how results are coming as search results
plz need help
generating list with permuted tuples in a list
generating list with permuted tuples in a list
How to permute the tuple on a list.
A= [(a,b), (c,d), (e, f)]
If A is a list then it's permutations are
[(a,b), (c,d), (e, f)]
[(a,b), (c,d), (f, e)]
[(a,b), (d,c), (e, f)]
[(a,b), (d,e), (f, e)]
....
It has 8 such list.
How to permute the tuple on a list.
A= [(a,b), (c,d), (e, f)]
If A is a list then it's permutations are
[(a,b), (c,d), (e, f)]
[(a,b), (c,d), (f, e)]
[(a,b), (d,c), (e, f)]
[(a,b), (d,e), (f, e)]
....
It has 8 such list.
Thursday, September 26, 2013
How to show download progress for MVC4 page
How to show download progress for MVC4 page
How to implement a download progress bar or an animation gif indicating
file downloading in progress on an MVC4 page. The download progress bar
animation should start with click of "download" button .How to identify
when the download is completed so as to hide the animation.
How to implement a download progress bar or an animation gif indicating
file downloading in progress on an MVC4 page. The download progress bar
animation should start with click of "download" button .How to identify
when the download is completed so as to hide the animation.
Wednesday, September 25, 2013
How turn off autofocus with CameraBridgeViewBase opencv4android
How turn off autofocus with CameraBridgeViewBase opencv4android
I'm developing an app for Android 4.2.2, and I want to turn off the
autofocus. There is a way to do it if i'm using CameraBridgeViewBase ?
The version of the opencv library is 2.4.5. The specific device in wich
that i want the app to work fine is Samsung Galaxy s3
I'm developing an app for Android 4.2.2, and I want to turn off the
autofocus. There is a way to do it if i'm using CameraBridgeViewBase ?
The version of the opencv library is 2.4.5. The specific device in wich
that i want the app to work fine is Samsung Galaxy s3
Thursday, September 19, 2013
unresolved external symbol, but I included files with the function definitions?
unresolved external symbol, but I included files with the function
definitions?
I'm writing a C++ console app to test an API. I added the ...\SDK\include\
folder path under "Additional Include Directories." Here's the code for my
main .cpp file:
#include "stdafx.h"
#include <iostream>
#include "aaapi.h"
#include "aaapidef.h"
#include "aaapiver.h"
#include "aaatypes.h"
#include "aadmsapi.h"
#include "aadmsdef.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
LPCWSTR dbName=L"xyz.com:abc";
LPCWSTR user=L"";
LPCWSTR pwd=L"";
LPCWSTR schema=L"";
bool resultInit=aaApi_Initialize(AAMODULE_ALL);
bool resultLogin=aaApi_Login(AAAPIDB_UNKNOWN,dbName,user,pwd,schema);
return 0;
}
I'm getting these errors:
unresolved external symbol _aaApi_Initialize@4 referenced in function _wmain
unresolved external symbol _aaApi_Login@20 referenced in function _wmain
From the errors, it seems like both of the API functions are undefined,
but I thought the #include statements would have taken care of that,
especially because their function headers show up in the Intellisense.
What am I missing here?
definitions?
I'm writing a C++ console app to test an API. I added the ...\SDK\include\
folder path under "Additional Include Directories." Here's the code for my
main .cpp file:
#include "stdafx.h"
#include <iostream>
#include "aaapi.h"
#include "aaapidef.h"
#include "aaapiver.h"
#include "aaatypes.h"
#include "aadmsapi.h"
#include "aadmsdef.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
LPCWSTR dbName=L"xyz.com:abc";
LPCWSTR user=L"";
LPCWSTR pwd=L"";
LPCWSTR schema=L"";
bool resultInit=aaApi_Initialize(AAMODULE_ALL);
bool resultLogin=aaApi_Login(AAAPIDB_UNKNOWN,dbName,user,pwd,schema);
return 0;
}
I'm getting these errors:
unresolved external symbol _aaApi_Initialize@4 referenced in function _wmain
unresolved external symbol _aaApi_Login@20 referenced in function _wmain
From the errors, it seems like both of the API functions are undefined,
but I thought the #include statements would have taken care of that,
especially because their function headers show up in the Intellisense.
What am I missing here?
Creating lists from subtrees
Creating lists from subtrees
For an application I'm writing, I need to create flat lists from a tree
based structure which contain the items of the sublist.
For example, if I had this tree:
-a
|-b
|-c
|-d
I'd like to create lists from the left and right leaves recursively, so
for example:
[a][b,c,d]. [b][c,d], [c][d]
etc
So far I'm storing my tree as a tuple like so:
(1.0,(0.5,(0.25, (0.125,'d'),(0.125,'c')),(0.25,'b')),(0.5,'a'))
I have a function which prints the information on the leaves:
def printTree(tree, prefix = ''):
if len(tree) == 2:
print tree[1], prefix
else:
printTree(tree[1], prefix + '0')
printTree(tree[2], prefix + '1')
(This is a Huffman).
I've tried creating a function whoneich replaces the print statements with
list() statements, but that didn't work.
Does anyone have any ideas about how I could go about this?
For an application I'm writing, I need to create flat lists from a tree
based structure which contain the items of the sublist.
For example, if I had this tree:
-a
|-b
|-c
|-d
I'd like to create lists from the left and right leaves recursively, so
for example:
[a][b,c,d]. [b][c,d], [c][d]
etc
So far I'm storing my tree as a tuple like so:
(1.0,(0.5,(0.25, (0.125,'d'),(0.125,'c')),(0.25,'b')),(0.5,'a'))
I have a function which prints the information on the leaves:
def printTree(tree, prefix = ''):
if len(tree) == 2:
print tree[1], prefix
else:
printTree(tree[1], prefix + '0')
printTree(tree[2], prefix + '1')
(This is a Huffman).
I've tried creating a function whoneich replaces the print statements with
list() statements, but that didn't work.
Does anyone have any ideas about how I could go about this?
How to count self-intersections in contour [on hold]
How to count self-intersections in contour [on hold]
I have vector of 2D points, decribed contour. I want to count it
self-intersections. How to do it most effectively?
I have vector of 2D points, decribed contour. I want to count it
self-intersections. How to do it most effectively?
FPDF Footer on last page using {nb}
FPDF Footer on last page using {nb}
I have seen quite a few questions on this but not definitive answer. Im
using FPDF to dynamically create PDF with values form a DB, I only want a
footer on the last page, seeing as its values are based on DB values the
PDF could be 2,3,4 pages long. So i started messing around with the
footter of FPDF like so
function Footer()
{
$this->SetY(-15);
$this->SetFont('Arial','I',8);
//Page number
$pagenumber = '{nb}';
if($this->PageNo() == 2){
$this->Cell(173,10, ' FOOTER TEST - '.$pagenumber, 0, 0);
}
}
This retruns the value "FOOTER TEST - 2" on the second page and if i set
the if to "<=2" will put the same on page one and two, GREAT! it
recognises $pagenumber as 2 or if i had 3 pages as 3, so it can see that i
have however many pages, however, when i change the code to:
function Footer()
{
$this->SetY(-15);
$this->SetFont('Arial','I',8);
//Page number
$pagenumber = '{nb}';
if($this->PageNo() == $pagenumber){
$this->Cell(173,10, ' FOOTER TEST - '.$pagenumber, 0, 0);
}
}
Thinking that it output the last page once, adding that to the if
statement will make it work, it doesn't display anything, like the if
statement cant recognize the value for $pagenumber, is this because it is
a string or int trying to compare to the opposite or something else?
Any help greatly appropriated.
Ian
I have seen quite a few questions on this but not definitive answer. Im
using FPDF to dynamically create PDF with values form a DB, I only want a
footer on the last page, seeing as its values are based on DB values the
PDF could be 2,3,4 pages long. So i started messing around with the
footter of FPDF like so
function Footer()
{
$this->SetY(-15);
$this->SetFont('Arial','I',8);
//Page number
$pagenumber = '{nb}';
if($this->PageNo() == 2){
$this->Cell(173,10, ' FOOTER TEST - '.$pagenumber, 0, 0);
}
}
This retruns the value "FOOTER TEST - 2" on the second page and if i set
the if to "<=2" will put the same on page one and two, GREAT! it
recognises $pagenumber as 2 or if i had 3 pages as 3, so it can see that i
have however many pages, however, when i change the code to:
function Footer()
{
$this->SetY(-15);
$this->SetFont('Arial','I',8);
//Page number
$pagenumber = '{nb}';
if($this->PageNo() == $pagenumber){
$this->Cell(173,10, ' FOOTER TEST - '.$pagenumber, 0, 0);
}
}
Thinking that it output the last page once, adding that to the if
statement will make it work, it doesn't display anything, like the if
statement cant recognize the value for $pagenumber, is this because it is
a string or int trying to compare to the opposite or something else?
Any help greatly appropriated.
Ian
How Can i run WordPress on local host?
How Can i run WordPress on local host?
How Can i run WordPress on local host?? <<
WordPress Error: PHP is not running WordPress requires that your web
server is running PHP. Your server does not have PHP installed, or PHP is
turned off.
< I have an installed version of XAMPP1.7.4 installed and running but
the above error is shown))
How Can i run WordPress on local host?? <<
WordPress Error: PHP is not running WordPress requires that your web
server is running PHP. Your server does not have PHP installed, or PHP is
turned off.
< I have an installed version of XAMPP1.7.4 installed and running but
the above error is shown))
When should bug fixing and end to end testing happen in a Sprint?
When should bug fixing and end to end testing happen in a Sprint?
Our sprint duration is 2 weeks during which we develop some features and
test them by developers. then we release the product to the end to end
testing team and the sprint ends. The testing team will test and report
back to us for bug fixing after our sprint has ended in their own sprint.
One idea is that when a sprint ends we should have a bug-free and
deliverable product. This means that we should be changing our sprint
duration to 3 weeks and spend the last week for testing and bug fixing so
that we're sure that end of sprint means a deliverable product.
But that's not realistic, we don't know how long testing takes.
When should bug fixing and end to end testing happen in a Sprint?
What's the best practice on this?
Our sprint duration is 2 weeks during which we develop some features and
test them by developers. then we release the product to the end to end
testing team and the sprint ends. The testing team will test and report
back to us for bug fixing after our sprint has ended in their own sprint.
One idea is that when a sprint ends we should have a bug-free and
deliverable product. This means that we should be changing our sprint
duration to 3 weeks and spend the last week for testing and bug fixing so
that we're sure that end of sprint means a deliverable product.
But that's not realistic, we don't know how long testing takes.
When should bug fixing and end to end testing happen in a Sprint?
What's the best practice on this?
Wednesday, September 18, 2013
Path exists in sys.path but still gives module not found error in Python
Path exists in sys.path but still gives module not found error in Python
So, I print the sys.path in the python terminal inside the working python
project directory, and find the directory there. I've also put in a
init.py in the directory, too
But when I do a import directoryname, I get a module not found error.
Where can I possibly be going wrong?
So, I print the sys.path in the python terminal inside the working python
project directory, and find the directory there. I've also put in a
init.py in the directory, too
But when I do a import directoryname, I get a module not found error.
Where can I possibly be going wrong?
Google Cloud Storage return error when creating bucket
Google Cloud Storage return error when creating bucket
"The account for the specified project has been disabled"
I have enabled GCS service and billing.
Any idea?
"The account for the specified project has been disabled"
I have enabled GCS service and billing.
Any idea?
How do I invoke a method that takes a "Collection
How do I invoke a method that takes a "Collection
The method signature looks like this:
public void addThemAll(Collection<? extends T> c)
Which essentially just adds every element of the collection to my
LinkedList. But I keep trying to feed this method an Array or a Linked
List and I always get an error. For example:
double[] myarray = new double[]{3.4, 4.5, 8.6};
mylist.addThemAll(myarray);
I'm sure this is something straightforward, but I can't find an example
online that just passes an array/linked list into a method like this.
The method signature looks like this:
public void addThemAll(Collection<? extends T> c)
Which essentially just adds every element of the collection to my
LinkedList. But I keep trying to feed this method an Array or a Linked
List and I always get an error. For example:
double[] myarray = new double[]{3.4, 4.5, 8.6};
mylist.addThemAll(myarray);
I'm sure this is something straightforward, but I can't find an example
online that just passes an array/linked list into a method like this.
R: How to get something like adjacency matrix, but on the intersection value of third column?
R: How to get something like adjacency matrix, but on the intersection
value of third column?
I have data frame like this:
V1 V2 LABEL
1 83965 891552 A
2 88599 891552 B
3 42966 891552 C
4 83965 891553 D
5 88599 891553 D
6 42966 891553 B
How can I convert it to something like adjacency matrix, but on the
intersection of colum-row i would like to have, the third colum value,
like that:
891552 891553
42966 C B
83965 A D
88599 B D
value of third column?
I have data frame like this:
V1 V2 LABEL
1 83965 891552 A
2 88599 891552 B
3 42966 891552 C
4 83965 891553 D
5 88599 891553 D
6 42966 891553 B
How can I convert it to something like adjacency matrix, but on the
intersection of colum-row i would like to have, the third colum value,
like that:
891552 891553
42966 C B
83965 A D
88599 B D
How to get PDF page dimensions
How to get PDF page dimensions
I have an existing pdf and extracting text from the pdf. Here is the code
I have already
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.IO;
public string ReadPdfFile(string fileName)
{
StringBuilder text = new StringBuilder();
if (File.Exists(fileName))
{
PdfReader pdfReader = new PdfReader(fileName);
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
ITextExtractionStrategy strategy = new
SimpleTextExtractionStrategy();
string currentText =
PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
currentText =
Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default,
Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
text.Append(currentText);
}
pdfReader.Close();
}
return text.ToString();
}
I would like to get the dimensions of the pdf page. I need the dimensions
so I can create a wrapper class that contains this information. Then the
class can determine if rectangles are out of bounds.
I have an existing pdf and extracting text from the pdf. Here is the code
I have already
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.IO;
public string ReadPdfFile(string fileName)
{
StringBuilder text = new StringBuilder();
if (File.Exists(fileName))
{
PdfReader pdfReader = new PdfReader(fileName);
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
ITextExtractionStrategy strategy = new
SimpleTextExtractionStrategy();
string currentText =
PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
currentText =
Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default,
Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
text.Append(currentText);
}
pdfReader.Close();
}
return text.ToString();
}
I would like to get the dimensions of the pdf page. I need the dimensions
so I can create a wrapper class that contains this information. Then the
class can determine if rectangles are out of bounds.
Connect Device to an iPhone via BTLE
Connect Device to an iPhone via BTLE
How to connect a device to an iPhone that causes launching of my iPhone
app in the background and the most important thing - starting the
connection from the device, and not from the iPhone (they are paired)? If
you give me some working TESTED samples that would be great. Thanks!
How to connect a device to an iPhone that causes launching of my iPhone
app in the background and the most important thing - starting the
connection from the device, and not from the iPhone (they are paired)? If
you give me some working TESTED samples that would be great. Thanks!
Image Search inside another Image
Image Search inside another Image
I want to find similar images for a given image file.
For example:
Images 1,2,3,4 are similar.
Images 4,5,6,7 are similar. 3 may be similar with those.
I have tested http://www.phash.org/demo/ . There are three algorithms it
is used: Radial,DCT, Marr/Mexican.
DCT suggests 1-2 as similar. But it doesn't find 1-4 as similar.
Can you suggest different libs, algorithms especially to find 1-4 as
similar? As I said before my aim is to find (1,2,3,4) as similar and
(4,5,6,7) as similar.
I want to find similar images for a given image file.
For example:
Images 1,2,3,4 are similar.
Images 4,5,6,7 are similar. 3 may be similar with those.
I have tested http://www.phash.org/demo/ . There are three algorithms it
is used: Radial,DCT, Marr/Mexican.
DCT suggests 1-2 as similar. But it doesn't find 1-4 as similar.
Can you suggest different libs, algorithms especially to find 1-4 as
similar? As I said before my aim is to find (1,2,3,4) as similar and
(4,5,6,7) as similar.
Do I must need to dispose FileStream object
Do I must need to dispose FileStream object
I am pretty depressed by my programming knowledge but do we really need to
dispose FileStream Object ?
Reason I am asking is because code is throwing "File being used by another
process" exception once in 100 cases and for a moment as if i try again(to
download file using file stream) it works fine.
Please refer to this question for code.
Since it only happening once in 100 or so making me so confused and it's
happening on production server so can't debug at all, but works perfectly
on my development machine...
I am pretty depressed by my programming knowledge but do we really need to
dispose FileStream Object ?
Reason I am asking is because code is throwing "File being used by another
process" exception once in 100 cases and for a moment as if i try again(to
download file using file stream) it works fine.
Please refer to this question for code.
Since it only happening once in 100 or so making me so confused and it's
happening on production server so can't debug at all, but works perfectly
on my development machine...
TCPDF writeHTML()
TCPDF writeHTML()
I am working on two column layout input comes from an editor which has
images and text. Images can come as one column or full width. Everything
works fine when I insert images in one column. But when I insert image as
2 column it fits perfectly in the column but the text after that is
somewhat not aligned.
Text covers the after space correctly but when it goes to second column
some space from the top till where the image ends on the first column is
blank and starts after that.
if ($this->myResetColumn) {
$this->resetColumns();
$this->setEqualColumns($this->myCols, $this->myWidth);
$this->setXY($this->GetX(), $this->GetY());
$this->selectColumn();
}
$this->writeHTML($content, true, false, true, false, $align);
Second Question
It there a way, I can make few checks while the writeHTML() function is
executing or I have to change the function itself, which will not be a
good idea to change the source code. For AddPage, I override it, after the
line at the end like this
$this->startPage($orientation, $format, $tocpage);
if (condition) {
// some function call
}
but writeHTML() is a lengthy function to override and it will lose many
options it has.
I am working on two column layout input comes from an editor which has
images and text. Images can come as one column or full width. Everything
works fine when I insert images in one column. But when I insert image as
2 column it fits perfectly in the column but the text after that is
somewhat not aligned.
Text covers the after space correctly but when it goes to second column
some space from the top till where the image ends on the first column is
blank and starts after that.
if ($this->myResetColumn) {
$this->resetColumns();
$this->setEqualColumns($this->myCols, $this->myWidth);
$this->setXY($this->GetX(), $this->GetY());
$this->selectColumn();
}
$this->writeHTML($content, true, false, true, false, $align);
Second Question
It there a way, I can make few checks while the writeHTML() function is
executing or I have to change the function itself, which will not be a
good idea to change the source code. For AddPage, I override it, after the
line at the end like this
$this->startPage($orientation, $format, $tocpage);
if (condition) {
// some function call
}
but writeHTML() is a lengthy function to override and it will lose many
options it has.
Tuesday, September 17, 2013
Mysql query with if exists check in where clause
Mysql query with if exists check in where clause
I have two tables (A and B) where my query compares a calculation from
table A with a range in table B and then insert a corresponding value to
the range(also in table B) in the third table(table C) based on dates.
However,it is a possibility that table A may not have data for everyday
and for those days i want to enter the value against the second lowest
range.
I am looking for a way to embed IF EXISTS in the WHERE clause something
like this:
SELECT B.value from TableB B INNER JOIN TableA A ON A.id=B.id WHERE B.id=4
and (IF DATA EXISTS) B.v1+B.v2 between A.min and A.max (ELSE Choose the
second lowest A.min)
The query above is an example to explain what i am trying to do, hence, it
is not a valid query. I do not want to use a subquery for obvious
performance issues.
I will appreciate any help.Thanks in advance :)
I have two tables (A and B) where my query compares a calculation from
table A with a range in table B and then insert a corresponding value to
the range(also in table B) in the third table(table C) based on dates.
However,it is a possibility that table A may not have data for everyday
and for those days i want to enter the value against the second lowest
range.
I am looking for a way to embed IF EXISTS in the WHERE clause something
like this:
SELECT B.value from TableB B INNER JOIN TableA A ON A.id=B.id WHERE B.id=4
and (IF DATA EXISTS) B.v1+B.v2 between A.min and A.max (ELSE Choose the
second lowest A.min)
The query above is an example to explain what i am trying to do, hence, it
is not a valid query. I do not want to use a subquery for obvious
performance issues.
I will appreciate any help.Thanks in advance :)
Using matlab matrix as input for a python code
Using matlab matrix as input for a python code
Is it possible to use a matrix generated with matlab and saved in a binary
file as input of a python script?
Is it possible to use a matrix generated with matlab and saved in a binary
file as input of a python script?
Checking php variable from contact form, from direct access
Checking php variable from contact form, from direct access
I have a simple php mail script which has a client-side verification
(jquery based), works fine. But some times someone make a direct post to
it and I've reseive many empty spam emails.
How I can check, if some field is not null (empty). For example,
"usermail" variable.
<?php
$sendto = "youremail@youremail.com";
$usermail = $_POST['email'];
$content = nl2br($_POST['msg']);
$subject = "New Feedback Message";
$headers = "From: " . strip_tags($usermail) . "\r\n";
$headers .= "Reply-To: ". strip_tags($usermail) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>New
User Feedback</h2>\r\n";
$msg .= "<p><strong>Sent by:</strong> ".$usermail."</p>\r\n";
$msg .= "<p><strong>Message:</strong> ".$content."</p>\r\n";
$msg .= "</body></html>";
if(@mail($sendto, $subject, $msg, $headers)) {
echo "true";
} else {
echo "false";
}
?>
I have a simple php mail script which has a client-side verification
(jquery based), works fine. But some times someone make a direct post to
it and I've reseive many empty spam emails.
How I can check, if some field is not null (empty). For example,
"usermail" variable.
<?php
$sendto = "youremail@youremail.com";
$usermail = $_POST['email'];
$content = nl2br($_POST['msg']);
$subject = "New Feedback Message";
$headers = "From: " . strip_tags($usermail) . "\r\n";
$headers .= "Reply-To: ". strip_tags($usermail) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>New
User Feedback</h2>\r\n";
$msg .= "<p><strong>Sent by:</strong> ".$usermail."</p>\r\n";
$msg .= "<p><strong>Message:</strong> ".$content."</p>\r\n";
$msg .= "</body></html>";
if(@mail($sendto, $subject, $msg, $headers)) {
echo "true";
} else {
echo "false";
}
?>
C++ memory leaks with unordered_map
C++ memory leaks with unordered_map
I've discovered that I have a memory leak somewhere in my application but
I've been having trouble narrowing it down. I've tried using the function
_CrtDumpMemoryLeaks as instructed in this example but it doesn't show file
names. So, I've been trying to find the first point of memory leaks (as
there seem to be quite a few according to the output) by placing calls to
this dump function at various points. It seems that I am getting a lot of
them straight away very early in my constructors for objects.
Upon further investigation, I seem to be getting them with definitions for
std::unordered_map even to the point where having a simple main function
that just declares a local variable has a memory leak.
For example the following code produces a memory leaks:
void main()
{
_CrtDumpMemoryLeaks(); // executing this line, no memeory leaks found
std::unordered_map<int, int> intMap;
_CrtDumpMemoryLeaks(); // executing this line, memeory leaks found
}
I'm completely confused at this point and get the feeling that chasing
this is not going to help me find the memory leak that I am originally
noticed.
Any help is very much appreciated.
I've discovered that I have a memory leak somewhere in my application but
I've been having trouble narrowing it down. I've tried using the function
_CrtDumpMemoryLeaks as instructed in this example but it doesn't show file
names. So, I've been trying to find the first point of memory leaks (as
there seem to be quite a few according to the output) by placing calls to
this dump function at various points. It seems that I am getting a lot of
them straight away very early in my constructors for objects.
Upon further investigation, I seem to be getting them with definitions for
std::unordered_map even to the point where having a simple main function
that just declares a local variable has a memory leak.
For example the following code produces a memory leaks:
void main()
{
_CrtDumpMemoryLeaks(); // executing this line, no memeory leaks found
std::unordered_map<int, int> intMap;
_CrtDumpMemoryLeaks(); // executing this line, memeory leaks found
}
I'm completely confused at this point and get the feeling that chasing
this is not going to help me find the memory leak that I am originally
noticed.
Any help is very much appreciated.
regex to match a string that could extend over several lines
regex to match a string that could extend over several lines
I have examples in a text document line this:
set ( blah blah blah )
and
set ( blahlblah
blahlbal )
and
set ( blah
blah
blah
blah
blah )
I am using text mate and want to find these and replace with nothing
I got this to work with one line but stumped on how to do this over
multiple lines. I tried this:
SET \(.*\n.*\)
I have examples in a text document line this:
set ( blah blah blah )
and
set ( blahlblah
blahlbal )
and
set ( blah
blah
blah
blah
blah )
I am using text mate and want to find these and replace with nothing
I got this to work with one line but stumped on how to do this over
multiple lines. I tried this:
SET \(.*\n.*\)
Complex number equals method
Complex number equals method
I'm making a complex number class in Java like this:
public class Complex {
public final double real, imag;
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
... methods for arithmetic follow ...
}
I implemented the equals method like this:
@Override
public boolean equals(Object obj) {
if (obj instanceof Complex) {
Complex other = (Complex)obj;
return (
this.real == other.real &&
this.imag == other.imag
);
}
return false;
}
But if you override equals, you're supposed to override hashCode too. One
of the rules is:
If two objects are equal according to the equals(Object) method, then
calling the hashCode method on each of the two objects must produce the
same integer result.
Comparing floats and doubles with == does a numeric comparison, so +0.0 ==
-0.0 and NaN values are inequal to everything including themselves. So I
tried implementing the hashCode method to match the equals method like
this:
@Override
public int hashCode() {
long real = Double.doubleToLongBits(this.real); // harmonize NaN bit
patterns
long imag = Double.doubleToLongBits(this.imag);
if (real == 1L << 63) real = 0; // convert -0.0 to +0.0
if (imag == 1L << 63) imag = 0;
long h = real ^ imag;
return (int)h ^ (int)(h >>> 32);
}
But then I realized that this would work strangely in a hash map if either
field is NaN, because this.equals(this) will always be false, but maybe
that's not incorrect. On the other hand, I could do what Double and Float
do, where the equals methods compare +0.0 != -0.0, but still harmonize the
different NaN bit patterns, and let NaN == NaN, so then I get:
@Override
public boolean equals(Object obj) {
if (obj instanceof Complex) {
Complex other = (Complex)obj;
return (
Double.doubleToLongBits(this.real) ==
Double.doubleToLongBits(other.real) &&
Double.doubleToLongBits(this.imag) ==
Double.doubleToLongBits(other.imag)
);
}
return false;
}
@Override
public int hashCode() {
long h = (
Double.doubleToLongBits(real) +
Double.doubleToLongBits(imag)
);
return (int)h ^ (int)(h >>> 32);
}
But if I do that then my complex numbers don't behave like real numbers,
where +0.0 == -0.0. But I don't really need to put my Complex numbers in
hash maps anyway -- I just want to do the right thing, follow best
practices, etc. And now I'm just confused. Can anyone advise me on the
best way to proceed?
I'm making a complex number class in Java like this:
public class Complex {
public final double real, imag;
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
... methods for arithmetic follow ...
}
I implemented the equals method like this:
@Override
public boolean equals(Object obj) {
if (obj instanceof Complex) {
Complex other = (Complex)obj;
return (
this.real == other.real &&
this.imag == other.imag
);
}
return false;
}
But if you override equals, you're supposed to override hashCode too. One
of the rules is:
If two objects are equal according to the equals(Object) method, then
calling the hashCode method on each of the two objects must produce the
same integer result.
Comparing floats and doubles with == does a numeric comparison, so +0.0 ==
-0.0 and NaN values are inequal to everything including themselves. So I
tried implementing the hashCode method to match the equals method like
this:
@Override
public int hashCode() {
long real = Double.doubleToLongBits(this.real); // harmonize NaN bit
patterns
long imag = Double.doubleToLongBits(this.imag);
if (real == 1L << 63) real = 0; // convert -0.0 to +0.0
if (imag == 1L << 63) imag = 0;
long h = real ^ imag;
return (int)h ^ (int)(h >>> 32);
}
But then I realized that this would work strangely in a hash map if either
field is NaN, because this.equals(this) will always be false, but maybe
that's not incorrect. On the other hand, I could do what Double and Float
do, where the equals methods compare +0.0 != -0.0, but still harmonize the
different NaN bit patterns, and let NaN == NaN, so then I get:
@Override
public boolean equals(Object obj) {
if (obj instanceof Complex) {
Complex other = (Complex)obj;
return (
Double.doubleToLongBits(this.real) ==
Double.doubleToLongBits(other.real) &&
Double.doubleToLongBits(this.imag) ==
Double.doubleToLongBits(other.imag)
);
}
return false;
}
@Override
public int hashCode() {
long h = (
Double.doubleToLongBits(real) +
Double.doubleToLongBits(imag)
);
return (int)h ^ (int)(h >>> 32);
}
But if I do that then my complex numbers don't behave like real numbers,
where +0.0 == -0.0. But I don't really need to put my Complex numbers in
hash maps anyway -- I just want to do the right thing, follow best
practices, etc. And now I'm just confused. Can anyone advise me on the
best way to proceed?
Sunday, September 15, 2013
Null value in order by clause
Null value in order by clause
I have a weird scenario, in which I need to keep all the rows at top in
which X column has NULL value else sort by Y column. Can you help me in
writing query.
I have a weird scenario, in which I need to keep all the rows at top in
which X column has NULL value else sort by Y column. Can you help me in
writing query.
What is $transaction == BEGIN_TRANSACTION testing for?
What is $transaction == BEGIN_TRANSACTION testing for?
I'm trying to convert some old code by converting to mysqli. Unfortunately
I can't figure out what part of the code is trying to do, so I don't know
how to change it. It seems to be a standard safety check that everyone who
uses the original mysql extension used, but I can't find anyone who
explains why. Here is the original code:
function query($query = "", $transaction = FALSE)
{
//
// Remove any pre-existing queries
//
unset($this->query_result);
if( $query != "" )
{
$this->num_queries++;
if( $transaction == BEGIN_TRANSACTION && !$this->in_transaction )
{
$result = mysql_query("BEGIN", $this->db_connect_id);
if(!$result)
{
return false;
}
$this->in_transaction = TRUE;
}
$this->query_result = mysql_query($query, $this->db_connect_id);
}
else
{
if( $transaction == END_TRANSACTION && $this->in_transaction )
{
$result = mysql_query("COMMIT", $this->db_connect_id);
}
}
if( $this->query_result )
{
unset($this->row[$this->query_result]);
unset($this->rowset[$this->query_result]);
if( $transaction == END_TRANSACTION && $this->in_transaction )
{
$this->in_transaction = FALSE;
if ( !mysql_query("COMMIT", $this->db_connect_id) )
{
mysql_query("ROLLBACK", $this->db_connect_id);
return false;
}
}
return $this->query_result;
}
else
{
if( $this->in_transaction )
{
mysql_query("ROLLBACK", $this->db_connect_id);
$this->in_transaction = FALSE;
}
return false;
}
}
I can't figure out what they're doing with
if( $transaction == BEGIN_TRANSACTION && !$this->in_transaction )
Can anybody explain this to me?
I'm trying to convert some old code by converting to mysqli. Unfortunately
I can't figure out what part of the code is trying to do, so I don't know
how to change it. It seems to be a standard safety check that everyone who
uses the original mysql extension used, but I can't find anyone who
explains why. Here is the original code:
function query($query = "", $transaction = FALSE)
{
//
// Remove any pre-existing queries
//
unset($this->query_result);
if( $query != "" )
{
$this->num_queries++;
if( $transaction == BEGIN_TRANSACTION && !$this->in_transaction )
{
$result = mysql_query("BEGIN", $this->db_connect_id);
if(!$result)
{
return false;
}
$this->in_transaction = TRUE;
}
$this->query_result = mysql_query($query, $this->db_connect_id);
}
else
{
if( $transaction == END_TRANSACTION && $this->in_transaction )
{
$result = mysql_query("COMMIT", $this->db_connect_id);
}
}
if( $this->query_result )
{
unset($this->row[$this->query_result]);
unset($this->rowset[$this->query_result]);
if( $transaction == END_TRANSACTION && $this->in_transaction )
{
$this->in_transaction = FALSE;
if ( !mysql_query("COMMIT", $this->db_connect_id) )
{
mysql_query("ROLLBACK", $this->db_connect_id);
return false;
}
}
return $this->query_result;
}
else
{
if( $this->in_transaction )
{
mysql_query("ROLLBACK", $this->db_connect_id);
$this->in_transaction = FALSE;
}
return false;
}
}
I can't figure out what they're doing with
if( $transaction == BEGIN_TRANSACTION && !$this->in_transaction )
Can anybody explain this to me?
Geolocation unit test with JsTestDriver
Geolocation unit test with JsTestDriver
I'm testing geolocation using JsTestDriver, this is my code:
GeoLocationTest.prototype.testLocation = function(){
expectAsserts(1);
var coordinate = new Coordinate();
var location = coordinate.getLocation();
assertEquals("1,1",location);
};
Te test always fails because it tests immediately, before getting the
geolocation coordinates. I tried using a timeout but the test also
executes immediately.
setTimeout(function(){assertEquals("1,1",location);},10000);
And this is the javascript I'm trying to test
function Coordinate () {
this.latitude = 0.0;
this.longitude = 0.0;
this.date = new Date();
this.errorMsg = "";
}
Coordinate.prototype.getLocation = function(){
if (this.isBrowserSupported()){ //this test passes
navigator.geolocation.getCurrentPosition(this.setPosition,this.setError);
return "" + this.latitude + "," + this.longitude;
}
return "Browser not supported";
}
Coordinate.prototype.setPosition = function(position){
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
}
AssertError: expected "1,1" but was "0,0"
I'm testing geolocation using JsTestDriver, this is my code:
GeoLocationTest.prototype.testLocation = function(){
expectAsserts(1);
var coordinate = new Coordinate();
var location = coordinate.getLocation();
assertEquals("1,1",location);
};
Te test always fails because it tests immediately, before getting the
geolocation coordinates. I tried using a timeout but the test also
executes immediately.
setTimeout(function(){assertEquals("1,1",location);},10000);
And this is the javascript I'm trying to test
function Coordinate () {
this.latitude = 0.0;
this.longitude = 0.0;
this.date = new Date();
this.errorMsg = "";
}
Coordinate.prototype.getLocation = function(){
if (this.isBrowserSupported()){ //this test passes
navigator.geolocation.getCurrentPosition(this.setPosition,this.setError);
return "" + this.latitude + "," + this.longitude;
}
return "Browser not supported";
}
Coordinate.prototype.setPosition = function(position){
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
}
AssertError: expected "1,1" but was "0,0"
The "while" command doesn't save itself
The "while" command doesn't save itself
First, I just want to say I recently started with programming, so I'm not
very good. This is my problem:
x = int(input("Write a number between 1-100: "))
while x > 100:
x = int(input("The number must be less than 101: "))
while x < 1:
x = int(input("The number must be higher than 0: "))
else:
print ("The number is:",x)
There's a way to cheat the code by doing this:
Write a number between 1-100: 101
The number must be less than 101: 0
The number must be higher than 0: 101
The number is: 101
I basically don't want the user to be able to write a number higher than
100 or lower than 1.
I'm sorry for the bad explanation but I tried my best and, one again, i
recently started programming,
Thanks!
ps. I'm using python 3.3!
First, I just want to say I recently started with programming, so I'm not
very good. This is my problem:
x = int(input("Write a number between 1-100: "))
while x > 100:
x = int(input("The number must be less than 101: "))
while x < 1:
x = int(input("The number must be higher than 0: "))
else:
print ("The number is:",x)
There's a way to cheat the code by doing this:
Write a number between 1-100: 101
The number must be less than 101: 0
The number must be higher than 0: 101
The number is: 101
I basically don't want the user to be able to write a number higher than
100 or lower than 1.
I'm sorry for the bad explanation but I tried my best and, one again, i
recently started programming,
Thanks!
ps. I'm using python 3.3!
Define array from another array
Define array from another array
I'm trying to define an array starting from data that come from another
array. The code will explain the situation better than thousands words.
public class QualityCheck {
public QualityCheck (JTable table)
{
//the data come from a JTable (that represents a school timetable)
String [] dailyLessons= new String[table.getColumnCount()];
String [] dailyClasses= new String[table.getColumnCount()];
//checking all the days
for (int i=1; i<table.getColumnCount(); i++)
{
//checking all the hours in a day
for (int j=0; j<table.getRowCount(); j++)
{
//lesson is an array that contains the subject and the room in
which the subject is erogated
//lesson[0] contains the subject
//lesson[1] contains the room
String[] lesson =
((TabellaOrario.MyTableModel)table.getModel()).getLesson(j,i);
//I'd like to put ALL the daily subjects in dailyLesson
dailyLessons[j] = lesson[0];
//I'd like to put All the daily rooms in dailyClasses
dailyClasses[j] = lesson[1];
}
//trying if dailyLessons has the elements
for (String s: dailyLessons)
{
System.out.println(s);
}
}
}
}
If a run this code, the compiler protest with this error:
Exception in thread "AWT-EventQueue-0"
java.lang.ArrayIndexOutOfBoundsException: 7
and it evidence the string
dailyLessons[j] = lesson[0];
How can I do to define dailyLesson?
I'm trying to define an array starting from data that come from another
array. The code will explain the situation better than thousands words.
public class QualityCheck {
public QualityCheck (JTable table)
{
//the data come from a JTable (that represents a school timetable)
String [] dailyLessons= new String[table.getColumnCount()];
String [] dailyClasses= new String[table.getColumnCount()];
//checking all the days
for (int i=1; i<table.getColumnCount(); i++)
{
//checking all the hours in a day
for (int j=0; j<table.getRowCount(); j++)
{
//lesson is an array that contains the subject and the room in
which the subject is erogated
//lesson[0] contains the subject
//lesson[1] contains the room
String[] lesson =
((TabellaOrario.MyTableModel)table.getModel()).getLesson(j,i);
//I'd like to put ALL the daily subjects in dailyLesson
dailyLessons[j] = lesson[0];
//I'd like to put All the daily rooms in dailyClasses
dailyClasses[j] = lesson[1];
}
//trying if dailyLessons has the elements
for (String s: dailyLessons)
{
System.out.println(s);
}
}
}
}
If a run this code, the compiler protest with this error:
Exception in thread "AWT-EventQueue-0"
java.lang.ArrayIndexOutOfBoundsException: 7
and it evidence the string
dailyLessons[j] = lesson[0];
How can I do to define dailyLesson?
PHP Function in ajax url?
PHP Function in ajax url?
i'm a new JQuery user and i have 2 questions ..
this is my code:
<script type="text/javascript">
$(document).ready(function(){
$('#module').change(function(){
var module = $("select#module").val();
var dataAll = 'module=' + module ;
$.ajax({
url: "name.php",
type : "POST",
data : dataAll,
dataType :"html",
success : function(msg){
$('#result').html(msg)
}
});
});
});
</script>
so first, how can i use PHP function in url field , for example i'm using
Codeigniter and i want to put base_url function as a url .
and how can i request just an id from the page, not all the page ..
thanks a lot :)
i'm a new JQuery user and i have 2 questions ..
this is my code:
<script type="text/javascript">
$(document).ready(function(){
$('#module').change(function(){
var module = $("select#module").val();
var dataAll = 'module=' + module ;
$.ajax({
url: "name.php",
type : "POST",
data : dataAll,
dataType :"html",
success : function(msg){
$('#result').html(msg)
}
});
});
});
</script>
so first, how can i use PHP function in url field , for example i'm using
Codeigniter and i want to put base_url function as a url .
and how can i request just an id from the page, not all the page ..
thanks a lot :)
Pig throws error for simple Group by and count occurrence task
Pig throws error for simple Group by and count occurrence task
Using Hadoop's PIG-Latin to find the number of occurrences of unique
search strings from a search engine log file.(click here to view the
sample log file)
Pig script
excitelog = load '/user/hadoop/input/excite-small.log' using PigStorage() AS
(encryptcode:chararray, numericid:int, searchstring:chararray);
GroupBySearchString = GROUP excitelog by searchstring;
searchStrFrq = foreach GroupBySearchString Generate group as
searchstring,count(searchstring);
Error encountered
[main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1070: Could not
resolve count using imports: [, org.apache.pig.builtin.,
org.apache.pig.impl.builtin.]
Using Hadoop's PIG-Latin to find the number of occurrences of unique
search strings from a search engine log file.(click here to view the
sample log file)
Pig script
excitelog = load '/user/hadoop/input/excite-small.log' using PigStorage() AS
(encryptcode:chararray, numericid:int, searchstring:chararray);
GroupBySearchString = GROUP excitelog by searchstring;
searchStrFrq = foreach GroupBySearchString Generate group as
searchstring,count(searchstring);
Error encountered
[main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1070: Could not
resolve count using imports: [, org.apache.pig.builtin.,
org.apache.pig.impl.builtin.]
Saturday, September 14, 2013
How can I use Twitter Bootstrap Dropdowns to include the first item as a toggle?
How can I use Twitter Bootstrap Dropdowns to include the first item as a
toggle?
Twitter Bootstrap Dropdowns Docs show the following syntax for a dropdown:
<div class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Dropdown
trigger</a>
<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
<li role="presentation"><a role="menuitem" tabindex="-1"
href="#">Menu Item 1</a></li>
...
</ul>
</div>
But instead I'd like the first item (Drowdown trigger above) to be
included in the menu items.
Can you suggest a strategy to trigger a dropdown menu from a list
including all items?
Here's an example HTML format of what I'm after.
<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
<li role="presentation"><a class="dropdown-toggle btn"
data-toggle="dropdown" href="#">General Support <b
class="caret"></b></a></li>
<li role="presentation"><a role="menuitem" tabindex="-1"
href="#">Sales</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1"
href="#">Accounting</a></li>
</ul>
My actual use case is a little more complex and is the reason I can't
simply use an HTML select input.
toggle?
Twitter Bootstrap Dropdowns Docs show the following syntax for a dropdown:
<div class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Dropdown
trigger</a>
<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
<li role="presentation"><a role="menuitem" tabindex="-1"
href="#">Menu Item 1</a></li>
...
</ul>
</div>
But instead I'd like the first item (Drowdown trigger above) to be
included in the menu items.
Can you suggest a strategy to trigger a dropdown menu from a list
including all items?
Here's an example HTML format of what I'm after.
<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
<li role="presentation"><a class="dropdown-toggle btn"
data-toggle="dropdown" href="#">General Support <b
class="caret"></b></a></li>
<li role="presentation"><a role="menuitem" tabindex="-1"
href="#">Sales</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1"
href="#">Accounting</a></li>
</ul>
My actual use case is a little more complex and is the reason I can't
simply use an HTML select input.
The transparent background imageview makes the normally opaque text that comes on it transparent too. How do I fix this?
The transparent background imageview makes the normally opaque text that
comes on it transparent too. How do I fix this?
What i want is an opaque text on a transparent background imageview.
Without the image the webview text is opaque and text that isnt on the the
background imageview is still opaque. I have searched but couldnt find a
solution for this.
here is my xml layout
'
<ScrollView
android:id="@+id/SCROLLER_ID"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:fillViewport="true">
<WebView
android:id="@+id/tvAnimalJoke"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge"
/>
</ScrollView>
<ImageView
android:id="@+id/ivAwesome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/awesome50jp"
/>
</RelativeLayout>
'
and here is my webview in java ' Random r = new Random();
number = r.nextInt(9851);
String randomjoke = getStreamTextByLine("9851.txt", number);
String numstr = Integer.toString(number);
String head = "<head><style>@font-face {font-family: 'verdana';src:
url('file:///android_asset/annoyingkettle.ttf');}body {font-family:
'verdana';}</style></head>";
String htmlData = "<html>" + head + numstr + "<body>" + "<p
align=\"justify\">"
+ randomjoke + "</p>" + "</body></html>";
Mywebview.loadDataWithBaseURL(null, htmlData, "text/html", "utf-8",
"about:blank");
' Here is an image of what im talking about
comes on it transparent too. How do I fix this?
What i want is an opaque text on a transparent background imageview.
Without the image the webview text is opaque and text that isnt on the the
background imageview is still opaque. I have searched but couldnt find a
solution for this.
here is my xml layout
'
<ScrollView
android:id="@+id/SCROLLER_ID"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:fillViewport="true">
<WebView
android:id="@+id/tvAnimalJoke"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge"
/>
</ScrollView>
<ImageView
android:id="@+id/ivAwesome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/awesome50jp"
/>
</RelativeLayout>
'
and here is my webview in java ' Random r = new Random();
number = r.nextInt(9851);
String randomjoke = getStreamTextByLine("9851.txt", number);
String numstr = Integer.toString(number);
String head = "<head><style>@font-face {font-family: 'verdana';src:
url('file:///android_asset/annoyingkettle.ttf');}body {font-family:
'verdana';}</style></head>";
String htmlData = "<html>" + head + numstr + "<body>" + "<p
align=\"justify\">"
+ randomjoke + "</p>" + "</body></html>";
Mywebview.loadDataWithBaseURL(null, htmlData, "text/html", "utf-8",
"about:blank");
' Here is an image of what im talking about
PHP Merge 1 Dimensional Array with 2 Dimensional Array on keys and keep all keys unique and values from 2nd Array
PHP Merge 1 Dimensional Array with 2 Dimensional Array on keys and keep
all keys unique and values from 2nd Array
1st Array: One Dimension, 2nd Array: Two Dimension
I want to merge the two arrays by key, keep the keys and the values of the
2nd Array
1st Array (
[30] => 30
[28] => 28
[27] => 27
[16] => 16
)
2nd Array (
[27] => Array (
[person_id] => 27
[person_name] => Jazz Club
[person_job] => 10
[drink_price] => 5
)
)
Expected result Array (
[30] => 30
[28] => 28
[27] => [27] => Array
(
[person_id] => 27
[person_name] => Jazz Club
[person_job] => 10
[drink_price] => 5
)
[16] => 16
)
all keys unique and values from 2nd Array
1st Array: One Dimension, 2nd Array: Two Dimension
I want to merge the two arrays by key, keep the keys and the values of the
2nd Array
1st Array (
[30] => 30
[28] => 28
[27] => 27
[16] => 16
)
2nd Array (
[27] => Array (
[person_id] => 27
[person_name] => Jazz Club
[person_job] => 10
[drink_price] => 5
)
)
Expected result Array (
[30] => 30
[28] => 28
[27] => [27] => Array
(
[person_id] => 27
[person_name] => Jazz Club
[person_job] => 10
[drink_price] => 5
)
[16] => 16
)
how to add where clause in formtype symfony2
how to add where clause in formtype symfony2
its been days now that am looking for the 'how' of this problem. I just
learned symfony2 and i cant find a way to this, i've tried different stuff
found on the net but i could not get any to work.
Here is my problem, I have a form PictureType in which i include another
entity Collection (which is a collection of picture or if you prefer an
album of picture).
When the user uploads his picture he needs to select in which album he
wants to put it.
My problem is that I cant figure out how to tell in my PictureType to
select ONLY the collections of the current user.
here is my pictureType
$builder
->add('file')
->add('collection', 'entity', array(
'class' => 'AppPictureBundle:Collection',
'property' => 'name'
));
I want to insert after property something like this
Where 'user_id' = $this->getUser()
I have a manyToOne on Collection target User and a ManyToOne on picture
target collection.
its been days now that am looking for the 'how' of this problem. I just
learned symfony2 and i cant find a way to this, i've tried different stuff
found on the net but i could not get any to work.
Here is my problem, I have a form PictureType in which i include another
entity Collection (which is a collection of picture or if you prefer an
album of picture).
When the user uploads his picture he needs to select in which album he
wants to put it.
My problem is that I cant figure out how to tell in my PictureType to
select ONLY the collections of the current user.
here is my pictureType
$builder
->add('file')
->add('collection', 'entity', array(
'class' => 'AppPictureBundle:Collection',
'property' => 'name'
));
I want to insert after property something like this
Where 'user_id' = $this->getUser()
I have a manyToOne on Collection target User and a ManyToOne on picture
target collection.
String length validation in javascript
String length validation in javascript
I have a small problem with a task I've been asigned. I'm trying to make
an alert message appear if the length of the inputted number does not
equal 7. The message appears even if the length of the number is equal to
7 and I can't figure out why, any help would be appreciated! thanks.
var msg = "";
if (document.Entry.Number.length!== 7) {
msg+="Your Number should be 7 digits. Please check this. \n";
document.Entry.nNumber.focus();
document.getElementById('Number').style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
I have a small problem with a task I've been asigned. I'm trying to make
an alert message appear if the length of the inputted number does not
equal 7. The message appears even if the length of the number is equal to
7 and I can't figure out why, any help would be appreciated! thanks.
var msg = "";
if (document.Entry.Number.length!== 7) {
msg+="Your Number should be 7 digits. Please check this. \n";
document.Entry.nNumber.focus();
document.getElementById('Number').style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
How to Upload Image Using Ajax - PHP
How to Upload Image Using Ajax - PHP
How can i upload Image/File Using Ajax ? Check Facebook Comments with
Image (Same as facebook).
Is there any possible way to do so ?
If there is a way than how can we Move that Selected Image File to our
Specified Images Directory?
Here is the HTML :
<input name="image_src" type="file" id="image_src" />
How can i upload Image/File Using Ajax ? Check Facebook Comments with
Image (Same as facebook).
Is there any possible way to do so ?
If there is a way than how can we Move that Selected Image File to our
Specified Images Directory?
Here is the HTML :
<input name="image_src" type="file" id="image_src" />
How to setup context sharing between GPUImage and cocos2d to capture gameplay video
How to setup context sharing between GPUImage and cocos2d to capture
gameplay video
I'd like to capture video from cocos2d gameplay in my app. I can just
simply use glReadPixels, but it's very slow. I found out that
GPUImage/GPUImageMovieWriter uses more advanced approach, but I have to
setup context sharing between GPUImage and cocos2d
Anybody knows how to make that?
I've tried to push GPUImage's sharegroup into cocos2d, but I have no luck:
container = [CCGLView viewWithFrame:CGRectMake(116, 37, 480, 640)
pixelFormat:kEAGLColorFormatRGB565 depthFormat:0 preserveBackbuffer:NO
sharegroup:[[[GPUImageContext sharedImageProcessingContext] context]
sharegroup] multiSampling:NO numberOfSamples:0];
Any help would be appreciated.
gameplay video
I'd like to capture video from cocos2d gameplay in my app. I can just
simply use glReadPixels, but it's very slow. I found out that
GPUImage/GPUImageMovieWriter uses more advanced approach, but I have to
setup context sharing between GPUImage and cocos2d
Anybody knows how to make that?
I've tried to push GPUImage's sharegroup into cocos2d, but I have no luck:
container = [CCGLView viewWithFrame:CGRectMake(116, 37, 480, 640)
pixelFormat:kEAGLColorFormatRGB565 depthFormat:0 preserveBackbuffer:NO
sharegroup:[[[GPUImageContext sharedImageProcessingContext] context]
sharegroup] multiSampling:NO numberOfSamples:0];
Any help would be appreciated.
Named arguments call in C# with variable parameter number
Named arguments call in C# with variable parameter number
Suppose I have the following C# function:
void Foo(int bar, params string[] parpar) { }
I want to call this function using named arguments:
Foo(bar: 5, parpar: "a", "b", "c");
The compiler gives error message: "Named arguments cannot precede
positional" since I have no name before "b" and "c".
Is there any way to use named arguments without manually representing
params as an array?
Suppose I have the following C# function:
void Foo(int bar, params string[] parpar) { }
I want to call this function using named arguments:
Foo(bar: 5, parpar: "a", "b", "c");
The compiler gives error message: "Named arguments cannot precede
positional" since I have no name before "b" and "c".
Is there any way to use named arguments without manually representing
params as an array?
Friday, September 13, 2013
Incomplete implementations
Incomplete implementations
New to StackOverFlow and working on a project in Xcode getting an error
from didReceiveMemoryWarning and incomplete implementation. This is the
main file and this is
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
@interface LoginViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIScrollView *scroller;
@property (weak, nonatomic) IBOutlet UITextField *FirstNameField;
@property (weak, nonatomic) IBOutlet UITextField *SurnameField;
@property (weak, nonatomic) IBOutlet UITextField *EmailField;
@property (weak, nonatomic) IBOutlet UITextField *PasswordField;
@property (weak, nonatomic) IBOutlet UITextField *ReenterPasswordField;
- (IBAction)RegisterAction:(id)sender;
@end
This is .m file:
#import "LoginViewController.h"
@interface LoginViewController ()
@end
@implementation LoginViewController
@synthesize scroller;
- (void)viewDidLoad
{
[super viewDidLoad];
[scroller setScrollEnabled:YES];
[scroller setContentSize:CGSizeMake(340, 600)];
}
- (void)viewDidAppear:(BOOL)animated
{
PFUser *user = [PFUser currentUser];
if (user.email != nil) {
[self performSegueWithIdentifier:@"login" sender:self];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)RegisterAction:(id)sender {
[_FirstNameField resignFirstResponder];
[_SurnameField resignFirstResponder];
[_EmailField resignFirstResponder];
[_PasswordField resignFirstResponder];
[_ReenterPasswordField resignFirstResponder];
[self checkFieldsComplete];
[self checkFieldsComplete];
}
- (void) checkFieldsComplete {
if ([_FirstNameField.text isEqualToString:@""] || [_SurnameField.text
isEqualToString:@""]|| [_EmailField.text isEqualToString:@""] ||
[_PasswordField.text isEqualToString:@""] ||
[_ReenterPasswordField.text isEqualToString:@""]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops"
message: @"Make sure to complete every field" delegate: nil
cancelButtonTitle: @"Ok" otherButtonTitles: nil];
[alert show];
} else {
[self checkPasswordsMatch];
}
}
- (void) checkPasswordsMatch {
if (![_PasswordField.text isEqualToString:_ReenterPasswordField.text]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops"
message: @"Passwords don't match" delegate: nil cancelButtonTitle:
@"Ok" otherButtonTitles: nil];
[alert show];
}
}
- (void) registerNewUser {
PFUser *newUser;
newUser.username = [NSString stringWithFormat: _FirstNameField.text,
_SurnameField.text];
newUser.email = _EmailField.text;
newUser.password = _PasswordField.text;
[newUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
NSLog(@"Welcome to Vici!");
[self performSegueWithIdentifier:@"login"
sender:self];
} else {
NSLog(@"There was an error in registration");
}
}];
}
@end
Can anyone point out a solution?
New to StackOverFlow and working on a project in Xcode getting an error
from didReceiveMemoryWarning and incomplete implementation. This is the
main file and this is
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
@interface LoginViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIScrollView *scroller;
@property (weak, nonatomic) IBOutlet UITextField *FirstNameField;
@property (weak, nonatomic) IBOutlet UITextField *SurnameField;
@property (weak, nonatomic) IBOutlet UITextField *EmailField;
@property (weak, nonatomic) IBOutlet UITextField *PasswordField;
@property (weak, nonatomic) IBOutlet UITextField *ReenterPasswordField;
- (IBAction)RegisterAction:(id)sender;
@end
This is .m file:
#import "LoginViewController.h"
@interface LoginViewController ()
@end
@implementation LoginViewController
@synthesize scroller;
- (void)viewDidLoad
{
[super viewDidLoad];
[scroller setScrollEnabled:YES];
[scroller setContentSize:CGSizeMake(340, 600)];
}
- (void)viewDidAppear:(BOOL)animated
{
PFUser *user = [PFUser currentUser];
if (user.email != nil) {
[self performSegueWithIdentifier:@"login" sender:self];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)RegisterAction:(id)sender {
[_FirstNameField resignFirstResponder];
[_SurnameField resignFirstResponder];
[_EmailField resignFirstResponder];
[_PasswordField resignFirstResponder];
[_ReenterPasswordField resignFirstResponder];
[self checkFieldsComplete];
[self checkFieldsComplete];
}
- (void) checkFieldsComplete {
if ([_FirstNameField.text isEqualToString:@""] || [_SurnameField.text
isEqualToString:@""]|| [_EmailField.text isEqualToString:@""] ||
[_PasswordField.text isEqualToString:@""] ||
[_ReenterPasswordField.text isEqualToString:@""]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops"
message: @"Make sure to complete every field" delegate: nil
cancelButtonTitle: @"Ok" otherButtonTitles: nil];
[alert show];
} else {
[self checkPasswordsMatch];
}
}
- (void) checkPasswordsMatch {
if (![_PasswordField.text isEqualToString:_ReenterPasswordField.text]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops"
message: @"Passwords don't match" delegate: nil cancelButtonTitle:
@"Ok" otherButtonTitles: nil];
[alert show];
}
}
- (void) registerNewUser {
PFUser *newUser;
newUser.username = [NSString stringWithFormat: _FirstNameField.text,
_SurnameField.text];
newUser.email = _EmailField.text;
newUser.password = _PasswordField.text;
[newUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
NSLog(@"Welcome to Vici!");
[self performSegueWithIdentifier:@"login"
sender:self];
} else {
NSLog(@"There was an error in registration");
}
}];
}
@end
Can anyone point out a solution?
how to spsc_queue.pop() this struct?
how to spsc_queue.pop() this struct?
I'm trying to spsc_queue.pop() this struct
enum action_type {
SUBSCRIBE,
UNSUBSCRIBE,
MESSAGE
};
struct action {
action() = default ;
action(action_type t, connection_hdl h) : type(t), hdl(h) {}
action(action_type t, server::message_ptr m) : type(t), msg(m) {}
action_type type;
websocketpp::connection_hdl hdl;
server::message_ptr msg;
};
with
action a;
while(m_actions.pop(a)){
...
but whenever I test with
std::cout << "'" << a.type << "'" << std::endl;
'0' is written to the terminal, but it should only be one of the values of
action_type. I have read that the default value for a struct is 0, but why
can't spsc_queue.pop() set a?
(boost::lockfree::spsc_queue)
I'm trying to spsc_queue.pop() this struct
enum action_type {
SUBSCRIBE,
UNSUBSCRIBE,
MESSAGE
};
struct action {
action() = default ;
action(action_type t, connection_hdl h) : type(t), hdl(h) {}
action(action_type t, server::message_ptr m) : type(t), msg(m) {}
action_type type;
websocketpp::connection_hdl hdl;
server::message_ptr msg;
};
with
action a;
while(m_actions.pop(a)){
...
but whenever I test with
std::cout << "'" << a.type << "'" << std::endl;
'0' is written to the terminal, but it should only be one of the values of
action_type. I have read that the default value for a struct is 0, but why
can't spsc_queue.pop() set a?
(boost::lockfree::spsc_queue)
ImportError: No module named mechanize
ImportError: No module named mechanize
I'm using easy_install, and I entered:
easy_install mechanize
and the last line it returned was:
Finished processing dependencies for mechanize
Now when I try to:
import mechanize
I get this error:
ImportError: No module named mechanize
Any idea what's wrong? Thanks
I'm using easy_install, and I entered:
easy_install mechanize
and the last line it returned was:
Finished processing dependencies for mechanize
Now when I try to:
import mechanize
I get this error:
ImportError: No module named mechanize
Any idea what's wrong? Thanks
htacess subdirectory rewrite for Joomla Test site
htacess subdirectory rewrite for Joomla Test site
Thanks for the help. I am trying to add a joomla site to my test server in
a sub directory but I am having trouble with the rewrites.
Here is the current
RewriteCond %{HTTP_HOST} !^www.#############.net$ RewriteRule (.*)
http://www.#######.net/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^141.101.125.182 RewriteRule (.*)
http://www.########.net/$1 [R=301,L]
Basically I just want this testsite to be working in a subdirectory..
Thanks so much guys, Richie
Thanks for the help. I am trying to add a joomla site to my test server in
a sub directory but I am having trouble with the rewrites.
Here is the current
RewriteCond %{HTTP_HOST} !^www.#############.net$ RewriteRule (.*)
http://www.#######.net/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^141.101.125.182 RewriteRule (.*)
http://www.########.net/$1 [R=301,L]
Basically I just want this testsite to be working in a subdirectory..
Thanks so much guys, Richie
Thursday, September 12, 2013
parsing success callbacks from ajax call
parsing success callbacks from ajax call
I have a backbone object that I'm calling save on. How do I know what
comes back in the ajax call. Looking at the code for the project I got put
on, I see some people just have a generic
success: function (data) {
console.log(data);
Then other times, I see:
success: function (library, response) {
console.log(library);
console.log(response)
I'm confused on how you would know you would have I presume a library or
response object, vs a general data. When I look at the second example, I
am looking at the output of
console.log(response);
and I see response has three attributes:
Notifications
Response
ResponseStatus
Response itself looks like Object {Id="12345", href="the/href", Name="asdf"}
So it looks like a Javascript object to me, but then when I try to do
console.log(response.Name);
I always get undefined even though I can see the value.
So I'm trying to understand how the callback in an ajax calls. Like when
you can use an actual library object, response object, vs a data object,
and how I can go about parsing the results properly. Thanks in advance!
I have a backbone object that I'm calling save on. How do I know what
comes back in the ajax call. Looking at the code for the project I got put
on, I see some people just have a generic
success: function (data) {
console.log(data);
Then other times, I see:
success: function (library, response) {
console.log(library);
console.log(response)
I'm confused on how you would know you would have I presume a library or
response object, vs a general data. When I look at the second example, I
am looking at the output of
console.log(response);
and I see response has three attributes:
Notifications
Response
ResponseStatus
Response itself looks like Object {Id="12345", href="the/href", Name="asdf"}
So it looks like a Javascript object to me, but then when I try to do
console.log(response.Name);
I always get undefined even though I can see the value.
So I'm trying to understand how the callback in an ajax calls. Like when
you can use an actual library object, response object, vs a data object,
and how I can go about parsing the results properly. Thanks in advance!
simple Ruby Input and Output Exercise log
simple Ruby Input and Output Exercise log
I have a project in my programming class. This is my assignment: Create a
program that allows the user to input how many hours they exercised for
today. Then the program should output the total of how many hours they
have exercised for all time. To allow the program to persist beyond the
first run the total exercise time will need to be written and retrieved
from a file.
This is the code I have so far:
File.open("exercise.txt", "r") do |fi|
file_content = fi.read
puts "This is an exercise log. It keeps track of the number hours of
exercise. Please enter the number of hours you exercised.
hours = gets.chomp.to_f
end
output = File.open( "exercise.txt", "w" )
output << hours
output.close
end
What else to do I have to add?
I have a project in my programming class. This is my assignment: Create a
program that allows the user to input how many hours they exercised for
today. Then the program should output the total of how many hours they
have exercised for all time. To allow the program to persist beyond the
first run the total exercise time will need to be written and retrieved
from a file.
This is the code I have so far:
File.open("exercise.txt", "r") do |fi|
file_content = fi.read
puts "This is an exercise log. It keeps track of the number hours of
exercise. Please enter the number of hours you exercised.
hours = gets.chomp.to_f
end
output = File.open( "exercise.txt", "w" )
output << hours
output.close
end
What else to do I have to add?
T-SQL Creating Dynamic Tables and Populating
T-SQL Creating Dynamic Tables and Populating
Im fairly new to T-SQL and could use some help with a Script I am writing.
The purpose of the script is to create dynamic tables and populate them
with related data. Currently Im getting a vague error which Im guessing is
caused because Im missing some syntax. The script is below. The idea is
that I will run the script one time to create and load these tables. This
process is part of a data migration project. Here's the error Im receiving
when I "Execute" the script. Any tips or suggestions are appreciated.
Thanks ahead of time.
ERROR
Msg 102, Level 15, State 1, Line 81
Incorrect syntax near 'getSFContactID'.
SCRIPT
USE mylocalDB;
GO
-- Declare variables to temporarily hold dynamic SQL scripts
DECLARE @V_SF_CONTACT_ID VARCHAR(18) = '',
@V_TABLESCRIPT NVARCHAR(MAX) = '',
@V_INSERTSCRIPT NVARCHAR(MAX) = '',
-- Declare variables to temporarily hold query records
@V_FIRST_NAME nvarchar(50) = '',
@V_LAST_NAME nvarchar(50) = '',
@V_COMPANY nvarchar(100) = '',
@V_ADDRESS_1 nvarchar(50) = '',
@V_ADDRESS_2 nvarchar(50) = '',
@V_CITY nvarchar(50) = '',
@V_STATE nvarchar(2) = '',
@V_ZIP nvarchar(10) = '',
@V_Phone nvarchar(20) = ''
DECLARE getSFContactID CURSOR
FOR SELECT distinct CONTACTSFID FROM xrefListContactToAccountKey
OPEN getSFContactID
FETCH NEXT FROM getSFContactID
INTO @V_SF_CONTACT_ID
WHILE @@FETCH_STATUS = 0
BEGIN
/******************************************************
BEGIN CREATING DYNAMIC TABLES
*******************************************************/
SET @V_TABLESCRIPT = '';
SET @V_INSERTSCRIPT = '';
IF OBJECT_ID(@V_SF_CONTACT_ID, 'U') IS NOT NULL
BEGIN
SET @V_TABLESCRIPT = 'CREATE TABLE [dbo].[' + @V_SF_CONTACT_ID + '](
[Key] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[FIRST_NAME] [nvarchar](50) NOT NULL,
[LAST_NAME] [nvarchar](50) NOT NULL,
[COMPANY] [nvarchar](100) NOT NULL,
[ADDRESS_1] [nvarchar](50) NOT NULL,
[ADDRESS_2] [nvarchar](50) NOT NULL,
[CITY] [nvarchar](50) NOT NULL,
[STATE] [nvarchar](2) NOT NULL,
[ZIP] [nvarchar](10) NOT NULL,
[Phone] [nvarchar](20) NULL,
CONSTRAINT [PK_' + @V_SF_CONTACT_ID + '] PRIMARY KEY NONCLUSTERED
([Key] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON
[PRIMARY]) ON [PRIMARY]';
--PRINT @V_SF_CONTACT_ID
EXEC (@V_TABLESCRIPT)
BREAK
SET @V_INSERTSCRIPT = 'INSERT INTO [dbo].[' + @V_SF_CONTACT_ID + ']
Select CL.FirstName as FIRST_NAME,
CL.LastName as LAST_NAME,
CL.COMPANY,
CL.Street as ADDRESS_1,
CL.Street2 as ADDRESS_2,
CL.CITY,
CL.[STATE],
CL.ZIP,
CL.Phone
FROM [dbo].[Contact] CL
WHERE CONTACTSFID = ''' + @V_SF_CONTACT_ID + '';
EXEC (@V_INSERTSCRIPT)
FETCH NEXT FROM getSFContactID INTO @V_SF_CONTACT_ID
END
CLOSE getSFContactID
DEALLOCATE getSFContactID
Im fairly new to T-SQL and could use some help with a Script I am writing.
The purpose of the script is to create dynamic tables and populate them
with related data. Currently Im getting a vague error which Im guessing is
caused because Im missing some syntax. The script is below. The idea is
that I will run the script one time to create and load these tables. This
process is part of a data migration project. Here's the error Im receiving
when I "Execute" the script. Any tips or suggestions are appreciated.
Thanks ahead of time.
ERROR
Msg 102, Level 15, State 1, Line 81
Incorrect syntax near 'getSFContactID'.
SCRIPT
USE mylocalDB;
GO
-- Declare variables to temporarily hold dynamic SQL scripts
DECLARE @V_SF_CONTACT_ID VARCHAR(18) = '',
@V_TABLESCRIPT NVARCHAR(MAX) = '',
@V_INSERTSCRIPT NVARCHAR(MAX) = '',
-- Declare variables to temporarily hold query records
@V_FIRST_NAME nvarchar(50) = '',
@V_LAST_NAME nvarchar(50) = '',
@V_COMPANY nvarchar(100) = '',
@V_ADDRESS_1 nvarchar(50) = '',
@V_ADDRESS_2 nvarchar(50) = '',
@V_CITY nvarchar(50) = '',
@V_STATE nvarchar(2) = '',
@V_ZIP nvarchar(10) = '',
@V_Phone nvarchar(20) = ''
DECLARE getSFContactID CURSOR
FOR SELECT distinct CONTACTSFID FROM xrefListContactToAccountKey
OPEN getSFContactID
FETCH NEXT FROM getSFContactID
INTO @V_SF_CONTACT_ID
WHILE @@FETCH_STATUS = 0
BEGIN
/******************************************************
BEGIN CREATING DYNAMIC TABLES
*******************************************************/
SET @V_TABLESCRIPT = '';
SET @V_INSERTSCRIPT = '';
IF OBJECT_ID(@V_SF_CONTACT_ID, 'U') IS NOT NULL
BEGIN
SET @V_TABLESCRIPT = 'CREATE TABLE [dbo].[' + @V_SF_CONTACT_ID + '](
[Key] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[FIRST_NAME] [nvarchar](50) NOT NULL,
[LAST_NAME] [nvarchar](50) NOT NULL,
[COMPANY] [nvarchar](100) NOT NULL,
[ADDRESS_1] [nvarchar](50) NOT NULL,
[ADDRESS_2] [nvarchar](50) NOT NULL,
[CITY] [nvarchar](50) NOT NULL,
[STATE] [nvarchar](2) NOT NULL,
[ZIP] [nvarchar](10) NOT NULL,
[Phone] [nvarchar](20) NULL,
CONSTRAINT [PK_' + @V_SF_CONTACT_ID + '] PRIMARY KEY NONCLUSTERED
([Key] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON
[PRIMARY]) ON [PRIMARY]';
--PRINT @V_SF_CONTACT_ID
EXEC (@V_TABLESCRIPT)
BREAK
SET @V_INSERTSCRIPT = 'INSERT INTO [dbo].[' + @V_SF_CONTACT_ID + ']
Select CL.FirstName as FIRST_NAME,
CL.LastName as LAST_NAME,
CL.COMPANY,
CL.Street as ADDRESS_1,
CL.Street2 as ADDRESS_2,
CL.CITY,
CL.[STATE],
CL.ZIP,
CL.Phone
FROM [dbo].[Contact] CL
WHERE CONTACTSFID = ''' + @V_SF_CONTACT_ID + '';
EXEC (@V_INSERTSCRIPT)
FETCH NEXT FROM getSFContactID INTO @V_SF_CONTACT_ID
END
CLOSE getSFContactID
DEALLOCATE getSFContactID
Is it safe to return a VLA?
Is it safe to return a VLA?
The following code uses the heap:
char* getResult(int length) {
char* result = new char[length];
// Fill result...
return result;
}
int main(void) {
char* result = getResult(100);
// Do something...
delete result;
}
So result has to be deleted somewhere, preferably by the owner.
The code below, from what I understand, use an extension called VLA, which
is part of C99, and not part of the C++ standard (but supported by GCC,
and other compilers):
char* getResult(int length) {
char result[length];
// Fill result...
return result;
}
int main(void) {
char* result = getResult(100);
// Do something...
}
Am I correct in assuming that result is still allocated on the stack in
this case?
Is result a copy, or is it a reference to garbage memory? Is the above
code safe?
The following code uses the heap:
char* getResult(int length) {
char* result = new char[length];
// Fill result...
return result;
}
int main(void) {
char* result = getResult(100);
// Do something...
delete result;
}
So result has to be deleted somewhere, preferably by the owner.
The code below, from what I understand, use an extension called VLA, which
is part of C99, and not part of the C++ standard (but supported by GCC,
and other compilers):
char* getResult(int length) {
char result[length];
// Fill result...
return result;
}
int main(void) {
char* result = getResult(100);
// Do something...
}
Am I correct in assuming that result is still allocated on the stack in
this case?
Is result a copy, or is it a reference to garbage memory? Is the above
code safe?
C++ Fix for checking if input is an integer
C++ Fix for checking if input is an integer
for example, if I enter "2a", it does not show an error nor asks the user
to re-input the value. how do i fix this?
while (std::cin.fail())
{
std::cout << "ERROR, enter a number" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin >> dblMarkOne;
}
std::cout << "" << std::endl;
for example, if I enter "2a", it does not show an error nor asks the user
to re-input the value. how do i fix this?
while (std::cin.fail())
{
std::cout << "ERROR, enter a number" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin >> dblMarkOne;
}
std::cout << "" << std::endl;
Subscribe to:
Comments (Atom)