text:
Q: Fetching data from specified columns to a table I am stuck with the subject of automated updating a report table with a separate source file, let me briefly explain the problem:
I have got a source file like on first screenshot below. I need to fetch only data in columns with headings highlighted in red.

Sample of source file
The next necessary condition is that in the result table (in a separate file), the records imported must be unique based on the first column (ID).

Sample of result file
How to write a proper macro which will check the IDs, skipping already existing and paste the records?
I started my code by opening a source file like below:
Sub Updater()
 Dim SrcWbk As Workbook
 Dim DestWbk As Workbook
 Dim Ws As Worksheet
 Dim Filename As String

    Set DestWbk = ThisWorkbook

    Filename = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls*), *.xls*", Title:="Select a Report File", MultiSelect:=False)

Set SrcWbk = Workbooks.Open(Filename)

SrcWbk.Activate

End Sub

A: Here is one approach. You must provide the sheet names and header rows for the source worksheet and the destination worksheet. I've done so here with constants.
I first find the columns of the fields that need to be copied from the source worksheet using Application.WorkSheetFunction.Match. I then loop through each ID in the source worksheet and check for a match in the destination worksheet. If no match is found, then the record is new and needs to be copied.
Then it's just a simple reference back to the source worksheet using the previously identified column numbers.
I save and close the destination workbook at the end, but you can remove or comment this as needed.
Sub Updater()

    ' Define source and destination sheets and header rows
    Const srcShtName = "Sheet1"
    Const destShtName = "Sheet1"
    Const srcHdrRow = 7
    Const destHdrRow = 1

    'Defing header range for source worksheet
    Set srcWS = ThisWorkbook.Worksheets(srcShtName)
    Set hdrRng = srcWS.Range(srcWS.Cells(srcHdrRow, 1), srcWS.Cells(srcHdrRow, 1).End(xlToRight))

    ' Get all IDs from source worksheet
    srcIdCol = Application.WorksheetFunction.Match("ID", hdrRng, 0)
    Set srcIDs = srcWS.Range(srcWS.Cells(srcHdrRow + 1, srcIdCol), srcWS.Cells(srcHdrRow + 1, srcIdCol).End(xlDown))

    ' Define fields to copy to destination worksheet and find corresponding column numbers
    fieldsToCopy = Array("Branch ID", "Product", "Shipment Category", "Port of Loading", "Year", "Month", "Day")
    ReDim srcColumns(0 To UBound(fieldsToCopy))
    fieldIdx = 0
    For Each field In fieldsToCopy
        srcColumns(fieldIdx) = Application.WorksheetFunction.Match(field, hdrRng, 0)
        fieldIdx = fieldIdx + 1
    Next field

    ' Open destination worksheet
    filename = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls*), *.xls*", Title:="Select a Report File", MultiSelect:=False)
    Set destWS = Workbooks.Open(filename).Worksheets(destShtName)

    ' Define header range of destination worksheet
    Set destHdrRng = destWS.Range(destWS.Cells(destHdrRow, 1), destWS.Cells(destHdrRow, 1).End(xlToRight))
    destIdCol = Application.WorksheetFunction.Match("ID", destHdrRng, 0)

    ' Loop through each record in source worksheet
    For Each ID In srcIDs

        ' Look for an ID in the destination worksheet that matches the current rcord
        destRow = Empty
        Set destIdRng = Intersect(destWS.Columns(destIdCol), destWS.UsedRange)
        On Error Resume Next
        destRow = Application.WorksheetFunction.Match(ID.Value, destIdRng, 0)
        On Error GoTo 0

        ' If destRow is empty, the record was not found in the destination and we need to add it
        If destRow = Empty Then
            nextRow = destWS.UsedRange.Rows.Count + 1
            For fieldIdx = 0 To UBound(srcColumns)
                destWS.Cells(nextRow, destIdCol).Value = ID.Value
                destWS.Cells(nextRow, fieldIdx + 2).Value = srcWS.Cells(ID.Row, srcColumns(fieldIdx)).Value
            Next fieldIdx
        End If

    Next ID

    ' Save the destination workbook and close it
    Application.DisplayAlerts = False
    destWS.Parent.Save
    destWS.Parent.Close
    Application.DisplayAlerts = True

End Sub


