text:
Q: i cant adding item to my jcombobox from my database i've been trying for hours to insert the data to jcombobox and its frustates me
can someone please help me to find my error
here's my code
import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;

import java.awt.GridLayout;
import java.awt.Font;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.JComboBox;

import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class StaffEditDelete extends JFrame {

    private JPanel contentPane;
    private JTextField textField;
    private JTextField textField_1;
    private JTextField textField_2;
    private JTextField textField_3;
    private JTextField textField_4;
    private JTextField textField_5;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    StaffEditDelete frame = new StaffEditDelete();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */

    Connect con;

//  String []alpha;
    Vector<String> alpha;
    JComboBox comboBox;

    public StaffEditDelete() {
        setTitle("Staff");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 450, 424);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new BorderLayout(0, 0));

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.NORTH);

        JLabel lblStaff = new JLabel("Staff");
        lblStaff.setFont(new Font("Times New Roman", Font.BOLD, 24));
        panel.add(lblStaff);

        JPanel panel_1 = new JPanel();
        contentPane.add(panel_1, BorderLayout.CENTER);
        panel_1.setLayout(new GridLayout(7, 2, 10, 10));

        JLabel lblNewLabel = new JLabel("ID");
        panel_1.add(lblNewLabel);
        con.rs = con.executeQuery("Select * from Detail");
        try {
            while(con.rs.next())
            {
            //  System.out.println("True");
                comboBox.addItem(con.rs.getString(1));
            }
        } catch (Exception e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }

        comboBox = new JComboBox();
        comboBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e)
            {
                String items = e.getSource().toString();
                con.rs = con.executeQuery("select * from Staff where [ID Staff ='"+items+"']");
                try {
                    textField.setText(con.rs.getString(2));
                    textField_1.setText(con.rs.getString(3));
                    textField_2.setText(con.rs.getString(4));
                    textField_3.setText(con.rs.getString(5));
                    textField_4.setText(con.rs.getString(6));
                    textField_5.setText(con.rs.getString(7));
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        panel_1.add(comboBox);

        JLabel lblNewLabel_1 = new JLabel("Nama");
        panel_1.add(lblNewLabel_1);

        textField = new JTextField();
        panel_1.add(textField);
        textField.setColumns(10);

        JLabel lblNewLabel_2 = new JLabel("Alamat");
        panel_1.add(lblNewLabel_2);

        textField_1 = new JTextField();
        panel_1.add(textField_1);
        textField_1.setColumns(10);

        JLabel lblNewLabel_3 = new JLabel("Nomor Telepon");
        panel_1.add(lblNewLabel_3);

        textField_2 = new JTextField();
        panel_1.add(textField_2);
        textField_2.setColumns(10);

        JLabel lblNewLabel_4 = new JLabel("Jabatan");
        panel_1.add(lblNewLabel_4);

        textField_3 = new JTextField();
        panel_1.add(textField_3);
        textField_3.setColumns(10);

        JLabel lblNewLabel_5 = new JLabel("Password");
        panel_1.add(lblNewLabel_5);

        textField_4 = new JTextField();
        panel_1.add(textField_4);
        textField_4.setColumns(10);

        JLabel lblNewLabel_6 = new JLabel("Gaji");
        panel_1.add(lblNewLabel_6);

        textField_5 = new JTextField();
        panel_1.add(textField_5);
        textField_5.setColumns(10);

        JPanel panel_2 = new JPanel();
        contentPane.add(panel_2, BorderLayout.SOUTH);

        JButton btnEdit = new JButton("Edit");
        btnEdit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (cekTelpon())
                {
                    int reply = JOptionPane.showConfirmDialog(null, "Edit "+comboBox.getSelectedItem().toString()+"?","Edit?",JOptionPane.YES_NO_OPTION);
                    if (reply == JOptionPane.YES_OPTION)
                    {
                        con.executeUpdateStaff(comboBox.getSelectedItem().toString(), textField.getText(), textField_1.getText(), textField_2.getText(), textField_3.getText(), textField_4.getText(), textField_5.getText());
                        JOptionPane.showMessageDialog(null, "Data Berhasil di Edit");

                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Nomor Telepon Harus Angka", "ERROR", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panel_2.add(btnEdit);

        JButton btnDelete = new JButton("Delete");
        btnDelete.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int reply = JOptionPane.showConfirmDialog(null, "Delete "+comboBox.getSelectedItem().toString()+"?","Delete?",JOptionPane.YES_NO_OPTION);
                if(reply == JOptionPane.YES_OPTION)
                {
                    con.executeDeleteStaff(comboBox.getSelectedItem().toString());
                    JOptionPane.showMessageDialog(null, "Data Berhasil di Delete");

                }
            }
        });
        panel_2.add(btnDelete);

        JButton btnReset = new JButton("Reset");
        btnReset.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                comboBox.setSelectedIndex(0);
                con.rs = con.executeQuery("Select * from Staff where [ID Staff] = '"+ comboBox.getSelectedItem().toString()+"'");

                try {
                    textField.setText(con.rs.getString(2));
                    textField_1.setText(con.rs.getString(3));
                    textField_2.setText(con.rs.getString(4));
                    textField_3.setText(con.rs.getString(5));
                    textField_4.setText(con.rs.getString(6));
                    textField_5.setText(con.rs.getString(7));

                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

            }
        });
        panel_2.add(btnReset);

        JButton btnCancel = new JButton("Cancel");
        btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        panel_2.add(btnCancel);
    }

    public boolean cekTelpon()
    {
        int flag = 0;
        for (int i =0 ;i < textField_2.getText().length();i++)
        {
            if (textField_2.getText().charAt(i) == '0')
            {
                flag ++;
            }
            if (textField_2.getText().charAt(i) == '1')
            {
                flag ++;
            }
            if (textField_2.getText().charAt(i) == '2')
            {
                flag ++;
            }
            if (textField_2.getText().charAt(i) == '3')
            {
                flag ++;
            }
            if (textField_2.getText().charAt(i) == '4')
            {
                flag ++;
            }
            if (textField_2.getText().charAt(i) == '5')
            {
                flag ++;
            }
            if (textField_2.getText().charAt(i) == '6')
            {
                flag ++;
            }
            if (textField_2.getText().charAt(i) == '7')
            {
                flag ++;
            }
            if (textField_2.getText().charAt(i) == '8')
            {
                flag ++;
            }
            if (textField_2.getText().charAt(i) == '9')
            {
                flag ++;
            }
        }

        if (flag == 0)
        {
            return true;
        } else
        {
            return false;
        }
    }

}

here's my error
java.lang.NullPointerException

at StaffEditDelete.<init>(StaffEditDelete.java:85)

at StaffEditDelete$1.run(StaffEditDelete.java:44)

at java.awt.event.InvocationEvent.dispatch(Unknown Source)

at java.awt.EventQueue.dispatchEventImpl(Unknown Source)

at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)

at java.awt.EventQueue.dispatchEvent(Unknown Source)

at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)

at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)

at java.awt.EventDispatchThread.pumpEvents(Unknown Source)

at java.awt.EventDispatchThread.pumpEvents(Unknown Source)

at java.awt.EventDispatchThread.run(Unknown Source)

ive trying for hours please help me find the error in the code

A:
java.lang.NullPointerException
at StaffEditDelete.(StaffEditDelete.java:85)

You are initializing the JComboBox after the comboBox object using. So this statement should be before your while loop where you are using this object.
 comboBox = new JComboBox();
 //should be before this block
 try {
        while(con.rs.next())
        {
        //  System.out.println("True");
        //here you are using comboBox. so it should be initialized before this statement.
            comboBox.addItem(con.rs.getString(1));
        }
    } catch (Exception e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }//not after this block

And one more problem is con object is not created yet. So check this one also.
Just look at this statement.
  con.rs = con.executeQuery("Select * from Detail");

what is con and rs here.


text:
Q: Can I change the port on which my application runs in SAP Web IDE for HANA? I got a SAP HANA system installed. In the SAP Web IDE for HANA, I run an application, this application runs on port 51066. My question is: can I change this port to e.g. 80?

A: Assuming that you have a HANA XSA installation, You can change the port on which an application runs. However you can't change it to port 80.
ID: demo_mta
_schema-version: '2.0'
description: Demo
version: 0.0.2
modules:
  - name: site-LPH
    type: nodejs
    path: site-web
    parameters:
      memory: 64M
      port: 52000 #Explicitly specify port(s)
      host: site-web

You can also specify multiple ports/range.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Workflow email latest document in library I have a custom content type that is a excel spreadsheet. Users access this to create quote requests. At the moment, when a new request is saved to the library, an email is sent telling an admin user a new request exists. However, it doesn't reference the document or a hyperlink of some variety.
How can I get the workflow to send the email containing either the name of the document, or a link directly to it (ideally, both).

A: You could create a workflow to handle this. Instead of the alert, just trigger the workflow anytime an new item is added you would email a specific user and add the parameters for a hyperlink as well as document name. This is really easy to build in SharePoint Designer.


text:
Q: Are there any workflow engines in existence that don't use BPMN and BPEL? Our business is planning on building a rather large business application with about 2000 or so users.
Many objects in the system require a mildly complex series of approvals, notifications, etc.
For various reasons, our company has decided to reject formal use of BPMN or BPEL.  What I am looking for is a workflow engine that I can pass these objects to as a means of facilitating, tracking, and managing the state of these objects.  We are implementing this project using EJB 3.1 with a WebSphere AS.
Am I correct in my understanding of a workflow engine? Everything seems tied to BPMN or BPEL...am I just missing something here as to why most solutions seem to implement BPMN or BPEL?  Some advice would be wonderful!

A: Workflow engines typically take an active role in an enterprise architecture. They execute a declarative process model, which is basically a directed graph consisting of nodes, which represent activities or tasks and edges, which represent the control flow between these edges. Such edges can be annotated with conditions to allow for expressing conditional branching/merging. There are several modelling languages around, like YAWL, XPDL, jPDL, BPEL and BPMN 2.0, which sit on top of these abstract concepts and some syntatic, visual and functional sugar, but only the latter are official industry standards. This is important to avoid vendor locks, make models interchangeable (at least to a certain extent), supportable by experts and different tools. During runtime, process instances are created based on a process model and are executed according to the control flow defined by the model. So the engine actively navigates from one activity to the next activity and thus "orchestrates" your business logic. The main difference between BPMN 2.0 and BPEL is that BPEL is tightly coupled to Web services, i.e. business functions to be invoked by activities are supposed to be rendered as Web service. So if you want to orchestrated WS-* services, it is still the best choice since BPMN 2.0 lacks well-defined and standardized bindings to concrete service implementations. In any case, I'd strongly recommend to use one of the standardized languages since they are both broadly accepted in industry and well supported by various vendors and open source communities.
I tried to explain that in more details because I was not entirely sure about what you mean by "facilitating, tracking, and managing the state of these objects". This sounds a little bit like you are more interested in passively monitoring an object's state change as opposed to actively controlling state changes using a workflow engine. If this assumption is right, then perhaps a abstract state machine would fit your needs better.

