text:
Q: How to post the name or id of a textbox, like the way we post the value of it I have two textboxes called text1 and text2, and variables value1 and value2.
When the user submits the form, I want to create a url like below
mydomain.com/?text1=value1&text2=value2

How can I pass the name of the texbox or a dropdown list?

A: Assuming I understood your question, you should set the method attribute in your form to "get". Once the form is submitted you'll see the form fields' submitted values in the url.

A: I assume you know how to use $_GET. If not, you need to learn about the difference between get and post.
Otherwise, if you really must use $_POST, you can use http_build_query() or if it's not available, something like this after the form submit:
$url = '?';
foreach ($_POST as $k => $v)
{
     $url .= "&".urlencode($k).'='.urlencode($v);
}
header("Location: mydomain.com/$url");

The most sensible solution is to use $_GET, which will do this for you automatically.
<form method="get" action="mydomain.com">


text:
Q: Django Unit Tests don't clear the database after executing I'm running a series of unit tests on a view, but I'm noticing that the database which is being accessed in each test isn't changing.
For example, the first test I might run might have the command:
Post.objects.create(title='TEST1',...)

and if I get the response, the queryset will contain:

However, all tests I run after this will return the same
<Post: TEST1>

No test, other than the first one, creates an object with the title 'TEST1'; they are all created with other numbers, e.g. 'TEST2', 'TEST3', etc.
Additionally, if I run the tests individually, I have no problems, but if I run all the tests for the application, these errors arise. Does anyone know what's happening? I'm using django.test.TestCase for all tests.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Qt5: error: 'WA_LockPortraitOrientation' is not a member of 'Qt' I'm trying to compile a Qt4/Symbian project to Qt5, while preserving support for Qt4/Symbian.
Currently the MainWindow::setOrientation auto-generated boilerplate function is giving me trouble.
It gives me these compiler errors:
error: 'WA_LockPortraitOrientation' is not a member of 'Qt'
error: 'WA_LockLandscapeOrientation' is not a member of 'Qt'
error: 'WA_AutoOrientation' is not a member of 'Qt'

A: Yes, those were removed in Qt 5 as you noted yourself.
The reason is that these are Symbian-only features and such things just confuse the Qt users if they only work on a certain platform, especially if that platform is not even supported by Qt 5, inherently.
The corresponding gerrit change can be found in here:
https://codereview.qt-project.org/#change,11280
You need to change these lines
#if QT_VERSION < 0x040702
    // Qt < 4.7.2 does not yet have the Qt::WA_*Orientation attributes

to these:
#if (QT_VERSION < QT_VERSION_CHECK(4, 7, 2)) || (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    // Qt < 4.7.2 does not yet have the Qt::WA_*Orientation attributes
    // Qt 5 has removed them.

The nice way for conditionally allowing certain features based on the Qt version would be this:
#if (QT_VERSION < QT_VERSION_CHECK(4, 7, 2)) || (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
...
#endif

It is cleaner and nicer than hard-coding hex values. It is also the recommended way that existing Qt modules follow, like QtSerialPort.

A: I fixed it by changing these line:
#if QT_VERSION < 0x040702
    // Qt < 4.7.2 does not yet have the Qt::WA_*Orientation attributes

to these:
#if (QT_VERSION < QT_VERSION_CHECK(4, 7, 2)) || (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    // Qt < 4.7.2 does not yet have the Qt::WA_*Orientation attributes
    // Qt 5 has removed them.


text:
Q: Simple python script to get a libreoffice base field and play on vlc I've banged my head for hours on this one, and I don't understand the LibreOffice macro api well enough to know how to make this work:
1) This script works in python:
#!/usr/bin/env python3
import subprocess
def play_vlc(path="/path/to/video.avi"):
    subprocess.call(['vlc', path])
    return None
play_vlc("/path/to/video.avi")

2) I've got python scripts working fine in LibreOffice Base, and this script is fired on a button press. The video opens (with an error - see below)
Now, how do open the path found in a given record's field labeled "path" -- ie, what is being passed to python, and how do I pull that relevant bit of info?
Further, whenever I fire this, the video plays, but I also get:
com.sun.star.uno.RuntimeExceptionError during invoking function play_vlc in module file:///usr/lib/libreoffice/share/Scripts/python/vlc.py (<class 'TypeError'>: Can't convert 'com.sun.star.lang.EventObject' object to str implicitly
  /usr/lib/python3.5/subprocess.py:1480 in function _execute_child() [restore_signals, start_new_session, preexec_fn)]
  /usr/lib/python3.5/subprocess.py:947 in function __init__() [restore_signals, start_new_session)]
  /usr/lib/python3.5/subprocess.py:557 in function call() [with Popen(*popenargs, **kwargs) as p:]
  /usr/lib/libreoffice/share/Scripts/python/vlc.py:8 in function play_vlc() [subprocess.call(['vlc', path])]
  /usr/lib/libreoffice/program/pythonscript.py:870 in function invoke() [ret = self.func( *args )]
)

Please help!

A: For example, say the form is based on a table containing a column called PATH.  Assign the button's Execute action event to this function:
def playvlc_button_pressed(oEvent):
    oForm = oEvent.Source.getModel().getParent()
    lNameCol = oForm.findColumn('PATH')
    sPath = oForm.getString(lNameCol)
    play_vlc(sPath)

Documentation for Base macros is confusing, but there is some at:
http://www.pitonyak.org/database/


text:
Q: Python - Multiline SQL with List - Not all parameters were used in the SQL statement I'm usually a C# Dev, in an attempt to get some python experience.
So at this current time I got a List of values I want to import into MYSQL, as there will be quite a few lines I want go with a single big import than thousands of small ones.
Looking at the docs on pynative I can see the example being provided as:
 mySql_insert_query = """INSERT INTO Laptop (Id, Name, Price, Purchase_date)
                           VALUES (%s, %s, %s, %s) """

    records_to_insert = [(4, 'HP Pavilion Power', 1999, '2019-01-11'),
                         (5, 'MSI WS75 9TL-496', 5799, '2019-02-27'),
                         (6, 'Microsoft Surface', 2330, '2019-07-23')]

    cursor = connection.cursor()
    cursor.executemany(mySql_insert_query, records_to_insert)
    connection.commit()