text:
Q: How to call initialization function $main(function(){
    org.mathdox.formulaeditor.FormulaEditor = $extend(Object, {

       textarea : null,
       canvas : null,
       presentation : null,
       cursor : null,

       initialize : function(textarea, canvas) {...},

       other functions...
    }

I am having trouble calling the initialize function. Is there a certain scope for the function? Can I only call it inside that main function? Can I call it in external JavaScript files?
$('#fe_reset').click(function () {
    $('#divTextArea').remove();
    var textareadiv = document.createElement('div');
    textareadiv.className = 'formula_editor_textarea';
    textareadiv.id = 'divTextArea';
    var thetextarea = document.createElement('textarea');
    thetextarea.className = 'mathdoxformula';
    thetextarea.id = 'formula1';
    thetextarea.style.rows = '10';
    thetextarea.style.cols = '80';
    textareadiv.appendChild(thetextarea);
    document.getElementById('formula_editor_container').insertBefore(textareadiv, document.getElementById('fe_cancel'));

        initialize(thetextarea); // CAN I NOT CALL IT LIKE THIS?

    $('#fe_save').css({'cursor': 'default', 'opacity': '0.55'}).attr('disabled','disabled');
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retain previous value in Excel on cell error I'd like to have a way for a cell on a spreadsheet to retain its previous value if a new calculation has an error. As a simplified example:
    A   B   C
1   1   2   =A1/B1

Cell C1 will contain 0.5. Now if I change B1 to 0, I'd like C1 to stay at 0.5 instead of showing #DIV/0!. I've tried using the IFERROR function but it results in a circular reference.
I'd like this to work in a non-macro-enabled workbook.

A: Easy....first enable iterative calculation with 1 max iterations in Excel options......then set up A1,  B1 (as 2) and C1 as in your example............then in D1:
=IF(ISERROR(C1),D1,C1)

Then set B1 = 0
D1 will freeze up to the last non-error value if C1 errs out.
EDIT#1:
Based on pnuts's comment:
=IF(ISERROR(A1/B1),C1,A1/B1)

can be placed in C1 to achieve the exact behavior

A: You either have to use the iteration calculation method (with all its downsides) or use something like the SpeedTools(costs, both 64 and 32-bit) Previous() function or MoreFunc(free, 32-bit only)  Recall() function. Both SpeedTools and MoreFunc are XLL addins, so do not require a macro-enabled workbook but require installing the XLL addin.
You can just about do this in a kludgy way using VBA and a macro-enabled workbook: see http://fastexcel.wordpress.com/2012/01/08/writing-efficient-vba-udfs-part-8-getting-the-previously-calculated-value-from-the-calling-cells/
Disclaimer: I develop and sell the SpeedTools addin (works with 64-bit Excel, both 64 and 32-bit)


text:
Q: passive motion detect How can I detect mouse passive motion with opengl ? In other words, how can I understand whether it is moving forward, backward, left, right ?
I have done
glutPassiveMotionFunc ( func )

void func ( int x, int y ) {

   // x and y always positive, I wait it should be negative if it goes left
   //   acc. to  my coordinate system determined in glLookAt.
}

A: From the docs:

The x and y callback parameters indicate the mouse location in window relative coordinates.

If you're interested in how the cursor moved between two frames (a delta), store the cursor position every frame and calculate the difference between the "current" position and the "last seen" position.

A: You don't do it with OpenGL, you do it with GLUT.
Store the previous recorded mouse position. Compare the new position with previous position, to know whether its going up, down, left or right.
Something like this:
int x=0, y=0;
enum { LEFT, RIGHT, UP, DOWN };
int direction;

void func(int mx, int my)
{
     if(mx < x) direction = LEFT;
     else if(mx > x) direction = RIGHT;
     else if(my > y) direction = DOWN;
     else if(my < y) direction = UP;

     x = mx;
     y = my;
}

The origin is at the top-left corner.


text:
Q: Removing data from redux and saving scroll position I have an array of objects in redux which I am showing in my browser:

[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…},
  {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

object-0
object-1
object-2
object-3
object-4
object-5
object-6
object-7
object-8
object-9
object-10
object-11
object-12
object-13
object-14
object-15
object-16
object-17
object-18
object-19 <------ scroll position

On scrolling down, I am hitting an api and appending objects to the array. I have added a check that if number of objects in array becomes more than 20 then top 10 data should get deleted.
   case "DELETE_LISTING_TOP_PROFILES":

        let tempListingData = state[action.payload.listingId];
        let tempListingProfiles = [...state[action.payload.listingId].profiles];
        tempListingProfiles.splice(0,10);
            state
            ={
                ...state,
                [action.payload.listingId]:{
                    ...tempListingData,
                    profiles: tempListingProfiles
                }
            }

In my redux, the first 10 data gets deleted and my view becomes:
object-10
object-11
object-12
object-13
object-14
object-15
object-16
object-17
object-18
object-19
object-20
object-21
object-22
object-23
object-24
object-25
object-26
object-27
object-28
object-29 <------------ scroll position

As you can observe that the scroll position is now changed to object-29. I want it to remain at position 19, as follows:
object-10
object-11
object-12
object-13
object-14
object-15
object-16
object-17
object-18
object-19 <----------- scroll position
object-20
object-21
object-22
object-23
object-24
object-25
object-26
object-27
object-28
object-29

So, after deleting data from redux and adding some data to it, how can I save the scroll position?

A: You can read about getSnapshotBeforeUpdate() lifecycle method (official documentation).
In pair with refs feature (official documentation) it will help you to manage the scroll position right before changes are going to be applied to the DOM after changes in props, for example.


text:
Q: cannot resolve symbol 'vrtoolkit' As a newbe to cardboard, I have created a simple pano app in Android Studio by trying to duplicate the google cardboard sample simplepanowidget. The java activity class shows the vrtoolkit as being unresolved, e.g. in import statements such as:
    import com.google.vrtoolkit.cardboard.widgets.pano.VrPanoramaEventListener;
I am trying to include the appropriate library but do not know which one it should be: is it libvrtoolkit.so or in a .aar archive?

A: The answer is pretty obvious (after unzipping and looking in the class tree for panowidget provided with the google cardboard sample): it is in panowidget.aar.


text:
Q: Missing printers in wx.PrintDialog We are finally migrating our old workstations with Xubuntu 9.04 to
Xubuntu 10.04, and in the process we're testing our in-house wxPython
application on the new systems.
Everything works nicely, except that wx.PrintDialog's popup shows NO
printers available, there's only a "Default printer" with empty
"Device" and "Status". This happens even with wxPython's PrintDialog
demo. What could I check out?
(Xubuntu 10.04, wxPython 2.8.10.1)

A: It looks like you have to install libgnomeprintui:
apt-get install libgnomeprintui2.2-0
(found here)


text:
Q: Determine temperature from Sound? I was told that you could determine the air temperature by using a BoomWhacker (its a muscial instrument that is a plastic tube and when you strike it against a surface, it will produce one and only one specific note only). How could you do this? Would you measure the length of the open tube and determine the wavelength, so wavelength = 2 × length. Then you could use the universal wave equation and speed of sound equation to get:
2 × length x frequency = 331 m/s +0.59m/(s × celcius) × Temperature
So you can solve for temperature. How could you get the frequency of the note produced by the BoomWacker?

A: Dean you're pretty much at the answer already. As you write, the speed of sound as a function of temperature (in Celcius) is
$$c = 331 + 0.59 \ T$$
We can rearrange to write a formula for temperature as a function of the speed of sound
$$T = \frac{c - 331}{0.59}$$

Knowing your BoomWhacker of length $\ell$ has two possible states, open-end or closed-end we have two fundemental frequencies that may be observed:
$$
  f =
\begin{cases}
\frac{c}{2 \ \ell},  & \text{if end is open} \\[10 pt]
\frac{c}{4 \ \ell}, & \text{if end is closed}
\end{cases}
$$
Now we can put it all together to arrive at
$$
  T =
\begin{cases}
\frac{2 \ell f - 331}{0.59},  & \text{if end is open} \\[10 pt]
\frac{4 \ell f - 331}{0.59}, & \text{if end is closed}
\end{cases}
$$
Where I live there's a pretty impressive range of temperatures: -43 to 32 C.  By these figures an open-ended BoomWhacker $0.61 \ m$ long would range from $251 \ \text{Hz}$ on the coldest winter day to $287 \ \text{Hz}$ on the hottest summer day. That's not much of a change, so it would take a precise measurement of frequency to do a good job at estimating temperature.
And as commenters have suggested, to actually measure temperature, you could use the spectrum analyzer built into any of a number of open-source audio recording programs. An unfortunate limitation here seems to be that impulsive (i.e., 'percussive') sounds don't last very long and thus limit the precision of frequency measurements. If you could blow across the tube you may be able to generate a sustained tone that would work better.
I'd be curious how well this approach works in practice!


text:
Q: PHP Twitter-like mentions with notifications I'm trying to create a system similar to Twitter for mentioning users and receiving a notification if you are mentioned. There has been a lot of questions asking similar things on here but none have appeared to be conclusive and help me out in any way.
My first trouble is parsing the mention when the status is posted, it works to some extent, but I'm not good with the expressions needed to be used. If I posted a status for example saying "@user1 hello there its @user2", then user1 would parse correctly with the @ being the first character but my user2 displays the space as part of the parsed profile link, here is my preg_replace and expression:
$STRING = preg_replace('/(^|\s)(@\w+)/','$0', $STRING);

I also need to know how to display just the username without the @ in the profile link, the current $0 produces the @ symbol too.
As for notifications, I have a table called alerts with this structure:
id | userid | sentby | message | received
The message field contains the notification message content. I was wondering how I can extract any mentions from my submitted form and check if the username exists and then from there create an alert for the user that they have been mentioned in a post.

A: As for your first regular expression, you could do something like this:
$string = preg_replace('/(^|\s)@(\w+)/', '$1$2', $string);

That should get you the username without the initial space or @ sign. Basically, we capture the initial space or beginning of the string into a variable, and print that out in the beginning of the replacement. What you end up with in $2 is only what follows the @ sign. You could accomplish this with a lookbehind as well, but I feel that this is simpler.
As for your database structure, maybe something like this would do:
messages -
id | user_id | message

mentions -
message_id | user_id

For each mention, you insert the user_id into the table for the message. You can choose if you'd like to send your alerts in realtime or wait for a batch process (or potentially - depending on performance requirements - just query for posts with a user mentioned whenever you need to by joining the tables).

A: I have been thinking about this question for a couple hours and although I am somewhat of a novice, I believe I have a way that extracts the mentions and the alerts and stores them into two unidimensional arrays.
    <?php
         //a variable ($string) that I thought might look like what you are describing
         $string='@steve how are you? @tom nice to hear from you. So happy that you joined @joe, cool! @mike sweeet!';
         //regex to pull out the mentions and the messages
         preg_match_all('/@(\w+)|\s+([(\w+)\s|.|,|!|?]+)/', $string, $result, PREG_PATTERN_ORDER);
         for ($i = 0; $i < count($result[0]); $i++) {
            $mention[$i]= $result[1][$i];
            $message[$i]= $result[2][$i];
         }
         //test to make sure that all mentions are stored
         for ($j = 0; $j< $i; $j++){
            echo $mention[$j],'
';
         }
         //test to make sure that all messages are stored
         for ($k = 0; $k< $j; $k++){
            echo $message[$k],'
';
         }
    ?>

The explanation, as provided by Regex Buddy), of the regex that I used: @(\w+)|\s+([(\w+)\s|.|,|!|?]+):
Match either the regular expression below (attempting the next alternative only if this one fails) «@(\w+)»
 Match the character "@" literally «@»
  Match the regular expression below and capture its match into backreference number 1 «(\w+)»
  Match a single character that is a "word character" (letters, digits, and underscores) «\w+»
  Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
 Or match regular expression number 2 below (the entire match attempt fails if this one fails to match) «\s([(\w+)\s|\.|,|!|?]+)»
Match a single character that is a "whitespace character" (spaces, tabs, and line breaks) «\s+»
 Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the regular expression below and capture its match into backreference number 2 «([(\w+)\s|\.|,|!|?]+)»
  Match a single character present in the list below «[(\w+)\s|\.|,|!|?]+»
     Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
     The character "(" «(»
     A word character (letters, digits, and underscores) «\w»
     One of the characters "+)" «+)»
     A whitespace character (spaces, tabs, and line breaks) «\s»
     The character "|" «|»
     A . character «\.»
     One of the characters "|,!?" «|,|!|?»

This will even return words in messages that are off-set by parentheses (e.g. (hello)). You should be able to perform any operation you describe using the variables defined in the arrays. If this is not correct, or you are unable, let me know and I will see what I can come up with.

A: Please check this tutorial to implement twitter style mention system with PHP, MYSQL and jQuery
You have use regrex match to extract @mentions from the content
Thanks


text:
Q: Mistic problems when I'm connecting to MongoDB I've been working with some course on "Udemy" about two weeks, and I didn't have any problem till this day. I made a Profile, added a Validation and then when I run the server I have a problem like that:

(node:9140) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.

Guys, do you have any ideas how to solve this problem. I stuck and need your help.
I connect to my database in this way:
mongoose
  .connect(db)
  .then(() => console.log("MongoDB connected"))
  .catch(err => console.log(err));

I also tried some recommendations from other topics of StackOverflow:
enter image description here
My code:
const db = require("./config/keys").mongoURI;

//Connect to MongoDb
mongoose
  .connect(
    db,
    { useNewUrlParser: true }
  )
  .then(() => console.log("MongoDB connected"))
  .catch(err => console.log(err));

As my version less than 4, I used the second method, but I still have problems:
enter image description here
And it's been working all two weeks.
All versions of node.js and mongodb:
enter image description here
My dependencies:
enter image description here

A: The deprecation warning is not a problem, its just a warning for future versions (which will need to be addressed in the future).
As far as i can tell from the picture you posted is that your problem specifically is the statement res.strtus at line 83 on the file users.js


text:
Q: TypeError: 'dict' object is not callable while using dict( ) I was using Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2 , when i ran the folllowing code in it the corresponding error is shown .I searched a lot about this but am unable to find why is it so
>>> bob=dict(name='bob smith',age=42,pay='10000',job='dev')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable

A: On a previous line in that interactive session, you have rebound the dict name to some variable. Perhaps you have a line like dict={1:2} or dict=dict(one=1, two=2).
Here is one such session:
>>> dict=dict(one=1)
>>> bob=dict(name='bob smith',age=42,pay='10000',job='dev')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable
>>>

As a general rule, one should not use built-in type names as variable names, to prevent this error.

A: edit: Ignore this, I am told this is bad practice.
As mgilson stated, the issue is likely that you have a variable called dict. The solution to this would be to run
del dict

which deletes the variable by that name.

A: In a fresh interpreter:
>>> bob=dict(name='bob smith',age=42,pay='10000',job='dev')
>>> bob
{'age': 42, 'pay': '10000', 'job': 'dev', 'name': 'bob smith'}

However, you are getting a TypeError:

TypeError: 'dict' object is not callable

This error you get tells you that your dict is not callable.
Since my dict is callable when I open a fresh interpreter, it means that your dict is different.
Most likely, you defined a dict variable, which overrode the built-in dict. Look for the
dict = {...}

line, and rename your variable.
As pointed out by @Robᵩ, don't use built-in names for your variables. Especially avoid the tempting str, list, and so on.


text:
Q: How do I enable or disable the global application menu? I'm fairly excited for Unity, as it looks like a promising new direction for Ubuntu.  However, I do have a concern - will it be possible to use Unity without the global menu?
I have my window manager set to focus-follows-mouse/sloppy focus, and find the productivity gains to be immense. Sloppy focus is incompatible, however, with global menus, as it is possible for the focus to change while you move from window to menu.
Will Unity support an option to use window menus while still using Unity?

A: I have been successfully using unity with focus follows mouse and the global menu by only accessing the application menu via the f10 key shortcut. In many ways this is better than moving the mouse away from where ever you were focused on anyway.

A: 11.10
To disable the menu, instead of removing the indicator-appmenu you could hide its shared library file:
sudo mv /usr/lib/indicators/5/libappmenu.so /usr/lib/indicators/5/libappmenu.so.old

and to reenable, undo it:
sudo mv /usr/lib/indicators/5/libappmenu.so.old /usr/lib/indicators/5/libappmenu.so

source

A: 14.04
The Global Menu can be optionally switched in favour of Local Integrated Menus (LIM) - aka - more traditional window based menus.
The reason for this additional ability is ostensibly due to the increasing prevalence of high-resolution displays and as such the perceived mouse-travel from application to the global-menu would be relatively large.
To toggle the global menu off or on can be achieved via the appearance control-panel applet:

Once clicked, the application menus appear within the window decoration as shown here:

Command line.
The above can be achieved using the terminal command:
gsettings set com.canonical.Unity integrated-menus true

Integrated menus can be disabled (i.e. switch global menu back on)
gsettings set com.canonical.Unity integrated-menus false

If you dont like Locally Integrated Menus then the old trick of removing indicator-appmenu still works although this will break the HUD
sudo apt-get remove indicator-appmenu

A: For reference, here is how to disable the global menu on a per application basis: https://wiki.ubuntu.com/DesktopExperienceTeam/ApplicationMenu#Troubleshooting

To disable appmenu support on a per application basis, set the
  UBUNTU_MENUPROXY variable to null, with:
env UBUNTU_MENUPROXY= eclipse

the env keyword is useful if your trying to launch the application
  with the ALT-F2 shortcut.

A: 11.04 - 13.10 - How to disable the global menu (appmenu / application menu)
For current user only, all applications
Add this to ~/.gnomerc and log out of the desktop and in again:
STARTUP="env UBUNTU_MENUPROXY= $STARTUP"

For current user only, only applications launched from the shell
Add this to ~/.bashrc and restart the shell:
UBUNTU_MENUPROXY=

For current user only, only for specific applications launched from the shell
Add lines like this to ~/.bashrc and restart the shell:
alias gvim='UBUNTU_MENUPROXY= gvim'

Based on https://askubuntu.com/a/132581/32651.
For current user only, only for specific application launchers
See https://askubuntu.com/a/6802/32651.
For all users, all applications (fix it in /etc)
Create config file with fix (note that the parentheses are part of the command):
(umask 022; echo UBUNTU_MENUPROXY= | sudo tee /etc/X11/Xsession.d/81ubuntumenuproxy)

After this, log out of the desktop and in again.
To remove the fix:
sudo rm /etc/X11/Xsession.d/81ubuntumenuproxy

Based on http://www.webupd8.org/2011/03/disable-appmenu-global-menu-in-ubuntu.html.
For all users, all applications (uninstall packages)
Ubuntu 11.04 and 11.10:
sudo apt-get remove appmenu-gtk indicator-applet-appmenu indicator-appmenu

Ubuntu 12.04:
sudo apt-get remove appmenu-gtk appmenu-gtk3 appmenu-qt indicator-appmenu

After this, log out of the desktop and in again.
To undo, just install the packages again: sudo apt-get install [...]
From http://www.webupd8.org/2011/03/disable-appmenu-global-menu-in-ubuntu.html.
Notes 1
Just doing
sudo apt-get remove indicator-appmenu

will still give problems with
gvim
and
image viewers etc.
since UBUNTU_MENUPROXY will still be set to 'libappmenu.so' by
the appmenu-gtk and appmenu-gtk3 packages.
Notes 2
The default value is UBUNTU_MENUPROXY='libappmenu.so'.
The UBUNTU_MENUPROXY= statement clears the variable.
Note that export [...] is not required when changing an already existing variable.
See also

*

*Gvim might spit out this warning 25 seconds after being started:
** (gvim:20320): WARNING **: Unable to create
Ubuntu Menu Proxy: Timeout was reached
To fix this, either disable global menu, at least for gvim, or fix
gvim.

*Delayed in-window menu creation is a problem in
image viewers etc.,
for example eog.
To fix this, disable the global menu properly, at least for those applications.

*Get both global menu and in-window menu:
APPMENU_DISPLAY_BOTH=1
See https://askubuntu.com/a/6802/32651.

References

*

*https://wiki.ubuntu.com/DesktopExperienceTeam/ApplicationMenu#Troubleshooting

A: 11.04 - 13.10
Yes, the Desktop version of Unity will use the global menu by default.

*

*To disable the global menu remove the indicator-appmenu
package, then log out and back in.

Unity will continue to run without it and your menus will appear inside the application windows as normal. You can also tell the appmenu to ignore specific applications if you're having a problematic app.
The command line way to remove the package is:
sudo apt-get remove indicator-appmenu

Removing the appmenu will break the HUD feature

A: 18.04
Maybe there is an more-obvious way that i missed, but this somehow did the trick:
sudo apt-get install gnome-tweak-tool
gnome-tweaks

Go to "Top Bar"

A: 11.10
I successfully disabled the global application menu by following the advice from http://www.addictivetips.com/ubuntu-linux-tips/how-to-disable-global-menu-in-ubuntu-11-10-tip/.
I deinstalled the packages appmenu-gtk3, appmenu-gtk and appmenu-qt by running:
sudo apt-get remove appmenu-gtk3 appmenu-gtk appmenu-qt

Apparently, you can get the functionality back by reinstalling the packages.


text:
Q: Two functions $f(x)$ and $g(x)$ such that : 1) Does there exist $f(x)$ and $g(x)$ such that $f(g(x))=x$ but $f(x)$ and $g(x)$ are not inverse of each other.
2) Does $f(g(x)) = x$ automatically imply $g(f(x))=x$?
Note that an example can be fabricated as follows :
Let $g(x) = 1$ for $x = 0$ and it is only defined for $x=0$.
Let $f(x) = x-1$.
Clearly $f(g(x)) = x$ at $x = 0$ and $f(x)$ and $g(x)$ are not inverse of each other.
I am however looking for two continuous functions $f(x)$ and $g(x)$, not an isolated function as is $g(x)$ in the example above.

A: Given any surjective function $f:A \to B$, you can find such $g$ (if you assume the axiom of choice). The construction is as follows:
Consider for any fixed $b \in B$, define $K_b=\{a\in A: f(a)=b\}$. By surjectivity, this set is non-empty for all $b\in B$. Now, by the axiom of choice, we can choose an $a_b\in K_b$ for each $b\in B$. Then we can define
$$g:B\to A, b\mapsto a_b$$
Note that for any $b\in B$, $f(g(b))=f(a_b)=b$.
Obviously, there are a lot of continuous surjective functions that are not injective.
Remark: In fact, you can also show that if $f:A\to B$ has a function $g:B\to A$ such that $f(g(x))=x$, then $f$ is surjective. (This part would not require the axiom of choice.)


text:
Q: Pass "any character" into a PHP value? Update:
I'm importing an XML feed daily, that is updated every 24h via an XML feed supplier, that gets dumped into our FTP. The file starts with the date, then the time of the export, followed by the rest of the file name.
So every day there is a new file added to our FTP, I'm using date() to get the days date but the time could vary depending on when the server ran export (usually is only off by a minute or so).
So what I need, is to pass 4 number values between the $date & $file and therefore take the latest file from the necessary folder?
The script joins the multiple values together to create the URL, then sets that value as the location in header(); :
<?php

$date = date("Ymd");
$webroot = "http://WEBSITE-URL/";
$file = "-XML-FILE.xml";

$xmlfilelocation = $webroot.$date."0206".$file;

header('Location: '.$xmlfilelocation);

?>

The 0206 string is the time, that could vary, is there anyway I can pass any value in there?
Create a $time = ???; variable maybe, that is equal to ANY 4 characters?

A: You could use glob() function for this. As there might be multiple files, you may want to return the first one :
$serverRoot = '/the/real/server/location/';
chdir($serverRoot); // go to the directory where the file is located
$xmlfile = $date."*".$file;
foreach (glob($xmlfile) as $filename) {
    header('Location: '.$webroot.$filename);
    break; // or even exit
}

Note : You will have to use the server path for the glob() function.

A: In the end I've used an alternate approach for this:
<?php

//Get web directory
$webdir = "THE-URL";

//Get local directory for scandir
$dir = 'THE-DIRECTORY';

//Create array of file names
$filelist = scandir($dir);

//Count file name and reduce by 1 to account for [0] array item
$recordcount = count($filelist) - 1;

//Get the latest filename from array
$latestfile = $filelist[$recordcount];

//Compile the web directory and filename to create a URL
$xmlfile = $webdir.$latestfile;

//Redirect to necessary URL
header('Location: '.$xmlfile);

?>


text:
Q: How to get inner XML of a node in pugixml? I parse a document and want to retrieve part of the XML tree as string. The document (example):
<?xml version="1.0"?>
<MyConfig>
    <MyData>
        <Foo bar="baz>42</Foo>
    </MyData>
    <OtherData>Something</OtherData>
</MyConfig>

The code:
  pugi::xml_document doc;
  doc.load_file(documentFileName);
  pugi::xml_node root = doc.child("MyConfig");

  // parse custom data
  _customData = root.child("MyData"). <-- HOW TO GET INNER XML?

Expected contents of custom data (if formatting is lost, I don't mind):
"<Foo bar="baz>42</Foo>"

How to do this?

A: I think pugi::xml_node::print() is a way.
pugi::xml_node node = root.child("MyData");
pugi::xml_node child = node.first_child();

std::stringstream ss;
child.print(ss);
std::string s = ss.str();

The trouble is that s will now have value
<Foo bar="baz>42</Foo>     </MyData>     <OtherData>Something</OtherData> >
</MyConfig>" />

*

*It's the textual tree from the node onwards, and;

*It's messy with html escape sequences rather than < and >
Not ideal, but these can obviously be solved with some string manipulation.
// replace < with <
size_t off = 0;
while ((off = s.find("<", off)) != s.npos)
  s.replace(off, 4, "<");

// replace > with >
off = 0;
while ((off = s.find(">", off)) != s.npos)
  s.replace(off, 4, ">");

// truncate at the closing tag
size_t end_open = s.find(">", 0);
size_t end_close = s.find(">", end_open + 1);
s = s.substr(0, end_close + 1);

Which will lead to s having value
<Foo bar="baz>42</Foo>

A: I found a solution directly in the docs, it's just that google does not index them well, so I had to look it up manually. My solution was to use pugi::xml_writer and node.print. In the docs, they even already show an implementation for std::string:
struct xml_string_writer: pugi::xml_writer
{
    std::string result;

    virtual void write(const void* data, size_t size)
    {
        result.append(static_cast<const char*>(data), size);
    }
};

With that available, I just made a convenience function to merge XML of all child nodes:
std::string InnerXML(pugi::xml_node target)
{
  xml_string_writer writer;
  for (pugi::xml_node child = target.first_child(); child; child = child.next_sibling())
    child.print(writer, "");
  return writer.result;
}


text:
Q: Calculating the limit of a geometrical construction Suppose I have a rectangle ABCD, with AD larger than AB. I trace its diagonal AC, then the perpendicular to AC that goes through B. It intersects AC in $B_1$. I then trace the perpendicular to AD that goes through $B_1$, which intersects AD in $A_1$, and the perpendicular to CD that goes through $B_1$, which intersects CD in $C_1$.

We iterate the process to make $B_2$, $A_2$, $C_2$...

So on, so forth.
Clearly, $\lim_{n \to +\infty}$$C_n$ is D. But $\lim_{n \to +\infty}A_n$ is not D, and is instead somewhere on AD.
Question : Given the initial size AD and AB, with AD>AB, what's the length of $\lim_{x \to +\infty}A_n$D?
I think that if the initial lengths are $\{a,b\}$, the lengths on the next step are $$\left\{\frac{a^3}{a^2+b^2},\frac{b^3}{a^2+b^2}\right\},$$ but I have no idea where to go from there...

A: The lengths of the next step you obtained are correct.
Now consider the ratio between the initial height and width, i.e. write $b = ka, k>1$.
The new lengths are given by:
$$\frac {a^3}{a^2+ b^2} = \frac {a^3}{a^2 + k^2a^2} = \frac a{1+k^2}$$
$$\frac {b^3}{a^2+b^2} = \frac {k^3a^3}{a^2+b^2}$$
hence the new ratio of height and width is $k^3$. We can also write
$$\frac {b^3}{a^2 + b^2} = \frac {bk^2a^2}{a^2+k^2a^2} = \frac b{1+k^{-2}}$$
and so a recurrence relation becomes apparent. For the height, we are looking for:
$$\frac a{(1+k^2)(1+(k^3)^2)(1+((k^3)^3)^2)\dots} = \frac a{\prod_{n=0}^\infty (1+k^{2\cdot 3^n})}$$
Since $k > 1$, the infinite product diverges, so the height tends to zero as expected.
As for the width, the opposite occurs: we are looking for
$$\frac b{(1+k^{-2})(1+(k^3)^{-2})(1+((k^3)^3)^{-2})\dots} = \frac b{\prod_{n=0}^\infty (1+k^{-2\cdot 3^n})}$$
To show that the infinite product converges, we can check the equivalent series
$$\sum_{n=0}^\infty k^{-2\cdot 3^n} < \sum_{n=0}^\infty k^{-n} = \frac1{1-k^{-1}}$$
which converges as $0 < k^{-1} < 1$. It can also be expressed as the infinite sum:
$$\prod_{n=0}^\infty (1+k^{-2\cdot 3^n}) = 1 + k^{-2} + k^{-6} + k^{-8} + k^{-18} + \dots = \sum_{n \in S} k^{-n}$$
where $S$ is the set of all nonnegative integers that does not contain $1$ in their base $3$ representation (https://oeis.org/A005823).
A trivial upper bound is $\displaystyle \sum_{n = 0}^\infty k^{-2n} = \frac 1{1-k^{-2}} = \frac {k^2}{k^2-1}$, which shows that the limit of the width cannot be less than $\dfrac {b(k^2-1)}{k^2} = b\left(1-\dfrac1{k^2}\right)$. I am however unable to think of a closed form for the infinite product or the infinite sum.


text:
Q: Uniform convergence of functional sequence $f_{k}(x) =\frac{1}{ln(1+kx)} , k\geq 1$
a)x>1  b)x>0
My attempt :
a) because for x>0 the natural logaritm is a monotonic decreasing function the sequence converges to 0.
b) $M_{k} = Sup_{x>0} \frac{1}{ln(1+kx)}$ , for $x =\frac{1}{k}$
$M_{k}=\frac{1}{ln2}\not\Rightarrow 0$
Since M_k does not go zero it does not converge uniformly.
Can you please tell me if am correct or not ? am new on this topic , a detailed answer would be very helpfull
Thanks in advance


text:
Q: How to delete table on Cassandra using C# Datastax driver? var keyspace = "mydb";
var datacentersReplicationFactors = new Dictionary<string, int>(0);
var replication = ReplicationStrategies.CreateNetworkTopologyStrategyReplicationProperty(datacentersReplicationFactors);

using (var cluster = Cluster.Builder().AddContactPoints("my_ip").Build())
using (var session = cluster.Connect())
{
    session.CreateKeyspaceIfNotExists(keyspace, replication, true);
    session.ChangeKeyspace(keyspace);

    var entityTable = new Table<Models.Entity>(session);
    var attributeTable = new Table<Models.Attribute>(session);

    entityTable.CreateIfNotExists(); // Worked
    attributeTable.CreateIfNotExists(); // Worked

    entityTable.Delete(); // Does nothing
    attributeTable.Delete();  // Does nothing
}

EDIT: Without using raw queries session.Execute("DROP TABLE entities;"); working fine.

A: Delete() method is not intended for drop of the tables. It returns representation of a DELETE cql statement. If you call it, you just get {DELETE FROM entities}.
If you need to drop a table, the easiest way is just to execute DROP statement:
session.Execute("DROP TABLE entities;");

A: Unless there is already a method for dropping tables that I not aware of, you can use this extensions.
public static class DastaxTableExtensions
{
    public static void Drop<T>(this Table<T> table)
    {
        table.GetSession().Execute($"DROP TABLE {table.Name};");
    }

    public static void DropIfExists<T>(this Table<T> table)
    {
        table.GetSession().Execute($"DROP TABLE IF EXISTS {table.Name};");
    }
}

Then you can use it like this
entityTable.Drop();
attributeTable.DropIfExists();


text:
Q: Can you add a new version of an existing Google Doc using the Drive REST API? Wondering if anyone has actually added new versions of docs using the Drive REST API, automating the manual process of right clicking on a Doc in Drive, going to Manage Versions, Upload New Version?  I'm looking to add new versions of a PDF in my case.
The closest I have come to finding the answer via the Drive REST API documentation is here, using File:update:
https://developers.google.com/drive/v2/reference/files/update
But I don't see in there if it would actually add a new version or not, leaving historical versions in tact.
Thanks in advance for any input or advice,
Dave

A: The answer is YES, anytime you perform update on a file/folder,
 Drive mGOOSvc;
 ...
/****************************************************************
   * update file in GOODrive,  see https://youtu.be/r2dr8_Mxr2M
   * @param resId  file  id
   * @param titl  new file name (optional)
   * @param mime  new mime type (optional, "application/vnd.google-apps.folder" indicates folder)
   * @param file  new file content (optional)
   * @return      file id  / null on fail
   */
  String update(String resId, String titl, String mime, String desc, java.io.File file){
    com.google.api.services.drive.model.File gFl = null;
    if (mGOOSvc != null  && resId != null) try {
      com.google.api.services.drive.model.File meta = new File();
      if (titl != null) meta.setTitle(titl);
      if (mime != null) meta.setMimeType(mime);
      if (desc != null) meta.setDescription(desc);

      if (file == null)
        gFl = mGOOSvc.files().patch(resId, meta).execute();
      else
        gFl = mGOOSvc.files().update(resId, meta, new FileContent(mime, file)).execute();

    } catch (Exception e) { e.printStackTrace();}
    return gFl == null ? null : gFl.getId();
  }

you will see a new version of the object using drive.google.com ->  Manage versions...
It works in the 'update' branch, I did not test the 'patch' branch, though.
Good Luck


text:
Q: SQL Server query GROUP BY with Where I have table tblEvents with columns dEvent_Date, dEvent_Time, tEvent_Emp_Code_num
I must group all dates and get all minimum time from each of them.
For example I wrote below query, but its nothing printed.
SELECT dEvent_Date, MIN(dEvent_Time) as minTime
FROM tblEvents
WHERE
     tEvent_Emp_Code_num = 26 AND dEvent_Date = 11/18/2010
GROUP BY dEvent_Date

After that I tested below query, it works, but it prints all days, I need only specified date's data.
SELECT dEvent_Date, MIN(dEvent_Time) as minTime
FROM tblEvents
WHERE tEvent_Emp_Code_num = 26 GROUP BY dEvent_Date

Can you help me?

A: How is your Date stored in table? The default Date format of MySQL is: yyyy-mm-dd. Also you must enclose date in single quotes.
And you should search like:
where dEvent_Date = '2010/11/18'
if you are not specifying Date Format.

A: if db is dql this the Formate to check the value In DB,,,,,
or else u,,,,
you have to convert the date value into '2010-11-18' like
$date   =   date('Y-m-d',strtotime(11/18/2010));

   dEvent_Date = $date

A: i had same problem and i have used cast function in mysql where my query look like
CREATE VIEW v_a AS SELECT
  tblEvents .*,
  EXTRACT(YEAR FROM dEvent_Date) AS 'year',
  EXTRACT(MONTH FROM dEvent_Date) AS 'month',
  DAYOFMONTH(dEvent_Date) AS 'day'
FROM tblEvents WHERE tEvent_Emp_Code_num = 26;
SELECT
  v.year,
  v.month,
  v.day,
  count(v.id)
FROM v_a AS v
GROUP BY v.year,v.month,v.day

for SQL SErver you may use  CONVERT Function
SELECT CONVERT(VARCHAR(8), GETDATE(), 4) AS [DD.MM.YY]

or cast function
SELECT CAST(YEAR(GETDATE()) AS VARCHAR(4))

perhaps following post is more useful
Get Date Only Function

A: This will work for this case:
SELECT dEvent_Date, MIN(dEvent_Time) as minTime
FROM   tblEvents
WHERE  tEvent_Emp_Code_num = 26
GROUP BY dEvent_Date
HAVING  CAST('2015/01/01 00:00:01' AS DATETIME) < dEvent_Date
        AND dEvent_Date >  CAST('2015/05/05 00:00:01' AS DATETIME)

(Refrences) how to use the keyword having:

http://www.w3schools.com/sql/sql_having.asp
https://msdn.microsoft.com/en-us/library/ms180199.aspx


text:
Q: Getting New Relic Running for PHP on Heroku So I've seen New Relic's guide here at https://newrelic.com/docs/php/new-relic-for-php
I ran heroku run /etc/init.d/newrelic-daemon restart and it shows:
    Running `/etc/init.d/newrelic-daemon restart` attached to terminal... up, run.1
    bash: /etc/init.d/newrelic-daemon: No such file or directory

So it looks like the proxy daemon was not installed by installing the New Relic add-on.
Any help is appreciated!

A: Contacted New Relic about this. Looks like it's currently not possible to run on Heroku.


text:
Q: Why can't I hold EnumMap entries via a "for" loop, even if I use "final"? Best workaround? I'm having some strange behaviour.
[UPDATE: Full runnable example given:]
package finaltestwithenummapentry;

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.Map.Entry;

public class FinalTestWithEnumMapEntry {

    enum SomeEnum{
        ONE, TWO, THREE;
    }

    public static void main(String[] args) {
        EnumMap<SomeEnum, Integer> map = new EnumMap<SomeEnum, Integer>(SomeEnum.class);
        map.put(SomeEnum.ONE, 1);
        map.put(SomeEnum.TWO, 2);
        map.put(SomeEnum.THREE, 3);

        ArrayList<Entry<SomeEnum, Integer>> entryList = new ArrayList<Entry<SomeEnum, Integer>>();

        for(final Entry<SomeEnum, Integer> entry : map.entrySet()){
            System.out.println("Key is " + entry.getKey() + ", value is " + entry.getValue());
            //This prints the correct keys and values

            entryList.add(entry);
        }

        System.out.println("");

        for(Entry<SomeEnum, Integer> entry:entryList){
            System.out.println("Key is " + entry.getKey() + ", value is " + entry.getValue());
            //This prints only the last entry each time
        }
    }
}

Output (JavaSE 1.6):
Key is ONE, value is 1
Key is TWO, value is 2
Key is THREE, value is 3

Key is THREE, value is 3
Key is THREE, value is 3
Key is THREE, value is 3

My entry, which I'm presuming is final, is seemingly overwritten by the next one each time. I need to be able to capture the correct entry each time, as I am passing each item to an anonymous inner class instance inside the for loop.
[UPDATE: This problem doesn't exist in Java 7, only Java 6 (and maybe before) ]
UPDATE:
I might have to make my code work whether it's compiled against Java 6 or 7, so what's the most efficient workaround for making it work in either case?

A: I think I've figured out what's going on here, and it has nothing to do with the final keyword. If you remove the final modifier from this line:
for(final Entry<SomeEnum, Integer> entry : map.entrySet()){

the exact same behavior occurs.
But what's this? From the Map.Entry JavaDocs (emphasis added):

A map entry (key-value pair). The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry objects are valid only for the duration of the iteration.

...which I read as "don't try to use Map.Entry objects outside of an iteration on the collection-view returned by Map.entrySet" — this invokes undefined behavior.

This answer explains it in more detail. The problem the OP sees is related specifically to EnumMap's implementation of Map.Entry.

A: This is a behaviour in Java 6 and earlier for EnumMap and IdentityHashMap. It was done for the sake of performance (source - Josh Bloch, 13:56, "Java Puzzlers", May 2011 (original video link given by Voo in comment)). It no longer happens as of Java 7, where you can now rely on collected Map.Entry objects, regardless of subsequent iterations.
The best workaround, if you intend to use an entry after the next iteration occurs, is to clone it via
new AbstractMap.SimpleImmutableEntry(entry)

and use that instead.

A: OK, I went spelunking into the source code - EnumMap does a very weird thing when it comes to sending out the keySet, valueSet and entrySet. From the JDK Source code:
/**
 * Since we don't use Entry objects, we use the Iterator itself as entry.
 */
private class EntryIterator extends EnumMapIterator<Map.Entry<K,V>>
        implements Map.Entry<K,V>
{
    public Map.Entry<K,V> next() {
        if (!hasNext())
            throw new NoSuchElementException();
        lastReturnedIndex = index++;
        return this;
    }

They have a bunch of custom classes in EnumMap that return the value during the iteration, thus the reason they don't want you to use it outside that iterator.
That's why it behaves differently than other Map.Entry. The solution for you is to keep/create a separate map/list and fill it with the keys/values, instead of keeping the Entry objects.
(old answer below)
'final' in this case defines that behavior for a single iteration. If you're passing it to an inner class, define final at the class entry point:
for(final Entry<K, V> entry : map.entrySet()){
  System.out.println("Key is " + entry.getKey() + ", value is " + entry.getValue());
  //This prints the correct keys and values
  doSomething(entry);
}

private void doSomething(final Entry<K,V> entry){}

Like that.

A: What do you mean by this?
//This prints only the last entry each time

Using this piece of code (Java 7):
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;

public class ForeachLoopWithFinal {

enum MyEnum {
    ONE("one"),
    TWO("two"),
    THREE("three");

    private String name;

    private MyEnum(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }

}

public static void main(String[] args) {
    List<Map.Entry<MyEnum, Integer>> entryList = new ArrayList<>();
    Map<MyEnum, Integer> map = new EnumMap<>(MyEnum.class);

    map.put(MyEnum.ONE, 1);
    map.put(MyEnum.TWO, 2);
    map.put(MyEnum.THREE, 3);

    for (final Map.Entry<MyEnum, Integer> entry : map.entrySet()) {
        System.out.printf("Key is %s, value is %s%n", entry.getKey(), entry.getValue());
        entryList.add(entry);
    }

    for (Map.Entry<MyEnum, Integer> entry : entryList) {
        System.out.printf("Key is %s, value is %s%n", entry.getKey(), entry.getValue());
    }
}

}
I get exactly this output. So the exact same number of entries is printed the first and the second time.
Key is one, value is 1
Key is two, value is 2
Key is three, value is 3
Key is one, value is 1
Key is two, value is 2
Key is three, value is 3

Using your example I get the same.
Key is ONE, value is 1
Key is TWO, value is 2
Key is THREE, value is 3

Key is ONE, value is 1
Key is TWO, value is 2
Key is THREE, value is 3

A: I believe it's because your 'entry' is getting created each time a loop happens so it's actually a new variable each time. If you tried to set entry to something else inside the loop, I believe you'd get a compiler error.
Edit, based on feedback: There must be something you're not showing us.
Map<String, String> map = new HashMap<String, String>();
        map.put("barf", "turd");
        map.put("car", "bar");
        ArrayList<Entry<String, String>> entryList = new ArrayList<Entry<String, String>>();

        //Assuming I have a Map<K,V> called "map":
        for(final Entry<String, String> entry : map.entrySet()){
            System.out.println("Key is " + entry.getKey() + ", value is " + entry.getValue());
            //This prints the correct keys and values

            entryList.add(entry);
        }

        for(Entry<String,String> entry:entryList){
            System.out.println("Key is " + entry.getKey() + ", value is " + entry.getValue());
            //This prints only the last entry each time
        }

prints out:
    Key is car, value is bar
    Key is barf, value is turd
    Key is car, value is bar
Key is barf, value is turd

See this post: Iterating over EnumMap#entrySet It will explain things.

A: According to the Java Language Specification, the enhanced for loop when using an iterator that looks like this:
for ( VariableModifiersopt Type Identifier: Expression) Statement

is exactly equivalent to:
for (I #i = Expression.iterator(); #i.hasNext(); ) {
        VariableModifiersopt Type Identifier = #i.next();
   Statement
}

(where I is the type of Expression.iterator()). In your case, VariableModifiersopt is final. As is clear from the equivalent form, the final applies only to the use of the variable within Statement.


text:
Q: Getting the value in a range which gives the maximum of a bounded function in z3py I have to get the value (in a range of them) that gives the maximum of a function, using z3py.
For example: I have a function (foo(x,y) = 2*x + 1 + y), and I want to find the value of [x,y] (using the constraint lo <= foo(x,y) <= hi) such that foo(x,y) is maximum.
In other words I have to solve a maximum problem within a range, is that possible?
I have wrote this simple script in python:
    s = Solver()
    # hi is given by the user
    # expr is foo(x)
    s.add(expr <= hi)
    s.add(expr >= lo)
    s.add(X >= 0)
    s.add(Y >= 0)

    if  s.check() == sat:
        print('_upper_bound: got model %s' % s.model())

If I use only a variable (e.g., foo(x) = 2*x + 1), the given model is correct and the value of foo(x) is the highest. If I use more than one variable (e.g., foo(x,y) = 2*x+y) the found result is the minimum.
All the points in the range are in the domain of the function.
EDIT: Apparently, if I remove the two constraints about X and Y, I get the maximum value.

A: using scipy, you can minimize (you maximize -f if you minimize f)
scipy.optimize.minimize(fun, x0, args=(), method='BFGS', jac=None,
    hess=None, hessp=None, bounds=None, constraints=(), tol=None,
    callback=None, options=None)

as you see, you have a bounds parameter,

bounds : sequence, optional Bounds for variables (only for L-BFGS-B,
  TNC, COBYLA and SLSQP). (min, max) pairs for each element in x,
  defining the bounds on that parameter. Use None for one of min or max
  when there is no bound in that direction.

More detail on the optimization routines to be found here.


text:
Q: Should 404 response include body I wanted to know what fellow developers follow while designing rest API error responses.
For all the not-found  get resources, do you also send the some sort of body indicating that resource was not found or some more detailed level error messages or only error code with null or blank response?

A: It is very common for 404 responses to contain content in the body.  The first example would be when you go to web sites, you get a helpful HTML page that has links to go back or go to the front page.
There is no reason why an API call shouldn't return a response body.  In fact, it's something that the JSON:API specification encourages.  The main reason is that it simplifies the error handling code on the client side if your server always returns content.
On the other hand, if you are not using the JSON:API standard, then you can make your own informed decision on the matter.  The HTTP Status code does provide sufficient information for the client to know the resource does not exist.  The only downside is that error handling in the client may be slightly more complex.
The only return HTTP status codes I am aware of that explicitly say should not have content include your 3XX codes for redirects and the 204 No Content code.
Bottom Line
As Eric Lippert cautions, if you return a body, make sure that the error message you provide does not share information that the user is not authorized to know.  A 404 indicates that there is no resource by that URL.
I work with systems where every call to the core APIs are authenticated, so I know who is making the call, and I am assured of what permissions they have.  That said, I do prefer to have a body that includes a generic error message saying the resource they were looking for could not be found.

A:
For all the not-found get resources, do you also send the some sort of body indicating that resource was not found or some more detailed level error messages or only error code with null or blank response?

Safety first!
The first thing to consider is: can an attacker use that information for anything, including crafting better attacks in the future?
I often tell the cautionary tale of an exception in a pre-release version of .NET where the exception error message was basically "You don't have permission to know the name of directory C:\foo". That's a very helpful error message, but it defeats the purpose of hiding the secret from low-trust code. (This problem was caught and fixed before any version of .NET shipped to customers.)
In particular be careful of error messages that distinguish between "that doesn't exist" and "that exists but you can't see it". It is often a good idea to simply never return a 403 "forbidden" error and instead always return 404 "not found".
If your diagnostics allow an attacker to distinguish between forbidden and not found, they can use that difference to gradually enumerate the space of possibly-existing resources to determine which do and do not exist.
I introduced exactly this vulnerability into VBScript in the 1990s; an attacker could write a web page that gradually learned your machine's directory structure by checking error messages that made this distinction. They could not read files, but they could determine the names of files and directories by trial and error.
Thus, a good practice for web-based APIs is to fail to the secure mode: say as little as possible in an error message unless you know the client to be authenticated and trusted to have all the information in the error message.

A:
The 4xx (Client Error) class of status code indicates that the client seems to have erred.  Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.

404 is, of course, a status code of the 4xx class, therefore the body of the response should (in the RFC 2119 sense) include a message body.
Because the response includes a 4xx status code, general purpose components will know (a) that the included representation is that of an error, and not the resource itself (b) will know whether or not the error representation is cacheable (in the case of 404, by default the representation may be cached).
RFC 7807 describes application/problem+json, a media type designed for general purpose communication of errors.

A: HTTP status codes are for machines (software), the response body is for human beings (users). A browser will understand the status code and it will display the body to the user. The user is not expected to know what status code 404 means and the browser will not try to parse the response body.
For a REST API, the question is, of what use would a status body be? Should it be displayed to the user? Should it be understandable by software (e.g. the body is XML or JSON data)? If the answer is no in both cases, of what use would a body be? And if it is of no use, why would you want to include a body?


text:
Q: SSRS - Remove Duplicate Date in a Date Range Parameter I am trying to remove duplicate dates in the date range parameters.  I have found a VB code block online for removing text duplicates.  I believe that a slight modification on the codes will solve my problem.  However, apologies in advance that I am a newbie in VBC and I am having a hard time to modify the codes.  Please help Thank you!!!
Update:
I am using one of the columns "Ship_Date", which has duplicate values, as the values in my two parameters ("Start_Date" and "End_Date"). I am trying to contain only distinct values in the drop-down menu.
Please click this for reference
Public Shared Function RemoveDuplicates(parameter As Parameter) As String()

Dim items As Object() = parameter.Value
System.Array.Sort(items)
Dim k As Integer = 0

For i As Integer = 0 To items.Length - 1
If i > 0 AndAlso items(i).Equals(items(i - 1)) Then
Continue For
End If

items(k) = items(i)
k += 1
Next
Dim unique As [String]() = New [String](k - 1) {}
System.Array.Copy(items, 0, unique, 0, k)

Return unique
End Function


text:
Q: Getting FileNotFoundException when pass jrxml file to JasperFillManager.fillReport Its working perfectly when I check the preview and give a parameter using eclipse but doesn't when I try to pass it via the servlet.... I intend to accept an input from the user via HTML and pass it onto the Servlet
Extra Info: The query is defined in the jrxml file and a connection is provided too
Not a duplicate to:  Where to place a .txt file so that a java servlet can read it during runtime
More info after first stack trace
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

Code I'm concerned with
        HashMap map = new HashMap();
        JasperPrint jasperPrint = null;
        Connection connection = null;
        map.put("uLimit","2");
        try {
            jasperPrint = JasperFillManager.fillReport("Ticket.jrxml",map,connection);

        } catch (JRException e) {
            e.printStackTrace();
        }
    }

Error:
net.sf.jasperreports.engine.JRException: java.io.FileNotFoundException: Ticket.jrxml
    at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:110)
    at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:99)
    at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:272)
    at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:745)
    at com.sjr.controller.TicketReport.doGet(TicketReport.java:46)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)