A: Take a look at jBPM5, it provides a very flexible core that allows you to build your own domain specific language on top of it. Right now the language provided is BPMN2, but you can easily add your own.
Cheers

A: We are building a product that has a migration path for BPMN 2.0 but does not - internally, use BPMN. We believe checklists are much easier to use in real-time workflows than flowcharts. Is still however, has rules/triggers/conditionals and more - so it's a tool that effectively models processes as "checklists on steroids":
Check it out at http://tallyfy.com


text:
Q: How to remove item from SQLite Android? I have one RecyclerView and my method in RecyclerView adapter is working, but only for position i select and for example, when i click image with sign X i'm deleting first item which i positioned in remove method, but i want this to happens when user click image with sign X, to give him ability to select what item from the list he will delete.
Also i would like to delete that item from SQLite, but my method isn't good probably in helper class.
Here is MainActivity:
    public class MainActivity extends AppCompatActivity {

    RecyclerView mRecyclerView;
    RecyclerView.LayoutManager mLayoutManager;
    GridAdapter mGridAdapter;
    DBHelper dbh;
    String firstName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        initAddImage();

        dbh = new DBHelper(this);

        initRecyclerView();

        initDeleteImage();
    }

    public List<Birthday> getData() {
        List<Birthday> birthdays = new ArrayList<>();
        Birthday birthday = null;
        Cursor c = dbh.getBirthdayData();
        if (c != null) {
            while (c.moveToNext()) {
                int nameIndex = c.getColumnIndex(dbh.BIRTHDAY_NAME);
                String nameText = c.getString(nameIndex);
                this.firstName = nameText;

                int lastNameIndex = c.getColumnIndex(dbh.BIRTHDAY_LAST_NAME);
                String lastNameText = c.getString(lastNameIndex);

                birthday = new Birthday();
                birthday.setNAME(nameText);
                birthday.setLAST_NAME(lastNameText);
                birthdays.add(birthday);

            }
        }
        return birthdays;
    }

    private void initRecyclerView(){
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mRecyclerView.setItemAnimator(new ScaleInAnimator());

        // The number of Columns
        mRecyclerView.setHasFixedSize(true);

        mLayoutManager = new GridLayoutManager(this, 3);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mGridAdapter = new GridAdapter(getData());

        mRecyclerView.setAdapter(mGridAdapter);
    }

    private void initAddImage(){
        ImageView addImage = (ImageView) findViewById(R.id.add_image);
        addImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AddBirthday.class);
                startActivity(intent);
            }
        });
    }

    private void initDeleteImage(){
        ImageView deleteImage = (ImageView) findViewById(R.id.delete_image);
        deleteImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mGridAdapter.removeItem(0);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initRecyclerView();
    }
}

Here is my RecyclerView Adapter:
    public class GridAdapter extends RecyclerView.Adapter<GridAdapter.MyViewHolder> {

    private List<Birthday> birthdays;
    DBHelper dbh;

    public GridAdapter(List<Birthday> birthdays){
        this.birthdays = birthdays;
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        CustomTextView firstName, lastName;
        TextView dateOfBirthday;

        public MyViewHolder(View itemView) {
            super(itemView);
            firstName = (CustomTextView) itemView.findViewById(R.id.first_name);
            lastName = (CustomTextView) itemView.findViewById(R.id.last_name);
            dateOfBirthday = (TextView) itemView.findViewById(R.id.date_of_birthday);
        }
    }

    public void removeItem(int position) {
        birthdays.remove(position);
        notifyItemRemoved(position);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_item, parent, false);
        MyViewHolder holder = new MyViewHolder(v);
        return holder;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        holder.firstName.setText(birthdays.get(position).getNAME());
        holder.lastName.setText(birthdays.get(position).getLAST_NAME());

    }

    @Override
    public int getItemCount() {
        return birthdays.size();
    }

}

And here is my Database: Method for deleting item is at the bottom of class
public class DBHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;

private static final String DATABASE_NAME = "_database";

private static final String BIRTHDAY_TABLE_NAME = "birthday_table";

public static final String BIRTHDAY_ID = "birthday_id";
public static final String BIRTHDAY_NAME = "birthday_name";
public static final String BIRTHDAY_LAST_NAME = "birthday_last_name";

private static final String CREATE_BIRTHDAY_TABLE = "CREATE TABLE " + BIRTHDAY_TABLE_NAME +
        " ( " + BIRTHDAY_ID + " INTEGER PRIMARY KEY,"
        + BIRTHDAY_NAME + " TEXT," + BIRTHDAY_LAST_NAME + " TEXT );";

SQLiteDatabase database;

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_BIRTHDAY_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + BIRTHDAY_TABLE_NAME);
    onCreate(db);
}

public void setBirthdayData(String birthdayName, String birthdayLastName) {
    database = getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(BIRTHDAY_NAME, birthdayName);
    cv.put(BIRTHDAY_LAST_NAME, birthdayLastName);
    database.insert(BIRTHDAY_TABLE_NAME, null, cv);
}

public Cursor getBirthdayData() {
    database = getReadableDatabase();
    String[] columns = {BIRTHDAY_ID, BIRTHDAY_NAME, BIRTHDAY_LAST_NAME};
    Cursor c = database.query(BIRTHDAY_TABLE_NAME, columns, null, null, null, null, BIRTHDAY_ID + " DESC");
    return c;
}

public Cursor getBirthdayName(String[] args) {
    database = getReadableDatabase();
    String query = "SELECT " + BIRTHDAY_NAME + " FROM " + BIRTHDAY_TABLE_NAME + " WHERE " + BIRTHDAY_NAME + " =?";
    Cursor c = database.rawQuery(query, args);
    return c;
}

public boolean deleteItem(long rowId) {
    SQLiteDatabase db = getWritableDatabase();
    return db.delete(BIRTHDAY_TABLE_NAME, BIRTHDAY_ID + "=" + rowId, null) > 0;
}
}

A: Assume your X sign is an ImageButton
Add the ImageButton in your grid_item.xml
In your MyViewHolder add ImageView as item named deleteItem
In OnBindViewHolder
`holder.deleteItem.setOnclickListener(new OnClickListener(){
@Override
public void onClick(View v){
dbHelper.deleteItem(birthdays.get(position).getItemId); /* you pass birthday id to a method deleteItem() in your DBHelper.java */
birthdays.remove(position);
GridAdapter.this.notifyDataSetChanged();
});`
deleteItem(long birthdayId) method
deleteItem(long birthdayId){
return database.delete(BIRTHDAY_TABLE_NAME, BIRTHDAY_ID + " = '" + birthdayId +"'", null, null, null, null);
}


text:
Q: Is there a way to refer to a long host name and use that reference to log into mysql? In order to log into MySQL in the command line, I have to do the usual to log in:
mysql -u [username] -h [host name] -p
But my host name is very long, so I'm constantly having to copy it from a document and paste it in the field. Is there a way I can save it to some sort of variable and then use that variable in the host name field? This would save me some time. I've looked but can't find anything about this. Maybe it's not possible, but if it is, I would appreciate if someone can show me how to do this. Also, I am using Windows if that's helpful.

A: Create a file .my.cnf in your home directory. Put:
[client_h1]
host=host name 1
user=username 1
database=db 1

[client_h2]
host=host name 2
user=username 2
database=db 2

Then you can use:
mysql --defaults-group-suffix=_h1 -p

to get the defaults from the [client_h1] group, and
mysql --defaults-group-suffix=_h2 -p

to get the defaults from the [client_h2] group.
If you have any defaults that are the same for both servers, you can put them together in a single [client] group instead of repeating them in each group.

A: You could use environment variables, either set permanently via control panel --> system, or ad hoc (meaning that their lifetime is the one of the command line window), on the command line, like this:
set h1=verververylongname.thaticannotrembereasily.com

and then
mysql -u [username] -h %h1% -p

You can make one variable per host to contact obviously


text:
Q: Magento 2 - Do not scroll to invalid field on form validation On the log in page, when I don't input input in fields, the error message displays focusing on the invalid input. The window scrolls upto the invalid field at the same time.
I do not want the window to scroll.
Where can I find the code for scrolling?

A: copy MAGENTO_ROOT/vendor/magento/magento2-base/lib/web/mage/validation.js
into app/design/frontend/THEME_ROOT/web/mage/
then comment (start in line 1956)
if (firstActive.length) {
                $('html, body').animate({
                    scrollTop: firstActive.offset().top
                });
                firstActive.focus();
            }

become
if (firstActive.length) {
                /*$('html, body').animate({
                    scrollTop: firstActive.offset().top
                });*/
                firstActive.focus();
            }

or just delete
if (firstActive.length) {

                    firstActive.focus();
                }


