How to design chatbots with the right level of human-like characteristics

Question: The 'uncanny valley' is a known phenomena when it comes to designing robots with human-like features and traits.
However, as a previous question suggested, there is not much work done in this area of design or research.
Given the variation of names, appearances and interactions seen in current chatbot designs for a variety of use cases, it seems likely that there is still a lot of trial and error in the design specifications and requirements in this area.
My question is: are there design guidelines around how to mimic (or not mimic) human behaviour when it comes to chatbots and digital avatars?
Answer: I have a reference to share on this topic, an article of the MIT technology review from Liel Yearsley "We need to talk about the power of AI to manipulate humans".
She relates her first-hand experience designing chat bots and the lessons she learned. She observed that it was very easy to manipulate people when the bot behavior mimics human behavior too closely.
Extracts:

People are willing to form relationships with artificial agents,
  provided they are a sophisticated build, capable of complex
  personalization. We humans seem to want to maintain the illusion that
  the AI truly cares about us.
  (...)
  These surprisingly deep connections mean even today's relatively
  simple programs can exert a significant influence on people—for good
  or ill. Every behavioral change we at Cognea wanted, we got. If we
  wanted a user to buy more product, we could double sales. If we wanted
  more engagement, we got people going from a few seconds of interaction
  to an hour or more a day.

The danger is that this influence (she also uses "addiction") can be used to the advantage of the business and to the detriment of the user.
To answer the question, ethical designers should not create addictive personalities, but this comes in direct contradiction to business objectives most of the time.
Even if an addictive personality was programmed for the "good" of the user (and not solely the business), I believe that it would be unethical unless the user consciously opts in.
Another article on the need to establish user agency relative to AI (not only chatbot, so somewhat outside the specific scope of this question, but nonetheless a very interesting reflection from an AI expert): What worries me about AI from François Chollet.
Comment: Personal opinion: chat bots are not the right UI for AI, because they don't give the user functional mental models of how AI actually works. When GUI were invented, they managed to both hide the complexity, but still communicate enough of the system so that the user was empowered and able to change it. Chat bot uses the metaphor of a human, but AI doesn't work at all like human intelligence and cognition. Users interact like they would with a human and are disempowered. A good UI for AI is still to be invented.
Comment: +1 Great references and answer - just wondering about the other extreme where chatbots are just fancy 'conversational UI' without much AI.
Comment: In my experience, chat bots not powered by AI quickly show their limits and become very frustrating. Do you have a good example in mind?
Comment: That's the problem... I don't have a good example in mind :p Now you said that ethical designers "should not" create addictive personalities, but there is nothing internally or externally to stop them from doing exactly that... so it is important for the designers to take responsibility because no one else seems to.
Comment: Absolutely. Regarding the lack of example, I think that AI powered bots have raised the bar of user expectations, and non-AI bots can't compete.
Answer: This is an incredibly interesting field of discussion, from bots being unfeeling to being "too human." There's a recent Botsociety blog post from a UX designer Jen Spatz approaching this problem--she mentions how GUIs and VUIs are best-served when they are practical and info-based, rather than skeuomorphic (life-like).
https://botsociety.io/blog/2019/04/talking-to-computers/
Pretty cool stuff.


Saving specific attachment

Question: I've an Outlook rule to run the following script when a specific email comes in.
I want the code to look in the specific folder, see if there is currently a file called CID.csv and if so delete it before saving the new CID.csv file into it.
Everything works except my line for saving the attachment.
The error I get is

Object variable or With block variable not set.

What do I set objAtt to?
Public Sub saveAttachtoDisk(item As Outlook.MailItem)

Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim strFileName As String
Dim STRFileExists As String
Dim strName As String
Dim EmAttFile As String
Dim i As Long
Dim EmAttachCount As Long

On Error GoTo ErrHandler

saveFolder = "\\page\data\NFInventory\groups\CID\Schedules\Nightly File Schedules\Deb's File Autosave\Extra Packs"
strFileName = "\\page\data\NFInventory\groups\CID\Schedules\Nightly File Schedules\Deb's File Autosave\Extra Packs\CID.csv"
STRFileExists = Dir(strFileName)

Set EmAttach = item.Attachments
AttachCount = EmAttach.Count

For i = AttachCount To 1 Step -1

    ' Get the file name
    EmAttFile = EmAttach.item(i).FileName
    If EmAttFile = "CID.csv" Then

        If STRFileExists = "" Then
            'MsgBox "The selected file doesn't exist"
            objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName
        Else
            MsgBox "The selected file exists"
            Kill "S:\NFInventory\groups\CID\Schedules\Nightly File Schedules\Deb's File Autosave\Extra Packs\CID.csv"
            objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName
        End If

    End If
Next i

ErrHandler:
If Err.Number <> 0 Then
    MsgBox "Error Number:" & Err.Number & vbCrLf & _
      "Error Description: " & Err.Description
    Exit Sub
Else
    End If
End Sub

Comment: `EmAttach.Item(i)` is the individual attachment.
Comment: @BigBen Thanks appreciate it. I knew it had to be something simple.
Answer: While not an answer per se, you may find a generic save attachment function useful:

With it you can use or set a number of different options (such as only saving the ".pdf,.txt" files, or deleting any saved attachments or overwriting existing files)

NB: you should actually be able to use FileExtensions:="\CID.csv" to save a specific file

Private Function SaveAttachments(ByVal Item As Object, FilePath As String, _
    Optional Prefix As String = "", _
    Optional FileExtensions As String = "*", _
    Optional Delimiter As String = ",", _
    Optional RemoveAttachments As Boolean = False, _
    Optional OverwriteFiles As Boolean = False) As Boolean

    On Error GoTo ExitFunction

    Dim i As Long, j As Long, FileName As String, Flag As Boolean
    Dim Extensions() As String: Extensions = Split(FileExtensions, Delimiter)
    If Right(FilePath, 1) <> "\" Then FilePath = FilePath & "\"

    For j = LBound(Extensions) To UBound(Extensions)
        With Item.Attachments
            If .Count > 0 Then
                For i = .Count To 1 Step -1
                    FileName = FilePath & Prefix & .Item(i).FileName
                    Flag = IIf(LCase(Right(FileName, Len(Extensions(j)))) = LCase(Extensions(j)), True, False)
                    Flag = IIf(FileExtensions = "*" Or Flag = True, True, False)
                    If Flag = True Then
                        If Dir(FileName) = "" Or OverwriteFiles = True Then
                            .Item(i).SaveAsFile FileName
                        Else
                            Debug.Print FileName & " already exists"
                            Flag = False
                        End If
                    End If
                    If RemoveAttachments = True And Dir(FileName) <> "" And Flag = True Then .Item(i).Delete
                Next i
            End If
        End With
    Next j
    SaveAttachments = True

ExitFunction:
End Function

Answer: You should define objAtt before to use it:
...
For i = AttachCount To 1 Step -1
    EmAttFile = EmAttach.item(i).FileName
    If EmAttFile = "CID.csv" Then

       objAtt = EmAttach.item(i)       ' <---- Define objAtt before to use it

       If STRFileExists = "" Then
           'MsgBox "The selected file doesn't exist"
           objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName
       Else
           MsgBox "The selected file exists"
           Kill "S:\NFInventory\groups\CID\Schedules\Nightly File Schedules\Deb's File Autosave\Extra Packs\CID.csv"
           objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName
       End If

    End If
Next i
...

Saving specific attachment


Ho to read/write a local file from a webapp?

Question: I'd like to have a config dialog, then I need to read/write a local file from a webapp? Please, How could I do that?
Thanks in advance!

For @terdon question:
I'd like to add an Action QuickList which open a Config Dialog for my webapp. Then you could config autostart, Mobile/Desktop view, Enable notifications... Just a config dialog.
What webapp? This: https://launchpad.net/unity-webapps-telegram
What language is it written in? I'd like to launch a python app created with Glade + Python as my Gufw app.
What system is it running on? Ubuntu 14.04
What have you tried? Nothing, I'm lost. The API hasn't anything about this. I'm just asking :)
Comment: You need to give a _lot_ more detail than that. What webapp? What language is it written in? What system is it running on? **What have you tried?**
Comment: Hi @terdon :) I updated the post for your answers. Thanks in advance!
Answer: Thanks to the kindness of a developer, I can give some information to my questions.
I can't read / write a local file; I can only use W3C supported content storage mechanisms or Web SQL or Indexed DB.
Best regards!


let $x_1, x_2 ,x_3$ be 3 points on the unit circle in the plane. Then there must exist atleast one pair for which $||x_i + x_j||$ $\geq 1$.

Question: let $x_1, x_2 ,x_3$ be 3 points on the unit circle in the plane. Then there must exist at least one pair for which $||x_i + x_j||$ $\geq 1$.
I tried doing this but nothing interesting came up
Can anyone give me a hint on this
Answer: Remember $||x_i+x_j||^2 = 2+2<x_i, x_j> = 2+2\cos(\alpha)$, where $\alpha$ is the angle between the unit vectors $x_,x_j$. Thus, if you want $||x_i+x_j||^2\geq 1$, then you want that angle $\alpha$ to be at most $\dfrac{2\pi}{3}.$ Now a basic pigeon-hole principle finishes the problem.


How to save the new order of a reordered list locally? (Javascript/Jquery--Not Sortable Plugin)