I tried
String Path=getServletContext().getRealPath("/WebContent/Ticket.jrxml");

jasperPrint = JasperFillManager.fillReport(Path,map,connection);

StackTrace
net.sf.jasperreports.engine.JRException: java.io.FileNotFoundException: C:\dilip new woorkspace 3-19-2016\DJ_Party_2.0\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\DJPartyManagement vC\WebContent\Ticket.jrxml
    at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:110)
    at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:99)
    at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:272)
    at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:745)
    at com.sjr.controller.TicketReport.doGet(TicketReport.java:54)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.io.FileNotFoundException: C:\dilip new woorkspace 3-19-2016\DJ_Party_2.0\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\DJPartyManagement vC\WebContent\Ticket.jrxml
    ... 27 more

And
String Path =(getServletContext().getContextPath()+"/Ticket.jrxml");

StackTrace
net.sf.jasperreports.engine.JRException: java.io.FileNotFoundException: \DJPartyManagement_vC\Ticket.jrxml
    at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:110)
    at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:99)
    at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:272)
    at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:745)
    at com.sjr.controller.TicketReport.doGet(TicketReport.java:54)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.io.FileNotFoundException: \DJPartyManagement_vC\Ticket.jrxml
    ... 27 more

And
InputStream Path = getServletContext().getResourceAsStream("/Ticket.jrxml");