text:
Q: How to stop a WCF serialized Entity Framework class from trying to Lazy Load? I've read several questions/articles about WCF serialization of Entity Framework generated objects, but all of the solutions I've found involve turning on eager loading, which is exactly the thing I've trying NOT to do.
I'm essentially getting the same error as mentioned here The ObjectContext instance has been disposed - Winforms Entity Framework , the difference being that I'm consuming my WCF service from a Silverlight application.
I have a table User_Notifications that has a foreign key to a table User_Info. (A single User_Info can point to many User_Notifications in case I'm not using the terminology correctly). I'm using Entity Framework 4, which has created a class for both of those. I have a WCF call that returns:
return DBEntity.User_Notifications.Where(w => w.UserGUID == UserGuid && w.IsDismissed == false).ToArray();

This gives me all the User_Notifications that I need, but I get an ObjectContext Instance has been disposed error on the client side, which looks like from an attempt to load the associated User_Info class. I don't want the User_Info data though, I want it to just stay null or whatever, I don't need it for displaying notifications.
So, how can I pass my Entity Object without needing to pass the Associated Object?
My boss says this is just another reason why 'we don't need foreign keys in the database' and I'd really like to not go down that path.

A: For what it's worth, it's nuts not to have foreign keys in the DB.  They should be there, period.
Insofar as your question... it sounds like you want to return a collection of User_Notifications where the User_Info object is not loaded on the initial query, right?  By default, a query to a table should not eager load associated objects.
In your service function, just do:
return (from n in DBEntity.User_Notifications
        where n.UserGUID == UserGuid && n.IsDismissed == false
        select n).ToArray();

If you find that you need the User_Info object on the client side, then just change the above to:
return (from n in DBEntity.User_Notifications.Include("User_Info")
....

A: My recommendation would be to not expose your EF entities directly through WCF, and instead expose DTOs through your service.
This has two advantages, firstly, you're dealing with real POCO's (not lazy loaded proxies), which do not have persistent specific details in them.  The second is that you only expose what the consumer actually needs, which means you can change the underlying implementation without forcing clients to recompile, and you don't have to expose your entire data model to them.
In your example, you could have:
// I'm not a fan of the Dto suffix, but it makes this example easier
public class UserNotificationDto
{
    // the properties you want to expose through WCF
    public Guid UserGuid { get; set; }
    public string Message { get; set; }
    // ...
}

// your service method
IEnumerable<UserNotificationDto> GetNotifications(Guid userGuid)
{
    using (var ctx = new Context())
    {
        return ctx.User_Notifications
            .Where(x => !x.IsDismissed && x.UserGuid == userGuid)
            .Select(
                x => new UserNotificationDto {
                    UserGuid = x.UserGuid,
                    Message = x.Message
                }
            ).ToList();
    }
}

You may use automapper to make the conversion between EF entities and your DTOs easier, but this is just a contrived example.


text:
Q: History of Lagrange Multipliers How did Lagrange discover Lagrange multipliers? Also, was it related to his work on the calculus of variations? And how did he originally understand/implement the technique?

A: Here is some information from the book A History of Analysis written by Hans Niels Jahnke

Excerpt from section 5.2 The analytical mechanics, 5.2.1 The principle of virtual velocities:

Lagrange presented his new conception in a memoir (Lagrange 1764), written to answer a question advanced in 1762 by the Academy of Paris, concerning the libration of the moon. More than fifteen years later (Lagrange 1780), he outlined a more elaborate and general version of the same program. He finally realised this program in the Méchanique analitique (Lagrange 1788).
Lagrange's idea has two clear sources. The first is the Bernoullian principle of virtual velocities for the equilibrium of any system of bodies animated by central forces. ... The second source is d'Alembert's principle for dynamics. ... Lagrange showed ((Lagrange $1780$, $218$-$220$) and (Lagrange $1788$, $216$-$227$)) that, if the forces are conservative, then $(5.7)$ gives rise to the equation
$$\sum_{i=1}^{\nu}\left[d\frac{\delta T}{\delta d\varphi_i}-\frac{\delta T}{\delta \varphi_i}+\frac{\delta U}{\delta \varphi_i}\right]\delta \varphi_i = 0\qquad(5.8)$$
where $T$ and $U$ are what we would now call the kinetic and the potential energy of the system. This is the original version of  the so-called Lagrangian equation of motion. Its deduction from $(5.7)$ depends on the choice of the variable $\varphi_i$. We must ensure that the variations for these variables are mutually independent.

Thus, we have to chose these variables in a suitable way, subject to the equations of conditions of the system. Since this could be difficult, Lagrange presented a way of making this elimination easier in the Méchanique analitique. This device is now known as the method of Lagrange multipliers (Lagrange $1788$, $44$-$58$ and $227$-$232$).
The basic idea is to express the internal constraints of the system by adding to the first term of $(5.8)$ a suitable term for any equation of condition. If this equation is $\Psi=0$, this term has to be of the form $\psi\delta\Psi$, where $\psi$ is an indeterminate multiplier to be determined by analytical procedures.

The Lagrangian equation of motion and the method of Lagrange multipliers are important contributions to the theoretical mechanics. However, they appear in both the $1780$ memoir on the libration of the moon and in the Méchanique analitique as tools to make possible an application of the quasi-algebraic method of undetermined coefficients to the general equation expressing the principle of virtual velocities, in order to deduce from it the equations of motion for any system of bodies.

Added 2014-05-17: Information added according to the comment of NotNotLogical
He was asking for some more information about what insight drove Lagrange to make the discovery. Here are additional aspects which I found in the paper On the Genesis of the Lagrange Multipliers from P. Bussotti (see also the comment from Steve Kass to this question).

The following text is essentially from P. Bussottis paper: On the Genesis of the Lagrange Multipliers

1.) The Lagrange Multiplier were introduced in the framework of statics

He introduced this mathematical approach in the framework of statics in order to determine the general equations of equilibrium for problems with constraints. At the beginning of his Mécanique Analytique (Ref $1$), Lagrange tackles statics and poses three principles as the foundations for the subject: (i) the principle of the lever (ii) the principle of the composition of forces and (iii) the principle of virtual velocities. It was this third principle virtual velocities where the Lagrange Multiplier occurred the first time.

Lagrange writes in (Ref $1$, pages $17$-$18$):
By virtual velocity, it has to be meant the one that a body in an equilibrium condition would receive if the equilibrium was interrupted; namely, the velocity that the body would really assume in the first instant of movement; the principle consists in this: the forces are in equilibrium if they are in the inverse proportion to their virtual velocities. . . .

So, if we consider a material point to which only two forces $P$ and $Q$ are applied and if $\frac{dp}{dt}$ and $\frac{dq}{dt}$ ($p$ and $q$ being the directions, respectively, of $P$ and $Q$) are the virtual velocities that the body receives, respectively, by the forces $P$ and $Q$, then the body is in equilibrium if
$$P\frac{dp}{dt}+Q\frac{dq}{dt}=0$$
This equation represents the principle of the virtual velocities. The quantity $\frac{dp}{dt}$ is the moment of the force $P$.
At the beginning of Section $2$ (Ref. $1$, paragraph $1$), when the real mathematical treatment begins, Lagrange replaces  $\frac{dp}{dt}$
 with $dp$. He justifies the substitution in this way (Ref. $1$, page $24$):

Lagrange  (Ref. $1$, page $24$):
In order to express this principle by means of formulas, we suppose that the forces $P, Q, R$ are directed along given lines and that they are in equilibrium; let $p, q, r$, etc. denote the lines that are directions of the forces $P, Q, R$.
We indicate the variations or the differences (now called differentials) of these lines with $dp, dq, dr$, etc., and suppose that they are caused by an arbitrary infinitesimal change in the position of the different bodies or points of the system. It is clear that these differences will express the spaces that are covered in the same instant by the action of the forces $P, Q, R$ along their respective directions . ...
The differences $dp, dq, dr$ will be
  proportional to the virtual velocities of the forces $P, Q, R$. In order to simplify the treatment, it will be possible to consider these differences
  instead of the velocities.

So, the general equation of the equilibrium of a point on which three forces are applied will be
$$Pdp+Qdq+Rdr=0$$

2.) Lagrange's motivation for introducing the multiplier method:
At the end of Section $2$ (Ref. 1, paragraph 3, page 27), he points out
  that
  it is important to reduce Mechanics to purely analytical operations and to free it from intuitive geometrical considerations.
For this reason, in Section $4$, he introduces the method of the multipliers (Méthode des multipliers is the title of paragraph $1$ of Section $4$).

In this way, Lagrange is able to solve the problem in a more general and in a simpler way. Particularly, he studies in detail the equilibrium under constraints. He examines, in a first instance, the equilibrium of a material point or of a system of material points that are submitted to constraints. If the constraining equations are $L=0, M=0$, . . . and if $L, M$ are functions of several variables, it follows necessarily that $dL=0, dM=0$, etc. Consequently, if $\lambda,\mu$ are arbitrary real numbers [Lagrange calls them quantités
indéterminées or coefficientes indéterminées (Ref. $1$, page $70$)], we have $\lambda dL=0, \mu dM=0$, etc. He explains:

Lagrange (Ref. $1$, page $70$):
We will consider the sum of all the moments of the forces that must be in equilibrium, we will add the different differential functions that must be zero, on the basis of the conditions of the problem, after having multiplied every function by an indeterminate coefficient; we will make the whole equal to zero and so we will have a differential equation that we will treat as an ordinary equation de maximis et minimis.

The general form of this differential equation is
$$P dp+Q dq+\cdots+\lambda dL+\mu dM\cdots = 0$$
Such equation is the general equation of equilibrium. Considering each variable of an orthogonal reference frame, we will have a particular equation of equilibrium. For example, in the direction $x$, we will have
$$P \frac{dp}{dx}+Q \frac{dq}{dx}+\cdots+\lambda \frac{dL}{dx}+\mu \frac{dM}{dx}\cdots = 0$$
From a physical point of view, the reaction of the constraint is equated to an agent force; indeed, $\lambda$ and $\mu$ are treated as forces and the expressions $\lambda dL$ and $\mu dM$ represent the virtual works that are realized by these forces (Lagrange continues to call them moments).

The advantage of this method is that it allows the treatment of the problems with constraint in the same way as free problems, adding the virtual works realized by the reaction of the constraints to the virtual works realized by the agent forces.
A first extremely important consequence of such an approach is that* the analytical and numerical treatment of the constraints is postponed to the writing of the equilibrium condition*.

From a mathematical point of view, Lagrange points out that the difficulty consists in determining the values of $\lambda , \mu$, etc. Actually, this difficulty can be overcome easily (Ref. $1$, paragraph $4$, Section $4$, page $71$), since in fact the use of the constraints allows having a system where the number of the equations and the number of the variables is the same.
An example can be useful to interpret and clarify the Lagrange reasoning: if we have two agent forces $P$ and $Q$ and a constraint represented by the equation $L=0$, we will have (imagining it to be in the ordinary space) the three unknown quantities $x, y, z$ and the unknown quantity $\lambda$ , and we will have four equations
\begin{align*}
P \frac{dp}{dx}+Q \frac{dq}{dx}+\lambda \frac{dL}{dx}=0\\
P \frac{dp}{dy}+Q \frac{dq}{dy}+\lambda \frac{dL}{dy}=0\\
P \frac{dp}{dz}+Q \frac{dq}{dz}+\lambda \frac{dL}{dz}=0\\
L=0
\end{align*}
If the multiplier is interpreted as a new coordinate, the last equation can be replaced by another one that must be valid in the case of equilibrium:
\begin{align*}
P \frac{dp}{d\lambda}+Q \frac{dq}{d\lambda}+ \lambda \frac{dL}{d\lambda}=0
\end{align*}

In this way, the solution of the problem of the equilibrium of a material point or of a system of material points appears to be, from a mathematical point of view, analogous to the problem of determining the maximum or the minimum of a function under constraints.


text:
Q: Complex solutions of polynomial question $2z^3-6z^2+mz+n = 0$ $m, n$ are real and $1+\sqrt{ 2} i$ is a solution. Find $m$ and $n$.
Attempt to solve :
Giving the known theorem $1-\sqrt{2}i$ is also a solution, so we can substitute each time one of the roots and get a system in two unknowns to solve. I find this to be rather complex and not elegant. I wonder, are there any other solutions to this problem, which are perhaps not as tedious?

A: By Vieta's formulas, the sum of the roots is $ -\frac {6}{2} = 3 $. You know that two of the roots are $ 1 + 2i $ and $ 1- 2i $, so the third root must be $ 1 $. Plugging in $1$ to the polynomial we obtain that $ m + n = 4 $. By Vieta's formulas we also know that the product of the roots is $ -\frac {n}{2} = (1+2i)(1-2i)(1) = 5 $. Therefore, $ n = -10 $ and $ m = 14 $.

A: Hint: $(z-a)(z-b)(z-c)$ has roots $a,b,c$ and if $z_0$ is a complex root, then its conjugate too :).