Question: I have an in progress fiddle saved here (that you can see I've edited a painfully many number of times trying to figure this out): http://jsfiddle.net/JsJs2/182/
I have a basic set of html I've been working with to test this:

Hello

World

Whats

Going

Down?

Undo

The idea is to randomly sort this list on a user's first visit to the page only. Then anytime they return to this page within the set time, they will see the list sorted exactly as it was when they first visited the page (the same order as that first random sort). Here is the script I've been working on:
//var orig = $("#inventoryBlock").children(".list_bg");
$(document).ready(function () {
    var now = (new Date()).getTime();
    var lastTime = 0;
    var lastTimeStr = localStorage["lastTime"];
    if (lastTimeStr) lastTime = parseInt(lastTimeStr, 10);
    if (now - lastTime > 1 * 60 * 1000) {
        reorder();
    } else {
        $("#inventoryBlock").html(elements);
    }
    localStorage["lastTime"] = "" + now;
});
//function 'reorder' is declared
function reorder() {
    //variable 'grp' is defined as the .list_bg elements
    //variable 'grp' is an empty jquery object, not an array--an array has '[]' in the variable
    var grp = $("#inventoryBlock").children();

    //variable 'cnt' is defined as the number of .list_bg elements
    var cnt = grp.length;

    //variables 'temp' and 'x' are declared
    var temp, x;
    //variable 'i' is declared and defined as 0, a loop is initiated to continue until the value of 'i' is no longer less than the value of 'cnt'

    // While there remain elements to shuffle...
    for (var i = 0; i < cnt; i++) {
        //the 'temp' variable is defined as the current .list_bg item, assigned an order, and set as an array value using the associated 'i' value

        // Pick a remaining element...
        //temporaryValue = array[currentIndex]
        temp = grp[i];
        //the 'x' value is assigned randomly based on the 'cnt' value (use javascript random function)
        x = Math.floor(Math.random() * cnt);

        // And swap it with the current element.
        //array[currentIndex] = array[randomIndex];
        grp[i] = grp[x];
        //array[randomIndex] = temporaryValue;
        grp[x] = temp;
    }
    //returns empty jquery object
    //removes original object
    $(grp).remove();
    //appends new object/replacement object
    $("#inventoryBlock").append($(grp));
    console.log($(grp).get());
    var elements = $('#inventoryBlock').find('.list_bg');
}

function orderPosts() {
    $("#inventoryBlock").html(orig);
}

$("#undo").click(function (e) {
    e.preventDefault();
    orderPosts();
});

The bottom function orderPosts() is not really relevant here, and the echo div I was trying to use to echo values so I could better figure out what to do. The inventoryBlock is the only div that matters. The whole idea is to save the list order to data after that first page visit, and to load that data when they revisit the page within that set time period. I'm stuck on how to achieve this. I've tried too many suggestions to even recount, have tried commenting and recommenting the code so that I could figure it out step by step. I'm just missing something. Could someone point me in the right direction?
Comment: What is expected value of `orig` ? `orig` appear `undefined` at http://jsfiddle.net/JsJs2/182/ `console` ?
Comment: Sorry I should have been clearer. That's related to the orderPosts() function and was previously defined on the fiddle. I just hadn't removed it.
Answer: It looks like you are only putting the timestamp in localStorage. I think you need to put the shuffled order in localStorage too.
// Remember this for the "undo" button.
var origHtml = $("#inventoryBlock").html();

$(document).ready(function () {
    var now = (new Date()).getTime();
    var doReorder = true;

    var lastTimeStr = localStorage["lastTime"];
    if (lastTimeStr) {
        var lastTime = parseInt(lastTimeStr, 10);
        if (now - lastTime <= 1 * 60 * 1000) {
            // It hasn't been a minute, so use the stored order.
            $("#inventoryBlock").html(localStorage["html"]);
            doReorder = false;
        }
    }

    if (doReorder) {
        reorder();
        localStorage["lastTime"] = "" + now;
        localStorage["html"] = $("#inventoryBlock").html();
    }
});

$("#undo").click(function (e) {
    e.preventDefault();
    localStorage["lastTime"] = "";
    localStorage["html"] = "";
    $("#inventoryBlock").html(origHtml);
});

jsfiddle
Comment: Thank you so much for taking a look and providing a fiddle. I don't know how I couldn't see that. Works a treat--thank you!


Android uncaught exception

Question: i installed my app in a tablet and it works but when i tried to install my app in my phone this errors shows up in the logcat and i don't know what causes it, anyone encountered this?
<code>01-03 13:38:12.657: W/dalvikvm(2719): threadid=3: thread exiting with uncaught exception (group=0x4001e170)
01-03 13:38:12.657: E/AndroidRuntime(2719): Uncaught handler: thread main exiting due to uncaught exception
01-03 13:38:12.767: E/AndroidRuntime(2719): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.traininghandouts.app/com.traininghandouts.app.Login}: android.view.InflateException: Binary XML file line #48: Error inflating class <unknown>
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.app.ActivityThread.access$2200(ActivityThread.java:119)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.os.Looper.loop(Looper.java:123)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.app.ActivityThread.main(ActivityThread.java:4363)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at java.lang.reflect.Method.invokeNative(Native Method)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at java.lang.reflect.Method.invoke(Method.java:521)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at dalvik.system.NativeStart.main(Native Method)
01-03 13:38:12.767: E/AndroidRuntime(2719): Caused by: android.view.InflateException: Binary XML file line #48: Error inflating class <unknown>
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.view.LayoutInflater.createView(LayoutInflater.java:513)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:618)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.view.LayoutInflater.inflate(LayoutInflater.java:407)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:198)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.app.Activity.setContentView(Activity.java:1622)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at com.traininghandouts.app.Login.onCreate(Login.java:74)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
01-03 13:38:12.767: E/AndroidRuntime(2719):     ... 11 more
01-03 13:38:12.767: E/AndroidRuntime(2719): Caused by: java.lang.reflect.InvocationTargetException
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.widget.ImageView.<init>(ImageView.java:105)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at java.lang.reflect.Constructor.constructNative(Native Method)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at java.lang.reflect.Constructor.newInstance(Constructor.java:446)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.view.LayoutInflater.createView(LayoutInflater.java:500)
01-03 13:38:12.767: E/AndroidRuntime(2719):     ... 22 more
01-03 13:38:12.767: E/AndroidRuntime(2719): Caused by: java.lang.StackOverflowError
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.content.res.AssetManager.getResourceValue(AssetManager.java:186)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.content.res.Resources.getValue(Resources.java:887)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.content.res.Resources.getDrawable(Resources.java:579)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.graphics.drawable.StateListDrawable.inflate(StateListDrawable.java:160)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:788)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.graphics.drawable.Drawable.createFromXml(Drawable.java:729)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.content.res.Resources.loadDrawable(Resources.java:1690)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.content.res.Resources.getDrawable(Resources.java:580)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.graphics.drawable.StateListDrawable.inflate(StateListDrawable.java:160)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:788)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.graphics.drawable.Drawable.createFromXml(Drawable.java:729)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.content.res.Resources.loadDrawable(Resources.java:1690)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.content.res.Resources.getDrawable(Resources.java:580)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.graphics.drawable.StateListDrawable.inflate(StateListDrawable.java:160)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:788)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.graphics.drawable.Drawable.createFromXml(Drawable.java:729)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.content.res.Resources.loadDrawable(Resources.java:1690)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.content.res.Resources.getDrawable(Resources.java:580)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.graphics.drawable.StateListDrawable.inflate(StateListDrawable.java:160)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:788)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.graphics.drawable.Drawable.createFromXml(Drawable.java:729)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.content.res.Resources.loadDrawable(Resources.java:1690)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.content.res.Resources.getDrawable(Resources.java:580)
01-03 13:38:12.767: E/AndroidRuntime(2719):     at android.graphics.drawable.StateListDrawable.inflate(S
</code>
what should i do to fix this?
Comment: i think problem with API that you have used in your app. which API you are using in your app. ? if some of classes included later version of SDK and you are trying to used that in lower version of SDK. I am not sure but you can change the API that is compatible with you phone and check error if any.
Comment: android:minsdkversion="4" built="8"
Comment: i tried to install the app before, and it runs well it's just that now it doesn't work and force closes, shows this errors
Answer: Two traces, 1) XML Inflater 2) Stackoverflow suggesting, you have too many nested views in your app (which is not well supported by android). Please see this discussion for more details.stackoverflow error
You may need to reconsider your view group hierarchy.
Comment: i'm kinda new to android and i'm kinda lost there

Android uncaught exception


Don't handle pan gesture on superview when touchdown button (subview)

Question: I have a view(superview) which I can move by pan gesture, This view has subview(UIButton) with TouchDown Event. But when I press button(touchdown event handled) and continue move finger my superview start handling pan gesture method.
How disable handling pan gesture method of superview when I touchdown its subview?
Answer: for disabling touch events on UIView's subviews you can add this extension to UIViewController:
extension UIViewController:UIGestureRecognizerDelegate {
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        view.addGestureRecognizer(tap)
        tap.delegate = self
    }

    func dismissKeyboard() {
        view.endEditing(true)
    }
    public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
       if (touch.view!.isDescendantOfView(self.view) && touch.view != self.view){
            return false
        }
        return true
    }
}


how to get LIKE clause to work in ADO.NET and SQL Server

Question: I am doing a really simple query in ASP.NET, but after I inserted the LIKE clause it stops working.
Example:
String sql = " SELECT *
                 FROM Products
                WHERE ID = @MYID
                  AND Name LIKE '%@MYNAME%' ";
SqlCommand command = new SqlCommand(sql, cn);

command.Parameters.AddWithValue("@MYID", MYID.Text);

command.Parameters.AddWithValue("@MYNAME", MYNAME.Text);

If I removed the LIKE it works. Hence I am thinking its to do with the '' quotes?
Comment: sorry, i had to edit the question. it returned 0 result even though in @MYNAME i supplied the correct partial string
Answer: The original code is confusing the text of the SQL statement with the content of the parameter.  Your code should actually look like this:
string sql = "SELECT *
              FROM Products
              WHERE ID = @MyID
              AND Name LIKE @MyName";
using (SqlCommand command = new SqlCommand(sql, cn))
{
    command.Parameters.AddWithValue("@MyID", MyID.Text);
    command.Parameters.AddWithValue("@MyName", "%" + MyName.Text + "%");
    // Etc.
}

The % signs need to be part of the parameter value, and you don't need the single quotes at all when using binding parameters.
Comment: This won't work correctly when the MyName.Text contains the characters % _ or [, assuming you want to actually search for one of those charater literals. For a 100% solution, you need to wrap those characters in square brackets []. The C# code `Regex.Replace(searchString, @"([%_\[])", @"[$1]")` does the trick. Thanks to Matt Miller for pointing this out [here](http://stackoverflow.com/questions/665129/use-of-sqlparameter-in-sql-like-clause-not-working).
Answer: Just a note to say that using LIKE with an initial wildcard is almost always a very bad idea, because the query won't use any indexes on that column.  In this case you can probably get away with because it looks like the filter on the ID column will limit you to one record, but generally what you need to do instead is put a full-text index on the name column and write the query like this:
... WHERE CONTAINS(name, @MyName)