StackTrace
net.sf.jasperreports.engine.JRException: Error loading object from InputStream
    at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:249)
    at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:229)
    at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:405)
    at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:824)
    at com.sjr.controller.TicketReport.doGet(TicketReport.java:55)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.io.StreamCorruptedException: invalid stream header: 3C3F786D
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
    at java.io.ObjectInputStream.<init>(Unknown Source)
    at net.sf.jasperreports.engine.util.ContextClassLoaderObjectInputStream.<init>(ContextClassLoaderObjectInputStream.java:58)
    at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:244)
    ... 26 more

Thank You for reading....


text:
Q: Specify time of events sent with AppInsights? Is there a way to set the time of events manually sent in App Insights? I'm using the ApplicationInsights package from @microsoft/applicationinsights-web in a react app. As an example, I want to execute something like this at 6:00pm ETC Apr 26, 2022:
    appInsights.trackEvent({
        name: "my cool event",
        properties: {
            greeting: "hello world"
        },
    });

But have it logged in my azure portal as happening at 5:00pm ETC Apr 26, 2022. I figured there would be a time property or something I could set on the parameter object, but that doesn't seem to be the case.

A: AFAIK, We have trackDependencyData, which is the IDependencyTelemetry interface, which has startTime as a parameter to know the telemetry event start time.
Sample code:-
var success = false;
var startTime = new Date().getTime();
try
{
    success = dependency.Call();
}
finally
{
    var elapsed = new Date() - startTime;
    telemetry.trackDependency({
        dependencyTypeName: "myDependency",
        name: "myCall",
        duration: elapsed,
        success: success
    });
}