A: Hint: You know that $1+\sqrt{2}i$ and $1+\sqrt{2}i$ are solutions of
$$z^3-3z^2+\frac{m}{2}z+\frac{n}{2} = 0$$
-3, the coefficient of $z^2$ is the sum of the solutions, so you easily get the third.


text:
Q: When were headshots possible in the series? I play The Elder Scrolls: Tamriel Unlimited a lot and in the forums there has been a (ridiculous) demand of enabling locational damage for bows.
As this is not possible, because in that MMO the character always auto-aims at the chest, I asked myself:
In which games of The Elder Scrolls series were Headshots possible?
I've spent my whole youth in Morrowind, walked through Cyrodiil and have slain dragons across Skyrim. Though I was never used to a bow - sure, I tested them to see how physics are working and how they implemented it, but I mostly sticked to a "Mage blade" character.
And now I'm curious: Have there been games in the series that used locational damage? Like less damage on the toes, but more on the head.

A: This has never been possible (vanilla). However, there are quite a few mods which achieve this, in Skyrim and Oblivion.
Interesting fact : Fallout 3 and New Vegas are using nearly the same engine as Oblivion, and they do localize damage.


text:
Q: How to share partition between multiple user in linux I want lebara user to access the files from the directory which mclaw user created. I have made sure that mclaw and lebara are having the same group.
id
uid=333(mclaw) gid=333(mclaw) groups=333(mclaw),500(lebara)
id
uid=500(lebara) gid=500(lebara) groups=500(lebara),333(mclaw)

I want the lebara user to access only to this directory /var/opt/anritsu/mclaw/lebara2.
drwx------  2 mclaw  lebara    6 Mar 24 12:54 lebara2
In /home/lebara , I wish to create a soft link like ln -s /var/opt/anritsu/mclaw/lebara2 .
However with lebara user I am never able to access lebara2 folder.

lrwxrwxrwx  1 mclaw  mclaw    30 Mar 24 13:18 lebar ->
  /var/opt/anritsu/mclaw/lebara2

Please guide me how this can be done. I tried getfactl and setfactl but not successful.

A: I'm not sure I completely understand your question (and the lack of formatting makes it harder) but likely the reason user lebara is not able to access /var/opt/anritsu/mclaw/lebara2, via a symlink or otherwise, shouldn't matter, is probably because that user does not have permission to traverse that entire path. Meaning: if they are not allowed to list /var/opt/anritsu, they will be stopped.
If you want a shared directory between two users, it may be better to put it somewhere else like /mnt/shared instead of a user-specific path and then verify the correct user/group/other permissions for the entire path.


text:
Q: Call function template overload for derived variadic class template I have a variadic class template deriv which derives off variadic class template base.
I have a function template which takes any type T, and an overload for base<Ts...> types;
How can I get the base<Ts...> overload to be used when passing a const deriv<Ts...>&?
Working example below:
#include <iostream>
#include <tuple>

template<typename... Ts>
struct base
{
    std::tuple<Ts...> tuple;
};

template<typename... Ts>
struct deriv : base<Ts...>
{
};

//--------------------------------

template<typename T>
void func(const T&)
{
    std::cout << "T" << std::endl;
}

template<typename... Ts>
void func(const base<Ts...>&)
{
    std::cout << "base<Ts...>" << std::endl;
}

//----------------------------------------

int main()
{
    int a;
    base <int, double> b;
    deriv<int, double> c;

    func(a);
    func(b);
    func(c); // <--- I want func<base<Ts...>> not func<T> to be called here

    exit(0);
}

Output from exemplar:
T
base<Ts...>
T

What I want the output to be:
T
base<Ts...>
base<Ts...>

A: Unless you are ready to re-engineer your code, you cannot, and for a good reason.
Your non-variadic overload of func() is a better match than the variadic version: in fact, when attempting to resolve your function call, the type parameter T for the non-variadic overload will be deduced to be derived<int, double>.
On the other hand, the parameter pack Ts in your variadic overload will be deduced to be int, double. After type deduction, this will practically leave the compiler with these two choices for resolving your call:
void func(const deriv<int, double>&); // Non-variadic after type deduction
void func(const base<int, double>&);    // Variadic after type deduction

Which one should be picked when trying to match a call whose argument is of type derived<int, double>?
deriv<int, double> c;
func(c);

Obviously, the first, non variadic overload is a better match.
So how do you get the second overload called instead of the first? You have a few choices. First of all, you can qualify your call by explicitly specifying the template arguments:
func<int, double>(c);

If you do not like that, maybe you can re-think the definition of the non-variadic overload of func(): do you really want it to accept any possible type T? Or are there some types for which you know this overload is not to be invoked? If so, you can use SFINAE techniques and std::enable_if to rule out the undesired matches.
As a further possibility, you can relax a bit the signature of your template function and allow deducing its argument as an instantiation of a certain template class:
template<template<typename...> class T, typename... Ts>
void func(const T<Ts...>&)
{
    std::cout << "base<Ts...>" << std::endl;
}

This change alone should fix your program's behavior in the way you want.
UPDATE:
If you want your specialized function template to be invoked only for classes derived from any instance of the base<> class template, you can use the std::is_base_of<> type trait and std::enable_if in the following way:
template<template<typename...> class T, typename... Ts>
void func(
    const T<Ts...>&,
    typename std::enable_if<
        std::is_base_of<base<Ts...>, T<Ts...>>::value
        >::type* = nullptr
    )
{
    std::cout << "base<Ts...>" << std::endl;
}

ADDENDUM:
In those situations where template function overloading won't help with your design, notice that you can always resort to partial template specialization. Unfortunately, function templates cannot be specialized, but you can still exploit class template partial specialization and add a helper function to hide the instantiation of that template. This is how you would rewrite your code:
namespace detail
{
    template<typename T>
    struct X
    {
        static void func(const T&)
        {
            std::cout << "T" << std::endl;
        }
    };

    template<template<typename...> class T, typename... Ts>
    struct X<T<Ts...>>
    {
        static void func(const T<Ts...>&)
        {
            std::cout << "base<Ts...>" << std::endl;
        }
    };
}

template<typename T>
void func(const T& t)
{
    details::X<T>::func(t);
}

A: The generic-template overload is a better match, since it requires no conversion (except adding const, which both overloads have).
You can get the base-template overload by adding an explicit cast (example):
func(static_cast<base<int, double> &>(c));

(Alternatively, you could forgo the multiple overloads and instead stick some is_base_of helper logic into your main function template's body.)


text:
Q: How to change the content of the UITableView with a button click? I have a UItableview with array of contents in it.There are two array ,I want to switch the array by using a button click.
My code is
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

tab.backgroundColor = [UIColor clearColor];
tab.separatorColor = [UIColor clearColor];
cell.chapterAndVerse.text = [NSString stringWithFormat:@"%d",indexPath.row+1];
cell.chapterAndVerse.font = [UIFont fontWithName:@"Georgia" size:17.0];
cell.chapterAndVerse.frame=CGRectMake(0, 10, 30.0, 20.0);
cell.textLabel.text =  [NSString stringWithFormat:@"  %@",[delegate.allSelectedVerseMalayalam objectAtIndex:indexPath.row]];

cell.textLabel.font = [UIFont fontWithName:@"testfont" size:18];
cell.backgroundColor = [UIColor clearColor];
}

my array is delegate.allSelectedVerseMalayalam ,I want this array to be changed with delegate.allSelectedVerseEnglish in button click.When the button for english is clicked by the user it changes the tableviewcontent(my table names is tab)to delegate.allSelectedVerseEnglish .How is this possible.Plese help me to figure out from this problem.
Thanks in advance.
EDIT:
 - (void)viewDidLoad {
NSLog(@"%@", delegate.allSelectedVerseMalayalam);
    tempArray = [[NSMutableArray alloc] init];
    [tempArray addObjectsFromArray:delegate.allSelectedVerseMalayalam];
    NSLog(@"%@", tempArray);

    [self.tab reloadData];
}
-(IBAction)_clickbtndefaultlnguageset:(id)sender
{
    [tempArray removeAllObjects];
    [tempArray addObjectsFromArray:delegate.allSelectedVerseHindi];
    [self.tab reloadData];

}

in tableview
cell.chapterAndVerse.text = [NSString stringWithFormat:@"%d",indexPath.row+1];
cell.chapterAndVerse.font = [UIFont fontWithName:@"Georgia" size:17.0];
cell.chapterAndVerse.frame=CGRectMake(0, 10, 30.0, 20.0);
cell.textLabel.text =  [NSString stringWithFormat:@"  %@",[tempArray objectAtIndex:indexPath.row]];

// cell.textLabel.textColor = [UIColor darkGrayColor];
cell.textLabel.font = [UIFont fontWithName:@"testfont" size:18];
cell.backgroundColor = [UIColor clearColor];

A: do one thing take one extra array and allocated it
define in your source file .h file
NSMutableArray *tempArray;

-(void)viewDidLoad{
//NSLog(@"%@", your Array);
tempArray = [[NSMutableArray alloc] init];
[tempArray addObjectsFromArray:yourfirstarray];
NSLog(@"%@", tempArray);
[self.tableview reloadData];
}

after prees the button
-(void)pressedBtn{
//NSLog(@"%@", your Array);
[tempArray removeAllObjects];
[tempArray addObjectsFromArray:yoursecondArray];
[self.tableView reloadData];
}

use this temp array into table array


text:
Q: Cannot remove an observer for the key path "delegate" from because it is not registered as an observer for IOS I am developing iPhone/iPad Calendar application and I am using the SACalendar.h third party class and I also have a side menu. When moving from one view to another view I am getting error like this:

Error :Terminating app due to uncaught exception 'NSRangeException',
  reason: 'Cannot remove an observer  for the key
  path "delegate" from  because it is not
  registered as an observer.'


text:
Q: Why is Backward Euler not converging to 0? I'm trying to implement Backward Euler for a simple physics simulation. My understanding is that Forward Euler 'overapproximates' and adds energy to the system, and so should spiral to infinity, but Backward Euler 'underapproximates' and removes energy to damp to zero.
I have a 2D force field centered at $[\begin{smallmatrix}0\\0\end{smallmatrix}]$, which applies a force tangent to the radial vector. So for some position $\vec{r}=[\begin{smallmatrix}x\\y\end{smallmatrix}]$, the acceleration will be in the direction $\vec{a}=[\begin{smallmatrix}y\\-x\end{smallmatrix}]$. As a matrix equation, I believe the formulation is $\vec{a}=\big[\begin{smallmatrix}
  0 & 1\\
  -1 & 0
\end{smallmatrix}\big]\vec{r}$. I'll use $B=\big[\begin{smallmatrix}
  0 & 1\\
  -1 & 0