As my records to insert will be data pulled from an API, I had the "briliant" idea of building the list the most basic and probably the worst method possible.
By creating the list with a pre-formatted string.
  val = []
  sql = """INSERT INTO equipment (ItemStaticID, ItemID, ItemType, Element, Tier, Level, Hp, Atk, Hit, Def, Spd) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
  for x in range(len(test)):
    print(test[x].id, test[x].itemId, test[x].itemSubType, test[x].elementalType, test[x].grade, test[x].level, test[x].hP, test[x].aTK, test[x].hIT, test[x].dEF, test[x].sPD)
    value = "({},'{}','{}','{}','{}','{}','{}','{}','{}','{}','{}')".format(test[x].id, test[x].itemId, test[x].itemSubType, test[x].elementalType, test[x].grade, test[x].level, test[x].hP, test[x].aTK, test[x].hIT, test[x].dEF, test[x].sPD)
    print(value)
    val.append(value)

  insertcur = mydb.cursor()
  insertcur.executemany(sql, val)

When running this code I get a "Not all parameters were used in the SQL statement", I verified that the SQL Query was accurate and the fields listed matched, 11 column names and I got 11 params.
So I'm a bit lost why it believes that not all params are being used in the SQL statement.
The below is the content of my list "val"
["(10340000,'d3252f40-5cbb-4a7c-a140-dcc2badac580','BELT','NORMAL','4','1','0','0','555','0','1683')", "(10340000,'e8e16a7b-4271-4cd4-8700-4dfb17a9525f','BELT','NORMAL','4','2','0','0','534','0','1848')", "(10341000,'66e70f12-f13b-4572-a222-cd61740d78b8','BELT','FIRE','4','0','0','0','503','0','1921')", "(10130000,'7cc2027b-110e-4ba0-9d95-ce563eca4be9','WEAPON','NORMAL','3','0','0','99','0','0','0')", "(10130000,'88440779-0794-431e-a726-3cb63af1dae1','WEAPON','NORMAL','3','0','0','99','0','0','0')", "(10130000,'f513afc3-9035-40b4-a0bb-6d4a74b88c7d','WEAPON','NORMAL','3','0','0','100','0','0','88')", "(10130000,'e22a771e-3fd7-4ce4-93c4-254913e89551','WEAPON','NORMAL','3','0','0','100','0','0','93')", "(10230000,'bf97a302-41e1-4b21-b7ff-3d7786f96ec3','ARMOR','NORMAL','3','0','1707','0','0','33','0')", "(10233000,'69f4811f-f45b-4227-99eb-2f45f0705c2a','ARMOR','LAND','3','0','11254','0','0','0','0')", "(10431000,'0813b427-de85-4fd6-82a1-fe8b8708ad45','NECKLACE','FIRE','3','0','0','0','677','30','0')", "(10531000,'48fc6562-44b5-49ba-8ad2-837d0e981a70','RING','FIRE','3','0','0','65','0','90','0')", "(10120000,'e5ebcdb9-ae59-4fc2-adb8-50e3b673c26d','WEAPON','NORMAL','2','0','0','39','0','0','0')", "(10120000,'22194497-91d1-405d-8a46-9c25b36c7ffd','WEAPON','NORMAL','2','1','0','42','0','0','37')", "(10124000,'487e9efc-a5f6-4944-924a-38ff8bcfb014','WEAPON','WIND','2','0','0','421','0','0','0')", "(10124000,'d015eced-58ec-48c4-bdbd-4f790c9ccbe4','WEAPON','WIND','2','0','0','453','0','0','572')", "(10124000,'1c624b33-889d-42f1-ae6b-2ddda234c481','WEAPON','WIND','2','1','0','462','0','0','0')", "(10220000,'225f94e7-2342-4a50-a1b7-07ec789457f1','ARMOR','NORMAL','2','1','737','0','0','13','0')", "(10220000,'64bd3ce5-572a-4b83-b83c-5f8f7f728f9e','ARMOR','NORMAL','2','1','727','0','0','13','0')", "(10224000,'206d6a67-3d1e-4b22-ad94-1ee19bdb4e00','ARMOR','WIND','2','3','9597','0','0','67','0')", "(10224000,'0ddc84d4-b65d-4b6d-b332-b3de72defce2','ARMOR','WIND','2','3','8972','0','0','88','0')", "(10321000,'3d0f39cb-0684-42a4-a9b0-ec2466679d18','BELT','FIRE','2','0','0','0','0','0','176')", "(10423000,'4ebb7192-15d4-4e9d-999c-be4a2e7ac85a','NECKLACE','LAND','2','3','0','0','1833','63','0')", "(10523000,'d1260941-ba0f-4a2a-b452-b3c3a6d6ec81','RING','LAND','2','0','0','0','384','172','0')", "(10523000,'fdef3e38-88ba-4970-923e-1d46ea35d1c5','RING','LAND','2','3','0','0','295','282','0')", "(10523000,'e3657fe9-481e-45ea-9086-065a79e3bc06','RING','LAND','2','0','0','0','376','173','0')", "(10523000,'68ab4ca0-683f-43a8-a2c6-358788e4e5e8','RING','LAND','2','2','0','0','408','195','0')", "(10523000,'be3921cc-fc3a-48bb-8542-c385d83d99cb','RING','LAND','2','0','0','0','0','172','0')", "(10523000,'422bb5ab-bef6-42a8-8562-a572d07c7970','RING','LAND','2','0','0','0','0','175','0')", "(10523000,'708df542-4622-4849-899c-846938f98ef2','RING','LAND','2','0','0','0','392','173','0')", "(10111000,'54896e7e-9799-4c81-a704-124522ab9b91','WEAPON','FIRE','1','3','0','23','0','0','0')", "(10210000,'09f995cd-6a8c-47ae-8c46-18f799322c9a','ARMOR','NORMAL','1','2','264','0','0','5','0')", "(10212000,'4effa256-6fe1-4051-866d-0f77d4294004','ARMOR','WATER','1','0','374','0','0','0','0')", "(10312000,'326908bb-ba10-4be9-abf2-4499d413bbb0','BELT','WATER','1','2','0','0','23','0','110')", "(10412000,'390c39f3-756b-488a-ae3f-eb03021453af','NECKLACE','WATER','1','3','0','0','156','8','0')", "(10512000,'7f8f0faf-da5c-435c-a27b-14ccbf94dd08','RING','WATER','1','3','159','0','0','20','0')", "(10514000,'08049c6d-5923-49d6-ac5f-fb569fc69ed3','RING','WIND','1','2','0','0','0','224','232')", "(10514000,'8dce0420-4d09-4ab6-8d73-86343155f8b9','RING','WIND','1','3','0','0','0','230','433')"]


text:
Q: Table join only inserting values depending on values in column from other table I have two tables. One table with areas of certain types a.matrikulaere_foreninger with 274 rows and another table with a column called b.pnr.
I want to create a view where the pnr from table b is joined to table a, but I only want the pnr to be joined when a.type_mg is different from the value 'Almen boligforening'.
I have tried the following.
SELECT a.gid,
a.type_mg,
a.cvrnr,
a.the_geom,
CASE WHEN type_mg <> 'Almen boligforening'
    THEN b.pnr
    ELSE NULL
    END pnr
FROM _01_fysisk_plan_og_naturbeskyt.matrikulaere_foreninger a
    LEFT JOIN _00_grundkort.cvr_prod_enhkomgeoview b ON a.cvrnr = b.virksomhed_cvrnr;

The above query results i a new table with 311 rows because there are multiple pnr for every type_mg = 'Almen boligforening'. But I want to end up with a view with 274 rows with pnr values for each row with type_mgdifferent from 'Almen boligforening' and NULL values for columns with type_mg = 'Almen boligforening'.


text:
Q: I'm getting error in Logcat on DataChange while fetching data from firebase realtime database I have to retrive the user data from realtime data in profileActivity.
I have saved the data inside the "Users" node of the database, but when i wants to fetch it logcat shows the error onDataChange
Error shows on line inside the ProfileActivity at:
User value = snapshot.getValue(User.class)
        databaseReference.child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {

                    User value = snapshot.getValue(User.class);

                    if (user != null){
                        String fullname = value.name;
                        String email = value.email;
                        String phone = value.phone;

                        fullnametextview.setText(fullname);
                        emailtextview.setText(email);
                        phonetextview.setText(phone);
                    }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(ProfileActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
            }
        });

    }

}```

Reference of my database is "Users".

"Users": {
    "Dy4SkpgT0qdV0hAWCR05FlyUhN73": {
      "email": "juaavha@gmail.com",
      "name": "Wjshsb",
      "phone": "6434843482"
    },

Here is the error shows inside the logcat :

I/InputTransport: Create ARC handle: 0xb40000785af1b120
V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = android.view.ViewRootImpl@82c8817, this = DecorView@804ba58[ProfileActivity]
V/OplusZoomWindowDecorViewHelper: setLastReportedMergedConfiguration mZoomDisplayHeight: 2400 getDecorView.DecorView@804ba58[ProfileActivity]
V/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = android.view.ViewRootImpl@df32955, this = DecorView@6ee3b5e[Dashboard]
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.studystudio.enggdarbar, PID: 5601
    com.google.firebase.database.DatabaseException: Class com.studystudio.enggdarbar.User does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped.
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(CustomClassMapper.java:570)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(CustomClassMapper.java:563)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:433)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:232)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:80)
        at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:203)
        at com.studystudio.enggdarbar.ProfileActivity$1.onDataChange(ProfileActivity.java:55)
        at com.google.firebase.database.Query$1.onDataChange(Query.java:191)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
        at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:255)
        at android.app.ActivityThread.main(ActivityThread.java:8212)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:632)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049)
I/Process: Sending signal. PID: 5601 SIG: 9


text:
Q: Convert two subversion repos on googlecode to a single git repo on github (1) How do I convert two subversion repos, one of which is an external of the other to a single git repo on github?  I want the history to be interleaved so that the gitk output makes sense!
(2) Why would I want to use svnadmin dump instead of just git cloneing them and then moving them?
(3) How can I test my new repository to see that it matches the old pair of repositories?
For the sake of answering the questions, suppose the two subversion repositories are at http://acl2-devel.googlecode.com/svn and http://acl2-books.googlecode.com/svn, and that both repositories were setup with the standard svn layout (trunk, branches, tags).  Also, assume that I want a clean break and want a fresh start for branches and tags.

A: (1) Here is the meta-level discussion of what I did to combine the two repos into a single git repo.

*

*Dump both subversion repositories using svnsync and svnadmin

*Create a new svn repository with the books repo mounted in a books
subdirectory

*Remove all branches and tags from the svn repository (but leaving
their history)

*Convert the svn repo to git, canonicalizing emails to match github
account email addresses

*Remove all references to branches and tags in the history using "bfg"

*"Rewrite" the git history to accommodate the move from an internal server
many years ago, the moving of the ACL2 system trunk up to root, and
the moving of the books up a level

*Create a new repo and "cherry-pick" the 4000+ commits in order of
timestamp to create a nicely ordered history

*Pushed the resulting repo to github

The script that implements the above is long and available at:
    https://github.com/ragerdl/svn-to-git/blob/master/convert-acl2-books-svn-and-acl2-devel-svn-to-git.sh
(2) Why not use git svn clone on both repositories and then merge them?
Because, when I got to the cherry-pick step, there were a good number of conflicts.  Performing it in this order avoided those conflicts.
(3) You can test your repository by making sure that, for every extension you care about, the count of each extension is the same in both repositories.  You can also perform a diff.  See https://github.com/ragerdl/svn-to-git/blob/master/quality-assurance.sh for a script that performs those actions.
I realize that copy+pasting code would be good, but there is so much, and this is my first cut.  If someone else would like to clean up the script I wrote and paste it in here, it would be appreciated.  I wouldn't consider this a real value-add to society, except I spent many hours reading others' posts, and I couldn't find an answer to this question.  Thus, I think this answer should go somewhere easily found by search engines.


text:
Q: Execute a code after every function is called I have a scrolltobottom() function that is run after every function is executed.
How can I refactor the code so that I don't need to type scrolltobottom() everywhere?
Preferably without using Jquery.
async function initBot () {
  let botui = BotUI('homepage-bot', {
    vue: Vue
  })

  let scrolltobottom = () => {
    let ele = document.getElementById('botui')
    document.body.scrollTop = ele.clientHeight
  }

  await botui.message.bot({"Hello"})
  await scrolltobottom()

  await botui.message.bot({"Do you like apple or orange?"})
  await scrolltobottom()

  await botui.message.button({"Orange", "Apple"})
  await scrolltobottom()
}

A: You could create a decorator function
function decorateWith(targetFn, fn){
  return function(){
    targetFn.apply(this, arguments);
    fn();
  }
}

[ botui.message.bot,
  botui.message.button ]
  .forEach(fn => decorateWith(fn, scrolltobottom));


text:
Q: Indenting text in \tabfill (tabbing environment) I am not an expert in LaTeX. Thus, the question may sound trivial. I am using the tabbing environment, and I have long lines to wrap. Thus, I am using the \tabfill command in order to do so.
\newcommand\tabfill[1]{%\dimen@\linewidth%
\advance\dimen@\@totalleftmargin%
\advance\dimen@-\dimen\@curtab%
\parbox[t]\dimen@{#1\ifhmode\strut\fi}%
% or, to avoid stretching:
% \parbox[t]\dimen@{\raggedright #1\ifhmode\strut\fi}%
}

The only problem that I have with this command is that the text inside the \tabfill box is aligned to the left margin. I would like that when this text is wrapped (since it is inside a tabbing environment) it is also indented in the rows following the first. Any idea about how to modify this tabfill command in order to achieve this goal? Or any other solution?
Example of what I am looking for:
Column 1                Column 2
bla bla                 bla bla bla bla bla bla bla bla bla bla bla bla
                        bla bla bla bla
bla bla                 bla bla

Code (generating no indent):
\begin{tabbing}
\hspace{3.1cm} \= \kill
Column 1 \> Column 2\\
bla bla \> \tabfill{bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla}\\
bla bla \> \tabfill{bla bla}
\end{tabbing}

Does it make sense?

A: This is what I get from your original code (the first setting to \dimen@ uncommented):
\documentclass{article}
\makeatletter
\newcommand\tabfill[1]{%
  \dimen@\linewidth
  \advance\dimen@\@totalleftmargin
  \advance\dimen@-\dimen\@curtab
  \parbox[t]\dimen@{#1\ifhmode\strut\fi}%
}
\makeatother

\textwidth=.75\textwidth % just to make wrapping more evident

\begin{document}
\begin{tabbing}
\hspace{3.1cm} \= \kill
Column 1 \> Column 2\\
bla bla \> \tabfill{bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla}\\
bla bla \> \tabfill{bla bla}
\end{tabbing}
\end{document}

Let's add a \leftskip setting:
\documentclass{article}
\makeatletter
\newcommand\tabfill[1]{%
  \dimen@\linewidth
  \advance\dimen@\@totalleftmargin
  \advance\dimen@-\dimen\@curtab
  \parbox[t]\dimen@{%
    \leftskip=2em\hspace*{-2em}#1\ifhmode\unskip\nobreak\strut\fi}%
}
\makeatother

\textwidth=.75\textwidth % just to make wrapping more evident

\begin{document}
\begin{tabbing}
\hspace{3.1cm} \= \kill
Column 1 \> Column 2\\
bla bla \> \tabfill{bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla}\\
bla bla \> \tabfill{bla bla}
\end{tabbing}
\end{document}

If you don't plan using very complicated things inside the argument to \tabfill such as itemized or enumerated lists, this is the simplest solution. If you want to add \raggedright, place it in front of \leftskip.


text:
Q: How to Improve KeyDown Function I have a Main_Form_Keydown and Keyup function to control a robot with my keyboard.
The problem is that if I lose focus of the mainform window I cannot control the robot anymore unless I focus it again and it's a problem because I might crash the robot while doing it.
Any ideas how I can improve my code?
      public void Main_Form_KeyDown(object sender, KeyEventArgs e) //Controlo do drone com o teclado
    {
        switch (e.KeyCode) //Controlo pelo Teclado
        {
            case Keys.F:
                _droneClient.FlatTrim();
                break;
            case Keys.Back:
                if (!isSensitiveMode)
                {
                    flightSensitivityConst = 0.25f;
                    isSensitiveMode = true;
                }
                else
                {
                    flightSensitivityConst = 0.9f;
                    isSensitiveMode = false;
                }
                break;
            case Keys.W:
                _droneClient.Progress(FlightMode.Progressive, pitch: -flightSensitivityConst);
                break;
            case Keys.S:
                _droneClient.Progress(FlightMode.Progressive, pitch: +flightSensitivityConst);
                break;
            case Keys.A:
                _droneClient.Progress(FlightMode.Progressive, roll: -flightSensitivityConst);
                break;
            case Keys.D:
                _droneClient.Progress(FlightMode.Progressive, roll: +flightSensitivityConst);
                break;
            case Keys.I:
                _droneClient.Progress(FlightMode.Progressive, gaz: +flightSensitivityConst);
                break;
            case Keys.K:
                _droneClient.Progress(FlightMode.Progressive, gaz: -flightSensitivityConst);
                break;
            case Keys.J:
                _droneClient.Progress(FlightMode.Progressive, yaw: -flightSensitivityConst);
                break;
            case Keys.L:
                _droneClient.Progress(FlightMode.Progressive, yaw: +flightSensitivityConst);
                break;
            case Keys.E:
                _droneClient.Takeoff();
                break;
            case Keys.Q:
                _droneClient.Emergency();
                break;
            case Keys.Space:
                _droneClient.Land();
                break;
            //FLIPS
            case Keys.P:
                _settings.Control.FlightAnimation = new FlightAnimation(FlightAnimationType.FlipLeft);
                _droneClient.Send(_settings);
                //FLIP
                break;
            case Keys.O:
                _settings.Control.FlightAnimation = new FlightAnimation(FlightAnimationType.FlipRight);
                _droneClient.Send(_settings);
                //FLIP
                break;
            case Keys.Y:
                _settings.Control.FlightAnimation = new FlightAnimation(FlightAnimationType.FlipBehind);
                _droneClient.Send(_settings);
                break;
            case Keys.U:
                _settings.Control.FlightAnimation = new FlightAnimation(FlightAnimationType.FlipAhead);
                _droneClient.Send(_settings);
                break;
            case Keys.C:
                var configuration = new Settings();
                configuration.Video.Channel = VideoChannelType.Next;
                _droneClient.Send(configuration);
                break;
            case Keys.R:
                string path = string.Format("ttu_flight_{0:yyyy_MM_dd_HH_mm}" + ARDroneTrackFileExt, DateTime.Now);
                using (var dialog = new SaveFileDialog { DefaultExt = ARDroneTrackFileExt, Filter = ARDroneTrackFilesFilter, FileName = path })
                {
                    if (dialog.ShowDialog(this) == DialogResult.OK)
                    {
                        StopRecording();

                        _recorderStream = new FileStream(dialog.FileName, FileMode.OpenOrCreate);
                        _packetRecorderWorker = new PacketRecorder(_recorderStream);
                        _packetRecorderWorker.Start();
                    }
                }
                break;
        }
    } //Controlo do drone através do teclado

    private void Main_Form_KeyUp(object sender, KeyEventArgs e) //Se nao estiver a ser comandado pelo teclado
    {
        _droneClient.Hover(); //Fica pairado
    }

I was thinking to use a normal function on a timer but it will be missing KeyEventArgs e

A: Use a global key hook. This will also capture the keys when your window does not have the focus (see: http://www.codeproject.com/Articles/19004/A-Simple-C-Global-Low-Level-Keyboard-Hook or Global keyboard capture in C# application).
Alternatively, you could capture the LostFocus event of your form and then interrupt the program until the form gets focused again.


text:
Q: How to merge asynchronous function's callback result Here is the code to get some information about server.
    cpu.usage()
    .then(info => {
        console.log(info);
    });

    cpu.free()
    .then(info => {
        console.log(info)
    });

    mem.info()
    .then(info => {
        console.log(info)
    });

I want to get every result in a function.
get_resource () {
   ...
   console.log(cpu_usage, cpu_free, mem_info);
};

How can I design it?
Thank you.

A: You can try to use async/await to do that:
var get_resource = async function () {
   var cpu_usage = await cpu.usage();
   var cpu_free = await cpu.free();
   var mem_info = await mem.info();

   console.log(cpu_usage, cpu_free, mem_info);
};

Or
Promise.all([cpu.usage(), cpu.free(), mem.info()]).then(function (info) {
    console.log('cpu_usage:', info[0]);
    console.log('cpu_free:', info[1]);
    console.log('mem_info:', info[2]);
})

A: You can use Promise.all() as following:
let cpuUsage = cpu.usage()
let cpuFree = cpu.free()
let memInfo = mem.info()

Promise.all([cpuUsage, cpuFree, memInfo]).then((values) => {
  console.log(values);
});

If you can use ES6, then you can use array destructuring while getting results:
Promise.all([cpuUsage, cpuFree, memInfo]).then(([cpuUsageResult, cpuFreeResult, memInfoResult]) => {
  console.log(cpuUsageResult);
  console.log(cpuFreeResult);
  console.log(memInfoResult);
});

A: Callback Hell
This is the old scenario where you would have to call things inside one another
    cpu.usage()
    .then(cpu_usage => {
      cpu.free()
      .then(cpu_free => {
        mem.info()
        .then(mem_info => {
          console.log(cpu_usage, cpu_free, mem_info);
        });
      });
    });

Async Await
in this scenario you make a function that is asynchronous.
async function get_resource () {
    const cpu_usage = await cpu.usage();
    const cpu_free = await cpu.free();
    const mem_info = await mem.info();
   console.log(cpu_usage, cpu_free, mem_info);
};

The value assigned to each const in the async function is the same value that you get as an argument in the callback of the then.


text:
Q: Using Chebychev's Inequality to find a lower bound A fair coin is flipped 100 times. Find the lower bound, based on Chebyshev's bound, on the probability of the event that the number of heads observed is in {45,46,..,55}. Compare this to the exact probability 0.73.
So n = 100. p = 0.5. E(X) = 50. Standard deviation = sqrt(100*.5*.5) = 5
45 - 55 is within 1 standard deviation of the mean 50. So I get that k = 1, 1 - 1/k = 1 - 1/1 = 0.
P(|X-E(X)| < 5) = P(|X-E(X)| < 5σ/5) = P(|X-E(X)| < σ)
Then flip it around so we're looking at things outside of 45-55.
P(|X-E(X)| > σ) <= σ^2/σ^2
P(|X-E(X)| > σ) <= 1
How is this useful. I don't get how to use Chebyshev's when k = 1. Isn't this just telling me the probability is <= 1?
Not sure where to go from here...

A: The Chebyshev Inequality does not necessarily give good bounds!
However, the Inequality was slightly misused. I believe it says that the probability that $|X-\mu| \ge k\sigma$ is $\le \frac{1}{k^2}$. In our case, we are interested in $k\sigma=6$.


text:
Q: Example of addition of Twisted Edwards Curve on Sage, Python,.. Can somebody tell me how can I make a example of addition in Twisted Edwards Curve on sage?
For example:
$ax^2 + y^2 = 1 + dx^2y^2$

Given the following twisted Edwards curve with $a=3$ and $d=2$:
$3x^2 + y^2 = 1 + 2x^2y^2$

it is possible to add the points $P_1 = (1 , \sqrt{2})$  and$ P_2 = (1 , −\sqrt{2})$ using the formula given above. The result is a point $P_3$ that has coordinates:
x3 = (x1*y2 + y1*x2)/(1 + d*x1*x2*y1*y2) = 0
y3 = (y1*y2 − a*x1*x2)/(1 − d*x1*x2*y1*y2) = −1

A: It seems that long ago someone worked on this.
R.<y1,y2,c,d,x1,x2> = QQ[]
e = 1-d*c^4
S = R.quotient([x1^2+y1^2-c^2*(1+d*x1^2*y1^2), x2^2+y2^2-c^2*(1+d*x2^2*y2^2)])

# the Edwards addition law:
x3 = (x1*y2+y1*x2)/(c*(1+d*x1*x2*y1*y2))
y3 = (y1*y2-x1*x2)/(c*(1-d*x1*x2*y1*y2))

This preprint also seems to indicate it's possible.
  R.<a,d,x,y>=QQ[]
  A=2*(a+d)/(a-d)
  B=4/(a-d)
  S=R.quotient(a*x^2+y^2-(1+d*x^2*y^2))
  u=(1+y)/(1-y)
  v=(1+y)/((1-y)*x)
  0==S((B*v^2-u^3-A*u^2-u).numerator())

But I'm not an expert on this, so I can't verify whether this is what you are looking for.  Good luck.


text:
Q: Count repeated values in a column I have a column of year values by which I am sorting. I'd like to find the quantity per year (read: number of repeats of each year value). I'd like to chart said values. I'm not sure how to make this happen.
I am using Apple's Numbers '08, but if possible a general solution that multiple people could use would be preferred.

A: You should use the countif() function: http://office.microsoft.com/en-us/excel/HP052090291033.aspx
I did a similar thing to count how many hours of work there are for each upcoming version of my iPhone app. I was doing sumif(), but you just want countif().
See cells N4-N6 here: http://spreadsheets.google.com/ccc?key=0AhL0igVI9HVNdGpaS3U1cS1qOGVNd3h0Slg0a21vUWc&hl=en

A: On a new sheet, list the unique years in one column, then their quantity count in the column next to them.  Select the entire range created, then create a chart.
I'm unsure from your question what you would specifically need more than this (and I work in Excel 2003).


text:
Q: SQL sub query return value subtractions I am doing a sort based on names, for that, I am using rownum, since the sorting is according to names I am trying to fetch next and prev id according to rownum column.
I am trying to subtract subquery result near WHERE clause but its not showing any result. If I place a numeric value directly i.e 3 it will subtract properly.
I have tried typecasting the return value but it still gives me empty result set.
SELECT inner_id, first_name, rank as sort_id
FROM
(
SELECT id as inner_id, first_name, (@rownum:=@rownum+1) rank
    FROM ympa_applications, (SELECT @rownum:=0) t
    ORDER BY first_name ASC
) t WHERE rank = ( (SELECT DISTINCT CAST(rank AS UNSIGNED) FROM ympa_applications WHERE inner_id=132) - 1 )


text:
Q: How to move sound from left to right of earphones in swift? I am making an app for blind people with swift and I can play sound only on the right headphone or only on the left by using the pan property like this:
@IBAction func right(sender: UIButton) {
    player.pan = 1.0 //right headphone
}

@IBAction func left(sender: UIButton) {
    player.pan = -1.0 //left headphone

}

But I need to start playing sound in the right and then move it to the left headphone, how can I do this?

A: I don't know what the panning should be based on, but if you simply want it to move over time, you could just use a timer to update it.
var timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "update", userInfo: nil, repeats: true)

func update() {
    if player.pan == -1.0 {
        timer.invalidate()
        return
    }

    player.pan -= 0.1
}


text:
Q: JoinFormula: Migrating hbm to annotations We are converting all our hbm files to annotations and it's going well.
But we have problems with formulas.
There are 2 tables and 2 entities.
Table PERSON_TYPE
    SID      (number)
    CODE     (varchar2)

Table PERSON
    SID      (number)
    PERSON_B (boolean)

@Entity
Class PersonType
    @Id
    private Long sid;
    private String code;

@Entity
Class Person
    @Id
    private Long sid;
    @Column(name = "PERSON_B")
    private boolean personB;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumnsOrFormulas({
        @JoinColumnOrFormula(formula =
            @JoinFormula(value="(decode(PERSON_B, 1, "PersonType1", 'PersonType2'))", referencedColumnName = "CODE")
    })
    private PersonType personType;

We want to get Entity PersonType with a formula. When boolean personB is true, we want to have PersonType with CODE "PersonType1" otherwise we want PersonType with CODE "PersonType2".
After some attemps we have the above code but this give us following exception: "referencedColumnNames(CODE) of personType referencing PersonType not mapped to a single property".
It works when we use the sid (which is the primary key) instead of CODE in the formula, but we can not assume that we have them.


text:
Q: Print pdf document from MemoryStream I need to print a pdf document that I have altered without saving it back as a new pdf document.  This code below works without a problem.  However I would like to do this quite differently and I´m simultaneously having a brain-lag and can´t see the solution.
My code example
byte[] result;

using (MemoryStream ms = new MemoryStream())
{
    PdfReader pdfReader = new PdfReader("c:\\templatePdf.pdf");
    PdfStamper pdfStamper = new PdfStamper(pdfReader, ms);

    /* abbreviated but here I alter the template pdf */

    pdfStamper.FormFlattening = true;
    pdfStamper.Close();
    result = ms.GetBuffer();
}

/* Instead of saving a new file I would rather like to print
   the altered template pdf in memory and then discard it */
using (FileStream fs = File.Create("C:\\Test.pdf"))
{
    fs.Write(result, 0, (int)result.Length);
}

Process process = new Process();
process.StartInfo.FileName = "C:\\Test.pdf";
process.StartInfo.Verb = "printto";
process.StartInfo.Arguments = "\"" + ppr_PrinterDropDown.Text + "\"";
process.Start();
File.Delete("C:\\Test.pdf");

A: If you are using a file-based API, then you will struggle to do it without a file. You might be able to setup a named pipe server, but frankly that is a huge fiddle. I would, however, be tempted to look around for a fully managed PDF library with print support. But ultimately... what harm is the file system doing, really? Probably not a lot. I might suggest a few tweaks, though:

*

*use the temp area (Path.GetTempPath()), not C:\Test

*wait for the process to finish before deleting the file

A: First We Need To Write into our Memory Stream and then with the help of Memory Stream method "WriteTo" we can write to the Response of the Page as shown in the below code.
   MemoryStream filecontent = null;
   filecontent =//CommonUtility.ExportToPdf(inputXMLtoXSLT);(This will be your MemeoryStream Content)
   Response.ContentType = "image/pdf";
   string headerValue = string.Format("attachment; filename={0}", formName.ToUpper() + ".pdf");
   Response.AppendHeader("Content-Disposition", headerValue);

   filecontent.WriteTo(Response.OutputStream);

   Response.End();

FormName is the fileName given,This code will make the generated PDF file downloadable by invoking a PopUp.

A: This is easy. The hard part is getting useful info about print status completion and total page numbers.
var pq = LocalPrintServer.GetDefaultPrintQueue();
var theJob = pq.AddJob();
try{
    using(var js = theJob.JobStream){
        var buffer = File.ReadAllBytes("yourPathToPdf");
        js.Write(buffer,0,buffer.Length);
    }
    var done=false;
    while(!done)
    {
        pq.Refresh();
        theJob.Refresh();
        done = theJob.IsCompleted || theJob.IsDeleted || theJob.IsPrinted;
    }
}
catch(Exception ex){
    //handle this
}
finally{
    theJob?.Dispose();
    pq?.Dispose();
}

This is assuming your printer has native PDF support, of course. Otherwise you will have to do the rendering work yourself on the client and send it not as a raw stream.


text:
Q: How to get file extension in Marklogic Server? I want to get the file extension of uploaded file in Marklogic server. I know how to get the file name. But that gives filename plus extension like new.txt. But I want only extension not the full file name. How can I get just the file extension ?

A: There are many methods of getting file extensions from filename. For instance you can use functx:substring-after-last($filename, '.') or other methods (fn:substring-after) of getting substring after dot. Please see: xqueryfunctions.com
P.S. fn:tokenize($filename, '\.')[fn:last()]

A: I often use the following replace:
fn:replace("c:\a\b\c.d.e.txt", '^(.*\.)?([^\.]+)$', '$2')

But using functx is a good idea too, as suggested by Andrew. A copy of the functx library is distributed as part of the latter versions of MarkLogic. Just add the following import to get them available:
import module namespace functx = "http://www.functx.com" at "/MarkLogic/functx/functx-1.0-nodoc-2007-01.xqy";

HTH!

A: Just for variety, yet another expression that produces the extension :)  :
reversed-string(substring-before(reversed-string($filePath), '.'))

where reversed-string($s) can be defined as:
codepoints-to-string(reverse(string-to-code-points($s)))

So the whole expression with the substitution is:
codepoints-to-string(
             reverse(
              string-to-codepoints(
               substring-before(codepoints-to-string(reverse(string-to-codepoints($filePath))),
                               '.')
                                   )
                     )
                              )


text:
Q: Quadratic programming maximization -- matrix not positive definite I am trying to optimize the following simple objective function using the quadprog program in R:
max_{x} x'Ax
Most optimization problems I see use minimization, but if I simply use -A instead of A, I get an error that A is no longer positive definite. I am very new to this kind of thing. Does anyone know how to solve a simple quadratic maximization problem?
Here is sample code to reproduce the error:
if (!require(quadprog)) install.packages('quadprog')
library(quadprog)
set.seed(144)
mat <- abs(cor(matrix(rnorm(25),5,5)))
solve.QP(Dmat = -mat, dvec = rep(0,5), Amat = diag(5), bvec = rep(0,5), meq=0, factorized=FALSE)

Here is the resulting error:

Error in solve.QP(Dmat = -mat, dvec = rep(0, 5), Amat = diag(5), bvec
  = rep(0,  :    matrix D in quadratic function is not positive definite!


text:
Q: Concurrent access to groups of objects I'm trying to develop an application that consists of a pool of threads, using a work-stealing algorithm to concurrently execute tasks.
These tasks

*

*access a predefined set of objects;

*must "atomicly" acquire read/write permissions on all objects it accesses before actually running;

*upon finishing (and are guaranteed to eventually finish) release the objects they acquire.

One possible way to to solve this problem is to have each thread pick up a task at a time, then try to lock each of the objects using a predefined order. If at least one fails release all the locks, and proceed with another task.
This method however increases the probability of starvation of tasks with big object dependencies, and may even incur in live locks.
Is there another method to acquire a set of locks while maximizing concurrency? (without a global lock) Or perhaps change the system in a way that it is no longer required?
If so, any good papers about it?
ps: As thiton answered, this is a generalized version of the "dining philosophers" problem. I am looking for non-centralized solutions, in particular algorithms that fare well in high load (addition and deletion of tasks).

A: Ordering resources is a valid approach. Another straightforward aproach that comes to mind is to introduce a shared arbiter holding information about resource availability. Tasks would lock all the resources they need through the arbiter in a single atomic step "acquire(r1, r2, ..., rn)" and release them similarly with "release(r1, r2, ..., rn)".
If an "acquire" request A can be satisfied, the arbiter will make sure no other task may acquire any of the resources held by A until A releases them back.
The arbiter may use several strategies to satisfy incoming requests:

*

*Reject request that can't be immediately satisfied - tasks will have to re-try. This opens the door to live-locks and starvation.

*Keep all incoming requests in a queue and serving them in FIFO manner as resources needed for the request at head become available.

*Keep all unsatisfied requests in a list (without blocking their demanded resources) and iterate through them (perhaps with a priority for older requests) each time some resources get released, to find a request that can be satisfied.

A: If a task tries to lock objects only to fail at some point, it's possible that another task will fail to lock an object because the first task owns it at the time.
I think I would use a global lock when trying to acquire the locks initially and maybe also when releasing them all finally.
I'd worry about maximum concurrency when a simple solution proves to be inadequate in practice.

A: Your problem is called the Dining Philosophers. You should find any amount of literature you need under this keyword :-).


text:
Q: C# -infinite for loop private void button1_Click(object sender, EventArgs e)
{
    int j, counter=0;
    j = 2;
    for (int i = 0; i < 100; i=i*2)
    {
        j = j - i;
        while (j<25)
        {
            j = j + 5;
            counter++;
        }
    }
    MessageBox.Show("Test" + counter);
}

Hi.  I am trying to debug this code, but am not able to.
Can anybody please explain why this is causing an infinite loop?

A: This is because you started i at zero; no matter how many times you double zero, it's going to stay zero :)
for (int i = 1; i < 100; i=i*2) {
    j = j - i;
    while (j<25) {
        j = j + 5;
        counter++;
    }
}

A: Others have already explained the immediate cause. Let me just offer you an "algorithm" for hunting down these kinds of problems so you can solve them on your own in the future: use "Locals" or "Autos" or "Watch" or even "Immediate" panel in the debugger to inspect the values of the variables. You can also just place the mouse arrow over a variable and the hint that pops-up will allow you to see the current variable value.
Had you done that in this case, you'd have noticed that i is staying 0 forever and probably reached a conclusion about what is the root cause of the problem.

A: The reason is your condition for i
for (int i = 0; i < 100; i=i*2)

on the first loop, i = 0, and 0*2 = 0, so i stays at 0 forever.


text:
Q: What is the updating chart pattern with queue()? I think most people on this forum know the enter(), update(), exit() pattern in the reusable chart examples from Bostock.
My question is, how can you use queue(), which preloads data, with this pattern?
Because the essence of the e,p,e pattern is to callback the data function from within a closure and queue is by definition called once, then calls separate functions, is there a way to use it with updating charts?
Update: I would like to pass in the queued datafile as a function parameter, then access that object for my updates.
My initial code looks like:
rateById = d3.map();

queue()
.defer(d3.csv, "./data/femaleChloropleth.csv", function(d) { rateById.set(d.endneighborhood, d.rides); })
.await(ready);

function ready(error, femaleChloropleth) {

console.log(femaleChloropleth);

But console.log() is returning an empty array and i know d3 is accessing the csv file. If I remove the mapping function, it works fine. Any ideas?

A: The queue() library can be thought of as a way to make multiple data calls at once, then call a function on the results when that data is loaded.  It is very similar to d3.xhr functions like d3.json in this way:
To load a single file of external data, you might use the following:
d3.json("path/to/file.json", ready)

function ready(error, jsonData) {
  var selection = d3.selectAll(".something")
      .data(jsonData);
  selection.enter().append("something").attr(etc..);
  selection.attr(etc..);
  selection.exit.remove();
});

If you wanted to load multiple files and use this data together, you'd have to nest these, i.e., d3.json calls, and wait for each file to load in order.  Instead, queue() allows us to do the same thing, but loads multiple files concurrently:
queue()
  .defer(d3.json, "path/to/file.json")
  .defer(d3.csv, "path/to/file.csv")
  .defer(d3.tsv, "path/to/file.txt")
  .await(ready);

function ready(error, jsonData, csvData, tsvData) {
  //now you can use all three data sets in your general update paradigm
  //and did not have to wait for all three to load sequentially
}


text:
Q: Google Charts Setting vAxis To 0.25 Intervals My data will always be in intervals of 0.25 on a line chart. I will never have a point such as 100.14. It will always be numbers such as 100, 100.25, 100.75, 500, 680.50
But when charts are drawn all to often I get vAxis numbers such as 1.1 or 2.4 when these values could never be a "point" on the graph.
I'd like to ONLY show multiples of 0.25 ... or ONLY show actual points on vAxis not "filler" points between two points.
I currently have these options
  var options = {"title":"#{chart_title}",
                 "colors":["#0088cc"],
                 "titleTextStyle": {
                     color: "#0088cc",
                     fontName: "Verdana",
                     fontSize: 24,
                     bold: true,
                     italic: false
                  },
                  "hAxis": {
                             "textStyle": {
                               "fontSize": 14,
                               bold: true
                             }

                            },
                  "vAxis": {
                             "textStyle": {
                               "fontSize": 18,
                               bold: true
                             }

                            }

                 };

Is it possible to force Google charts to always show multiples of 0.25 on vAxis?
OR even the vAxis only needs labels for actual points on the line graph. Is that possible?

A: you can use the vAxis.ticks option to set specific axis labels...
vAxis: {
  ticks: [0, 0.25, 0.50, 0.75, 1, ...]
}

to build the labels dynamically, use the getColumnRange method on the data table,
var dataRange = data.getColumnRange(1);

which returns an object with properties for min and max
use values to build ticks array...
var vTicks = [];
for (var i = dataRange.min; i <= dataRange.max + interval; i = i + interval) {
  vTicks.push(i);
}

(add interval to max to allow a little extra room at the top)

see following working snippet...

google.charts.load('current', {
  callback: function () {
    var data = new google.visualization.DataTable();
    data.addColumn('number', 'x');
    data.addColumn('number', 'y');
    data.addRows([
      [0, 0],
      [1, 0.25],
      [2, 1.25],
      [3, 2.75],
      [4, 3.50],
      [5, 2.25],
      [6, 1.75],
      [7, 0.50]
    ]);

    var interval = 0.25;
    var dataRange = data.getColumnRange(1);

    var vTicks = [];
    for (var i = dataRange.min; i <= dataRange.max + interval; i = i + interval) {
      vTicks.push(i);
    }

    var container = document.getElementById('chart_div');
    var chart = new google.visualization.LineChart(container);

    var options = {
      chartArea: {
        top: 12,
        right: 12,
        bottom: 48,
        left: 48,
        height: '100%',
        width: '100%'
      },
      height: 800,
      legend: {
        position: 'bottom'
      },
      vAxis: {
        ticks: vTicks
      }
    };

    drawChart();
    window.addEventListener('resize', drawChart, false);
    function drawChart() {
      chart.draw(data, options);
    }
  },
  packages:['corechart', 'table']
});


text:
Q: How to prove : If a complex number is equal to its own complex conjugate, then it's real. \begin{align}
a+ib&=a-ib \\
a+i2b&=a \\
i2b&=0 \end{align}
To me, this seems weird. Any suggestions?

A: Let $z=a+bi$ be a complex number, where $a,b \in \mathbb R$.
Then, it's complex conjugate is : $\bar{z}=a-bi$.
If $z=\bar{z}$ then :
$$a+bi = a-bi \Leftrightarrow 2bi = 0 \Rightarrow bi = 0$$
Obviously, the imaginary unit $i$ is $\neq 0$, so it must be $b=0$.
But note that $b$ is the imaginary part of the complex number $z$ and more specifically :
$$b = \Im\{z\} = 0$$
Since the imaginary part is zero, this means that $z$ is a real number.

A: You're basically done. If $2bi = 0$, then $b=0$. Your number is of the form $a+bi$, so if $b=0$, the number is real (no imaginary part).

A: $$
a+bi=a-bi\implies bi=-bi\implies i(bi)=-i(bi)\implies -b=b
$$
either $b$ is zero or $1=-1$ which is silly. So $b=0$.
You may also multiply
$$
2bi=0
$$
on both sides by $\frac{-i}{2}$ to conclude $b=0$.


text:
Q: Are triggers bad for created/timestamp columns? We are in need of some better auditing on some of our MySQL tables.  Specifically, we'd like to store when the row was inserted and when it was last updated.
Originally, I thought DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP would be perfect, but unfortunately our current MySQL is below version 5.65, so it only supports doing this on one column and thus doesn't meet our needs.
Thus, my next thought was that triggers would be a good solution.  However, when I ran this by our DBA, he said that triggers are normally a bad idea and that I should just update the values in the code every place there is an update or insert.  This works, but I don't like the fact that it leaves an extra thing for everyone who creates/updates records to worry about, and if they forget then the values will be incorrect.  Thus, to me this seems like exactly the case where triggers should be used.
Is this a bad use of a trigger and why?

A: As far as I know, this is the reason Triggers were made.
To handle an event related to a change running in the DB.
I don't see any reason why you shouldn't be using a Trigger.
P.S. please ask your DBA of why he doesn't like Triggers, and report back. Thank you.


text:
Q: Qt - Crash when I use a tcp socket to write data if tcp server first closed and then reopened connection I'm moving my application from Qt 4.7 to Qt 6.3. In Qt 4.7 all works fine. In Qt 6.3 I have some issues when tcp server closes connection, I establish again connection, and I try to write data.
This is the function I use to write to socket:
void NetworkFacility::Write(QTcpSocket& oTCPSocket, const QVariant& oV)
{
    //Controls Socket is valid
    if (oTCPSocket.state() == QAbstractSocket::ConnectedState)
    {
        QByteArray block;                           //ByteArray to serialiaze object
        MyPacket oPacket;                           //Packet to send

        //Set Size of QVariant object
        oPacket.setPacketSize(getQVariantSize(oV));
        //Set QVariant
        oPacket.setTransport(oV);

        //Create stream to write on ByteArray
        QDataStream out(&block, QIODevice::WriteOnly);
        //Sets version
        out.setVersion(QDataStream::Qt_4_7);

        //Serializes
        out << oPacket;
        //TX to socket
        oTCPSocket.write(block);
    }
}

I manage disconnection this way:
void MyClient::remoteNodeDisconnected()
{
  m_pTCPSocket->flush();
  m_pTCPSocket->close();

}

void MyClient::ManagesTCPError(QAbstractSocket::SocketError socketError)
{
    //Clears last packets
    m_pTCPSocket->flush();
}

This is connection portion of code after disconnection:
m_pTCPSocket->connectToHost(m_sIpAddress, m_iIpPort);
//Waits connection
if (m_pTCPSocket->waitForConnected(MSEC_WAIT_FOR_CONNECTION))
{
  //Print connected and exit from while loop
  break;
}

Finally this is the way in which I manage the remote server connecte:
void MyClient::remoteNodeConnected()
{
    //Improve Network latency on this connection
    m_pTCPSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
}

The issue is that on the first connection all works fine. If the server disconnects (i.e. I umplugg the server cable in my LAN or I shutdown and restarts the server application) and then connects again the call to:
oTCPSocket.write(block);

in Networkfacility::Write method generates a crash.
Why the write method generates a crash after reconnection?

A: I fixed the issue by removing completely th oTCPSocket instance.
void MyClient::remoteNodeDisconnected()
{
  m_pTCPSocket->flush();
  m_pTCPSocket->close();
  m_pTCPSocket.deleteLater();
  m_pTCPSocket = 0;
}


text:
Q: getting 403 Forrbiden from UPS I'm using ImportJSONViaPost function to grab FedEx tracking status to my Google doc. which is working. Trying to do the same for UPS and hit a bump with 403-Forrbiden.
What I'm doing wrong?
Thank you.
Fedex
=INDEX(ImportJSONViaPost("https://www.fedex.com/trackingCal/track","data=%7B%22TrackPackagesRequest%22%3A%7B%22appType%22%3A%22WTRK%22%2C%22appDeviceType%22%3A%22DESKTOP%22%2C%22supportHTML%22%3Atrue%2C%22supportCurrentLocation%22%3Atrue%2C%22uniqueKey%22%3A%22%22%2C%22processingParameters%22%3A%7B%7D%2C%22trackingInfoList%22%3A%5B%7B%22trackNumberInfo%22%3A%7B%22trackingNumber%22%3A%22"&123456789012&"%22%2C%22trackingQualifier%22%3A%22%22%2C%22trackingCarrier%22%3A%22%22%7D%7D%5D%7D%7D&action=trackpackages&locale=en_US&version=1&format=json",,"/TrackPackagesResponse/packageList/scanEventList,/TrackPackagesResponse/packageList/trackingCarrierDesc","noHeaders"),1,5)

UPS
=INDEX(ImportJSONViaPost("https://www.ups.com/track/api/Track/GetStatus?loc=en_CA","%7B%22Locale%22%3A%22en_CA%22%2C%22TrackingNumber%22%3A%5B%221ZA668990495524105%22%5D%2C%22Requester%22%3A%22%22%2C%22returnToValue%22%3A%22%22%7D",,"/trackDetails[0].packageStatus","noHeaders"),1)

A: Based on the 403 status and the presence of "api" in the URL, I wonder if you're trying to access the UPS API in a way that requires an Access Key. The API Tech Support Guide walks nicely through the process for acquiring one.


text:
Q: Element.Click not executed when using PhantomJS selenium webdriver in .Net I am using our existing tool that works perfectly using the Firefox and Chrome implementations of the Selenium IWebdriver.
I am now doing some experimentation using the PhantomJS implementation.
So far so good. However, as soon as I want to click a button it does nothing.
I can retrieve the element, however, looking closer at its properties the 'Selected' property states the following:
    Error Message => 'Element is not selectable' caused by Request => {"headers":{"Accept":"application/json, image/png","Connection":"Close","Host":"localhost:37704"},"httpVersion":"1.1","method":"GET","url":"/selected","urlParsed":{"anchor":"","query":"","file":"selected","directory":"/","path":"/selected","relative":"/selected","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/selected","queryKey":{},"chunks":["selected"]},"urlOriginal":"/session/fcaf88a0-40b4-11e3-960d-bdce3224aacf/element/%3Awdc%3A1383063211142/selected"}

I would gather this is the cause that my click is not executed, however, I cannot make heads or tails from this error message. using Google did not help either.
Any help would be much appreciated.
Thanks in advance.

A: We had a lot of similar issues with PhantomJS.
So, couple of steps to figure out what the root cause to it

*

*Set you screen size (as suggested in comments; PhantomJS uses 400x300 by default):
driver.Manage().Window.Size = new Size(1920, 1080); //Size is type in System.Drawing"

*Use to verify that your element is actually visible:
new WebDriverWait(driver,
TimeSpan.FromSeconds(timeOut)).Until(ExpectedConditions.ElementExists((By.Id(login))));

*Click on the element with Javascript
IJavaScriptExecutor js = _driver as IJavaScriptExecutor;
js.ExecuteScript("arguments[0].click();", buttonToClick); //buttonToClick is IWebElement

For Java it would be as follows:

*

*Screen size
driver.manage().window().setSize(new Dimension(width, height));

*Verifying element is visible
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("LOCATOR")));

*Clicking with JS
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", buttonToClick); //buttonToClick is WebElement


text:
Q: Ask user to write the correct file name if he wrote wrong I want to upload some files using my upload function below.
I am asking user to write the name of the files that he wants to upload.
But I am trying to do some kind of validation before, if the user writes a filename that does not exist I want to show a message "The file you selected does not exist, please try again" and I want to ask again user to write same filename so he can write correctly. Do you see how can I achieve this?
def upload(filename):
    if(os.path.exists(filename)):
        # here I do the upload
    else:
        print "The file you selected does not exist, please try again"
        # here I want to ask user again for the field that he filled wrong
        # but this needs to be dynamic (first, second or third)
        uploadToS3(input("Select the first/second/third file:"))
print

raw_input("Press enter to transfer the files...")

upload(input("Select the first file:"))
upload(input("Select second file:"))
upload(input("Select third file:"))

A: Since you step through upload() file by file you can validate them one at a time in the function by locking them in a loop.  return out of the loop (and function) once it successfully uploads:
def upload(filename):
    while True:
        if(os.path.exists(filename)):
            # here I do the upload
            return
        else:
            print "The file you selected does not exist, please try again"
            filename = input("Select the first/second/third file:")

A: I'd probably do something like the following:
def get_filename(prompt):
    while True:
        fn = raw_input(prompt)
        if os.path.exists(fn): return fn
        print("The file you selected does not exist, please try again")

uploadToS3(get_filename("Select the fist file:"))
uploadToS3(get_filename("Select second file:"))
uploadToS3(get_filename("Select third file:"))

This also gets rid of your upload function.
This approach defines a function called get_filename that accepts as an argument, the prompt you want to present.
The prompt is presented and input collected.
If the input filename exists, it's returned to uploadToS3.
If the input filename doesn't exist, a message is printed saying so, and the prompt re-issued, input re-collected, etc.

A: What about something like this? It is a fast hack, but might work .
def upload(filename):
    if(os.path.exists(filename)):
        # here I do the upload
        return True
    else:
        print "The file you selected does not exist, please try again"
        # here I want to ask user again for the field that he filled wrong
        # but this needs to be dynamic (first, second or third)
        uploadToS3(input("Select the first/second/third file:"))
print
return False

def read_user_input(prompt):
    oper_status = upload(input(prompt))
    while oper_status is not True:
        oper_status = upload(input(prompt))

raw_input("Press enter to transfer the files...")

read_user_input(input("Select the fist file:"))
read_user_input(input("Select second file:"))
read_user_input((input("Select third file:"))

A: try a simple while loop. The while loop will remain True while the entered filename doesn't exist. Once the user enters a file name that exist it will break the while loop and continue on to the uploading section. Of course you should adapt the programming logic to fit your needs.
def upload(filename):
    while True:
        if not(os.path.exists(filename)):
            print "The file you selected does not exist, please try again"
        else:
            #upload stuff
            break

A: My answer using recursion is:
def upload(prompt):
    filename = input(prompt) #ask for filename using the given prompt
    if(os.path.exists(filename)):
        uploadToS3(filename)
    else:
        print "The file you selected does not exist, please try again"
        upload(prompt) #Repeat this function if the use did not give valid input
print

raw_input("Press enter to transfer the files...")

upload("Select the fist file:")
upload("Select second file:")
upload("Select third file:")

The second input will display the exact same message as the first one.


text:
Q: Jquery select next class What I am trying to do is to add a find in page functionality to a webpage I am working on. And I am using the Highlight plugin to highlight the search term. You can see a basic demo version on this fiddle.
Highlight plugin adds a span with class "highlight". I want to scroll to each "highlight" class when you press "Find" button repeatedly. What is the best and easy way to do this? I tried next() but couldn't get it to work.
function findText(str){
        searchTerm = str;
        $(".col-xs-8").unhighlight();
        $(".col-xs-8").highlight(str);
        $('html, body').animate({
            scrollTop: $(".highlight").offset().top
        }, 100);
      }

A: check this fiddle.
I have added the below code and I have made few changes in CSS as well. Has this solved your prob??
 function findText(str){
    searchTerm = str;
    $(".col-xs-8").unhighlight();
    $(".col-xs-8").highlight(str);
    $('html, body').animate({
        scrollTop: $(".highlight").eq($('.hide').val()).offset().top
    }, 100);
      $('.hide').val(parseInt($('.hide').val())+1);
  }


text:
Q: Error using getSymbols() in quantmod I'm trying to randomly select 50 stocks from the New York Stock Exchange, and then get the symbols for them. This code:
 require(quantmod)
 NYstocks<-stockSymbols(exchange="NYSE")
 NYsymbols<-NYstocks[["Symbol"]]
 my_portfolio<-sample(NYsymbols, 50, replace = FALSE)
 date_begin <- as.Date("2014-02-18")
 date_end <- as.Date("2016-02-18")
 tickers <- getSymbols(my_portfolio, from = date_begin, to = date_end)

gets the error

Error in read.table(file = file, header = header, sep = sep, quote = quote,  :
  more columns than column names

my_portfolio is a character vector, so I'm having a hard time figuring out what it means about columns and column names. I've tried using src="google" and got

Error in colnames<-(*tmp*, value = c("AIW.Open", "AIW.High", "AIW.Low",  :
  length of 'dimnames' [2] not equal to array extent

Thanks for any help!

A: As the Note in ?stockSymbols says:

The symbols returned by stockSymbols may not be in the format necessary to retrieve data using getYahooData.

And note that TTR::getYahooData downloads data from Yahoo Finance, just like getSymbols.yahoo.
You should also use set.seed when using functions that use the random number generator (i.e. sample) so your example will be reproducible.
A couple other things to keep in mind:

*

*Yahoo Finance, Google Finance, etc do not necessarily provide historical data for all instruments.

*Instruments returned by stockSymbols are not necessarily equities. They could be tickers for an ETF, ETN, etc.

There are other question/answers about how to use try or tryCatch to trap errors that may occur because a site doesn't provide historical data.


text:
Q: Measuring battery voltage fluctuations and spikes in an analog wall mounted clock when the second hand ticks As the title suggests, my goal is to be able to pickup minute voltage fluctuations of an AA battery cell of the wall-mounted clock, each time the second hand ticks.
My first intuition would be to ac-couple the battery into an op-amp, perhaps a low-noise instrumentational amplifier, and feed the output into a microcontroller.
Any suggestions is appreciated.


text:
Q: Как добавить ссылку "Построить маршрут в Яндекс Картах" Добрый день!
Я имею гео данные пользователя и гео данные объекта до которого нужно добраться, между ними мне нужно построить маршрут.
Как мне сгенерировать ссылку, перейдя по которой пользователю, либо откроется мобильное приложение яндекс карты, либо если такого приложения нет, то откроется сайт яндекс карты с построенным маршрутом?

A: Здравствуйте, у мобильного приложения Яндекс.Карты есть url-схема, которая позволяет сгенерировать такую ссылку. В ней доступны параметры rtext для определения координат точек маршрута и rtt для выбора типа маршрутизации.
Пример:
yandexmaps://maps.yandex.ru/?rtext=59.967870,30.242658~59.898495,30.299559&rtt=mt

Документация


text:
Q: Cannot WMI Query root\MSCluster namespace as Local Admin I'm trying to use WMI Explorer to query the root\MSCluster namespace on various hosts to obtain cluster resource group and resource object data. I can access the namespace with no issue on Win2K3 cluster nodes but am getting an access denied error attempting to connect to Win2K8 and Win2K8R2 nodes.
I can access the root\cimv2 namespace with no issue, just the MSCluster namespace even though I am a local Admin. Is there a feature setting, local security policy or server role I have to be a member of to access the namespace?

A: Not familiar with WMI Explorer, but does it let you specify the ImpersonationLevel?
Try the folling VBScript (not tested) on the local machine.  Then edit the strComputer = "." line to be the server name and execute remotely:
On Error Resume Next

Dim strComputer
Dim objWMIService
Dim colClusterNodes
Dim objClusterNode

strComputer = "."

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate,authenticationLevel=pktPrivacy}!\\" & strComputer & "\root\mscluster")
If Err.Number <> 0 Then
    WScript.Echo "ERROR : Failed to get WMI handle [" & Err.Description & "]"
    Err.Clear
Else

    Set colClusterNodes = objWMIService.ExecQuery( "Select * from MSCluster_Node")
    If Err.Number <> 0 Then
        WScript.Echo "ERROR : Failed to execute WMI query [" & Err.Description & "]"
        Err.Clear
    Else

        For Each objClusterNode in colClusterNodes
            Wscript.Echo "Caption : " & objClusterNode.Caption
            Wscript.Echo "State   : " & objClusterNode.State
            Wscript.Echo "Status  : " & objClusterNode.Status
            WScript.Echo ""
    Next

        Set colClusterNodes = Nothing
    End If

    Set objWMIService = Nothing
End If


text:
Q: Diferença entre void e void* Qual a diferença entre o void* e o void como tipo de retorno de uma função?
Exemplo 1:
void *func_nome(int param){
      ...
  }

Exemplo 2:
void func_nome(int param){
      ...
  }

A: Ao se declarar uma função em C, C++ (e outras linguagens derivadas, como Java e C#) é sempre necessário declarar o tipo de retorno da função. void é um tipo especial para indicar que a função não retorna nenhum valor. Significa literalmente "nada". É o que algumas outras linguagens (como Pascal) definiriam como um procedimento (procedure).
Qualquer tipo* indica um ponteiro para aquele tipo. Por exemplo: int* é um ponteiro para inteiro e char* é um ponteiro para caractere. Mas void* não é um ponteiro para "nada". Trata-se de um caso especial. Ele indica um ponteiro para qualquer tipo, como se fosse um coringa. É usando quando não se sabe qual o tipo de dado está sendo apontado. É utilizado, por exemplo, como retorno da função malloc, porque a memória que ela aloca pode ser utilizada para qualquer tipo de dado. Cabe ao programador depois fazer a coerção para o tipo pretendido.


text:
Q: apply my created function to a data frame I have the following function to calculate the black scholes model,
where I paste the necessary data from S0, K , K , T , r
and market_price in the function manually.
I would like to apply this same function to a pandas data frame
There I have the values needed to perform the calculation
Data frame example
data = {'Name':['BOVAE115', 'BOVAE119', 'BBDCE251', 'BBDCE246'],
        'Valor':[110.050003, 110.050003, 19.500000, 19.500000],
        'Strike Value':[15.00, 19.00, 24.67, 25.19],
        'Temp':[0.119048, 0.119048, 0.119048, 0.119048],
        'Taxa':[11.65, 11.65, 11.65, 11.65],
        'Market Price':[0.391968, 0.391968, 0.391968, 0.391968],
        'Order':['c','c','c','c']

       }

# Create DataFrame
df = pd.DataFrame(data)
df

How do I apply the created function to this list of values
Function
See the code
 S0 = df['Valor']
 K = df['Strike Value']
 T = df['Temp']
 r = df['Taxa']
 market_price = df['Price']
 flag = df['Order']

from py_vollib.black_scholes import black_scholes as bs
from py_vollib.black_scholes.greeks.analytical import vega

def implied_vol(S0, K, T, r, market_price, flag='c', tol=0.00001):

    #"""Calculating the implied volatility of an European option
    #    S0: stock price
    #    K: strike price
    #    T: time to maturity
    #    r: risk-free rate
    #    market_price: option price in market
    #"""

    max_iter = 500 #max no. of iterations
    vol_old = 0.3 #initial guess

    for k in range(max_iter):
        bs_price = bs(flag, S0, K, T, r, vol_old)
        Cprime = vega(flag, S0, K, T, r, vol_old)*100
        C = bs_price - market_price

        vol_new = vol_old - C/Cprime
        new_bs_price = bs(flag, S0, K, T, r, vol_new)
        if (abs(vol_old-vol_new) < tol or abs(new_bs_price-market_price) < tol):
            break
        vol_old = vol_new

    implied_vol = vol_new
    return implied_vol