For more information please refer the below links:-

*

*MICROSOFT DOCUMENT| trackDependency , API SUMMARY

*SO THREAD | Azure Application Insight JavaScript SDK trackEvent Timestamp


text:
Q: Add Using statement to every aspx-code behind file? This may be a pretty basic question (or not, I don't know), but I couldn't find any answer to this.
I'm in the process of refactoring an older Webapplication. I'm moving the App_Code folder (which is pretty huge) to a seperate Class Library, for one thing.
I'm wondering if there is a way to reference the classes in the DLL in every .aspx file in the entire web-app, without having to open every .aspx-file and adding the 'Using' statement manually. Can I add something in my web.config for example to reference the DLL automatically?
I'm not in the mood to open up every .aspx page one by one to add this - because there are a lot of them.
Thanks for any help you can give me.

A: You can add it to the Web.config file in your views directory(ies):
<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="Your.Namespace.Here" />
  </namespaces>
</pages>

There should already be some default namespaces included.

A: Yes, you can add your own namespaces in the web config under pages\namespaces:
    <pages>
        <namespaces>
            <add namespace="System.Web.Helpers" />
        <namespaces>
    <pages>


text:
Q: ComboBox DropDownStyle DropDownList : Change BackColor WinForms I am making one app where I highlight currently focused controls.
For TextBox I use the BackColor property.
But in case of a ComboBox with DropDownStyle = DropDownList, BackColor does not seem to make it highlight.
Any suggestion(border etc?) on how can I make the controls Highlight in a consistent manner.

A: As Reniuz said, you'll need to change the DrawMode properties.
Specifically, changing the DrawMode to OwnerDrawFixed will allow you to specify the BackColor.
System.DrawMode

Normal - All the elements in a control are drawn by the operating system and are of the same size.
OwnerDrawFixed - All the elements in the control are drawn manually and are of the same size.
OwnerDrawVariable - All the elements in the control are drawn manually and can differ in size.

See System.Windows.Forms.DrawMode for more information.

A: Try to change FlatStyle or DrawMode properties. But control will look a bit different. May be it will fit for you :)