\end{smallmatrix}\big]$ to denote the matrix here on out.
For Backward Euler, I have the following formulation:
\begin{equation}
\vec{r}_{t+\Delta{t}}=\vec{r}_t+\Delta{t}\vec{v}_{t+\Delta{t}}\\
\vec{v}_{t+\Delta{t}}=\vec{v}_t+\Delta{t}\vec{a}_{t+\Delta{t}}\\
\end{equation}
Thus, plugging in $\vec{a}_{t+\Delta{t}}$ and solving for $\vec{r}_{t+\Delta{t}}$,
\begin{equation}
\vec{v}_{t+\Delta{t}}=\vec{v}_t+\Delta{t}B\vec{r}_{t+\Delta{t}}\\
\vec{r}_{t+\Delta{t}}=\vec{r}_t+\Delta{t}(\vec{v}_t+\Delta{t}B\vec{r}_{t+\Delta{t}})\\
\vec{r}_{t+\Delta{t}}=\vec{r}_t+\Delta{t}\vec{v}_t+\Delta{t}^2B\vec{r}_{t+\Delta{t}}\\
\vec{r}_{t+\Delta{t}}-\Delta{t}^2B\vec{r}_{t+\Delta{t}}=\vec{r}_t+\Delta{t}\vec{v}_t\\
(I-\Delta{t}^2B)\vec{r}_{t+\Delta{t}}=\vec{r}_t+\Delta{t}\vec{v}_t\\
\vec{r}_{t+\Delta{t}}=(I-\Delta{t}^2B)^{-1}(\vec{r}_t+\Delta{t}\vec{v}_t)\\
\end{equation}
I then update the particle's new position and velocity with $\vec{r}_{t+\Delta{t}}$ and $\vec{v}_{t+\Delta{t}}$.
The problem I'm having is that when I implement this, the system gains energy each timestep instead of losing it. I expect the particle to spiral in towards the center, but instead it spirals out to infinity just like Forward Euler. I've been trying to search for why this happens but can't seem to figure it out.
Is there something wrong with my formulation? And why is the system not being damped/losing energy?
Thanks for reading.

A: In complexified coordinates $z=x+yi$ you want to solve $$\ddot z=-iz.$$ This has basis solutions
$$
\exp\left(\pm\frac{1+i}{\sqrt2}t\right),
$$
so already the exact solution will spiral out, it is not astonishing that a numerical solution follows this pattern.

*

*A radial vector field is always proportional to the radius vector, your vector field is normal to the radius vector. It is tangent to circles with center at the origin.

*Your vector field is not conservative, so any argument with changing vs. constant energy levels is invalid.
Always use a better integration method, a higher order method or smaller step sizes, if you think that your implementation has an error. It is then easy to see if the difference between the two is completely out-of-line or falls into an expected error growth pattern.


text:
Q: How to read local.properties android in java files I want to add custom fields in local.properties like
debug.username=test123
debug.password=abcd1234

can add .properties files in assets folder and read that easily.
Resources resources = context.getResources();
AssetManager assetManager = resources.getAssets();
Properties properties = null;
InputStream inputStream = assetManager.open(fileName);
properties = new Properties();
properties.load(inputStream);

But don't want to do this.
As i want every team member of our to use local.properties to specify there custom attribute. which is not the part of version control system.
So how to read local.properties placed in the root folder of gradle based android project in java files at runtime?

A: Properties properties = new Properties();
InputStream inputStream =
this.getClass().getClassLoader().getResourceAsStream("fileName.properties");
properties.load(inputStream);
Username=properties.getProperty("username");
password=properties.getProperty("password");

More detailed answer is here
http://pillsfromtheweb.blogspot.in/2014/09/properties-file-in-android.html
and for asset use this code
        AssetManager assetManager = getAssets();
        InputStream inputStream = null;
        try {
            inputStream = assetManager.open("fileName.properties");
            properties.load(inputStream);
            String Username = properties.getProperty("username");
            String password = properties.getProperty("password");
        }
        catch (IOException e){
            Log.e("message: ",e.toString);
        }

A: I know that this is an old question but I recently encountered the same thing and I thought I'd share my solution:

*

*Set the value in your local.properties file.

*Read the value in your Gradle build script and set it to a BuildConfig constant.

*Access the BuildConfig constant in your Java code.

local.properties
username=myUsername

build.gradle:
def getUsername() {
    Properties properties = new Properties()
    properties.load(project.rootProject.file('local.properties').newDataInputStream())
    return properties.getProperty("username");
}

android {
    defaultConfig {
        buildConfigField "String", "USERNAME", "\""+getUsername()+"\""
    }
}

Example Java class:
package your.package.name;

class MyClass {
    String getUsername() {
        return BuildConfig.USERNAME; // Will return "myUsername"
    }
}

A: Here's a variant of the other solutions, stripped down to the essentials:
local.properties:
username=test123
password=abcd1234

build.gradle
android {
    ...
    defaultConfig {
        ...
        Properties properties = new Properties()
        properties.load(project.rootProject.file('local.properties').newDataInputStream())
        buildConfigField "String", "USERNAME", "\"" + properties.getProperty('username') + "\""
        buildConfigField "String", "PASSWORD", "\"" + properties.getProperty('password') + "\""
    }
}

Java:
String userName = BuildConfig.USERNAME;


text:
Q: Multiple robots meta tags I've recently inherited a codebase and discovered this gem:
{% if PAGE_EXTRAS.hide_from_sitemap %}
    <META NAME="ROBOTS" CONTENT="NOINDEX, FOLLOW">
    <META NAME="ROBOTS" CONTENT="INDEX, NOFOLLOW">
    <META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
{% endif %}

I have no idea what it's trying to do. Is there a reason you'd put multiple, apparently-conflicting robots tags in a site like that? Or is it as insane as it looks to my uninformed eye?

A: This looks like a mistake to me. The only information I could find about this was in Google's Robots meta tag specification:

If competing directives are encountered by our crawlers we will use the most restrictive directive we find.

So, (for Google, at least) the code:
<meta name="robots" content="noindex, follow">
<meta name="robots" content="index, nofollow">
<meta name="robots" content="noindex, nofollow">

does exactly the same thing as:
<meta name="robots" content="noindex, nofollow">

It's conceivable this code might be intended as some sort of sneaky hack, intended to apply different rules to different crawlers by exploiting differences in how they resolve conflicts. If so, this is a terrible idea, IMHO. There is no need for a messy fragile hack when there's already a legitimate mechanism to do the same thing:
<meta name="googlebot" content="noindex, follow">
<meta name="bingbot" content="index, nofollow">


text:
Q: AttributeError at 'WSGIRequest' object has no attribute 'Post' When i click vote button I got this error AttributeError at /polls/2/vote/
'WSGIRequest' object has no attribute 'Post'. When i tried to vote for any poll. This is my results.html file
I am using django==3.2 and python 3.8
This is my results.html
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
<fieldset>
    <legend>
{{ question.question_text }}
</legend>
    {% if error_message %}

{{ error_message }}

    {% endif %}
    {% for choice in question.choice_set.all %}
        <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
        {{ choice.choice_text }}

    {% endfor %}
</fieldset>
<input type="submit" value="Vote" >
</form>

and this is my vote view function of polls app
It always shows Exception in line number 4 of the code
def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.Post['choice'])

    except(KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {'question': question, 'error_message': "You didn't select a choice"})

    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))


text:
Q: Binary representation starting with a least significant bit in C I'm trying to make a binary representation of an integer using binary() function and then use reverse() function to get bit reversal as can be seen below:
#include <stdio.h>

unsigned char reverse(unsigned char b) {
    b = (b & 0xF0) >> 4 | (b & 0x0F) << 4;
    b = (b & 0xCC) >> 2 | (b & 0x33) << 2;
    b = (b & 0xAA) >> 1 | (b & 0x55) << 1;
    return b;
}

int binary(int n)
{
    int b;

    if (n == 0)
    {
        return 0;
    }
    else
    {
        b = (n % 2) + 10 * binary(n / 2);
        unsigned char i = (unsigned char)b;
        return reverse(i);

    }

}

int main()
{
  int n;
  printf("Enter a decimal number: ");
  scanf("%d", &n);
  printf("The binary equivalent of %d is %d\n", n, binary(n));
  return 0;
}

The issue I'm having is that I expect binary() to produce a binary number (for example, a binary representation fo 18 would be 10010), and then reverse() function to take this number and produce a reversed binary representation starting with the least significant bit (LSB) which should be 01001 in this case. However, when I try to run it, I get returned 0.
I'm new to C and I'm thinking maybe the issue is in the unsigned char datatype, but when, why if I convert b into unsigned char it still doesn't work?

A: When reversing the bits, all you have to do is check the LSB. Add that value to an output variable. Then shift the output variable by one to the left and shift the original number by one to the right. In the mathematical example below, I do a first 0 shift so it become easier on the eye with the formatting.
In your example of 10010:
Round 1: output = (00000 << 1) + (10010 & 1) = 00000
         N      = 10010 >> 1                 = 01001

Round 2: output = (00000 << 1) + (01001 & 1) = 00001
         N      = 01001 >> 1                 = 00100

Round 3: output = (00001 << 1) + (00100 & 1) = 00010
         N      = 00100 >> 1                 = 00010

Round 4: output = (00010 << 1) + (0010 & 1)  = 00100
         N      = 00010 >> 1                 = 00001

Round 5: output = (00100 << 1) + (00001 & 1) = 01001
         N      = 00001 >> 1                 = 00000

Example:
#include <stdio.h>

int binary(int n)
{
    int output = 0;

    if ( n == 0 ) return 0;

    // Save one left shift
    output += n & 1;
    n = n >> 1;

    while( n != 0 ){
        output = output << 1;
        output += n & 1;
        n = n >> 1;
        printf("%d\n", output);
    }

    return output;
}

void printBin(int n){
    char bin[33] = {0};

    for (int i = 31; i > -1; i-- ){
        bin[i] = (char)((n & 1) ^ 48);
        n = n >> 1;
    }
    puts(bin);
}

int main()
{
    int n; int rb;
    printf("Enter a decimal number: ");
    scanf("%d", &n);

    rb = binary(n);

    printf("The binary equivalent of %d is %d\n", n, rb);

    printf("%11d:", n);
    printBin(n);

    printf("%11d:", rb);
    printBin(rb);

    return 0;
}


text:
Q: Prerequisites for understanding the Hodge conjecture The Hodge conjecture is a major open mathematical problem that states that on a complex manifold $X$ and its respective Hodge classes, defined as
$Hdg^k(X)= H^{2k}(X,\mathbb{Q})\cap H^{k,k}(X)$
that the Hodge classes are linear combinations with rational coefficients of the cohomology classes of complex subvarieties of $X$.
What are the prequisities for understanding this conjecture?
All answers are greatly appreciated.