S0 = 14.73
K =  15.04
T =  20/252
r = 0.1165
market_price = 0.41

print(implied_vol(S0, K, T, r, market_price)*100)

I wanted to return the implied vol value in a data frame column
How can I apply this function in my dataframe


text:
Q: i need a good layout for my forms I need some great idea in designing form contain some fieldsets.
Where can i find a nice collection? Is there anywhere?

A: Of course, read for example this article on Sitepoint or look at image replacing techniques or CSS3 solutions

A: To start off with I would recommend reading this article by Cameron Adams. It takes you through the markup side of things and shows you how to set it up in a nice css friendly way:

*

*http://articles.sitepoint.com/print/fancy-form-design-css
There is a nice gallery (with 77 examples at the time of posting) which will show you a lot of design inspirations for laying it out once you have the markup sorted:

*

*http://www.smileycat.com/design_elements/registration_forms/

A: I'm a fan of Smashing Magazine, and here's a good article/collection of what you're looking for.
Several good templates here and here as well.


text:
Q: openssl ssl encryption I want to discuss about openssl write and read method. Assume I have an data structure like below:

/-----------------------------------------------------\
|  my_header   |  PAYLOAD                             |
\-----------------------------------------------------/
       |                              |
      \ /                            \ /
 not encrypted                      encrypted