text:
Q: Regex match all words including slash I would like to remove all words behind the number.
12 - Balloon Cool
1 - I would like to sleep
541 - Sleep is for weak/sheep

Currently I 'm using this regex to replace them with empty
/ - (\w+( +\w+)*)/

It managed to filter some but not for the string with slash.
12
1
541sheep

A: To remove any thing after space-hyphen-space you can just use:
/ - .*$/m

RegEx Demo

A: I would use something like this:
Search: ^(\d+)\s+-.*?
Replace: $1


text:
Q: Exclude ApplicationStartup Event listener when testing I recently added an ApplicationStartup class to my SpringBoot project
@Component
public class ApplicationStartup
    implements ApplicationListener<ApplicationReadyEvent> { ...

It implements ApplicationListener.
Now when I run my old JUNit tests that have nothing to do with that class, The testrunner tries to Run my StartupListener, which is neither necessary not appropriate in these cases.
How do I skip the ApplicationListener when my tests initialize?
@RunWith(SpringRunner.class)
@SpringBootTest
public class SubmissionItemManagerTest {...

A: You can create a separate  application class for testing  and exclude the components that are not required for tests:
@SpringBootApplication
@ComponentScan(excludeFilters = @ComponentScan.Filter(
        type = FilterType.ASSIGNABLE_TYPE,
        value = { ApplicationStartup.class,
                 RealApplication.class }))

public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
}

Then in your SubmissionItemManagerTest class use the TestApplication class:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplication.class)
public class SubmissionItemManagerTest {
    ...
}

A: You can mock your ApplicationStartup class
Add this declaration to your test case:
@MockBean
private ApplicationStartup applicationStartup

This will create a mocked instance of ApplicationStartup and mark it as @Primary in your test context thereby replacing the actual instance ofApplicationStartup.


text:
Q: TwiML: Enqueueing inbound call with custom parameters I am using a TwiML app and PHP to handle inbound calls. I handle the inbound call in the TwiML voice xml call back.
I enqueue the call to the task router...
$voiceResponse = new VoiceResponse;
$waitUrl = $this->generateUrl('admin.callcenter:get-call-waiting-xml',['queueEntryId' => $queueEntryId,'scriptId' => $scriptId]);
$actionUrl = $this->generateUrl('admin.callcenter:get-call-action-xml',['queueEntryId' => $queueEntryId,'scriptId' => $scriptId]);
$enqueue = $voiceResponse->enqueue('',[
    'workflowSid' => $workflowSid,
    'action' => $actionUrl,
    'method' => 'POST',
    'waitUrl' => $waitUrl,
    'waitUrlMethod' => 'GET'
]);
$xml = $voiceResponse->asXml();
$response = new Response($xml, Response::HTTP_OK, ['context-type' => 'text/xml']);
return $response;

I pass customer parameters to the action and wait callbacks by encoding parameters in the URL.  However I cannot seem to add custom parameters to the task that is created as a result of the enqueue().
I've looked at using the task router status callback to add custom parameters to the task on the task.created event.  This works but it is not clear that these parameters will be added to the task before it is evaluated in the task queue.  There seems to be a race condition because I don't think that task router will wait on the return from the status call before putting the task in the queue.  At least there is nothing in the documentation that says so.
What I want to do is to add attributes like 'customer_id' => 5 and 'customer_type' => 'preferred' to the task attributes so as to effect the worker selection specified in the workflow filters.
Many examples in the workflow documentation for the task router use custom task attributes but there no example where custom parameters are added as a result of a voice API ENQUEUE which I would think would be a very common approach.

A: Add the task attributes when you enqueue the call to taskrouter. Here is the example from twilios documentation:
<?php
// Download the library and copy into the folder containing this file.
require_once '/path/to/vendor/autoload.php'; // Loads the library

use Twilio\TwiML\VoiceResponse;

$response = new VoiceResponse();
$response->enqueue(null, ["workflowSid" => "WW0123456789abcdef0123456789abcdef"])
    ->task("{'account_number':'12345abcdef'}");
print $response;
?>

<!-- alternatively -->

<?php
$workflowSid = "WW0123456789abcdef0123456789abcdef";

header('Content-Type: application/xml');
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";

?>
<Response>
    <Enqueue workflowSid="<?php echo $workflowSid ?>">
        <Task>{"account_number": "12345abcdef"}</Task>
    </Enqueue>
</Response>

Further more if you decide to use the event callback and update the task there. This will cause the task to be re sent through your taskrouter workflow. Any update to a task will cause the task to restart the assigned workflow. Hope this helps!


text:
Q: Application of Rouche's Theorem? I have this question which I struggled to apply Rouche's Theorem:
Let $f$ and $g$ be analytic inside and on a smooth regular closed curve $\gamma$. Suppose that $f(z) \neq 0$ for all $z$ on $\gamma$. Prove that there is $\varepsilon > 0$ such that $\mathbb{Z}(f) = \mathbb{Z}(f +\varepsilon g)$ inside $\gamma$, where $\mathbb{Z}$ is the number of zeros.
Any help or hints is appreciated.