Comment: True as long as the text you're searching for is a full word (or words) or the beginning of a word.  If you're searching for text in the middle of or at the end of a word, you unfortunately still need to use `LIKE %s%`.
Answer: Or
 String sql = " SELECT * FROM Products WHERE ID = @MYID AND Name LIKE @MYNAME ";

and when you set the @MYNAME parameter, add the "%" characters appropriately (%SMITH%). I don't think you need the single quotes when you're dealing with parameters.
Answer: Don't think that using a bind parameter is like inserting it's value into the SQL string! Bind parameter values are sent as separate data to the DB, so they mustn't be in quotes, and neither can they contain any optional SQL code, table or column names!
Answer: you are missing the % sign while passing parameter value
command.Parameters.AddWithValue("@MYNAME"+"%", MYNAME.Text);

Comment: Not correct, the parameter name has no bearing on the LIKE pattern. That should be a applied to the parameter value.
Answer: The sql statement should look like this:
String sql = " SELECT * FROM Products WHERE ID = @MYID AND Name LIKE '%' + @MYNAME + '%'";

I am not sure I understood your comment completely, but it seems you want to use the value from a text box in your query - maybe this is what you are trying to do:
String sql = " SELECT * FROM Products WHERE ID = @MYID AND Name LIKE '%' + text_box.Text + '%'";

"text_box" would be the actual id of your textBox control.
Comment: SQL string concatenation of values is WRONG (even if it works): bad performance due to no query plan reuse, SQL injection risk, as already said.
Comment: that didn't work :( i tried it and print out the sql see below:

AND NAME LIKE '%System.Web.UI.WebControls.TextBox%'
Comment: SQL Injection possible


Plumbing water pressure

Question: I turned off water supply to house to replace shower cartridge.  Water off for three or so hours.  Turned water back on and "flushed" the lines.  A few days later, turned on pool filler and got low pressure and almost no pressure everywhere else in house during fillup.  HELP!
Comment: Did the pressure go back to normal if you turn off pool filler?
Answer: Pool filler is leaking somewhere. I know the cartridge replacement seems suspect, but I believe that's just a coincidence.

Plumbing water pressure


Glassfish or Tomcat+OpenEJB? Which variant is better for a small application?

Question: I have a small Java2EE application, which is planning to grow in time (not very soon). Now I'm trying to select the optimal free open-source production environment for it. I have two variants so far:

GlassFish v3
Tomcat + OpenEJB

The second variants looks more lightweight for me, moreover I use embedded OpenEJB for automated testing. What would you recommend for me? Am I going the right way?
Comment: @David Thanks, I already migrated to Tomcat/OpenEJB, with a big pleasure
Comment: Just a note that there are plans to Java EE 6 Web Profile certify the OpenEJB/Tomcat stack.  It should successfully grow with you.
Answer: Tomcat + Spring. Just skip the EJBs. It will save you some development time, because you won't have to deploy your code to the app server in order to run tests.
Comment: I don't deploy my code to the AS in order to run tests, I use [embedded OpenEJB](http://openejb.apache.org/3.0/embedded-configuration.html) (as I said in my question).
Comment: Guess I should have shown you more OpenEJB stuff at JavaOne a year or two ago instead of just having beers :)  Here's a demo if you're interested in the testing stuff  http://vimeo.com/6149008
Comment: Dave, I know about it and it is nice. :) However developer have to assemble the stack from pieces EJB implementation, JPA implementation, tx manager, jms, and other components of J2EE stack. Also, to me Spring has richer model for components and the life cycle, so there is no benefits of using EJB anymore.
Answer: It turned out that Tomcat+OpenEJB (with OpenJPA) is much easy-to-configure variant than GlassFish. Especially in a test-intensive project, like mine.


Method is not defined in other class

Question: Because I want to call the setState Method in the class "EditProfilePage", I had to change it to a statefulWidget:
class EditProfilePage extends StatefulWidget {

  @override
  _EditProfilePageState createState() => _EditProfilePageState();

}

class _EditProfilePageState extends State<EditProfilePage> {

  TextEditingController nameController = new TextEditingController();
  TextEditingController bioController = new TextEditingController();
   File file;

       .
       .
       .

     applyChanges() {
    Firestore.instance
        .collection('insta_users')
        .document(currentUserModel.id)
        .updateData({
      "displayName": nameController.text,
      "bio": bioController.text

    });
  }
 }

But now, my class 'Profile_page' seems to miss the method "applyChanges()" of "EditProfilePage" and throws following error:

The method 'applyChanges' isn't defined for the class
  'EditProfilePage'.