I think the proper algorithm would be like this :
   SEND:
   build my_header with my own header.
   encrypt PAYLOAD with encryption function
   attach my_header and PAYLOAD (encrypted) to one buffer
   send it using common POSIX function just like send or sendto
   RECV:
   using common POSIX function just like recv or recvfrom.
   extract my_header and PAYLOAD(encrypted)
   decrypt PAYLOAD with decryption function
   at last i got my_header and PAYLOAD(decrypted).

How is your approach if you face a problem like above. Since openssl encrypt all of data that is sent to SSL_write function (CMIIW).
Thanks.
Maybe, the apropriate question is, what is the encryption and decryption function that can be used to encrypt/decrypt PAYLOAD in openssl?.

A: You can actually let OpenSSL do a lot of the heavy lifting for you.
You can create your networking primitives as before and associate the file descriptors with an Open SSL context, which will handle the SSL handshake, encryption and decryption. I'm glossing over a lot of the details but the sample code on the openssl website and in this book:
http://www.amazon.com/Network-Security-OpenSSL-John-Viega/dp/059600270X
will be very instructive. The book is also available online but I believe you have to pay to access it.
In OpenSSL's distribution you can find lots of sample code illustrating exactly how to do this.
Good luck.

A: OpenSSL comes with a libcrypto library which is commonly used to perform standalone encryption outside of an SSL context.
http://www.openssl.org/docs/crypto/evp.html
Alternatively, the bio portion of the library may be even closer to what you want:
http://www.openssl.org/docs/crypto/bio.html
But if you really intend to send this over the network, then I would question the safety of leaving the header unencrypted. Encryption is about more than privacy, it is also about ensuring the data has not been modified in transit. If someone is in a position to monitor your traffic, then they are usually in a position to tamper with it too.
If you want the header unecrypted so you can read it in wireshark for debugging, then I suggest making a flag in your application to fully enable/disable encryption for use in a debugging environment.