text:
Q: Advice on "leanest" package manager for OS X? Hope this is the right place to ask the following question:
I want to install Octave on my Macbook Air, which means I need a package manager. I had Homebrew installed previously, but I got the impression the manager took a huge bite out of my (rather limited) HDD space, possibly as well (or even: mainly) due to the necessary libraries.
Any advice on which OS X package manager I should get if HDD space is the main concern, and any advice how to use it to limit space impact?

A: The size of your package manager will be trivial (20 MB) compared to the data it needs for your packages (golang clocks in at 250 MB, node at 37 MB). I'd say stick with Homebrew and work with it if you find some libraries are causing large space usages.
My thoughts are what specifically are your HDD space concerns? You could install brew and the files it needs on an external volume, but my guess is you have other files that could be co-located elsewhere - even on an SD card if you can't accommodate these files on the boot volume.
Here are some target numbers for a clean install of OS X 10.11 with the store Xcode and homebrew installed.

*

*5.4 GB for /System

*5.1 GB for /private _( most of that is the RAM sleep image on a 16 GB Mac)

*2.4 GB for /Library

*1.1 GB for /Applications (and you could need an additional 5 GB for the full Xcode if you wish to carry that around - most of it isn't needed for command line and open source compilation)

*0.3 GB for /Users

So between 14.5 GB of minimal filesystem usage to 20 GB if you carry all of Xcode simulators and SDK for iOS, tvOS, Mac OS that are easily thinned if you only want command line tools.
Basically, even if you have a high cost/low storage capacity 64 GB SSD drive to boot your Mac, it's likely not full of system or tools, but what you've brought to run.


text: Q: Is it possible to configure thymeleaf to render html from database? Instead of rendering html files from resource folder i want thymeleaf to render some html string fetched from the database. I have been looking into the thymeleaf libraries, but no luck!


text:
Q: LWJGL Slick Java OS X Natives I'm trying to make a jar out of my game written with LWJGL and Slick. My technique is to extract the natives out of the jar into a temporary directory and then change the org.lwjgl.librarypath to the folder with the extracted files. Sadly this doesn't work on OS X... on Windows it runs fine, but on Mac it doesn't find "liblwjgl.dylib", which is actually not existing...
Exception in thread "main" java.lang.UnsatisfiedLinkError: Can't load library: /var/folders/r0/qwm413fs3b9djwyb0d4pwhn40000gr/T/wo42/natives/liblwjgl.dylib
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1828)
    at java.lang.Runtime.load0(Runtime.java:792)
    at java.lang.System.load(System.java:1059)
    at org.lwjgl.Sys$1.run(Sys.java:70)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.lwjgl.Sys.doLoadLibrary(Sys.java:66)
    at org.lwjgl.Sys.loadLibrary(Sys.java:95)
    at org.lwjgl.Sys.<clinit>(Sys.java:112)
    at org.lwjgl.opengl.Display.<clinit>(Display.java:135)
    at org.newdawn.slick.AppGameContainer$1.run(AppGameContainer.java:39)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.newdawn.slick.AppGameContainer.<clinit>(AppGameContainer.java:36)
    at org.alternativedev.wo42.Game.run(Game.java:136)
    at org.alternativedev.wo42.App.run(App.java:32)
    at org.alternativedev.wo42.App.main(App.java:23)

Has anyone already had the same problem and/or knows the solution?
BigTeddy

A: The problem is that in order for the jar to work you also need the native files. There is a tool called JarSplice that can allow you to put the natives inside your jars.

A: I had a similar problem and found a solution here. Essentially, you need to soft-link liblwjgl.jnilib from the natives dir to liblwjgl.dylib. That did it for me.


text:
Q: Angular on change event for select menu Using Angular I have a dataset which is called via $http.get, filtered and then displayed on the page. This link will sort data by country, is there a way that I can replicate this but using a select list instead of text links.
Country

Part of my app.js
app.controller('customersCrtl', function ($scope, $http, $timeout) {
        $http.get('ajax/getCustomers.php').success(function(data){
        $scope.list = data;
        $scope.currentPage = 1; //current page
        $scope.entryLimit = 20 //max no of items to display in a page
        $scope.filteredItems = $scope.list.length; //Initially for no filter
        $scope.totalItems = $scope.list.length;
    });
    $scope.filter = function() {
        $timeout(function() {
            $scope.filteredItems = $scope.filtered.length;
        }, 10);
    };
    $scope.sort_by = function(predicate) {
        $scope.predicate = predicate;
        $scope.reverse = !$scope.reverse;
    };
});

So I'd like this to replicate the sort based on the selected value...
<select class="form-control">
    <option value="firstname">First name</option>
    <option value="lastname">Last name</option>
    <option value="company">Company name</option>
</select>

A: First, you have to bind the dropdown into a value called sortValue of $scope
<select ng-model="sortValue" class="form-control">
   <option value="firstname">First name</option>
   <option value="lastname">Last name</option>
   <option value="company">Company name</option>
</select>

In the controller, set a watch to change the filter when the sortValue change:
$scope.$watch('sortValue',function(newValue, oldValue){
    //newValue here is the selected value
    $scope.sort_by(newValue);
});