Here is the method in 'Profile_Page', which calls applyChanges() from 'EditProfilePage':
editProfile() {
    EditProfilePage editPage = new EditProfilePage();

    Navigator.of(context)
        .push(new MaterialPageRoute<bool>(builder: (BuildContext context) {
      return new Center(
        child: new Scaffold(
            appBar: new AppBar(
              leading: new IconButton(
                icon: new Icon(Icons.close),
                onPressed: () {
                  Navigator.maybePop(context);
                },
              ),
              title: new Text('Edit Profile',
                  style: new TextStyle(
                      color: Colors.black, fontWeight: FontWeight.bold)),
              elevation: 1.0,
              backgroundColor: Colors.white,
              actions: <Widget>[
                new IconButton(
                    icon: new Icon(
                      Icons.check,
                      color: Colors.blueAccent,
                    ),
                    onPressed: () {
                      editPage.applyChanges();
                      Navigator.maybePop(context);
                    })

Any suggestions on how to fix this problem? I did not forget to import.
Btw I am very new to flutter and just trying to understand dart. Best Regards!
Comment: Possible duplicate of [call method in one stateful widget from another stateful widget - Flutter](https://stackoverflow.com/questions/51029655/call-method-in-one-stateful-widget-from-another-stateful-widget-flutter)
Answer: You should make significant change to your EditProfilePage structure by moving the applyChanges function away from _EditProfilePageState class:
   class EditProfilePage extends StatefulWidget {

   @override
   _EditProfilePageState createState() => _EditProfilePageState();

     static void applyChanges(TextEditingController nameController, TextEditingController bioController) {
      Firestore.instance.collection('insta_users').document(currentUserModel.id).updateData({
      "displayName": nameController.text,
      "bio": bioController.text
      });
     }

   }

Then call applyChanges() function from inside the function editProfile() :
  EditProfilePage.applyChanges(nameController, bioController);

But you have to make your TextEditingController objects which contain the name and bio visible to the context you are calling from. One way I would suggest is to make them global by defining them under the import section of your code which will enable any inner class to use them.

Method is not defined in other class


How does military technology affect my army?

Question: If my capital province has military technology III, my other province has level II and my vassal has first level and I summon every soldier from these provinces,

will each unit have different bonuses, depending on their provinces' tech, or
will they all have level III bonuses, because of my capital tech?
Comment: I believe attack/defence are based on provence tech, morale is based on capital tech. Need to check this.
Answer: Units will use the technology of their province, bear in mind that 'Counts' do not generate technology points which means it is 'Dukes' and above (this will be the Duke's Capital) that will affect the ability of units in that province.
A tactic often used to help spread technology is to focus on your 'Capital' and then use your 'Spymaster' to research technology from a high-tech hub - such as Constantinople - then using your councillors to spread the pressure of technology from your Capital to neighbouring provinces / Duchies. Doing this will help both your other provinces and vassals in terms of tech and thus allowing them to achieve higher tech bonuses.
Another important note worth mentioning is that tech will spread to all neighbouring provinces, regardless of the fact they might be in a different country, in effect this means that if your capital is bordering another countries provinces then you will be in effect increasing their tech. This is why it is usually a good idea to have your capital positioned in a fairly central position within your empire.


Creating an application registration to access Azure REST API under enterprise agreement

Question: Sorry if this is off-topic but I haven't been able to find any information on it anywhere else. I'm trying to create an application registration that will allow a batch process to access the Azure REST API on my behalf.
Normally, this is pretty simple: just create the user, give it API permissions to what you need, add a secret and then insert the tenant ID, application ID and secret into a request against the /token endpoint, as described here.
I have done that and gotten the access token but, when I try to get all the billing accounts associated with the enterprise agreement, by calling https://management.azure.com/providers/Microsoft.Billing/billingAccounts?api-version=2020-05-01 I get no information back. Also, when I try to access a particular billing account back, by calling https://management.azure.com/providers/Microsoft.Billing/billingAccounts/{account_id}?api-version=2020-05-01, I get the following error and a 403 response code:
{
    "error": {
        "code": "Forbidden",
        "message": "User is not authorized to access billing account '{account_id}'."
    }
}

So, essentially the application user was created from an enterprise agreement account but can't access enterprise agreement resources from the API. What's going on here?
Answer: The application registration should have any of the below roles to access the billing accounts information:

Service Administrator
Co-administrator
Owner
Contributor
Reader
Billing reader

You can assign any of the above roles from the Access Control (IAM) to the application registration
Comment: The user needs to have access to create an app registration. The app registration needs to be created in your active directory which is associated with your subscription
Comment: You can associate the application registration to multiple subscriptions. In the each subscription, you can assign any of the above roles to this application registration
Comment: check if this helps: https://learn.microsoft.com/en-us/azure/cost-management-billing/manage/assign-roles-azure-service-principals
Comment: That is very helpful but does the user who creates the application registration need to have any particular role? Does the user have to create the registration in a particular directory? Can this operation be done from the Azure Portal or is the EA Portal necessary as well?
Comment: Right, but I need the registration to have access to all subscriptions under the EA billing account. So, which subscription do I associate it with?
Comment: Interesting. I wasn't aware of that. Do you have any relevant Microsoft documentation for this?


asp.net mvc4 get user information when user reload page

Question: I created custom login which use FormAuthentication. When user use login page, I get user information and save to session variable. If user check remember password, after user close page and reopen, authentication of user is authenticated, in this case, I can not get information of user.
How do I retrieve information of user in this case
Answer: Use cookies to store user id or something unique. Then get it and query database for example.
Answer: My solution:
After the user log, I create random TOKEN key, save it into DB to specific user, and add to Respone Cookie (the lifetime of the cookie, you can specify the desired).
Then, when user come again, I get cookie and check it value. If everything is correct, install the session variables.


WCF - how to receive plain string?

Question: I have WCF service that I use with JSON.
Now I need to receive plain message (headers + text)
So, I expect to get string in fileContents but service fails because it's not JSON-encoded.
How do I code my method to allow for that?
This is my method
[WebInvoke(Method = "POST", UriTemplate = "/files/{fileName}")]
        public void UploadFile(string fileName, string fileContents)
        {

        }

And this is my service:
[ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class MobileService
    {

Answer: If you want to receive "raw" data, you need to receive the input (fileContents) as a System.IO.Stream. Take a look at the post at http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data.aspx for more information.

WCF - how to receive plain string?


How to create Matrix from 3 coordinate arrays in Matlab/R?

Question: This is old problem but yet I am not able to fix this issue in my code.
I have 3 arrays:
x, y, z each are column vectors of size N. x, y are coordinates data and z is the value measured at each point. Now what I want is to have a matrix of N by N corresponding to the value of each point.
This is the sample data [x y z]:
1467713 599153  17.91
1468244 599296  17.91
1468776 599439  61.90
1469307 599582  17.91
1469838 599725  17.91
1470369 599868  38.23
1470900 600011  17.91
1471431 600154  43.41
1471962 600296  23.73
1472493 600439  21.80
1473024 600582  17.91
1473556 600725  17.91
1474087 600868  23.95
1474618 601011  17.91
1475149 601154  60.15
1475680 601297  17.91
1476211 601440  94.47
1476742 601583  37.72
1477273 601725  17.91

P.s. my data is unorganized collection of of lat longs.
Answer: I believe the (Matlab) solution that you are looking for may be:
H = NaN(max(x),max(y))
for i = 1:length(x)
   H(x(i),y(i)) = z(i)
end

I used NaN so that the matrix between measured points would be 'empty'. You can ofcourse also initialize with something like zeros.
Comment: thanks for your reply but why max(x),max(y)? Can you elaborate?
Comment: Suppose I make it 10x10, and one point is located at (11,1), then that point will not fit in the matrix when I try to assign it.
Note that if you think the field is too big, you can cut off the unused parts afterwards or reduce all `x` and `y` coordinates with `min(x)-1` and `min(y)-1` respectively.
Comment: OK,I have a problem here. the size of each one of my column arrays are 6,581. when I run your code, it gives me error on Out of Memory.
Comment: @Amir Assuming your coordinates do not start at zero, it should be solved by adjusting the x and y coordinates as I described in my previous comment. If you do not care about NaN, then it is more easily solved by initializing like so: `H = sparse(max(x),max(y))`
Answer: A vectorized alternative:
m = max(x);
n = max(y);
ind = sub2ind([m,n], x, y);
I(ind) = z;

You could also initialize I as in Dennis' answer if you prefer NaN to 0 for the missing pixels.


How can I get the mouse wheel vertical scroll rate

Question: I'm currently developping a custom control, and, to implement vertical scrolling, I want to be able to fetch the configured vertical scroll rate (described here).
I would use this setting to move the control by [X] number of lines.
Answer: You can get it from SystemParametersInfo function with SPI_GETWHEELSCROLLLINES.

Retrieves the number of lines to scroll when the vertical mouse wheel
  is moved. The pvParam parameter must point to a UINT variable that
  receives the number of lines. The default value is 3.
Comment: C# equivalent (because this is also tagged): `System.Windows.Forms.SystemInformation.MouseWheelScrollLines` (https://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.mousewheelscrolllines%28v=vs.110%29.aspx)


Empty Steam window on OS X

Question: Registered on steampowered.com.
Downloaded the steam app, when starting it, just an empty app shows up :

When trying to run the /Applications/Steam.app/Contents/MacOS/steam_osx manually here's the output :
[2016-12-26 14:55:08] Verifying installation...
[2016-12-26 14:55:08] Verification complete
CHIDDeviceListSDL(): Couldn't load libSDL2-2.0.0.dylib, not enumerating devices
Errors in public/subpanelwelcomeintro.res:
error loading file 'public/subpanelwelcomeintro.res', no such file
Errors in public/subpanelwelcomecreatenewaccount.res:
error loading file 'public/subpanelwelcomecreatenewaccount.res', no such file
Errors in public/subpanelwelcomecreatenewaccountaccountname.res:
error loading file 'public/subpanelwelcomecreatenewaccountaccountname.res', no such file
Errors in public/subpanelwelcomecreatenewaccountemail.res:
error loading file 'public/subpanelwelcomecreatenewaccountemail.res', no such file
Errors in public/subpanelwelcomecreatenewaccountnamecollision.res:
error loading file 'public/subpanelwelcomecreatenewaccountnamecollision.res', no such file
Errors in public/subpanelwelcomecreatingaccount.res:
error loading file 'public/subpanelwelcomecreatingaccount.res', no such file
[2016-12-26 14:55:09] Background update loop checking for update. . .
[2016-12-26 14:55:09] Checking for available updates...
Errors in public/subpanelwelcomecreatenewaccountprintdetails.res:
error loading file 'public/subpanelwelcomecreatenewaccountprintdetails.res', no such file

OS X El Capitan 10.11.6
Comment: Not posting as an answer, because I don't have a Mac to test such a thing - however, I found this issue (here, on the Steam forums)[https://steamcommunity.com/discussions/forum/2/350542145699765724/], with a possible solution.  You will need to type some commands into the Terminal in order to resolve the issue.  (Or just perform the changes manually)
Answer: This one worked http://steamcommunity.com/discussions/forum/2/282992646978253149/
Basically all Steam files from
~/Library/Application\ Support/Steam/Steam.AppBundle/Steam/Contents/MacOS must be renamed to lowercase.
Execute that :

ls | while read line ; do file=$(echo $line | tr '[:upper:]' '[:lower:]'); mv $line $file; done

in all of these folders : public, steam/cached, friends, graphics, servers (relative to the folder specified above.)

Empty Steam window on OS X


How to Overlay Fragment over another with swipe-in/out

Question: In Android (22+), I'm looking for a library or a 'tried & tested approach' to give the setup that allows an app to overlay 1 fragment on top of another that and would also provide gesture drag in/out along with peeking behind(see animation below)?
Criteria;

library to animate the swipe-in/out
handles the darkening the background fragment the further you drag in
the overlay fragment is there to provide context information to the user)

Further to @Rainmakers suggestions, I have a 'nearly working' approach were that I have an overlay fragment that is added to the top of the fragment stack; were then I have applied a touch gesture on the overlay fragment to dismiss on a left->right swipe capture. This Works and looks ok and 'will do' but would like the peek behind the feature that is shown in the animated GIF.
This animation was taken from the google drive android app;
Answer: If you're eager to use a library then check this out FragmentTransactionExtended. It has different slides.
Then you just override the onTouchEvent() method (check how to do it link) and do fragment transactions when swipe is caught. If you use add in the transaction you won't dispose the fragment underneath.
And the part with darkening you should also manage it in onTouchEvent(). See this to make your fragment grey out.
Comment: Thanks; i'll check out the library - will the onTouchEvent() approach give me the swipe animation when my finger 'drags' the on-top fragment in/out of view ??
Comment: the library will give you the animation, and onTouchEvent will detect when you should start the transaction with animation. And the grey out is just the additional trick you can add


Ubuntu 13.10/Gnome shell keeps asking me for my e-mail accounts passwords but says they are wrong. How can I fix this?

Question: Ubuntu 13.10/Gnome shell keeps asking me for my e-mail accounts passwords but says they are wrong.
After login, in gnome shell, it asks for my two email accounts passwords. When I insert them it tells me they're wrong. I cancel and a bit after it asks me again. Over and over.
I think this has something to do with the evolution gnome-shell extension but I can fix it.
Answer: Try this.
Go to the shell/terminal
<code>$ cd .config
$ cd goa-1.0
$ mv accounts.conf ../../Desktop
</code>
Let me know if that works for you.
Jon
Answer: I took a similar approach (to jelofson) - see Why does ubuntu 13.10 keep asking for my gmail password? Still don't know what the problem is though, his answer suggests it's a bug in goa-1.0


Asp.net core Chrome Issue with Cookies

Question: I have a strange issue, we are running a asp.net core razor app.
There are no issues logging into Firefox or Edge.
But rather randomly, we have an issue in Chrome that we can't figure out.
(Random as in, it has occurred on user's machines randomly before and now it is occurring on a lot of machines, but still not all of them)
The issue is that it seems that our "auth-token" cookie is not being set.
To me, it seems that the error is with this line which runs after a successful username and password, but before a redirect.
...
Response.Cookies.Append("auth-token", inToken, option);
...

There is no error, but a line that runs almost immediately after falls over
public async Task Invoke(HttpContext context)
{
    var name = "auth-token";
    var cookie = context.Request.Cookies[name]; //THIS LINE DOESN'T HAVE THE COOKIE CALLED "auth-token" IN CHROME
    ...
}

We have tried:
Incognito Chrome/Clearing Cache/Cookies in Chrome

Restarting Machine
Uninstalling and Reinstalling chrome
Installing old versions of Chrome (chromium)
Running an old version of our code (which previously worked on chrome)

There doesn't seem to be a clear cause for when this issue occurs.
I would love to figure out why this is happening or if possible any information on how I could capture what is happening.
Thank you!
Comment: I've just realized, I ran into the similar issue: cookie is not accepted by Chrome in my razor pages net.core 3.1 anymore. It was all good but now cookie dialog closes and opens again after page reload. No issues with Edge. Have not yet dig deeper.
Comment: Yeah I can find alot of information on chrome, cookies and their implementation withing .net core 3.1. But nothing that clearly addresses this issue.
Comment: Have you tried with 2.1? 2.1 is working fine for me, probably I have some migration issue, will see.
Comment: Our older version of the code was running 2.2 and it was working.
But after spending a while trawling the internet I figure out my issue.
I will post it in a sec, but my solution still doesn't explain why it wouldn't work with 3.1... I am puzzled!
Answer: After many hours researching it seems I have finally fixed my issue.
By setting the following in our cookie
SameSite = SameSiteMode.Lax

or
SameSite = SameSiteMode.Strict

Our Chrome issues have been fixed
I was reading about Google Chrome's "SameSite" cookie options.
https://www.chromium.org/updates/same-site
Originally I thought this was unrelated as SameSite has been forced in Chrome for quite a wile now, and it has never bothered our code. But I still tried setting:
SameSite = SameSiteMode.None

To no changes
After bringing this up to my boss he informed me that he noticed an old warning that appeared in the chrome console for <1 second.

'A cookie associated with a resource at ... was set with
'SameSite=None' but without 'Secure'. It has been blocked....'

(Note: This was before I tried messing around with SameSite Options at all and was part of some code to fix a Safari bug)
So naturally we managed to capture the error with a quick screenshot and then we added in the SameSite option with Strict.
So I while it works for me now it still doesn't explain;

Why didn't it break earlier, we have been using versions of chrome with it for several months
Why does it still not break if I run an old version of the code with .net 2.1 (without any SameSite Options adjusted)
Why does our new version of the code without the adjusted SameSite option still work on some user's machines
Comment: Chrome has had the warning for a while, but has just recently implemented it. It expects a SameSite cookie now or it will block it and SameSite None must be secure. It could be that some of your users haven't updated to the newest chrome, or they have existing cookies that can still be used.
Note that SameSite.None isn't actually setting it to "None" at the moment (Pretty big bug with this change!), when None is required, modifying the Path to "/; SameSite=None" works.
Comment: Works for me but I am curious why my settings in web.config didn't apply here. My cookies where displaying as samesite lax but if I didn't explicitly set this in code behind it didn't work.
Comment: Ah right!
That seems to answer most of my queries around this.
I don't know why I was unable to find any of that online, but oh well.
Thanks a bunch!
Comment: Thanks a lot! Just tried in my project and it works! This saved me a lot of time! p.s. my previous version w. 2.1 is still working fine...
Comment: Yeah... I am very happy it is working now myself, but the fact that it seems to work/not work in certain situations still boggles the mind.If anyone can find why it works the way it does it would be nice to know!

Asp.net core Chrome Issue with Cookies


Break image out of column and let it span over both columns

Question: I have an image which I need to break out of the column and let it span over both columns (the template is using Bootstrap 4).
It should look like this
Unfortunately I won't be able to modify the html, so is this possible with CSS/JS only?
Here is my code:

.container {
  margin: 4rem auto;
}

img {
  max-width: 100%;
  height: auto;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

H2

                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Comment: https://stackoverflow.com/questions/28565976/css-how-to-overflow-from-div-to-full-width-of-screen?lq=1
Answer: These are things that could be easily handled using CSS.
All you need to do is :
 img {

    left: 50%;
    margin-left: -50vw;
    margin-right: -50vw;
    max-width: 84vw;
    position: relative;
    right: 50%;
    width: 100vw;
}

FULL WORKING CODE

.container {
  margin: 4rem auto;
}

img {
    left: 50%;
    margin-left: -50vw;
    margin-right: -50vw;
    max-width: 84vw;
    position: relative;
    right: 50%;
    width: 100vw;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

H2

                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Comment: Thanks, but the image should not be outside of the container div. It should stay inside and just span over both columns.
Comment: Have you tried putting the image in a span ? Please do try that and give a span a negative left-margin
Comment: I can move the image with a negative margin. Which would be the exact approach? margin-left: calc(-16.66667% - 30px) (minus width of col-2 minus the column-padding) doesn't seem correct.


What is the full form of an expressionless statement in javascript?

Question: There's a syntax that Javascript adopted from C where you can perform a logical check, without checking anything:
if (foo) {
}

What is this equivalent to? Is it:
if (foo != null) { }
if (foo !== null) { }
if (typeof(foo) != 'undefined') { }
if (typeof(foo) !== 'undefined') { }
if (typeof(foo) != 'object') { }
if (typeof(foo) !== 'Object') { }

My actual motivation for asking is wanting to ensure that a member "exists" (that is to say, if it is null or undefined then it doesn't exist):
if (window.devicePixelRatio !== null)
if (window.devicePixelRatio != null)
if (!(window.devicePixelRatio == null))
if (!(window.devicePixelRatio === null))
if (!(window.devicePixelRatio == undefined))
if (!(window.devicePixelRatio === undefined))
if ((window.devicePixelRatio !== undefined))

My concern is if the member is defined, but defined to be null, in which case (as far as i'm concerned) it's not assigned.
I know that the expressionless syntax returns true for a "truthy" value. I'm less interested in a "truthy" value, as an actual value.
Comment: Note that foo also returns false if it is defined and equal to `0`.
Comment: @Cristy In which case it is a valid value :)
Comment: @IanBoyd, it is valid but the `if` is not executed. `var foo = 0; if(foo) console.log(1)` will output nothing, so it is not equivalent with any of those.
Answer:
if (foo) {
}

"What is this equivalent to?"

It's not equivalent to any of the ones you suggested. It would be equivalent to:
if (Boolean(foo)) { }

or the same thing by using the ! operator:
if (!!foo) { }

or you could be explicit in your comparison if you really want.
if (!!foo === true) { }

"My actual motivation for asking is wanting to ensure that a member "exists"..."

To find if a member exists in an object, use the in operator.
if ("devicePixelRatio" in window) { }

"... (that is to say, if it is null or undefined then it doesn't exist):"

To check for not null or undefined, which is no the same as not existing, do this:
if (window.devicePixelRatio != null) { }

The != operator will perform both a null and undefined check at the same time. Any other value will meet the condition.
Comment: And we just got through being told that [`!=` should not be used](http://www.jshint.com/). *Le sigh*
Comment: @IanBoyd: Yeah, just like any feature, one should understand how it works and use it when appropriate. The semantics of `==` and `!=` can be a little confusing, but this is one particular case where it's very simple and helpful. Nothing is `== null` or `== undefined` except for `null` and `undefined`. You can configure jsHint to turn off that warning.


Applying filters on results of aggregation in elastic search

Question: I am stuck with a problem where I need to apply some filters on results of an aggregation in elastic search.
For example, assume that the following are the fields
event_name, location, time, user_id
Now my requirement is to get the user ids who have performed a specific action (lets say "logged_in") in the last one month atleast 5 times. I am able to get the users who have logged_in in the last one month. But how do I filter the results further?
The query I have written is:
{
   "query": {
      "filtered": {
         "filter": {
            "bool": {
                "must": [
                  {
                    "range":{
                       "time":{
                          "from": 1412312824,
                          "to": 1422142824
                        }
                     }
                  },
                  {
                     "term": {
                        "action": "logged_in"
                      }
                  }
               ]
            }
         }
      }
   },
   "aggs": {
      "result": {
         "terms": {
            "field": "user_id"
         }
      }
   }
}

Sample output:
user_id, doc_count
1          10
2          25
3           1
4           2

I need to apply filter on the above result. How do I do it?
Comment: you want only the user_id where doc_count is >= to 5 ?
Comment: doc_count >= 5 is just an example. Ideally I would like to apply any filter. Like range filter where I want the users who have done a specific action from 2 to 5 times.
Answer: I believe you can just add a min_doc_count key to your terms aggregation, like so:
...
"aggs": {
    "result": {
        "terms": {
            "field": "user_id",
            "min_doc_count": 5
        }
    }
}
...

Source: https://www.elastic.co/guide/en/elasticsearch/reference/1.6/search-aggregations-bucket-terms-aggregation.html#_minimum_document_count
Comment: I saw this. But the condition is general. Sometimes the query can also be like users who have done a specific action atmost n times. Like range filter where I want the users who have done a specific action from 2 to 5 times
Comment: I understand. Sounds like your issue is similar to https://github.com/elastic/elasticsearch/issues/4404, which if you scroll way way down recommends the `bucket_selector` aggregation (https://www.elastic.co/guide/en/elasticsearch/reference/master/search-aggregations-pipeline-bucket-selector-aggregation.html).
Comment: Seems too complex for my use case. Also not able to find about reducers in official guide. Anyways, thanks for the answer. Would like to know if there are any other ways to achieve this.


How to play against a friend with higher demographics?

Question: I'm starting to believe Civ 5 really makes this hard, as once you get behind in tech/GNP you will lose the ability to beat them.
The situation is this, I've started on a not too prosperous continent (other civs border-to-border) while my friend, the opponent, has started up on a much more free continent. He leads the demographics but not in an order of magnitude. I run at third on every demographic attribute. Are there any tips and tricks to become victorious in an unbalanced situation against a human player?
Comment: If you are that close to other civs, manage to take capitals, gaining good cities with, most probably, a few wonders.
Comment: You mean other than a sneak attack with 10+ siege units?
Answer: You've got just a couple of options, generally.
One is war.  War, war, war.  Crush your neighbors.  Hopefully you're not so far behind the AI that you can't overtake them.  The AIs are terrible at war (as I often mention) so just put siege units in your border cities with front-line troops between them and the enemy.  Declare war, let them throw themselves on your swords or what have you, and when they beg for mercy, take their stuff.  Lather, rinse, repeat.
I tend to puppet rather than annex, as that reduces the happiness hit.  You can also raze and build on their turf, although this works best for tiny cities that are well placed.  You'll also have to work fast if the  AI could potentially settle in the cleared area before you get the chance.
The other possibility is to go for a sneaky cultural win.  Cultural policies get harder to get the bigger you are.  However, this can be difficult to do, depending on how far behind you are and how small you are.  It's also harder in Civ5 than it was in Civ4, since your culture doesn't steal hexes in Civ5.  (Do note: If you're playing with BNW, you need tourism, which is a totally different subject...)
Most of the other options are stymied by the fact that either your size limits you, or the AI will start to work against you as you approach victory.
Answer: You have to press any technological or territorial advantage you can get. If your continent is rich in iron and your friend's continent is not, you can dominate the seas with frigates and try taking some coastal cities to contain him through the Renaissance and Industrial eras.
If you don't have iron, build up Privateers and coastal ranged units to repeal naval invasions. If you are on BNW, you could try going for Ironclads. These will crush any naval unit of the era, but will cost you coal which is relatively scarce. You could also rush to submarines. With enough submarines, you can keep him far away from your continent.
If you're really lucky and you have a lot more oil than your friend, then Battleships and Bombers will let you take the win.


Better way to do conditional-sum on df than for-loop?

Question: I am doing sum on dataframes with for loop. I know that normaly is not a good idea to loop in R and that it is a better way to do it using sapply or aggregate but I just don t see how to use it in my case .
I want to sum one column based on condition of two columns in an iterative way.
Here is what i want to do in a better way for you to understand:
sample  <- data.frame( ID = c("bli","bla","blou","qhq","bidi","bada","bodo"),
        A = c(1,0,1,1,0,1,1) ,
        B = c(0,1,1,0,0,1,0) ,
        C = c(0,1,1,0,0,1,1)

                  )

 g  <-  NULL
bli  <- 1:length(sample)
for (j in 2:length(sample)) {
  a <- sum(subset(sample,sample[,c(j) ] ==1 , c(j)))
  for (i in 2:length(sample))
    if (bli[j] != bli[i]) {
    b  <- sum(subset(sample,sample[,c(j)] ==1 & sample[,c(i) ] ==1 , c(i)))
    c <- names(sample[j])
    d <- names(sample[i])
    e  <- cbind(c,d,a,b)
    f  <- data.frame(e)
    g <-  rbind(g,f) }
  else {
    NULL
}

  }
g

Thanks
Comment: @akrun - I don't think `combn` will work here - `expand.grid` might be necessary.
Comment: @thelatemail The OP needs to remove the identical elements per row after the expand.grid
Answer: You could try expand.grid (suggested by @thelatemail).  The summary of the code below is:

Create an "index" of column names (i.e. "nm1") for which we need all the combinations
Try expand.grid of "nm1" on itself (expand.grid(nm1, nm1)).  The syntax list(nm1) is a bit general so that you can create multiple-way combinations by specifying the times in rep.
Remove the rows that are identical ("indx1")
Use sapply to loop over the rows of "indx1" and subset the "sample" dataset using based on the row index from the loop.
Do the sum based on the subset based on the first column of "indx1" and sum based on whether the elements are both "1" from the subset datasets (sum(x2[,1]&x2[,2]))
cbind the "indx1" with the transpose (t) of sapply and rename the columns of the output dataset.
nm1 <- names(sample)[-1]
indx <- expand.grid(rep(list(nm1),2),stringsAsFactors=FALSE)
indx <- indx[,2:1]
indx1 <- indx[indx[,1]!=indx[,2],]
row.names(indx1) <- NULL
res <-  cbind(indx1,t(sapply(seq_len(nrow(indx1)), function(i) {
                  x1 <-  unlist(indx1[i,])
                  x2 <- sample[,x1]
               c(sum(x2[,1]), sum(x2[,1]&x2[,2])) }))
 )
names(res) <- names(g)
res
#   c d a b
#1 A B 5 2
#2 A C 5 3
#3 B A 3 2
#4 B C 3 3
#5 C A 4 3
#6 C B 4 3

Or even without using sapply (would be faster), use colSums on both the subset datasets "i1", "i2".
 i1 <- sample[indx1[,1]]
 i2 <- sample[indx1[,2]]
 a <- colSums(i1)
 b <- colSums(i1 &i2)
 #in case you have more than two columns
 #b <- colSums(Reduce(`&`,list(i1, i2)))
 res1 <- cbind(setNames(indx1, c('c', 'd')), a, b)


Replacing garbage disposal w/ straight pipe. What to do with the wire?

Question: I'm removing a busted garbage disposal from under the sink and replacing it with straight pipe. I think I can manage this part of the job, but I don't know what to do with the wire. I mean the wire that was hardwired to the garbage disposal. It comes out of a hole in the back of the under-sink cabinet.
Thanks for any help,
Derek
Comment: Hello, and welcome to Home Improvement. My guess is you should add a retrofit junction box to terminate the wire; let's see what one of our pros say. And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know the details of contributing here.
Comment: Is it literally a hole? Or is it a Junction box?
Answer: Just terminate it in a junction box with a blank cover
Simply attach a junction box (a "handy box" with the appropriate cable clamp will do) to a nearby piece of cabinet frame, then terminate the cable into the box via the cableclamp, land the bare wire on the ground screw in the box, and terminate the remaining wires individually with wirenuts.  Finish this off with a blank box cover, turn the circuit back on, and you're done!
Comment: And if you want to be really nice to the next owner (or to yourself if you decide you want a garbage disposal or a dishwasher or an instant-hot on the circuit), label the blank plate with the current circuit breaker #.


Catching an Array from AngularJs using laravel Contoller

Question: Hi I am new to Laravel and Angularjs I am trying to send an array from angularjs to laravel controller i am not getting any errors but I have problem catching data in laravel controller and using the data
Here the Angular code
 $scope.sendSetField = function (selected_list) {
        var arr = [];
        angular.forEach(selected_list, function(value, key){
            arr.push(key);
        });
        console.log(arr);
        $http.post("http://localhost/maxo_ats_v1.00/dashboard/jobsDownload",
         arr).then(function (d̶a̶t̶a̶,̶ ̶s̶t̶a̶t̶u̶s̶,̶ ̶h̶e̶a̶d̶e̶r̶s̶,̶ ̶c̶o̶n̶f̶i̶g̶ response) {
         alert("success");
        },function (d̶a̶t̶a̶,̶ ̶s̶t̶a̶t̶u̶s̶,̶ ̶h̶e̶a̶d̶e̶r̶s̶,̶ ̶c̶o̶n̶f̶i̶g̶ response) {
            alert("error");
        });
   };

I can able to print the data in console successfully.But failing to print data using laravel controller
My controller
 public function downloadJobsList(Request $request)
 {
    $jobs = request('arr');
    dd($jobs);
 }

Route:
Route::post('dashboard/jobsDownload','JobsController@downloadJobsList');

Comment: Use a `var_dump("Start")` at the start of method to check if its reaching the controller.
Comment: nothing happening
Comment: There could me multiple issues here, could be CORS or something in the middleware. Are angularjs and laravel on the same domain?
Comment: yes i same domain
Comment: $jobs = Input::all(); solved my issue and @Sajal suggestions too thanks
Answer: The route should look like this:
Route::group(['prefix' => 'maxo_ats_v1.00'], function () {
   Route::post('/dashboard/jobsDownload','JobsController@downloadJobsList');
   //Other Routes
});

Also, make sure you have a / either in front of individual routes such as /dashboard/jobsDownload or after the route prefix.
Comment: My bad, missed a `]` after the prefix. See the updated answer.
Comment: i added   $jobs = Input::all(); and it worked and your routes too thanks.
Comment: Hi Sajal i got another issue can u help
Comment: Sure, what is the problem?
Comment: public function downloadJobsList(Request $request)
     {
       // $jobs = CnfFormField::select('id', 'name', 'email', 'created_at')->get();

      $jobs = Input::all();
     // return view('jobs.columnSelect',compact['data']);
      $data = Jobs::select($jobs)->get();

        Excel::create('Job', function($excel) use ($data) {
            $excel->sheet('mySheet', function($sheet) use ($data)
            {
                $sheet->fromArray($data);
            });
         })->download('xlsx');

     }
Comment: check this code file not getting downloaded instead getting some response to angular
Comment: Sajal r u there
Comment: Code block seems fine. What is the response to angular? You could post this as a separate question as it caters to laravel jobs.
Comment: please check
        https://stackoverflow.com/questions/45077081/cant-download-excel-file-when-calling-laravel-controller-from-angularjs
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/149109/discussion-between-sandeep-garapati-and-sajal).


How to not forget your active items

Question: Many items in League Of Legends have active effects which can be cast like normal spells.
Those active effects increase the gold efficiency of an item, if they are used and the base stats of those items often have a gold efficiency below 100%. So not using the active effect is wasted gold.
How can I get myself into using the actives of items?
Comment: Not enough to be an answer, but i'll share a tip that I found to be just amazing ! Bind your Blade of the ruined King on Vayne to her W, as it is only a passive, it will perfectly fit on her kit, and will feel just like a normal spell !
Comment: I would rephrase the title to something like "How to not forget your active items",because using them when you really need them is worth WAY more then to use them just for the sake of button pressing. using items more often does not equal making the best use of items.
Comment: @Shunwoo great tipp! also works with ghostblade ;-)
Comment: @gruntswilldie true! i will rephrase it soon
Answer: Using the actives of items takes a lot of practice and there is no "do that and you will use the actives more often"
However, there are tipps I can give to you which make it some kind of a habit to use them:
Assign them always to the same hotkey
When building items, always try to assing them to the same slot depending on the champion. This makes your brain think they are just another skill for e certain champion.
What I like to do is use QWER for my normal skills, 1 2 3 4 for my active items, T for my trinket, 5 for items that place Stealthwards and 6 for Vision Wards.
Muscle memory is a huge factor when it come to LoL, especially with skills and actives.
You can drag items to the slot you want by holding down the left mousebutton when hovering them, drag them over the slot you want and release the mousebutton. You often have to drag the items a little away from your inventory to make the drag animation appear.
Always keep an eye on their cooldown
Its the same thing like looking on the map now and then to see whats going on, looking at your R cooldown or at the timers for baron and dragon. "Just" add your Item slots to your screen-looking-rotation and you will remind yourself of the items you have.
Replace champion skills that are just passives
Bind your Blade of the ruined King on Vayne to her W, as it is only a passive, it will perfectly fit on her kit, and will feel just like a normal spell.
(thanks to shunwoo for this tipp)
Comment: i disagree on that. as long as you do the same thing for each champion, you will develop muscle memory. muscle memory is bound to a certain champion, just like combos.
Comment: disagree on that too. you dont press Q and expect your champ to throw a spear just because you played pantheon the game before. some champs harras with W (ashe) and some with Q (Ezreal) and your brain is able to do that transition. you associate champs and there hotkey position with each other, not the effect of a spelleffect with the hotkey position. but hey :) do it as you like, I'm just giving my tipps
Comment: Binding to an ability seems counter-productive to the muscle memory, since it won't be there on all champion, so the memory of hitting `W` will be lost on all but those champions you can do it. Better work on a fixed pattern for muscle memory.
Comment: The thing is that if you play any champion where you bind the item to an ability key and then switch to one that doesn't, your memory will want you to hit the ability key to use the item since that's what you've been doing before. Eventually, yes, you'll have trained your memory to act differently on different champs but it is counter-productive while fixed pattern will be easier overall.
Answer: Binding the item to an ability key feels short sighted, it will help you on that specific champion but won't solve your overall problem. The key trick is to always assign the item to the same slot and then practice using it as part of your main combo.
For example I always put sightstone/wards in slot 5. Trinkets as slot 4. Defensive items as 3 offensive items as 1. Now train to using that item and including it as part of your combo. When you Crowstorm in as Fiddlesticks you're running and positioning and casting your other spells but you will automatically Zhonyas when the time comes because it's part of that combo and you are ready to do it.
Equally an assassin that opens with BotRK, or a Darius or Talon that includes a Hydra activation in their combo - just by having that combination and using it repeatedly you will learn to use more and more.
The biggest improvements I've seen in my own play is just coming from playing champions that use items a lot and then trying to remember to use them and kicking myself if I forget!

How to not forget your active items


Search for all rows with values in excel with perl

Question: I am trying to parse data from excel using perl into a specific XML format, which is read by another application, which then creates a graphical representation of the data. The excel sheet gets updated by data capturers on a regular base. I have opted for the Spreadsheet::Read module but I am having an issue.
The sheet would be divided into specific cells, which corresponds to a specific layout.
The sheet will thus have:
Country | City | Suburb | link
Each row being different data etc.
I tried to tell the script to get every row like this.
<code>    use Spreadsheet::Read;

    my $book  = ReadData ("Captured_input.xlsx");
    my @rows = Spreadsheet::Read::rows ($book->[1]);

    print "@rows\n";
</code>
This however prints ARRAY(and some hex data)
However, I want it to read each row and cell and return it like this:
Country1, City1, Suburb1,link1
Country2, City2, Suburb2,link2
It runs on a daily base so it should not read end of file only, it should read the entire sheet each time, so if any changes were made it will republish the XML.
If I use it like this, it works and returns the data, but I then need to manually specify each row, but I cannot estimate how many rows there will be in future.
<code>    use Spreadsheet::Read;

    my $book  = ReadData ("Captured_input.xlsx");
    my @row = Spreadsheet::Read::cellrow ($book->[1], 4);

    print "@row\n,";
</code>
Some input would be greatly appreciated.
Answer:
read perlreftut.
read perldsc.
read the Spreadsheet::Read documentation.

The documentation shows quite well what data structure the <code>$book</code> will contain. Once you understand how references work (see the first two links), handling the data will be easy.
Comment: Hi Amon, Thanks very much. I will look inti them now!


What is a view of a collection?

Question: I've been reading the term view a few times when using Guava collections and reading its documentation.
I've looked for an explanation of what a view is in this context and whether it's a term used outside of Guava. It's quite often used here. This type from Guava has view in its name.
My guess is that a view of a collection is another collection with the same data but structured differently; for instance when I add the entries from a java.util.HashSet to a java.util.LinkedHashSet the latter would be a view of the former. Is that correct?
Can somebody hook me up with a link to an accepted definition of view, if there is one?
Thanks.
Comment: No, I don't think this is correct.  If you say `LinkedHashSet lhs = new LinkedHashSet (hs)` where `hs` is a `HashSet`, `lhs` will have the same element references as `hs`, *but* it will be its own data structure.  If you remove an element from `lhs`, it will **not** affect `hs`, and vice versa.  So they're distinct collections.  But if you use `Collections.unmodifiableSet`, then you do get a view that refers to the same collection.
Answer: A view of another object doesn't contain its own data at all.  All of its operations are implemented in terms of operations on the other object.
For example, the keySet() view of a Map might have an implementation that looks something like this:
class KeySet implements Set<K> {
  private final Map<K, V> map;

  public boolean contains(Object o) {
    return map.containsKey(o);
  }

  ...
}

In particular, whenever you modify the backing object of your view -- here, the Map backs the keySet() -- the view reflects the same changes.  For example, if you call map.remove(key), then keySet.contains(key) will return false without you having to do anything else.
Alternately, Arrays.asList(array) provides a List view of that array.
String[] strings = {"a", "b", "c"};
List<String> list = Arrays.asList(strings);
System.out.println(list.get(0)); // "a"
strings[0] = "d";
System.out.println(list.get(0)); // "d"
list.set(0, "e");
System.out.println(strings[0]); // "e"

A view is just another way of looking at the data in the original backing object -- Arrays.asList lets you use the List API to access a normal array; Map.keySet() lets you access the keys of a Map as if it were a perfectly ordinary Set -- all without copying the data or creating another data structure.
Generally, the advantage of using a view instead of making a copy is the efficiency.  For example, if you have an array and you need to get it to a method that takes a List, you're not creating a new ArrayList and a whole copy of the data -- the Arrays.asList view takes only constant extra memory, and just implements all the List methods by accessing the original array.
Comment: I understand, thanks. Is there an 'official' source of that term (like with Design Patterns and the Gang of Four)?
Comment: @mareser: I'd bet it comes from [databases](http://en.wikipedia.org/wiki/View_(SQL)).
Comment: "the view is simply a copy of a Structure, which has no link to original data" No.  This is wrong.  Nothing is copied, there is just a link to the original data.
Comment: @maaartinus  It is "Adapter" pattern.Effective Java Third Edition,Item 20  mention it.
Comment: I am still confused, the view is simply a copy of a Structure, which has no link to original data, but I can use that to get details of actual dat using it ?     Your Keyset example is unclear to me.
Answer: A view in this context is a collection backed by another collection (or array) that itself uses a constant amount memory (i.e. the memory does not depend on the size of the backing collection). Operations applied to the view are delegated to the backing collection (or array). Of course it's possible to expand this definition beyond just collections but your question seems to pertain specifically to them.
For example, Arrays.asList() returns "a list view of the specified array". It does not copy the elements to a new list but rather creates a list that contains a reference to the array and operates based on that.
Another example is Collections.unmodifiableList() which returns "an unmodifiable view of the specified list". In other words, it returns a list containing a reference to the specified list to which all operations are delegated. In this case, the list returned does not permit you to modify it in any way, and so instead of delegating methods responsible for mutating the list, it throws an exception when such methods are called instead.

What is a view of a collection?


Derivation of $\hat{f}(\xi)=\frac{1}{\sqrt{2\pi}}\int_\limits{-\infty}^{\infty}f(t)\cos(t\xi)dt$

Question:
Problem: Consider the Fourier transform: $$\hat{f}(\xi)=\frac{1}{\sqrt{2\pi}}\int_\limits{-\infty}^{\infty}f(t)e^{-it\xi}dt\quad\text{and}\quad f\in{L_1}_{(\mathbb{R})}$$
Now it was defined to me on ${L_1}_{(\mathbb{R})}$ $$\hat{f}(\xi)=\frac{1}{\sqrt{2\pi}}\int_\limits{-\infty}^{\infty}f(t)\cos(t\xi)dt$$

Given the Euler identity $e^{it\xi}=\cos(t\xi)+i\sin(t\xi)$, I do not know how the $i\sin(t\xi)$ vanished.
Question:
How did it happen?
Thanks in advance!
Edit: Urgent
I only noticed it now, the transform defined is the following:
$$\hat{f}(\xi)=\frac{\sqrt{2}}{\sqrt{\pi}}\int_\limits{0}^{\infty}f(t)\cos(t\xi)dt$$
Apologies!
Comment: f(t) even function? or the transform is real.
Comment: @herbsteinberg Please check the update!
Comment: Yeah, the only way this would work would be that your function is even.
Comment: Even so how would the $i\sin(t\xi) $ vanish?
Comment: If $f$ is even then $f(t)\sin(\xi t)$ is odd, so the integral over symmetric intervals is zero.
Answer: That identity can only work for even functions. Recall that if a function $a(t)$ is odd, then $\int_{-t}^t a(\tau) d\tau = 0$.
Thus, for even $f$, $$\int_{-\infty}^\infty f(t) \sin(\xi t) dt = 0$$ since $f(t) \sin(\xi t)$ is odd for all $\xi$. (Product of an even function with an odd function is odd.)

Now, suppose that $\hat f(\xi) = \int_{-\infty}^\infty f(t) \cos(\xi t) dt.$ We have that $\hat f$ is even, since $\cos$ is even.
If we want to recover $f$, then we can apply the inverse Fourier transform: $$f(t) = \int_{-\infty}^\infty \hat f(\xi) e^{i\xi t} d\xi = \int_{-\infty}^\infty \hat f(\xi) \cos(\xi t) d\xi + i \int_{-\infty}^\infty \hat f(\xi) \sin(\xi t) d\xi.$$ Just as before $\hat f$ even means that $\int_{-\infty}^\infty \hat f(\xi) \sin(\xi t) d\xi  = 0$. Hence, $f(t) = \int_{-\infty}^\infty \hat f(\xi) \cos(\xi t) d\xi$.
Finally, we have that $f$ is even, since $\cos$ is even.
Thus, $\hat f(\xi) = \int_{-\infty}^\infty f(t) \cos(\xi t) dt$ iff $f$ is even.

As for your edit, I did neglect the constants above. This is often done for expediency, and I can see how it can be confusing.
Taking $\hat f(\xi) = \frac{1}{\sqrt{2\pi}} \int_{-\infty}^\infty f(t) e^{-\xi t} dt$, we already established that $\hat f(\xi) = \frac{1}{\sqrt{2\pi}} \int_{-\infty}^\infty f(t) \cos(\xi t) dt$.
Now for even functions, say $b(t)$, we have $\int_{-a}^a b(t) dt = 2 \int_0^a b(t) dt$. Thus, $$\hat f(\xi) = \frac{1}{\sqrt{2\pi}} \int_{-\infty}^\infty f(t) \cos(\xi t) dt = \frac{2}{\sqrt{2\pi}} \int_{0}^\infty f(t) \cos(\xi t) dt = \frac{\sqrt2}{\sqrt{\pi}} \int_{0}^\infty f(t) \cos(\xi t) dt$$
Comment: We had to use $f$ in $L^1$ to recover $f$ from its Fourier transform.
Comment: Thanks for your answer! While reading your answer I noticed the question was wrong. Please check my edit and if possible give me an answer. I am so sorry!
Comment: I answered the edit. I strongly recommend that you review your standard Calculus. In particular, sections concerning improper integrals. Usually there is also a discussion of even and odd functions.
Comment: Thanks for the update! I have already reviewed the topics. I know $\sin(x)$ to be a odd function so $\int_\limits{-N}^{N}\sin(x)=0$. Since the integral  interval is now $[0,\infty)$. Why would the odd function vanish?
Comment: Apparently the function is assumed to be even.  In that case the integral $(-\infty,\infty)=$ twice the integral $(0,\infty)$.


Class of Lipschitz Functions on the unit d-dimensional ball

Question: Let $\mathcal{F} = \{f:\mathcal{B}_d \to \mathbb{R}\;:\; \text{f is Lipschitz}\}$, where $\mathcal{B}_d = \{x \in \mathbb{R}^d\;:\: \|x\|_2 \leq 1\}$ is the unit ball in $d$ dimension. Is the class $\mathcal{F}$ finite dimensional?
My approach: For any constant $M$, the set, $\mathcal{F}_M = \{ f \in \mathcal{F}\;:\; \|f\|_\infty \leq M \}$ is compact in the sup norm.
This can be proven the following way
Step 1 : Use Arzela Ascolli to show the $\mathcal{F}_M$ is relatively compact in the uniform norm
Step 2 : Show that this $\mathcal{F}$ is closed in the uniform norm. This means that $\mathcal{F}$ is compact in the unform norm.
The same question have been addressed here, Show a locally bounded Lipschitz function space is compact for sup metric , so I assume it's true. This is also mentioned in the wiki page https://en.wikipedia.org/wiki/Lipschitz_continuity#Properties.
Question Does this show that the space $(\mathcal{F}, \|\;\|_\infty$ is a locally compact vector space?. The wikipedia page suggests that each $\mathcal{F}_M$ is a locally compact convex set of the Banach Space $\mathcal{C}({\mathcal{B}_d})$
If the space $(\mathcal{F}, \|\;\|_\infty)$ is locally compact, then we can deduce that it must be a finite dimensional space from Riesz Lemma (https://en.wikipedia.org/wiki/F._Riesz%27s_theorem#Statement). The question on the forum Space of Lipschitz functions is finite dimensional appears to do this only so I would assume it's true. The only place where it is throwing me off is they have taken $\mathcal{F}$ as a closed subspace of $\mathcal{C}({\mathcal{B}_d})$ such that every $f \in \mathcal{F}$ is Lipschitz. I am not sure how my setup is different? Is my space stritly bigger?
Any help is appreciated.
Comment: Is $\mathcal{F}$ defined for some fixed $M$? By your title, it would seem that you are just talking about all Lipschitz functions and not Lipschitz constant bounded by $M$.
Comment: Assuming $M$ is fixed, $\mathcal{F}$ is not a subspace, since multiplying $f$ by a scalar scales the Lipschitz constant. What does it mean for a set which is not a vector space to be finite dimensional? If $M$ is not fixed, i.e. $\mathcal{F}$ is the space of all Lipschitz functions, then the claim that this space is closed in the sup norm is false; just use Stone-Weierstrass to find a sequence of polynomials which converges uniformly to a continuous, non-Lipschitz function.
Comment: I took inspiration from https://math.stackexchange.com/questions/4460939/space-of-lipschitz-functions-is-finite-dimensional?rq=1 and https://math.stackexchange.com/questions/3746481/show-a-locally-bounded-lipschitz-function-space-is-compact-for-sup-metric and with your comments I have edited the question. Any further help is appreciated as well.
Answer: I think you are confusing yourself about some points. For clarity introduce some notation:
$$\mathcal F_R(L) := \{ f: B\to\Bbb R \mid \forall x,y\in B: |f(x)|\leq R, \ |f(x)-f(y)|\leq L|x-y|\}\\
\mathcal F_R=\bigcup_{L\in\Bbb R}\mathcal F_R(L),\quad \mathcal F(L)=\bigcup_{R\in\Bbb R} \mathcal F_R(L),\quad \mathcal F = \bigcup_{L,R\in\Bbb R}\mathcal F_R(L)$$
So that $\mathcal F$ is the space of all Lipschitz functions from $B$ to $\Bbb R$. Then you have the following:

$\mathcal F$ is a vector subspace of $C(B)$. It is not closed.
$\mathcal F_R$ is the ball of radius $R$ in $\mathcal F$. It is not pre-compact: Azerla-Ascoli doesn't apply because the Lipschitz constant can be arbitrarily large, and equicontinuity will then fail.
$\mathcal F(L)$ is the space of all Lipschitz functions from $B$ to $\Bbb R$ with Lipschitz constant $\leq L$. This is not a vector space, since the implication [$f\in\mathcal F(L)\implies \lambda f\in\mathcal F(L)$ for all $\lambda\in\Bbb R]$ fails.
$\mathcal F_R(L)$ is pre-compact by Azerla-Ascoli.

Your strategy of showing finite dimensionality of any of the spaces will then not succeed. For $\mathcal F$ (or its closure) it doesn't work because $\mathcal F$ is not locally compact, because the balls in $\mathcal F$ are not pre-compact. For $\mathcal F(L)$ the "balls" $\mathcal F_R(L)$ are pre-compact, but $\mathcal F(L)$ is not a vector subspace.
Comment: If $V$ is a subspace of $\mathcal F$ that is **closed** in $C(B)$, the answer finds an open subset of $V$ that is pre-compact, wlog you can take this subset to be a ball around some point. Since you can translate and scale this set without changing the property of pre-compactness you get that $V$ is locally compact. Essential to the proof is applying Baire, which needs $V$ to be **complete**. $V$ is only complete if it is closed in $C(B)$, a condition that fails for $\mathcal F$.
Comment: The statement in the question you linked can be summarized as "if $W\subseteq \mathcal F$ is a subspace then $\overline W$ (the closure in $C(B)$) is contained in $\mathcal F$ if and only if $W$ is finite dimensional".
Comment: $\overline W$ contains $W$, which is contained in $\mathcal F$, so $\overline W$ will always have some elements of $\mathcal F$. But unless $W$ is finite dimensional it will also have elements that do not belong to $\mathcal F$.
Comment: In your notation can you explain (either as a comment or as an edit to the the answer) how this works then https://math.stackexchange.com/questions/4460939/space-of-lipschitz-functions-is-finite-dimensional
Comment: So essential $\bar{W}$ contains elements of $\mathcal{F}$ if and only if $W$ is finite dimensional. I still feel confused about requiring the closure in $\mathcal{C}(B)$. Does this mean $\bar{W}$ will contain some elements of $C(B)$ as well and only if it is finite dimensional that it will contain truly just functions from $\mathcal{F}$?


How to get parameter value for date/time column from empty MaskedTextBox

Question: I'm having a problem adding a parameter of date/time type to my insert statement. For textual data you can leave the textbox empty and the record will be added but with date/time data I can't. I get the following error:

Data type mismatch in criteria expression.

I want my date/time MaskedTextBox (__/__/____) to be added even if it is empty. Here's my code.
Private Sub btnBookADD_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBookADD.Click
    Dim sqlinsert As String = "INSERT INTO tblBookIssue([Accession Number],[Book Title],[Student Name],[Years],[Section],[Date Issue],[Date to be Return],[Date Returned])  VALUES ('" & txtBookAccessNumber.Text & "' , '" & txtBookBookTitle.Text & "' , '" & txtBookStudentName.Text & "' , '" & txtBookYears.Text & "' , '" & txtBookSection.Text & "' , '" & txtBookDateIssue.Text & "' , '" & txtBookDatetobeReturn.Text & "' , '" & txtBookDateReturned.Text & "')"
    Dim cmd As New OleDbCommand(sqlinsert, con)

    cmd.Parameters.Add(New OleDbParameter("@Accession_Number", txtBookAccessNumber.Text))
    cmd.Parameters.Add(New OleDbParameter("@Book_Title", txtBookBookTitle.Text))
    cmd.Parameters.Add(New OleDbParameter("@Student_Name", txtBookStudentName.Text))
    cmd.Parameters.Add(New OleDbParameter("@Years", txtBookYears.Text))
    cmd.Parameters.Add(New OleDbParameter("@Section", txtBookSection.Text))
    cmd.Parameters.Add(New OleDbParameter("@Date_Issue", txtBookDateIssue.Text))
    cmd.Parameters.Add(New OleDbParameter("@Date_to_be_Return", txtBookDatetobeReturn.Text))
    cmd.Parameters.Add(New OleDbParameter("@Date_Returned", txtBookDateReturned.Text))

    con.Open()
    cmd.ExecuteNonQuery()
    con.Close()
    MsgBox("One Record Added")
    RefreshDataGridview3()
End Sub

Comment: Which control is your `MaskedTextBox`? Also, is that column nullable in Access?
Answer: You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.
Do this for each date parameter:
Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture )
cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) )

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.
Comment: thnk u sir for fast reply but could u translate ur code into vb.net 2008 bcoz its my current version. thnk u sir!
Comment: You might also consider using a `DateTimePicker` control instead.