A: If you're building an encrypted protocol, that's exactly how I'd do it, assuming my_header contains enough information and nothing that in itself needs to be kept secure, such as the session key. Network packets at the low level (see tcpdump/libpcap) are just a char* ("string") and you extract different headers by moving along the array different lengths - what you're suggesting sounds just like this.

A: When you use TLS/DTLS, you have the choice : you cipher the whole frame, or nothing at all.
If you want to have some unciphered data in the frame, then you probably don't need TLS/DTLS. You might however use OpenSSL to compute a hash of your header (using SHA or any other related hash algorithm) and adding it at the end of the frame to avoid tampering.
For the ciphered part of the frame, you'll have to choose between symetric and asymetric cipher algorithms. But without knowing what you want to achieve, I cannot really advise on this.
Just keep in mind that symetric algorithms are usually faster but require a key exchange at first. To do so, you might use an asymetric algorithm, but then, you're reinventing TLS/DTLS ;)


text:
Q: Running ODI Package from Unix Terminal I want to run the ODI (Oracle Data Integrator) Package from the terminal. I have googled it and all i have came up with is the startscen.sh file which starts the scenario in the ODI from the terminal. Can any one guide me on how to run the ODI Package from the terminal.

A: startscen.sh will be used to execute a scenario, startloadplan.sh will be used to execute a loadplan and finally startcmd.sh will be used to execute any ODI tools from command prompt, however we can't execute any other objects from command prompt.
mean time would like to understand why do you wanna execute a package, why not scenario?