A: Your question is very large. I am not aware about your background, but you need to begin with the following items:
Atiyah, M. F.; Hirzebruch, F. (1961), "Vector bundles and homogeneous spaces", Proc. Sympos. Pure Math. 3: 7–38
Cattani, Eduardo; Deligne, Pierre; Kaplan, Aroldo (1995), "On the locus of Hodge classes", Journal of the American Mathematical Society 8 (2): 483–506, doi:10.2307/2152824, JSTOR 2152824, MR 1273413.
Grothendieck, A. (1969), "Hodge's general conjecture is false for trivial reasons", Topology 8 (3): 299–303, doi:10.1016/0040-9383(69)90016-0.
Hodge, W. V. D. (1950), "The topological invariants of algebraic varieties", Proceedings of the International Congress of Mathematicians (Cambridge, MA) 1: 181–192.
Moonen, B. J. J.; Zarhin, Yu. G. (1999), "Hodge classes on abelian varieties of low dimension", Mathematische Annalen 315 (4): 711–733.
Voisin, Claire (2002), "A counterexample to the Hodge conjecture extended to Kähler varieties", Int Math Res Notices 2002 (20): 1057–1075.
See also these links for more details about the references:
http://www.math.jussieu.fr/~voisin/Articlesweb/takagifinal.pdf
http://www.claymath.org/millennium/Hodge_Conjecture/hodge.pdf
This link is also very important:
https://mathoverflow.net/questions/54197/why-is-the-hodge-conjecture-so-important

A: Although Dan Freed's lecture remains a classic introduction, one cannot go wrong with the video series here too.
One needs to familiarize wit basic geometry, calculus, algebraic topology, differential topology, algebraic geometry, Bezout's theorem and Hodge theory in general.
Here is also a glimpse from Kevin Devlin's introduction to the Millenium problems.


text:
Q: Checklist с доп значениями Можно ли как то реализовать checklist, что бы отображался один текст, и к нему привязана другая строка? Опишу по подробнее, начал осваивать С#. Есть задача дать пользователю список баз данных, он отмечает строки и по кнопке идет обработка отмеченных значений. Но человек работает с наименованием, а обрабатывать нужно по ИД. Пока реализовал с помощью списка на форме с наименованиями, и массивом ИД с одинаковыми индексами. Но как мне кажется, это не совсем корректно использовать, да и накладывает ограничения. В общем идеально было бы, что бы у элемента списка было представление и значение.

A: Создайте модель данных:
public class Item
{
    public string Title { get; set; }
    public string Value { get; set; }
    public bool IsChecked { get; set; }
}

Title - это то, что будет позазываться пользователю (представление).
Value - значение. Тип выберите нужный вам.
IsChecked - выбран элемент или нет.
В приложении делаем привязку данных.
Контрол CheckedListBox зачем-то прячет некоторые унаследованные свойства. Получаем к ним доступ путём приведения к ListBox.
В событии ItemCheck отмечаем выбранные элемент.
При клике по свободному месту формы можно посмотреть значения выбранных элементов.
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;

namespace WinFormApp1
{
    public partial class Form1 : Form
    {
        CheckedListBox checkedListBox;
        List<Item> items;

        public Form1()
        {
            items = new List<Item>
            {
                new Item { Title="TitleA", Value="ValueA" },
                new Item { Title="TitleB", Value="ValueB" },
                new Item { Title="TitleC", Value="ValueC" },
            };

            checkedListBox = new CheckedListBox { Parent = this, Dock = DockStyle.Left };

            var listBox = (ListBox)checkedListBox;
            listBox.DataSource = items;
            listBox.DisplayMember = nameof(Item.Title);
            listBox.ValueMember = nameof(Item.Value);

            checkedListBox.ItemCheck += CheckedListBox_ItemCheck;
            this.Click += Form1_Click;
        }

        private void Form1_Click(object sender, EventArgs e)
        {
            var checkedValues = items.Where(x => x.IsChecked).Select(x => x.Value);
            this.Text = string.Join(", ", checkedValues);
        }

        private void CheckedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            items[e.Index].IsChecked = e.NewValue == CheckState.Checked;
        }
    }
}


text:
Q: Linq Sql Query Error for Get value Here is my linq query for get Qty and Number from first collection Qty - Second Collection Qty and first collection Number - Second Collection Number, Some times First collection RM not contain second colection
var summary = (from r in firstCollection
                       join s in secondCollection
                       on new { r.RM, r.Size } equals new { s.RM, s.Size }
                       group new { r, s } by new { RM = r.RM, Size = s.Size, Qty = (r.Qty - s.Qty), Number = (r.Number - s.Number) }
                           into grp
                           select new
                               {
                                   RM = grp.Key.RM,
                                   RMsize = grp.Key.Size,
                                   Qty = grp.Key.Qty,
                                   Number = grp.Key.Number
                               }).ToList();

there is an error like

Additional information: A group by expression can only contain
  non-constant scalars that are comparable by the server. The expression
  with type 'Manufacturing.DataAccess.tbl_RawMaterial' is not
  comparable.

How can i solve this ?

A: You can project to anonymous type first and then do a grouping. Try this:
var summary = (from r in firstCollection
                join s in secondCollection
                on new { r.RM, r.Size } equals new { s.RM, s.Size }
                select new
                {
                    RM = r.RM,
                    Size = s.Size,
                    Qty = (r.Qty - s.Qty),
                    Number = (r.Number - s.Number)
                } into tmp
                group tmp by new
                {
                    RM,
                    Size,
                    Qty,
                    Number
                } into grp
                select new
                {
                    RM = grp.Key.RM,
                    RMsize = grp.Key.Size,
                    Qty = grp.Key.Qty,
                    Number = grp.Key.Number
                }).ToList();

A: Looks like the problem is RM member which I assume is some navigation property of type Manufacturing.DataAccess.tbl_RawMaterial. As the exception message states, you can only group by simple properties.
Let say your entity Manufacturing.DataAccess.tbl_RawMaterial primary key is called Id (you can replace it with the actual name). Then the query could be something like this
var summary =
    (from r in firstCollection
     join s in secondCollection
     on new { r.RM.Id, r.Size } equals new { s.RM.Id, s.Size }
     group new { r, s }
     by new { Id = r.RM.Id, Size = s.Size, Qty = (r.Qty - s.Qty), Number = (r.Number - s.Number) }
     into grp
     select new
     {
         RM = grp.FirstOrDefault(e => e.r),
         RMsize = grp.Key.Size,
         Qty = grp.Key.Qty,
         Number = grp.Key.Number
      }).ToList();


text:
Q: How can i config properly RabbitMQ, messenger and amqp on symfony 5.2 without use docker_compose.yml? I want to submit a form with async method using messenger component and rabbitmq. After submitting this form, an email is sent to me. But when i implement rabbitmq it does not work. I have surely a problem with configuration. Maybe i have to add something in services.yml ? I dont want to use docker.
    transports:
        # https://symfony.com/doc/current/messenger.html#transport-configuration
        async :
            dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
            options:
                auto_setup: false
                use_notify: true
                check_delayed_interval: 60000
        # failed: 'doctrine://default?queue_name=failed'
        # sync: 'sync://'

    routing:
        # Route your messages to the transports
        'App\Message\MailNotification': async

.env file with amqp because i want to use rabbitmq
MESSENGER_TRANSPORT_DSN=amqp://guest:guest@localhost:5672/%2f/messages

Output give me this result when i submit form
Could not connect to the AMQP server. Please verify the provided DSN. ({"host":"localhost","port":5672,"vhost":"/","auto_setup":false,"use_notify":true,"check_delayed_interval":60000,"login":"guest","password":"********"}).

In addition, Rabbitmq UI appears on webprofiler DOWN, it does not turn to UP. I can't figure out. Help me please.


text:
Q: closing select2 on click away when closeonselect is false is there a better way to close select2 when you click away?  I have it closing with
$(document).click(function(event) {
    if(!$(event.target).hasClass("select2-selection__rendered") &&
       !$(event.target).hasClass("select2-results__option")) {
        $("#e1").select2('close');
    }
});

but that seems weird.
here is the fiddle
http://jsfiddle.net/jEADR/5557/


text:
Q: gridsplitter not behaving as excpected when coupled with scrollviewer and minWidth
*

*I have a grid as background container

*this grid contains a scrollviewer so that when I resize the window Up, the content extends with it, but when I resize the window down, the scrollbar appears on the scrollviewer when I reach the minWidth on the sv's content

*this scrollviewer contains a grid with two columns

*this grid contains one scrollviewer in each column, each one containing in turn a grid.

*I have a grid splitter on the first column so that I can resize the columns

disclaimer: I know this is not the optimal way to organize this layout, but this is actually the simplest representation I found to reproduce an issue I have with a much more elaborate layout so please do not offer a solution that would reorganize the layers
here is the xaml :
<Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Text Project">

    <!--background grid-->
    <Grid>

        <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">

            <!--two columns layout-->
            <Grid MinWidth="600">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>

                <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
                    <Grid MinWidth="200" Background="Red"/>
                </ScrollViewer>

                <GridSplitter HorizontalAlignment="Right" VerticalAlignment="Stretch" Width="6"/>

                <ScrollViewer Grid.Column="1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
                    <Grid MinWidth="200" Background="Blue"/>
                </ScrollViewer>
            </Grid>

        </ScrollViewer>

    </Grid>

</Window>

the goal is as follow:
- if I resize the window Up, everything scales
- if I resize down, when I reach the minWidth, the scroolbars on the topmost scrollviewer appear and its content stops shrinking.
(this part works fine)
- whatever the topmost scrollviewer's size, I can resize both columns with the gridsplitter
- when I reach one column's minwidth, the scrollbar appears on this column's scrollviewer and its content stops shrinking
issue: this second part never happens. What I get is that I can resize until I reach one of the two child grids's minWidth, and then the gridsplitter stops moving, I cannot shrink further and the scrollbars never appear.
I noticed that if I remove the topmost grid and its associated scrollviewer, it works as expected:
<Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Text Project">

            <!--two columns layout-->
            <Grid MinWidth="600">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>

                <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
                    <Grid MinWidth="200" Background="Red"/>
                </ScrollViewer>

                <GridSplitter HorizontalAlignment="Right" VerticalAlignment="Stretch" Width="6"/>

                <ScrollViewer Grid.Column="1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
                    <Grid MinWidth="200" Background="Blue"/>
                </ScrollViewer>
            </Grid>

</Window>

I don't understand why the fact that I put the inner grid into a scrollviewer would change the behaviour of the gridsplitter and of the inner scrollviewers, so I anybody knows of a solution, I'd be glad

A: Try binding the Width of the two column Grid to the ActualWidth of the outer ScrollViewer, like this:
<!--two columns layout-->
<Grid MinWidth="600" Width="{Binding RelativeSource={RelativeSource AncestorType=ScrollViewer}, Path=ActualWidth}">


text:
Q: Writing multiple files to (rewinding) tape archive I am new to tape archive world, but I find it odd that I cannot write two files to a tape without going through the tar -r option.
Here is what I am trying to do:
$ cd /tmp
$ touch first second
$ tar cvf /dev/st0 first
$ tar cvf /dev/st0 second
$ tar tvf /dev/st0
-rw-r--r-- mathieu/mathieu   0 2014-02-21 15:00 second