text:
Q: how to convert bytes to buffer in python i'm retrive a blob from mssql server which is showing something like this
b'%PDF-1.7\r\n%\xb5\xb5\xb5\xb5\r\n1 0 obj\r\n<</Type/Catalog/Pages 2 0 R/Lang(en-GB) /StructTreeRoot 30 0 R/MarkInfo<</Marked true>>/Metadata 820 0 R/ViewerPreferences 821 0 R>>\r\nendobj\r\n2 0 obj\r\n<</Type/Pages/Count 3/Kids[
            3 0 R 18 0 R 25 0 R
        ] >>\r\nendobj\r\n3 0 obj\r\n<</Type/Page/Parent 2 0 R/Resources<</XObject<</Image5 5 0 R>>/ExtGState<</GS6 6 0 R/GS9 9 0 R>>/Font<</F1 7 0 R/F2 10 0 R/F3 12 0 R/F4 14 0 R/F5 16 0 R>>/ProcSet[/PDF/Text/ImageB/ImageC/ImageI
        ] >>/MediaBox[
            0 0 595.44 841.68
        ] /Contents 4 0 R/Group<</Type/Group/S/Transparency/CS/DeviceRGB>>/Tabs/S/StructParents 0>>\r\nendobj\r\n4 0 obj\r\n<</Filter/FlateDecode/Length 7807>>\r\nstream\r\nx\x9c\xcd
    ]ms\xdc6\x92\xfe\xee*\xff\x07~\xba\x9a\xd9=Q\x04\xdf\xb9\xb5\xb7U\x8e\x9d\xb7\xdd8qb\xed\xa6R\xc9~P\xa4\x91\xadD\x96|\x92\xbc[\xfe\xf7\xd7\xddh\x80\x04\x89\x060\xc3\xf1\xdd\xa5\xca\x13I\xec\xe9~\xd8h4\x1a\x0f@\xf0\xf4\xd9\xfd\xe3\xf5\xd5\xf9\xc5c\xf6\xe7?\x9f>{|<\xbfx\xbb\xbb\xcc~>=\xbb{\xff\xcf\xd3\xb3\x8f\xefw\xa7\xaf\xce\xdf\\\xdf\x9e?^\xdf\xdd\x9e\xbe\xfe\xf0\xeb#\xfe\xe9\xab\xdd\xf9\xe5\xee\xfe/\x7f\xc9>{\xf1<;\xfd\xf2u\x9b\xbdyx\xfa\xe4\xbf\x9f>)\xb2"/

when i print the type of above blob it shows bytes i want to convert to buffer which is some thing like this {"type":"Buffer","data":[37,80,68,70,45,49,46,55,13,10,37,181,181,181,181,13,10,49,32,48,32,111,98,106,13,10,60,60,47,84,121,112,101,47,67,97,116,97,108,111,103,47,80,97,103,101,115,32,50,32,48,32,82,47,76,97,110,103,40,101,110,45,71,66,41,32,47,83,116,114,117,99,116,84,114,101,101,82,111,111,116,32,51,48,32,48,32,82,47,77,97,114,107,73,110,102,111,60,60,47,77,97,114,107,101,100,32,116,114,117,101,62,62,47,77,101,116,97,100,97,116,97,32,56,50,48,32,48,32,82,47,86,105,101,119,101,114,80,114,101,102,101,114,101,110,99,101,115,32,56,50,49,32,48,32,82,62,62,13,10,101,110,100,111,98,106,13,10,50,32,48,32,111,98,106,13,10,60,60,47,84,121,112,101,47,80,97,103,101,115,47,67,111,117,110,116,32,51,47,75,105,100,115,91,32,51,32,48,32,82,32,49,56,32,48,32,82,32,50,53,32,48,32,82,93,32,62,62,13,10,101,110,100,111,98,106,13,10,51,32,48,32,111,98,106,13} ..thanks in advance.

A: Python doesn't have the equivalent of a "Buffer" type, which is solely a Node.js invention. However, if you want to export the bytes object as JSON in a Node.js-compatible way, you could use the built-in json module:
>>> import json
>>> data = b'hello' # your data goes here
>>> json.dumps({ 'type': 'Buffer', 'data': list(data) })
'{"type": "Buffer", "data": [104, 101, 108, 108, 111]}'


text:
Q: Fixing my SQL Query View I've got a query that I am trying to write that displays the MOST RECENT StatusID data from the Action table.
Here's what my database looks like (Screenshot from SQL Server 2008):

From my sample data, you can see that the Action table contains two (2) entries for RequestID #26. I only want to display the most recent StatusID value (based on the DateStamp field).

I have created a View for my database. It is nasty looking, and bumps up onto my SQL writing ability.
SELECT
  P.ID AS PacketID, R.ID AS RequestID, A.ID AS ActionID, A.EmpID, P.DateStamp,
  RQ.Description AS RequestType, L.Description AS Line, R.PartNo, R.Workorder,
  R.Qty, RZ.Description AS ReasonType, R.MTF, S.Description AS Status
FROM Packet AS P
  LEFT OUTER JOIN Request AS R ON R.PacketID = P.ID
  INNER JOIN Action AS A ON A.RequestID = R.ID
  INNER JOIN RequestType AS RQ ON R.RequestTypeID = RQ.ID
  INNER JOIN Line AS L ON R.LineID = L.ID
  INNER JOIN ReasonType AS RZ ON R.ReasonTypeID = RZ.ID
  INNER JOIN Status AS S ON A.StatusID = S.ID

This View, however, is showing ALL of the values, and I need it to somehow only pull the most recent row for any given Action.
How would I modify my View to do this?

A: SELECT
  P.ID AS PacketID, R.ID AS RequestID, A.ID AS ActionID, A.EmpID, P.DateStamp,
  RQ.Description AS RequestType, L.Description AS Line, R.PartNo, R.Workorder,
  R.Qty, RZ.Description AS ReasonType, R.MTF, S.Description AS Status
FROM Packet AS P
  LEFT OUTER JOIN Request AS R ON R.PacketID = P.ID
  INNER JOIN Action AS A ON A.RequestID = R.ID
  INNER JOIN RequestType AS RQ ON R.RequestTypeID = RQ.ID
  INNER JOIN Line AS L ON R.LineID = L.ID
  INNER JOIN ReasonType AS RZ ON R.ReasonTypeID = RZ.ID
  INNER JOIN Status AS S ON A.StatusID = S.ID
where A.StatusID = (
    select top 1 StatusID
    from Action
    where RequestID = R.ID
    order by DateStamp desc
    )

A: You can create a derived table from the Action table that grabs the max DateStamp grouped by RequestID (this will give you the latest DateStamp for each RequestID). After you have the derived table, you can join it back to the Action table on the row from the Action table that has the matching latest DateStamp for a given RequestID.
SELECT
P.ID AS PacketID, R.ID AS RequestID, A.ID AS ActionID, A.EmpID, P.DateStamp,
RQ.Description AS RequestType, L.Description AS Line, R.PartNo, R.Workorder,
R.Qty, RZ.Description AS ReasonType, R.MTF, S.Description AS Status
FROM Packet AS P
LEFT OUTER JOIN Request AS R ON R.PacketID = P.ID

INNER JOIN
(SELECT RequestID, MAX(DateStamp) AS MostRecentDateStamp
 FROM Action GROUP BY RequestID) AS MostRecentAction
ON R.ID = MostRecentAction.RequestID

INNER JOIN Action AS A
ON
MostRecentAction.RequestID = A.RequestID
AND
MostRecentAction.MostRecentDateStamp = A.DateStamp

INNER JOIN RequestType AS RQ ON R.RequestTypeID = RQ.ID
INNER JOIN Line AS L ON R.LineID = L.ID
INNER JOIN ReasonType AS RZ ON R.ReasonTypeID = RZ.ID
INNER JOIN Status AS S ON A.StatusID = S.ID

or, another option would be to take the approach shown by Mr. Karwin here:
Join single row from a table in MySQL
SELECT
P.ID AS PacketID, R.ID AS RequestID, A.ID AS ActionID, A.EmpID, P.DateStamp,
RQ.Description AS RequestType, L.Description AS Line, R.PartNo, R.Workorder,
R.Qty, RZ.Description AS ReasonType, R.MTF, S.Description AS Status
FROM Packet AS P
LEFT OUTER JOIN Request AS R ON R.PacketID = P.ID

INNER JOIN Action AS A
ON
R.ID = A.RequestID

LEFT JOIN Action AS A2
ON
A.RequestID = A2.RequestID
AND
A.DateStamp < A2.DateStamp

INNER JOIN RequestType AS RQ ON R.RequestTypeID = RQ.ID
INNER JOIN Line AS L ON R.LineID = L.ID
INNER JOIN ReasonType AS RZ ON R.ReasonTypeID = RZ.ID
INNER JOIN Status AS S ON A.StatusID = S.ID

WHERE A2.RequestID IS NULL

I like the approach Mr. Karwin uses, especially when dealing with ties with a structure like you have:
SELECT
P.ID AS PacketID, R.ID AS RequestID, A.ID AS ActionID, A.EmpID, P.DateStamp,
RQ.Description AS RequestType, L.Description AS Line, R.PartNo, R.Workorder,
R.Qty, RZ.Description AS ReasonType, R.MTF, S.Description AS Status
FROM Packet AS P
LEFT OUTER JOIN Request AS R ON R.PacketID = P.ID

INNER JOIN Action AS A
ON
R.ID = A.RequestID

LEFT JOIN Action AS A2
ON
A.RequestID = A2.RequestID
AND
(A.DateStamp < A2.DateStamp OR (A.DateStamp = A2.DateStamp AND A1.RequestID < A2.RequestID))

INNER JOIN RequestType AS RQ ON R.RequestTypeID = RQ.ID
INNER JOIN Line AS L ON R.LineID = L.ID
INNER JOIN ReasonType AS RZ ON R.ReasonTypeID = RZ.ID
INNER JOIN Status AS S ON A.StatusID = S.ID

WHERE A2.RequestID IS NULL

A: To achive what you want, you can join to a subquery grouping the results by the packetID and selecting the MAX(ID) for each packetID. This works because ID field is an identity column and so and the highest number will always be the most recent. This is preferable over comparing on a timestamp because ints (especially indexed ints) are far faster to compare than timestamps.
SELECT
  P.ID AS PacketID, R.ID AS RequestID, A.ID AS ActionID, A.EmpID, P.DateStamp,
  RQ.Description AS RequestType, L.Description AS Line, R.PartNo, R.Workorder,
  R.Qty, RZ.Description AS ReasonType, R.MTF, S.Description AS Status
FROM Packet AS P
  LEFT OUTER JOIN (SELECT MAX(ID) as ID FROM Request GROUP BY PacketID) as UR ON P.ID = UR.ID
  INNER JOIN Request AS R ON R.PacketID = UR.ID
  INNER JOIN Action AS A ON A.RequestID = R.ID
  INNER JOIN RequestType AS RQ ON R.RequestTypeID = RQ.ID
  INNER JOIN Line AS L ON R.LineID = L.ID
  INNER JOIN ReasonType AS RZ ON R.ReasonTypeID = RZ.ID
  INNER JOIN Status AS S ON A.StatusID = S.ID

A: This will work.
WITH MaxDate AS
(
   SELECT RequestID, Max(DateStamp) AS MaxDate
   FROM Action
   GROUP BY RequestID
), ActionFiltered AS
(
   SELECT Action.*
   FROM Action
   JOIN MaxDate ON Action.RequestID=MaxDate.RequestID AND Action.DateStamp = MaxDate.MaxDate
)
SELECT
    P.ID AS PacketID, R.ID AS RequestID, A.ID AS ActionID, A.EmpID, P.DateStamp,
    RQ.Description AS RequestType, L.Description AS Line, R.PartNo, R.Workorder,
    R.Qty, RZ.Description AS ReasonType, R.MTF, S.Description AS Status
FROM ActionFiltered A
JOIN Request AS R ON A.RequestID = R.ID
JOIN Packet AS P ON P.ID = R.PacketID
JOIN RequestType AS RQ ON R.RequestTypeID = RQ.ID
JOIN Line AS L ON R.LineID = L.ID
JOIN ReasonType AS RZ ON R.ReasonTypeID = RZ.ID
JOIN Status AS S ON A.StatusID = S.ID

Here is what I'm doing:  First, for each requestID I find the most current date (MaxDate), then I get all the data from action table for those rows (ActionFiltered), finally I join all of that back to your tables with inner joins.
Potential problem:  If you have two records in the Action table with the same requestID and timestamp you will get two rows in the final table.
Note: I did not test so there may be typos.

A: I typically use rank() to get the latest version of a record, based on time.  It will assign a rank to each version of a record, based on the key you provide (the partition: in this case the request id).  If you order by desc, the rows with a rank of 1 are the newest.  If you order by asc, the rows with a rank of 1 are the oldest.
EDIT : Changed the name of the RequestId column that was returned in the subquery, to remove the error you were seeing.
SELECT
    P.ID AS PacketID, R.ID AS RequestID, A.ID AS ActionID, A.EmpID, P.DateStamp,
    RQ.Description AS RequestType, L.Description AS Line, R.PartNo, R.Workorder,
    R.Qty, RZ.Description AS ReasonType, R.MTF, S.Description AS Status
FROM Packet AS P
    LEFT OUTER JOIN Request AS R ON R.PacketID = P.ID
    INNER JOIN (
        select
                req.ID as RequestIdForJoin
                , act.*
                , rank() over (partition by req.ID order by act.DateStamp desc) as [Rank]
            from Request as req
                inner join Action as act on req.ID = act.RequestID
    ) as A
        on R.ID = A.RequestIdForJoin
    INNER JOIN RequestType AS RQ ON R.RequestTypeID = RQ.ID
    INNER JOIN Line AS L ON R.LineID = L.ID
    INNER JOIN ReasonType AS RZ ON R.ReasonTypeID = RZ.ID
    INNER JOIN Status AS S ON A.StatusID = S.ID
    where A.[Rank] = 1

For Duplicate Actions: If @Hogan's scenario of multiple actions with the same timestamp is possible, you can stage and then remove duplicates like this:
declare @View table (
PacketID int, RequestID int, ActionID int, EmpID int, DateStamp datetime,
RequestType int, Line int, PartNo varchar(50), Workorder int, Qty int,
ReasonType int, MTF varchar(50), Status int
)

insert into @View
SELECT
    P.ID AS PacketID, R.ID AS RequestID, A.ID AS ActionID, A.EmpID, P.DateStamp,
    RQ.Description AS RequestType, L.Description AS Line, R.PartNo, R.Workorder,
    R.Qty, RZ.Description AS ReasonType, R.MTF, S.Description AS Status
FROM Packet AS P
    LEFT OUTER JOIN Request AS R ON R.PacketID = P.ID
    INNER JOIN (
        select
                req.ID as RequestIdForJoin
                , act.*
                , rank() over (partition by req.ID order by act.DateStamp desc) as [Rank]
            from Request as req
                inner join Action as act on req.ID = act.RequestID
    ) as A
        on R.ID = A.RequestIdForJoin
    INNER JOIN RequestType AS RQ ON R.RequestTypeID = RQ.ID
    INNER JOIN Line AS L ON R.LineID = L.ID
    INNER JOIN ReasonType AS RZ ON R.ReasonTypeID = RZ.ID
    INNER JOIN Status AS S ON A.StatusID = S.ID
    where A.[Rank] = 1

-- Removing all but one duplicate
;with dups as (
    select
        RequestID
        ,row_number() over (partition by RequestID order by DateStamp) as [RowNumber]
    from @View
)
delete dups where [RowNumber] > 1

select * from @View


text:
Q: Why is my html being overwritten when I specify a css classname for a video element? I have an icon that I want to display on a video (with the i tag in the code below). However, when I add a css classname to the video tag (to perform a transform to mirror the video), the icon no longer displays. In addition, in the code, neither the icon nor the stuff in the next div are being displayed when I add the video classname. I want be able to both display the icon and have the classname for the video tag.
I'm aware that adding !important to the css classes will increase their specificity score, but from what I have read, that's not the best way to solve this problem.

{var}

<video className="mirror" ref={node => this.video = node}
    autoPlay={true}
    controls={false}
    playsInline={true}
    muted={true}
/>

I want to see the video displayed with both the var from the div tag and the icon from the i tag displayed.

A: First,className is not a valid html tag attribute, it is a property of a dom object in javascript. What you should use is:

Also, the i and videotags both need to be closed:

<video class="videoClass" ...></video>

Only empty elements can be closed at the end of the opening tag.
The empty elements in HTML are as follows:
<area>
<base>

<col>
<embed>

<input>
<keygen>(HTML 5.2 Draft removed)
<link>
<meta>
<param>
<source>
<track>
<wbr>