text:
Q: Any way to display AdMob ads (or other ad provider) in pure JavaScript Is there any way to display AdMob ads using only pure JavaScript? Or in any other way, that I can use it directly in PhoneGap application built with PhoneGap Build?
I'm developing mobile apps using PhoneGap. I've seen many solutions and approaches to this problem (like this or this). But since I'm using PhoneGap Build only, I can't use any of it. I've seen AdMob Cordova Plugin, but since it is platform-oriented (currently only available for iOS and Android) and has a lot of Java and SDK in documentation, I'm pretty sure, that I can't use it in app compiled with PhoneGap Build.
If there is no way to get AdMob via JS, then maybe there is another ad provider, which API is reachable entirely from JavaScript?
I've heard that MillenialMedia can display ads using pure JavaScript and even allows external ads providers (like AdMob). So this would be a perfect solution for me. But their page is so poorly organised (a lot of self-marketing bla-bla and no actual links to some API, examples or docs, at least no, when you're not logged in), that I can't confirm that it supports both JavaScript and AdMob. Does someone have any experience with this system and can confirm this?

A: tl;dr Displaying mobile ads using pure Javascript:

*

*AdMob: no,

*mMedia: no,

*AdSense: no (details),

*MobFox: yes.

I've been through this for long while and your request (JavaScript code) unfortunately is not available neither with mMedia nor AdMob.
mMedia : They have the following source code types for a mobile web site ( not android app ): ASP, Perl, PHP, JSP5, ruby on rails, and vb.net. to get the source code you need a mobile web site and the mobile web site has to be approved by mMedia then you get live ads and I guess if you used the source code of website in your android app they will have the account suspended because in mMedia every project has to be approved first so they expect their ads are displayed on the project they approved on. And there is no JavaScript code as you requested anyway. mMedia will provide with sdk and instruction to download and install in your app off course live ads would be displayed after their approval and I guess that what you don't want.
AdMob: It is little bit confusing reading about them , because in the past they used to serve ads through JavaScript method intended for mobile web site but after google buying the company they removed this and AdMob doesn't serve mobile website any more and for mobile web site they advise you to use AdSense. what confusing about it that there is still instruction for installing AdMob JavaScript which doesn't exist any more. I saw your links and I guess you where trying to install AdMob for iOS app. I did it for Android app which was straight forward and it was easy using In-App-Advertisements, but the problem was what ever I try it shows on the bottom.
AdSense: they have the JavaScript way but they don't allow you to use it on mobile apps and if they find out they will have your account suspended (details).
for MobFox: they serve ads for mobile web site and the source code types for mobile web site are : JavaScript, PHP, cURL, PHP, fSocket, J2SE 1.4, CGI/Perl and ASP.NET.
and for application you have to download the SDK. but there is nothing states in MobFox the you can't use their JavaScript for mobile app and they work like google once you are approved you get Publisher ID and do what ever you want without breaking their terms. Unlike mMedia they have to approve every thing first. And they have the Ad network mediation option for the following companies 4INFO, Aditic (Sofialys), Adfonic, AdMarvel, Admoda, BuzzCity, Hunt, Mobile Ads, InMobi, iVdopia, JumpTap, Komli Mobile (ZestAdz), Lumata Group(bMobile), m-perf, Madvertise, MdotM, MobGold, MobPartner, Mocean, Mojiva, Nexage Exchange, Smaato, TapIt!, Vserv, WapStart, YOC Performance (Mocean Platform), YOC Performance (Ubiyoo Platform)
As far as my research goes the only choice you have for JavaScript code would be with MobFox and you need a way to get the approval so you would have a publisher ID. I had a mobile web contains 4 pages with a little traffic like 20 per day and I got their approval.