Obviously I've lost first file. I fail to see how I could possible skip this first tar archive. I tried:
$ export TAPE=/dev/st0
$ mt fsf 2
/dev/st0: Input/output error
$ mt fsf 1
$ mt tell
At block 0.

My scenario is that I want two machines be able to create individual tarballs and then scp each onto the tape archivers (cron job) to stores thoses two as separated tarballs. Something like:
$ tar zcf - /home | ssh tape_archiver "cat > /dev/st0"

For reference:
$ mt status
SCSI 2 tape drive:
File number=0, block number=0, partition=0.
Tape block size 0 bytes. Density code 0x40 (DLT1 40 GB, or Ultrium).
Soft error count since last status=0
General status bits on (41010000):
 BOT ONLINE IM_REP_EN

According to tldp it should be possible to skip the first archive.

A: It seems the solution is pretty trivial, simply use the non-rewinding interface:
$ export TAPE=/dev/nst0

As seen here:
You seem to be using the device /dev/st0 which is a SCSI tape device. There is no problem with using that device, but it will always do a rewind after every completed access to that device. So after you have written a tar file to the device, it will do a rewind afterwards.

You wil need the device /dev/nst0. The "n" stands for no-rewind. After writing to that device, the tape position stays at the end of the tape. Try using the following commands:

mt -f /dev/nst0 rewind
tar cvf /dev/nst0 $HOME
mt -f /dev/nst0 status


text:
Q: Store some data in client side which can be accessed across angularjs app Hi I am new to angularjs. At the start of the app I need to hit the API and store some data in the client side so that it should be accessible across all the controllers and also in config.
Can you please suggest whats the best approach.
Here is what I have tried:
Service: My issue with it is every time I call , it will call the API.
I want to call only once and store it. I am fine with calling on page refresh.
Value: Cannot be accessed in config.
Thanks.

A: You can store data in angular js localstorage.
Ypu can add data in localstorage and get them anywhere in the app , also if you want ,you can remove from localstorage also.
Example
localStorage.setItem('test', data.item);
localStorage.getItem('test')
localStorage.removeItem('test');


text:
Q: How to use Special Relativity in simple numericals? So I was recently thinking about what an electron's velocity would be after it was accelerated through a potential difference of 1 V. Doing simple calculations like just dividing its energy (which would be 1 eV after being accelerated) by m/2 (from the K.E equation) results in a velocity of about 592000 m/s which is totally absurd. I know that mass increases with velocity so the calculation that I did was wrong. So can anyone please tell me how to work out the actual velocity of the electron using, presumably, the concepts from SR?
Thank you

A: As the comments have said, we deprecate questions that just involve churning through the maths without any conceptual content. However in this case I think there's room to discuss the concepts without things getting too homework like.
You started with the equation for the kinetic energy:
$$ E = \tfrac{1}{2} mv^2 \tag{1} $$
and knowing the energy (1eV) you worked out the corresponding velocity. This is fine as long as you bear in mind that equation (1) is an approximation that applies when $v \ll c$. As it happens this is fine for the 1ev energy you are considering, but you ask what happens when the energy is much higher. In that case you have to use an extended version of equation (1) that applies for high velocities:
$$ E^2 = p^2c^2 + m^2c^4 \tag{2} $$
where $p$ is the relativistic momentum:
$$ p = \frac{mv}{\sqrt{1 - \frac{v^2}{c^2}}} $$
While it's easy to get the velocity from the energy using equation (1), doing this with equation (2) is slightly messier, but only slightly. Substituting for $p$ in equation (2) and rearranging we get:
$$ \frac{E^2}{c^2} - m^2c^2 = \frac{m^2v^2}{1 - \frac{v^2}{c^2}} $$
which simplifies to:
$$ v = c\sqrt{1 - \frac{m^2c^4}{E^2}} $$
The last wrinkle is that the energy $E$ in this equation is the total energy i.e. the 1eV of energy the electron got from the potential difference plus the rest mass energy given by Einstein's famous equation $E = mc^2$. So if $V$ is the voltage, so the potential energy is $eV$, the full equation is:
$$ v = c\sqrt{1 - \frac{m^2c^4}{(eV + mc^2)^2}} \tag{3} $$
Just for fun I graphed this up to a million volts to see what it looked like:

Incidentally, equation (3) gives the velocity for 1 volt as 593096 m/s compared to your result of (as you say) about 592000 m/s.


text:
Q: Gatsby doesn't render MD in component inside of mdx file What is working:

*

*The layout is correctly applied to each of my pages

*The MDX file correctly gets the Hero and section component and renders the HTML/CSS of the container correctly

*The data from MDX is loaded and displayed

What is NOT working:

*

*The MD within the Hero or the Section Shortcode is not being rendered! # is not transformed into H1 etc.

What i have tried:

*

*Using the MDXRender in Section & Hero => Error

*Use the component directly in the MDX file instead of shortcode

Question:

*

*Is it not possible to render the MD correctly within the shortcode?
In other words, is the MDX not rendered recurisvely?

content/index.mdx:
---
title: Main Content English
slug: /main-content/
---

<Hero># This is a test, but never gets transformed</Hero>

# In Section Headline

# ABC

Officia cillum _asdasd_ et duis dolor occaecat velit culpa. Cillum eu sint adipisicing labore incididunt nostrud tempor fugiat. Occaecat ex id fugiat laborum ullamco. Deserunt sint quis aliqua consequat ullamco Lorem dolor pariatur laboris. Laborum officia ut magna exercitation elit velit mollit do. Elit minim nostrud cillum reprehenderit deserunt consequat. Aliqua ex cillum sunt exercitation deserunt sit aliquip aliquip ea proident cillum quis.

My layout.js looks like this:
import React, {useEffect} from "react";

import "./Layout.css";

import { MDXProvider } from "@mdx-js/react";
import { MdxLink } from "gatsby-theme-i18n";
...

import Hero from "../Hero/HomepageHero/HomepageHero"
import Section from "../Section/Section"

const components = {
  a: MdxLink,
  Hero, Section
};

export default function Layout({ children }) {
   ...
  return (

      <ScrollToTopButton />

        <MDXProvider components={components}>{children}</MDXProvider>

      <Copyright />

  );
}

my index.js page (loaded automatically) looks like this:
import * as React from "react";

import { graphql } from "gatsby";

import Layout from "../components/Layout/layout";
import { MDXRenderer } from "gatsby-plugin-mdx";

const IndexPage = ({ data }) => {

  return (
    <Layout>
      {data.allFile.nodes.map(({ childMdx: node }) => (

          {node ? (
            <MDXRenderer>{node.body}</MDXRenderer>
          ) : (

This page has not been translated yet.

          )}

      ))}
    </Layout>
  );
};

export default IndexPage;

export const query = graphql`
  query($locale: String!) {
    allFile(
      filter: {
        sourceInstanceName: { eq: "content" }
        childMdx: { fields: { locale: { eq: $locale } } }
      }
    ) {
      nodes {
        childMdx {
          body
        }
      }
    }
  }
`;

Gatsby Config:
module.exports = {
  siteMetadata: {
    siteUrl: "localhost:8000",
    title: "app",
  },
  plugins: [
    {
      resolve: "gatsby-plugin-google-analytics",
      options: {
        trackingId: "",
      },
    },
    "gatsby-plugin-sharp",
    "gatsby-plugin-react-helmet",
    "gatsby-plugin-sitemap",
    "gatsby-plugin-offline",
    {
      resolve: "gatsby-plugin-manifest",
      options: {
        icon: "src/images/icon.png",
      },
    },
    "gatsby-transformer-sharp",
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "images",
        path: "./src/images/",
      },
      __key: "images",
    },
    {
      resolve: `gatsby-theme-i18n`,
      options: {
        defaultLang: `en`,
        locales: `en el de`,
        configPath: require.resolve(`${__dirname}/i18n/config.json`),
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `pages`,
        path: `${__dirname}/src/pages/`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `content`,
        path: `${__dirname}/src/content/`,
      },
    },
    {
      resolve: `gatsby-plugin-mdx`,
      options: {
        defaultLayouts: {
          default: require.resolve(`./src/components/Layout/layout.js`),
        },
      },
    },
  ],
};

Section.js Component
import React from "react";
import PropTypes from "prop-types";
import "./Section.css";

export default function Section(props) {
  let content = props.children
  if (props.centered) {
    content = (

        {props.children}

    );
  }
  return
{content}
;
}

Section.propTypes = {
  centered: PropTypes.bool,
  children: PropTypes.element,
};

A: In the end it was a simple spacing issue.
It works perfectly fine without any additional work:
---
title: Main Content English
slug: /main-content/
---

<Hero>

# This is a test, but never gets transformed

</Hero>

# In Section Headline

...

Be aware of the empty lines!

A: With MDX you are rendering JSX inside a Markdown (MD + JSX) file so, # it's not recognized as a shortcode when it's wrapped by a JSX component when it's in the same declarative line:
Change:
<Hero># This is a test, but never gets transformed</Hero>

To:
<Hero>
    # This is a test, but never gets transformed
</Hero>

Alternatively, you can also change:
<Hero># This is a test, but never gets transformed</Hero>

To:
<Hero>
 This is a test, but never gets transformed
</Hero>

Another thing that may work for you is using a Markdown parser (like markdown-to-jsx) and:
---
title: Main Content English
slug: /main-content/
---

import Markdown from 'markdown-to-jsx';

<Hero><Markdown># This is a test, but never gets transformed</Markdown></Hero>

<Markdown># In Section Headline</Markdown>

# ABC

Officia cillum _asdasd_ et duis dolor occaecat velit culpa. Cillum eu sint adipisicing labore incididunt nostrud tempor fugiat. Occaecat ex id fugiat laborum ullamco. Deserunt sint quis aliqua consequat ullamco Lorem dolor pariatur laboris. Laborum officia ut magna exercitation elit velit mollit do. Elit minim nostrud cillum reprehenderit deserunt consequat. Aliqua ex cillum sunt exercitation deserunt sit aliquip aliquip ea proident cillum quis.

Alternatively, you add a custom mapping component, as you do with MdxLink but using your own component to parse the children as <Markdown> dependency does.


text:
Q: How to calculate the derivative of Jacobian in drake? I have successfully created MPB (of type double) in drake and managed to calculate numerical Jacobian for specified point with CalcJacobianTranslationalVelocity method.
But now I am interested in derivative of Jacobian at the same point. Automatic differentiation seems to be appropriate tool for that.
So I converted my plant from double to AutoDiffXd, but could not succeeded in converting Context to AutoDiffXd.
CreateDefaultContext of autodiff plant goes into segmentation fault.
So, is there a possibility to calculate value of derivative of Jacobian?