A: There's a powerful AdMob Plugin Pro (free, even though name pro sounds scary), that can be quite easily used in PhoneGap Build. I think, this is the state-of-art solution for this problem, because -- with introduction to npm plugins to PhoneGap Build -- you can now use in pure Javascript PhoneGap Build application all the ad networks, that  require you to use their native SDKs.
Key advantages (in context of this question) -- out-of-the-box support for:

*

*PhoneGap Build (see notice below),

*many ad types, including full screen ads,

*many ad providers and ad networks (with plugins, see below),

*serving ads using pure Javascript, with just a few lines of code.

Plugin supports following ad networks / providers:

*

*AdMob,

*DFP,

*Facebook Audience Network,

*Flurry,

*iAd,

*InMobi,

*Millennial Media,

*MobFox.

Where first two (in bold) has out-of-the-box support, while all other require use of additional plugins.
There's an article on using this plugin in PhoneGap Build. It is a bit out-dated. You should not use now deprecated plugins.cordova.io, but newly supported npm repository. For this, simply replace:
<gap:plugin name="com.google.cordova.admob" source="plugins.cordova.io" />

with:
<gap:plugin name="cordova-plugin-admobpro" source="npm"/>

Plugin's author offers an extensible documentation which includes API documentation, code examples and example implementations among different development platforms. Really good piece of work!
Resources:

*

*docs,

*GitHub repo,

*npm repository.

A: You can try InMobi, where you only need 3 lines of Javascript (details).

A: Check this AdMob's mobile guide.
I wasn't aware, they had such an API, until I googled it.


text:
Q: ArrayList getting changed without any operation on it I am trying to write a login in Android. The Logic is I am initiating an ArrayList in a constructor of a PopupWindow. In that PopupWindow I am showing a list using RecyclerView, by passing this ArrayList into the constructor of the Adapter Class. In that list I am using an EditText to search the list using addTextChangedListener.
The code is as follows,
MainActivity.Java
ArrayList<CompanyModel> companyList , backupCompanyList;
CompanyAdapter companyAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {

 //initialisation of both arraylists
    companyList = getCompanylist();
    backupCompanyList = companyList;

}

 // inner class declared in the MainActivity.java
public class ShowCompanyData{

    public ShowCompanyData(){

      //initialise popupwindow
      //get view of recyclerview and other view components of the popupwindow , and setadapter to the recyclerview

       companyAdapter = new CompanyAdapter(context , companyList );

       et_search.addTextChangedListener(new TextWatcher() {

                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {

                        String text = et_search.getText().toString().toLowerCase(Locale.getDefault());
                        companyAdapter.filter(text);

                }
            });
    }
 }

  //this button belongs to the Layout file of MainActivity.
  public void showPopupList(View v){
     // this is a button click where i am showing the company list popupwindow
       companyListPopupWindow.showAtLocation(layout, Gravity.CENTER, 0, 0);
  }

CompanyAdapter.java
public class CompanyAdapter extends RecyclerView.Adapter<CompanyAdapter.ViewHolder> {

Context context;
ArrayList<CompanyModel> mainArrayList;
ArrayList<CompanyModel> list;

 // other imp methods are also written , but not shown because not necessary to show here

    public CompanyAdapter(Context context, ArrayList<CompanyModel> mainArrayList) {

       this.context = context;
       this.mainArrayList = mainArrayList;
       this.list = new ArrayList<>();
       this.list.addAll(mainArrayList);

    }

    public void filter(String charText) {

        charText = charText.toLowerCase(Locale.getDefault());
        mainArrayList.clear();

        if (charText.length() == 0) {

            mainArrayList.addAll(list);

        } else {

           for (CompanyModel wp : list) {

            if (wp.getCompanyName().toLowerCase(Locale.getDefault()).contains(charText)) {

                mainArrayList.add(wp);

            }

           }
        }

    notifyDataSetChanged();

    }

}

Here the issue I am facing is, when I search something in in the EditText of PopupWindow where the list of Company's is shown, the ArrayList backupCompanyList is getting modified same as the companyList ArrayList.
My question is, I am not assigning anything to the backupCompanyList, also not passing it as a parameter to the Adapter Class, still when I debug the app the backupCompanyList are showing same contents as companyList, after searching anything in the EditText.
Where the backupCompanyList should contains the data (unchanged) assigned in OnCreate and should not modify the changes, because there are no operations or assignments done to the backupCompanyList in the entire program.
Can anyone guide me to overcome this issue.
Note :

*

*I have not written full code, I have written only necessary code

*Both ArrayLists (companyList & backupCompanyList) are showing proper data before entering any text into EditText of search. And issue is occuring only after searching.

A: In your Activity's onCreate method, your are assigning companyList reference to backupCompanyList reference. Both companyList and backupCompanyList are referring to the same ArrayList object reference returned from getCompanyList() method. That's why, it's reflecting both lists are changing together. In actual, there's only one ArrayList object.
Instead of:
companyList = getCompanyList();
backupCompanyList = companyList;

Use
companyList = getCompanyList();
backupCompanyList = new ArrayList<>(companyList);


text:
Q: Partial mocking a non static method does not call a private static method inside it I am using Powermock to write test case for one of my methods which is something like this :
class A{
  static String hello = "hello";
  private void static init(String s){
      hello = hello+" "+s;
  }
  public String getString(String s){
      init(s);
      return hello;
 }
}

class B{
    A a = new A();
    public String printHelloWorld(){
        return a.getString("World")+" from Hawaii";
    }
}

I am trying to test getStringFromA method of class B by mocking the method getString of class A using PowerMock like this :
@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
class TestClass{
  @Test
  public void testMethod(){

      //Mock Creation
      A dummy = createPartialMock(A.class,"getString",String.class);

     //Expect
     expectNew(A.class).andReturn(dummy);
     expect(dummy.getString("World")).andReturn("Hello World");

     //Replay
     replayAll();

     //Execute
     B b = new B();
     b.printHelloWorld();
  }
}

The problem is that this does not seem to work. getString() method of class A does not execute the private static method init(). I thought that this is because we are mocking the method getString(). However if the method getString() is also made static execution goes to init method.
What could be the reason of this anomaly.
Thanks,
Manas

A: Works exactly as expected. From the documentation:

PowerMock.createPartialMock(ClassToPartiallyMock.class, "nameOfTheFirstMethodToMock", "nameOfTheSecondMethodToMock") to create a mock object that only mocks the methods with name nameOfTheFirstMethodToMock ...

You are instructing PowerMock to mock getString(). Mocking means: it is a dummy, not doing anything.
In that sense: you should step back and read how to use mocking to do proper unit testing. You are not even clear on whether you want to test class A or B.
You see, to test class B, you do not need PowerMock or partial mocking. You simply do something like this:
A mockedA = mock(A.class);
when(mockedA.getString("foo")).thenReturn("bar");

B underTest = new B(mockedA);
assertThat(b.printHelloWorld(), is("bar from hawaii"));

or something alike. The above is using Mockito calls, but EasyMock isn't much different.
The point is: simply provide an instance of class A to B instead of doing new within the B class, and all your need for enhanced mocking features completely vanishes.
In other words: no partial mocking required here. And even if you would want to go for partial mocking - read the documentation carefully. All of these things are fully documented.


text:
Q: CentOS 6 donwgrade RPMForge packages I have a CentOS 6.6 server, and I tried some packages from rpmforge and rpmforge and extras. I did a yum update with those repos enabled and got a lot of stuff updated. Now I want to go backwards and replace all .rf an .rfx packages and have them replaced with the ones from standar repos. Is that posible???
Thanks!

A: Use yum history list to see recent yum transactions.
Use yum history info <ID> to view the details of a transaction.
Use yum history undo last to revert the most recent transaction, or yum history undo <ID> to revert a specific transaction.

A: Whay I ended up doing and worked for me:
yum list installed | grep @rpmforge
rpm --erase --nodeps <list obtained with first command>

Then disabled rpmforge repos from the config files
yum install <list obtained with first command>


text:
Q: hover for inline menu with :before I'm trying to make a default hover effect for all my inline menus but the hover effect are not covering the entirely "li a" element.
I've put the code below to ilustrate the problem.
http://jsfiddle.net/yWqK4/

A: You are modifying the <a> tag to a block disaply and doing all other kind of unnecessary things.
The only thing you need to do, is to change the background color of your element.
Replace your CSS that is used for the hover effect with:
.Menu li a:hover {
    background-color: rgba(0,0,0,0.3);
}

and it is working as expected. See http://jsfiddle.net/muNFY/

A: you don't need use :before to get desirable result. Fixed tour styles here http://jsfiddle.net/yWqK4/2/


text:
Q: proper use of count(*) with group by function In sql can you use a GROUP BY function with a column like country? (which would be a char/varchar)
SELECT country, population, COUNT(*) AS count_cities
FROM list_of_cities
GROUP BY country;

What would be a better way to write this?

A: SELECT country, SUM(population) AS country_population, COUNT(*) AS count_cities
FROM list_of_cities
GROUP BY country;


text:
Q: Login on every page with inclusion tags: example and doubts I need a Login form on every page of my project and I'm implementing it with inclusion tags. With django documentation and some examples like this one, I've written the following code so far:

*

*project tree:
myProj
├── myProj
│   └── settings.py
├── celeryPy2
│   ├── forms.py
│   ├── templatetags
│   │   └── my_tags.py
│   ├── urls.py
│   └── views.py
└── templates
    ├── base.html
    └── celeryPy2
        ├── login.html
        └── start.html

*urls.py
from django.contrib.auth.views import login, logout

urlpatterns = patterns('celeryPy2.views',
    url(r'^$',    'start',   name='start'),
    url(r'^accounts/login/$', login,  name='login'),
    url(r'^accounts/logout/$', logout, {'next_page':'/celeryPy2'}, name='logout'),
)

*views.py
def start(request):
    return render_to_response('celeryPy2/start.html', {},
                              context_instance=RequestContext(request))

*start.html
{% extends "base.html" %}
{% block title %}celeryPy2 start page{% endblock title %}
{% block content %}
{% load my_tags %}
{% login_form %}
{% endblock content %}

*base.html
<!DOCTYPE html>

<meta charset="utf-8" /><title>celeryPy2</title>

{% block header %}{% endblock %}

{% block content %}{% endblock %}

    {% block footer %}{% endblock %}

*my_tags.py
from django import template
register = template.Library()

from celeryPy2.forms import UserForm

@register.inclusion_tag('celeryPy2/login.html', takes_context=True)
def login_form(context):
    form = UserForm
    user = context['user']
    return {'form': form,'user': user}

*forms.py
class UserForm(ModelForm):
    class Meta:
        model = User
        fields = ('username','password')

*login.html
{% if not user.is_authenticated %}
    <form  id="idLogInForm" method="post" action="{% url 'django.contrib.auth.views.login' %}?next=/celeryPy2" class="loginForm">{% csrf_token %}
        {{ form.as_p }}
        <button id="idLogInSubmit" name="idLogInSubmit" type="submit">Login</button>
    </form>
{% else %}
    <form id="idLogOutForm" method="post" action="{% url 'django.contrib.auth.views.logout' %}">{% csrf_token %}
        Welcome, {{ user.username }}
        <button id="idLogOutSubmit" name="idLogOutSubmit" type="submit">Logout</button>
    </form>
{% endif %}

I have the following issues and doubts:

*

*Is that a correct way to implement it or I can get security issues?

*When I insert wrong user credentials I correctly get the error Please enter a correct username and password. Note that both fields may be case-sensitive. and the browser url bar is set to /celeryPy2/accounts/login/?next=/celeryPy2. But if I try to re-login, it tries to reach the non existent url /accounts/profile/. Why? I have to say that I have no LOGIN_URL or LOGIN_REDIRECT_URL in my settings.py. [SOLVED, see below]

*Why I get the password input field with clear text and not hidden by masked characters as it should be? [SOLVED, see below]

*Why I get the label Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters beside the username input field? [SOLVED, see below]
This is the way I found to have a code plug-in to reuse in every page, being more compliant as possible with django built in features. It looks a little tricky to me (a lot of files involved) and probably something is still to be refined, but I found this is the easiest way to get my task accomplished.
Any other better ideas are welcome!

A: I've solved points 2, 3 and 4 with the following code modifications:

*

*urls.py
from django.contrib.auth.views import login, logout

urlpatterns = patterns('celeryPy2.views',
    url(r'^$',    'start',   name='start'),
    url(r'^login/$', login, {'template_name':'celeryPy2/login.html'},  name='login'),
    url(r'^logout/$', logout, {'next_page':'/celeryPy2'}, name='logout'),
)

*forms.py
from django.forms import CharField
from django.forms import ModelForm, PasswordInput
from django.contrib.auth.models import User

class UserForm(ModelForm):
    username = CharField()
    class Meta:
        model = User
        fields = ('username','password')
        widgets = {'password': PasswordInput()}

*login.html
{% if not user.is_authenticated %}
    <form  id="idLogInForm" method="post" action="{% url 'login' %}" class="loginForm">{% csrf_token %}
        {{ form.as_p }}
        <button id="idLogInSubmit" name="idLogInSubmit" type="submit">Login</button>
    </form>
{% else %}
    <form id="idLogOutForm" method="post" action="{% url 'logout' %}">{% csrf_token %}
        Welcome, {{ user.username }}
        <button id="idLogOutSubmit" name="idLogOutSubmit" type="submit">Logout</button>
    </form>
{% endif %}

In the end I've added LOGIN_REDIRECT_URL='/celeryPy2' to myProj/settings.py.
Point 1 is still open: is this implementation a good one or could lead up to to security issues?