A: CreateDefaultContext for MBP AutoDiffXd should definitely not seg fault.  If you have a minimal reproduction case, please submit an issue.
I do think your workflow should work.  For some of the most common queries which need to be high performance, we provide analytical derivatives (often what one actually wants is Jdotv, for instance).. so there is a chance that we have or will have a better workflow than the autodiff route depending on your specific use case.


text:
Q: Keeping Drupal updated with Git I'm trying to figure out how to use the Drupal mirror on Git hub. I'm new to git but have worked out the following:
Set up a git Drupal repo
* git init
* git remote add drupal git://github.com/drupal/drupal.git
* git fetch drupal

* git tag
* git merge <tag_name>

Make a branch for my site
* git branch <my_site>
* git checkout <my_site>
* git add .
* git commit -a

Update core
* git checkout master
* git fetch drupal
* git tag
* git merge <new_versions_tag>

Update my_site's core
* git checkout <my_site>
* git rebase master

I'm keeping a separate branch for each of my sites. Each branch just keeps a separate sites directory because I'm not hacking core. I've done some experimenting and it looks like I could do everything as a merge without conflict but my limited reading makes rebase sound like the right answer.
I'm not interested in doing module development in this repo. I'm not keeping it on my server for direct deployment. I'm keeping it locally for upgrade testing and as raw material for a shell script to deploy from.
Do these look like the right solutions?

A: The rebase versus merge decision really comes down to whether or not you want to rewrite your branch's history every time you upgrade. If you just have the one repo, this may be a personal decision. See git-rebase for more information on how your history is rewritten.
If this isn't going to be just a single repo, and you (presumably) are sharing the branches, this will become a problem when you try to push/pull as the remote branches will have the last known history. This gets very dirty, very quick. If you plan on having more than one repo, just merge the master branch into your site branches to update them. You can do this as often as you like.
Hope that helps.


text:
Q: my if condition wont hide accordingly my next and previous buttons I need a if condition which hides the first page=1 previous button, and on page 8 it hides the next button
i did use the below code and try but it is not hiding accordingly:

var page = 8;
if(page == 0){
    $("#prev-button").hide();
    $("#next-button").show();
}else if (page == 8) {
    $("#prev-button").show();
    $("#next-button").hide();
}

  Next

  Prev

A: Maybe this will help you on what you're trying to achieve:
      var page = 0;
      $("#prev-button").hide();
      $("#next-button").show();

      function showBoth() {
        if (page < 8 && page > 0) {
          $("#prev-button").show();
          $("#next-button").show();
        }
      }

      $("#prev-button").on("click", function () {
        page--;
        showBoth();
        if (page == 0) $(this).hide();
      });
      $("#next-button").on("click", function () {
        page++;
        showBoth();
        if (page == 8) $(this).hide();
      });


text:
Q: meteor: getting error "No Iron.Layout found so you can't use yield" just getting started with meteor
following this autoform tutorial:
http://www.webtempest.com/meteor-js-autoform-tutorial

have these simple files: main.html:

  <title></title>

Posts

  {{> quickForm collection="Posts" id="insertPostForm" type="insert"}}

<template name="main">

      {{> yield}}

</template>

post.html:
<template name="post">

Edit Post

  {{> quickForm collection="Posts" id="updatePostForm" type="update" doc=this}}
    Back
</template>

posts.html:
<template name="posts">

Add Post

  {{> quickForm collection="Posts" id="insertPostForm" type="insert"}}

      {{#each posts}}

{{title}} - {{content}}

      {{/each}}

</template>

and the router:
Router.configure({
    layoutTemplate: 'main'
});
Router.route('/', 'posts');
Router.route('/posts/:_id', function () {
    var item = Posts.findOne({_id: this.params._id});
    this.render('post', {data: item});
}, {
    name: 'post.show'
});

When I run this, I get this error:
Error: No Iron.Layout found so you can't use yield! iron_layout.js:410

What can I do to fix this, please?

A: What you have in your main.html is invalid.  The  tag should not be after your layout definition.  Change it to:

  <title></title>

Posts

  {{> quickForm collection="Posts" id="insertPostForm" type="insert"}}

<template name="main">

      {{> yield}}

</template>


text:
Q: Как исправить reduce/reduce конфликт? Я пытаюсь написать парсер функций и переменных С++.
Имею вот такую грамматику(обрезана):
declaration:
    block_declaration
    | function_definition
    ;

block_declaration: simple_declaration;

simple_declaration: decl_specifier_seq init_declarator_list';';

decl_specifier_seq:
    decl_specifier
    | decl_specifier_seq decl_specifier
    ;

decl_specifier: type_specifier
    ;

type_specifier:
    simple_type_specifier
    | cv_qualifier
    ;

simple_type_specifier: type;

function_definition:
    decl_specifier_seq declarator function_body
    ;

function_body: '{' '}';

init_declarator_list:
    init_declarator
    | init_declarator_list ',' init_declarator
    ;

init_declarator: declarator initializer_opt;

declarator:
    direct_declarator
    | ptr_operator declarator
    ;

direct_declarator:
    declarator_id
    | direct_declarator '(' ')'
    | '(' declarator ')'
    ;

declarator_id: name | COLONCOLON name;

type:scope_id_seq_opt identifier;

name:scope_id_seq_opt unqualified_id;

scope_id_seq_opt:
    | scope_id_seq
    ;

scope_id_seq: scope_id_seq_opt SCOPE_ID COLONCOLON;

unqualified_id: identifier;

identifier:ID;

Конфликт reduce/reduce возникает в direct_declarator и связан с | '(' declarator ')' то есть если закоментировать эту строчку то всё хорошо, но теряется возможность распознать код вида int (*var);, а С++ поддерживает такой синтаксис. Как мне исправить данный конфликт?
Например парсим текст вида:
T add() {}

Лексер преобразует его в
ID(T) ID(add) '(' ')' '{' '}'

Должно быть так: ID(T) должен свернуться в type, а потом свернётся в  decl_specifier_seq. ID(add) '(' ')' должен свернуться в declarator через правило | direct_declarator '(' ')'.
Но из-за конфликта правила | direct_declarator '(' ')' с | '(' declarator ')' происходит вот так. В decl_specifier_seq сворачивается не ID(T), а ID(T) ID(add). А вот '(' ')' начинает сворачиваться в declarator по правилу | '(' declarator ')' и происходит syntax error, unexpected ')', expecting ID or SCOPE_ID
Использовать glr парсер я не могу по причине использования Lexical feedback


text:
Q: Init github repository I've just created a new Github repository, but apparently forgot to allow Github to create the README and so on with which it helpfully offers to initialize the repository.
I attempted to create this locally and push it with the following commands:
git remote add origin
git push -u origin master

However, it keeps giving me the error:
https://github.com/Arkaaito/<repo>/info/refs not found: did you run git update-server-info on the server?
I don't know how to run git update-server-info on Github because Github does not provide shell access via ssh; there's got to be some UI option for it somewhere, but I don't know where.  Can anyone help me find the blindingly obvious?

A: Could you post the result of git remote show origin From the looks of the error you got, you simply forgot to include the repo name after your username...
Also, the error is mentioned on this GitHub help article as the result of using a really old version of git or not having push access to a repo.  (It can also be the result of an incorrect remote origin URL, for instance a URL with incorrect capitalization.)
EDIT: Just noticed that it was the formatting that made <repo> appear blank, it's most likely that you just have an older version of git, so update.

A: *

*Create a repo on Github.

*Create a repo on your local machine:
$ cd Foo
$ touch README.md
$ git init
$ git add .
$ git commit -m "Initial commit"

*Link your repo between local & remote, then push to remote:
$ git remote add origin git@github.com:<your_username>/Foo.git
$ git push -u origin master

If you get a conflict then, pull from remote repo before push:
$ git pull


text:
Q: Macro for taking the middle value of a string from a closed workbook doesn't work One of problems I have is that, when I want to e.g. just map the middle of a string from other workbook, it doesn't work. In the cell it needs to take that middle value there is afterwards nothing, and I get REF! error. When I do the same thing without recording macro, it works perfectly.
Here is the code:
Workbooks.Open ("C:\Data\DA1\Korr\Makros\akt_5.9\Output\account-acc-std-mit-lineal.xlsx")
    With ActiveWindow
        .SplitColumn = 0
        .SplitRow = 0
    End With
    Windows("record_count_check.xlsm").Activate
    Range("B2").Select
    Selection.FormulaArray = _
        "=MID(INDEX('account-acc-std-mit-lineal.xlsx'!C1,MAX(('account-acc-std-mit-lineal.xlsx'!C1<>"""")*ROW('account-acc-std-mit-lineal.xlsx'!C1))),21,3)"
    Range("D2").Select
    Selection.FormulaArray = _
        "=RIGHT(INDEX('account-acc-std-mit-lineal.xlsx'!C2,MAX(('account-acc-std-mit-lineal.xlsx'!C2<>"""")*ROW('account-acc-std-mit-lineal.xlsx'!C2))),10)"
    Range("E2").Select
    ActiveCell.FormulaR1C1 = "=COUNTA('account-acc-std-mit-lineal.xlsx'!C2)"

What I need to do? How is the best way to code so that I'm able to access data from other workbooks?

A: If you are trying to ge values from another workbook, then you need to include the workbook and the sheet name in the formula. In your VBA, none of the functions include the name of the worksheet, just the workbook name and the cell address.
Also you need to be using the same cell address mode, i.e. R1C1 style or A1 style. If you are using FormulaR1C1 then you must use the R1C1 style.
For example,
ActiveCell.FormulaR1C1 = "=COUNTA('account-acc-std-mit-lineal.xlsx'!C2)"

Should be something like:
ActiveCell.FormulaR1C1 = "=COUNTA([account-acc-std-mit-lineal.xlsx]sheet_name!R2C3)"

EDIT: I've just realised that account-acc-std-mit-lineal.xlsx is the name of the workbook into which you are putting the formula. You can remove the the name of the workbook from the formula then.
ActiveCell.FormulaR1C1 = "=COUNTA(R2C3)"

You can always manually build the formula in the worksheet, select the cell and then in the Immediate window in the IDE enter "?Selection.FormulaR1C1" (without the quotes), press Enter to see what answer you get.


text:
Q: Is it possible to create multiple spouts in one topology? how? I have two topics BACKUPDATA and LIVEDATA.
what is the best solution for read both topics??
   1. Two different topologies?
   2. One topology with two spouts?
I tried with two different topology but storm not allocating slots to second topology.

A: Yes, you can use multiple spouts in a topology.
builder.setSpout("kafka-spout1", new KafkaSpout(spoutConf1), 1);
builder.setSpout("kafka-spout2", new KafkaSpout(spoutConf2), 1);

Well, configuration depends on how you process the data.
If you create separate topology for both, so one topology failure issue won't affect another one, but It'll affect the running cost.
And in case of single topology with multiple spout, both will be affected with each-other failures. If you want to club the data from both topics at the same time, you should use multiple spouts.