When is it appropriate to use a complex interface, and when we should keep things simple?

Question: I have a general question about layouts incorporating toolbars, sidebars, and/or panels.
Common design sense might stress simplicity, not to cram too many elements into the UI design. But we often see more complex interfaces employ a mix of these control elements. Take Photoshop, for example:

We have a crowd of panels, sidebars, and a toolbar on top. I guess as designers we're used to working in this setting, but if we step back and look at the interface, would we say it's too complex? Does the complexity of the program justify the complexity of the interface?
Here's why I'm asking this question: when we are creating an interface for a project, how should we know when we're "allowed" to use a complex interface, and when we should keep things simple?
Comment: @Jawa thanks for the edit, I was going to change the title but forgot.
Answer: Complexity is a relative term.  It depends on the context of the user and the tasks they are trying to complete using your interface.
For example, the instrument panel of a Cessna 182 will look very complex to a non-pilot:

Similarly, the instrument panel of a Boeing 787 will look very complex to a private pilot that has only ever flown a 182:

The question then becomes what is the least complex interface you can design that allows your user to operate at their level of proficiency?  The measure of "too complex" is going to be determined by how well your user is able to perform their tasks.
By that measure, you should never set out to make a complex interface.  You're never "allowed" to make a complex interface.  But complexity may be required in order to achieve your goals, to which end, you need to add only the minimal complexity required to complete the task.
To summarize: a superficially complex interface may not be complex to the user if they have sufficient aptitude in the problem domain.
A well designed interface, while having many interrelated functions and numerous elements, can be designed in a manner that does not make the already complicated function more complex than it needs to be.
A design that does not adequately take into account the users' abilities within the problem space and/or does not remove complexity where it is not essential will be perceived as "complex" or "difficult to use".  It is only your user, through user testing, that can tell you if the design is too complex for them.
Comment: Great answer, +1. **Proficiency** was the key word here.


What's the difference between two ways of adding property to an existing js object?

Question: Let's say we need to add a property to an existing js object
var billingData = {}

In my case, I want to store input value in the js object
Here's the basic input
<input type="text" class="form-control" id="billingFullName">

We, basically, have two ways to add the property to the js object:
The first one:
billingData["billingFullName"] = document.getElementById('billingFullName').value

And the second one:
billingData.billingFullName = document.getElementById('billingFullName').value

What's the difference between them?
I'm asking, because when I was submitting the js object using AJAX to MVC Controller, where properties where added using the [] notation, the model in the Controller appeared to be null. Whereas, the dot notation appeared to solve the issue and I'm wondering why..
Comment: There is no difference if you are using these strings.. Bracket notation is if you want to use a variable as the property name or you have a property name that will not be syntactically correct as dot notation, e.g., if there is a space of a plus sign, for example.
Answer: Typically you use bracket notation when you need to define a property dynamically such as with a variable or if the key is not in proper format for dot notation:
const obj = {}
const someKey = 'key'
obj[someKey] = 'somevalue'

console.log(obj.key) // 'somevalue'
console.log(obj.someKey) // undefined

Dot notation is when you already know the key:
const obj = {}
object.key = 'someValue'


Spacing out two separate strings in C#

Question: using System;

namespace Starter
{
    class Program
    {
        public static void Main() {
            //Variable declarations and initialization (assignment)//
            int venusMoonCount = 0;
            float windSpeed = 450.0f;
            string venusFact = "Venus is the only planet" + " that rotates clockwise.";
            //Display the variable values.//
            Console.WriteLine(venusFact);
            Console.Write("Total moons = ");
            Console.WriteLine(venusMoonCount);

            Console.Write("Venusian windspped = ");
            Console.WriteLine(windSpeed + " miles/hr");

            Console.ReadLine();
        }
    }
}

So I'm trying to run this exercise, when it comes to
string venusFact = "Venus is the only planet" + " that rotates clockwise.";
It won't add the space between the two strings. It outputs
"Venus is the only planetthat rotates clockwise
Total moons = 0
Venusian windspped = 450 miles/hr"
How do separate "planetthat"?
Comment: I can't reproduce this. It has the space for me. Can you upload a screenshot to show this? Your solution could be corrupt, try a Clean Build. If that doesn't work, close the solution and delete the Bin and Obj folders and the .suo file then reopen the solution and check.
Answer: Your code is correct. Are you compiling it?
The display result should be:
Venus is the only planet that rotates clockwise.
Total moons = 0
Venusian windspped = 450 miles/hr

Note that you could use the + to just make 3 Console.WriteLine
EDIT: on your screenshot you don't have the dot "." either so clearly this is not the output of your code. Check if you execute what you want to compile.
Comment: It could be because i'm running it through the terminal.
Comment: Ok now I can see it. Thank you!
Comment: You're welcome, it happens all the time not to be running the code we thought we were compiling!

Spacing out two separate strings in C#


Custom ScrollEventHandler not returning NewValue upon scrolling

Question: Can someone tell me what I'm doing wrong here.  I basically created my own scrolleventhandler within a custom listview so that I could get more control.  The OnScroll function gets called but for whatever reason NewValue is always 0 and OldValue is always -1.  Any reason why it's not being updated correctly?
public class ListViewXP : System.Windows.Forms.ListView
{
 ...
    [DllImport("user32.dll")]
    public static extern int GetScrollPos(IntPtr hWnd, int nBar);

    private const int SB_HORZ = 0;
    private const int SB_VERT = 1;

    public delegate void ScrollEventHandler(Object sender, ScrollEventArgs e);
    public event ScrollEventHandler Scroll;

    protected virtual void OnScroll(ScrollEventArgs e)
    {
        ScrollEventHandler handler = this.Scroll;
        if (handler != null) handler(this, e);
    }

    protected override void WndProc(ref System.Windows.Forms.Message m)
    {
        base.WndProc(ref m);
        if (m.Msg == WM_HSCROLL || m.Msg == WM_VSCROLL)
        {
            int scrollPos = 0;

            if (m.Msg == WM_HSCROLL)
                scrollPos = GetScrollPos(this.Handle, SB_HORZ);
            else
                scrollPos = GetScrollPos(this.Handle, SB_VERT);

            OnScroll(new ScrollEventArgs((ScrollEventType)(m.WParam.ToInt32() & 0xffff), scrollPos));
        }
    }

    ..
}

    listView1.Scroll += new ListViewXP.ScrollEventHandler(listView1_OnScroll);

    private void listView1_OnScroll(object sender, ScrollEventArgs e)
    {
        Console.WriteLine(e.NewValue.ToString());
        Console.WriteLine(e.OldValue.ToString());
    }

Comment: You are using the wrong constructor.  And you always pass 0 for *newvalue*.  Have a peek at the way the [framework does it](http://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/ScrollableControl.cs,1456).  Do keep in mind that the omission of the ListView.Scroll event was intentional, the values you get are not correlated to the list.
Answer: Within WndProc you are creating the ScrollEventArgs object that ultimately gets used in listView1_OnScroll. You're setting NewValue to 0, and not setting OldValue at all.
Try something like this:
protected override void WndProc(ref System.Windows.Forms.Message m)
{
    base.WndProc(ref m);
    if (m.Msg == WM_HSCROLL || m.Msg == WM_VSCROLL)
    {
        int scrollPos = 0;
        if (m.Msg == WM_HSCROLL)
          scrollPos = GetScrollPos(this.Handle, SB_HORZ);
        else
          scrollPos = GetScrollPos(this.Handle, SB_VERT);

        OnScroll(new ScrollEventArgs((ScrollEventType)(m.WParam.ToInt32() & 0xffff), scrollPos));
    }
}

If you want to set OldValue as well you'll need to store NewValue as a member variable and use the overloaded constructor for ScrollEventArgs.
Comment: Hi Wheatin, so I updated my original post and made the changes as you suggested. However, my scrollPos is still coming back as 0 all the time.


Keyboard notifications after modal dialog

Question: I have a UITableViewController with some rows containing textfields, and other rows that show a modal view. I register for the UIKeyboardWillShowNotification and UIKeyboardWillHideNotification in viewWillAppear, and unregister in viewWillDisappear.
Next I do this:
- click on a textfield. I get the UIKeyboardWillShowNotification, resize the table to have place for the keyboard.
- select a row that presents a modal view controller, I receive the UIKeyboardWillHideNotification, and viewWillDisappear is called.
- after closing the modal view controller, viewWillAppear is called, and I get a UIKeyboardWillShowNotification. But no keyboard is shown. So my table is resized, but no keyboard appears.
Is this a bug in the SDK? Or is it common behavior and I'm missing something?
Answer: Your logic seams correct to me. But I wonder about a possible problem with registering for a UIKeyboardWillHideNotification every time your viewWillAppear. Try to register only once in viewDidLoad and unsubscribe in dealloc. I am thinking that maybe when you register again after you dismiss the modal view the Notification Center sends you an old notification. If you register once for a notification you will not get it more then it is posted.
Comment: But why would I receive an old UIKeyboardWillShowNotification on a modal dismiss? I already received the correct willShow notification the first time. The second one only makes sense if the keyboard was going to appear.


Am I allowed to make these kinds of substitutions?

Question: I am trying to solve this:

Let $$\dfrac{u(x+1)+u(x-1)}{2} = f(x) \tag 1$$
and $$\dfrac{u(x+4)+u(x-4)}{2} = g(x) \tag 2$$
Express $u$ in terms of $f$ and $g$.

My question is if the following steps are justified (I think they're not):
Make the substitutions $x\to x+4$ and $x \to x+1$ in $(1)$ and $(2)$ respectively
Let $$\dfrac{u(x+5)+u(x+3)}{2} = f(x+4) \tag 3$$
$$\dfrac{u(x+5)+u(x-3)}{2} = g(x+1) \tag 4$$
Subtract $(4)$ from $(3)$:
$$\dfrac{u(x+3)-u(x-3)}{2} = f(x+4)-g(x+1) \tag 5$$
I continue and get the solution doing a few more of these substitutions, but I am just not quite sure if the substitutions are valid.
I don't think that I can just combine $3$ and $4$, this is just abuse of notation, right? Because actually I am setting $x=a+4$ and $x=b+1$, so I can't pretend like $a$ and $b$ are independent.
Comment: Your calculation is fine. For any given $x$ equations $(3)$ and $(4)$ are simultaneously true, so $(5)$ is also true for that $x$.
Comment: You're welcome.
Comment: @BrianM.Scott So I guess if I make the substitution $x=a+4$ in the first equation and $x=b+1$ in the second, $a$ and $b$ are completely independent I guess because they are in different equations? And then more formally I would get $$\dfrac{u(a+5)+u(a+3)}{2} = f(a+4)$$  and  $$\dfrac{u(b+5)+u(b-3)}{2} = g(b+1) $$ and say $a=b$ and the subtract them? Sorry, I don't really know what I'm doing; I just noticed that this pattern of substitutions symbolically leads to a solution, and I am trying to understand now why everything I did is valid.
Comment: If you were to do what you did in the comment, $a$ and $b$ would be unrelated; the first equation holds for any $a$ and the second for any $b$. However, you could then set $b$ equal to $a$, in which case the second equation would become $$\frac{u(a+5)+u(a-3)}2=g(a+1)\;,$$ and you could then combine this with the first equation.
Comment: @BrianM.Scott Ok thanks I think that agrees with what I said in the comment above
Comment: recommend books if you are not getting the style of these problems; here is one of many: https://books.google.com/books/about/Topics_in_Functional_Equations.html?id=7KA-nQEACAAJ    "This book is a systematic and comprehensive approach to functional equations as a whole. Unlike in other branches of competitive mathematics, there is very little theory; "
Answer: Hint: $$u(x+4) + u(x-4) = (u(x+4) + u(x+2)) - (u(x+2) + u(x)) - (u(x) + u(x-2)) + (u(x-2) + u(x-4)) + 2 u(x)$$


Shared URLSession vs URLSession with default configuration

Question: What is the difference between Shared URLSession and URLSession with default configuration?
In my app i was using URLSession.shared to send a request to server. Now i'm trying to change it to URLSession.init(configuration: URLSessionConfiguration.default).
But if i use URLSession.init(configuration: URLSessionConfiguration.default) all my request are taking more time to load.
Compared to URLSession.shared, URLSession.init(configuration: URLSessionConfiguration.default) is taking more time to load the request.(Shared Session is 5 to 10 time faster than URLSession with default Configuration).
What is the Difference between these two methods?
Why URLSession With Default Configuration is taking more to load the request?
Comment: Please share code - I am very skeptical that URLSessionConfiguration.default is slower
Answer: Limitations of the Shared Session

You don't provide a delegate or a configuration object.
You can't obtain data incrementally as it arrives from the server.
You can't significantly customize the default connection behavior.
Your ability to perform authentication is limited.
You can't perform background downloads or uploads when your app isn't running.

In other words, if you're doing anything with caches, cookies, authentication, or custom networking protocols, you should probably be using a default session instead of the shared session.
For more info: https://developer.apple.com/documentation/foundation/urlsession/1409000-shared
Answer: URLSession has a singleton shared session (which has no configuration object) for basic requests. It's not as customizable as sessions you create, but it serves as a good starting point if you have very limited requirements. URLSession.shared is already created object which no required extra time for configuration, and the issue is default value of default timeout
For me, one of the best practice is to create a shared instance of URLsession and use it for multiple tasks. No overhead configuration required because usually you need the same configuration for an api.
The benefit of this is that I had to create the session only once, so that will save repetition of same code and also the process to initialise the same thing again per api request. This will be more helpful in case you need to more custom configuration of the session.
Answer: URLSession.init(): Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated.
 note that: An object isn't ready to be used until it has been initialized.
URLSession.shared: For basic requests, the URLSession class provides a shared singleton session object that gives you a reasonable default behavior for creating tasks. Use the shared session to fetch the contents of a URL to memory with just a few lines of code.
Unlike the other session types, you don't create the shared session; you merely access it by using this property directly. As a result, you don't provide a delegate or a configuration object.


How to write a Connection String

Question: I am trying to use VBA in Excel to query a SQL database and I was given the below code as the starting point which is awesome but I don't know the syntax for writing a connection string and so far have been unable to find it. Hoping you guys can help me.
<code>Dim cn as new ADODB.Connection
Dim rs as new ADODB.Recordset

Cn.ConnectionString = "your connection string"
Cn.Open
Rs.Open "query like SELECT * FROM MYTABLE etc.", cn
Range("A1").CopyFromRecordset rs

Rs.close
Cn.close
</code>
Comment: if you do some googling im sure you will find tons of examples
Comment: [www.connectionstrings.com](http://www.connectionstrings.com/sql-server/) is a good place to start.  Something like this: `cn.ConnectionString = "Provider=SQLOLEDB.1;Data Source=ServerName;Initial Catalog=databaseName;TRUSTED_CONNECTION=YES"`
Comment: I have been googling for the last 2 weeks and had not yet found what I needed to make sense to my brain. However what Portland Runner provided is very useful Thank you sir. Now I just need to figure out why it is giving me a complie error: User-Defined type not defined error on the first line of Dim
Comment: Use the VBE's `Tools ► References` to include one of the ADO compiler reference libraries like *Microsoft ActiveX Data Objects 2.5 Library*.
Answer: This code may help you (it's just something I had on hand close to what you're trying to do and not a rewrite of yours), but your connection string will vary based on your database. Go here for more information on syntax for the string itself. You are getting a compile error because you do not have the proper references. In the VBE, go to Tools and select References. Make sure ActiveX Data Objects 6.1 Library is checked.
<code> Private Sub GetFieldNames()

 Set con1 = New ADODB.Connection
 Set rs1 = New ADODB.Recordset
 Dim ProjectName As String
 Dim ConCat As String

 con1.ConnectionString = "Provider=SQLOLEDB;Data Source=SERVERADDRESS;Initial Catalog=DATABSE;IntegratedSecurity=SSPI"
 con1.Open

 With rs1
     .ActiveConnection = con1
     .Open "SELECT column_name,* From information_schema.columns Where table_name = 'Projects' ORDER by ordinal_position"
     Sheet1.Range("A1").CopyFromRecordset rs1

     .Close

 End With

 con1.Close
 Set con1 = Nothing

 End Sub
</code>
Comment: This is probably to do with the `IntegratedSecurity=SSPI` part. You need to work out how you connect to your SQL Server database. Is it by windows authentication or SQL Server authentication? Then you need to alter your connection string accordingly. There is a lot of info around about connection strings. Ask a specific question and we may be able to help.
Comment: I was able to modify the code and add the reference as you suggested to get much further in this process however I am getting a different issue now where it says invalid authorization Specification error when it tries to open the connection string.
Comment: I was able to get it to work I had to add the Password to the connection string(it is SQL Server Authentication) I just did not think I needed that part as the connection file excel makes when you do it using the wizard does not have it in that file and I was using that file to help write the code.

How to write a Connection String


How do I set Ctrl+Alt+something for Audacious global hokeys?

Question: I want to set up global hotkeys in Audacious as follows. When I try and set these up it doesn't allow two mask keys.

Ctrl+Alt+Insert for play.
Ctrl+Alt+Home for pause.
Ctrl+Alt+End for stop.
Ctrl+Alt+Page Up for previous track.
Ctrl+Alt+Page Down for next track.
Ctrl+Alt+Up Arrow for volume up.
Ctrl+Alt+Down for volume down.
Ctrl+Alt+Left for skip back.
Ctrl+Alt+Right for skip forward.
Comment: Is using the Gnome Shortcuts plug-in an option?
Answer: assuming you use gnome, just run gnome-keybinding-properties and configure to your taste


Jacobian to do Newton's method.

Question: PICTUREI want to do a Newton's iteration using Jacobian and I did not understand how to do that. Can someone explain the steps to me please?
SOLUTION
Comment: Can you post more details and where you stuck?
Comment: @user251257 I added a picture. I do not know how to find J. I have the solutions but i didn't understand then. So i wanted to know if someone can tell me the steps..
Comment: do you know how to compute derivatives?
Comment: @user251257 yes
Comment: just compute the 4 partial derivatives and write them down as the Jacobian $J$.
Answer: Okay,
you have a system of two equations, namely
\begin{split}
f_1(x_1,x_1) = 0\\ f_2(x_1,x_2) = 0
\end{split}
The Newton method reads
$$\left[\begin{array}{c} x_1\\ x_2\end{array}\right]^{n+1} = \left[\begin{array}{c} x_1\\ x_2\end{array}\right]^{n} - \left(J^{-1}\right)^{n}\left[\begin{array}{c} f_1(x_1,x_2)\\ f_2(x_1,x_2)\end{array}\right]^n \tag1$$
Where $J^{-1}$ is the inverse of the Jacobian, that is
$$J=\left[\begin{array}{cc}
\frac{\partial f_1}{\partial x_1} & \frac{\partial f_1}{\partial x_2} \\ \frac{\partial f_2}{\partial x_1} & \frac{\partial f_2}{\partial x_2}\end{array}\right]
$$
Use the equation $(1)$ recursively, starting with $n=0$ with your initial guess
$$\left[\begin{array}{c} x_1\\ x_2\end{array}\right]^{0}=\left[\begin{array}{c} 1\\ 1\end{array}\right]$$
Comment: I just posted the solutions i have. I don't understand why they do not use J inverse for the first step
Comment: Okay, it is the same. For sure you calculate the "inverse" of $J$, solving $\vec{v}$ from
$$J^{n}\vec{v}=\vec{f}^{n}\tag2$$
and later you update your solution with
$$\vec{v} = \vec{x}^{n+1}-\vec{x}^{n}\tag3$$
You will also notice that the equation $(1)$ I wrote is formally the same as $(2)$ with $(3)$
Comment: I don't understand what v is .
Comment: $\vec{v}$ is defined on your homework. The procedure you follow in your solution is first solve $\vec{v}$ from the system in $(2)$ and update your solution by using $(3)$. Do you understand it know?
Comment: no .. :/ i still dont know how to replace the values or understand what is going on
Comment: Follow these steps loking at the same time to your solution please:
$$\quad$$
1. Compute the Jacobian $J$. It must be a function of $x_1$ and $x_2$. $$\quad$$
2. Substitute in the Jacobian $J(x_1,x_2)$ and function $\vec{f}(x_1,x_2)$ the values of $x_1$ and $x_2$ from the seed you are provided $(1,1)$.
$$\quad$$
3. Once computed, solve the system $J\vec{v}=\vec{f}$ for the computed $J$ and $\vec{f}$.
$$\quad$$
4. Now you know the value of $\vec{v}$. The next solution for $x_1$ and $x_2$ you will obtain is $\vec{x}^{n+1}=\vec{v}+(x_1,x_2)^{T}
$$\quad$$
Comment: Repeat the procedure from 1, this time with the initial solution of $\vec{x}^{n+1}$ instead of $(1,1)$
Comment: OMG IT IS SO EASY. I CAN'T BELIEVE I DIDNT UNDERSTAND THAT

Jacobian to do Newton's method.


Can't leave Mekar Island

Question: I was traveling from the Tabantha Stable to get the Sheikah tower in the region between that and Death Mountain (haven't explored this region yet).  I attempted to cross a river and ended up landing on an island in the middle of it.  From a map I found online, this island is called Mekar Island.

When I landed on the island, some Chuchus swarmed me...and that was it.  There is a lone rock on the island next to a tall dead tree and an unlit campfire.  I lifted the rock (no Korok Seed), found a Flint, lit the fire and nothing happened.  So I decided to leave the island and glided over to the other side.  I started climbing the steep riverbank when the screen started to fade to white and I was teleported back to the island (Link then looked around kind of perplexed).  I tried again using Revali's Gale to get even higher up and it teleported me mid glided.
I'm not sure if this is some sort of glitch because Link did look around confused like it he was programmed to do that, but I haven't found any sort of challenge on the island to complete or anyone else on the internet mentioning this same issue.  I haven't tried to Fast Travel yet in case there is a challenge there also (don't want to make the trek back).
Anyone know what's going on?
Comment: Definitely sounds like you keep going in the direction of the Lost Woods and are succumbing to the fog.  As @Yuuki said the fog is meant to teleport you back the way you came.  Instead of heading east I would recommend heading west if you actually want to leave the island.
Comment: I hadn't tried that last night, partly because I needed to go to bed and partly because I was focused on getting to that tower.  I'll try to go back to the other bank of the river real quick during my lunch break and comment again.
Comment: @Yuuki I was able to try this yesterday and you were right, I was trying to go into the Lost Woods.  I started exploring them shortly after escaping by going in the correct entrance and the teleport of going the wrong way was the same thing I had been seeing.  Thank you, and thank you @BlueBarren!
Answer: So Mekar Island is rather close to the Lost Woods. If you get too close to the Lost Woods when approaching from the incorrect direction, you will be teleported back. Instead of heading eastwards, head west and go south along the opposite shore.
Comment: @bubbajake00 also seems curious about the significance of Mekar Island. Timmy Jim suggests in [another question](https://gaming.stackexchange.com/a/306517/65440) that "Currently, there does not appear to be anything unique on this island. It is simply a reference to the sage Makar from the Wind Waker"

Can't leave Mekar Island


Migrating Django application from heroku (celery/redis) to aws fargate/lambda

Question: Apologies in advance for my little knowledge of AWS
I'm trying to draw parallels between my current setup on Heroku to a move to AWS. I've run into some memory issues on Heroku because of some machine learning models I'm running and Heroku seems too expensive for my needs.
I was recommenced to move to aws using fargate which would be a better fit for my app. Below is my whole architecture, I'm hoping for some guidance on my direction of what I have and where I plan to go.
A django application running on heroku.
The base of functionality is the user uploads a video from their mobile device and uploads it to s3. A message from SNS is sent to my Heroku server that the upload is completed. The server kicks off a celery task that downloads the video from s3 and uses a machine learning model to do some natural language processing, then saves the results to my postresql database. Obviously this is very compute intensive, so I've run into some memory issues and can for-see scaling issues to come.
After lots of tweaking and attempts to no avail, I've decided to move over to AWS and leverage some of the cost benefits that I've seen in comparison to heroku of running more memory intensive tasks.
I should also mention there is a web interface involved with this django project and it isn't just a REST Api.
As far as AWS goes, I'm looking for a bit of direction. Possibly just a rough outline of the architecture I should look deeper into.
My first plan is to dockerize my application and go from there...but I'm a bit stuck on how my application fits (website, rest api, worker threads) into the AWS ecosystem.
Answer: AWS is a great fit for the application you describe.  AWS Fargate / RDS will host your Django application.  You have the option of using AWS Batch to handle your processing.  One huge advantage is the ability to scale according to the needs of your application.
This image is one possible way to structure your application.  It's a lot of work to get to this point, but AWS offers a lot of power and flexibility for reasonable costs IMO.
Comment: I considering deploying my app like this. I am trying to estimate the costs. Can you perhaps give your five cents and tell me how much an APP with around 10000 CRUD requests a day would cost me plus 500 to 1000 Celery tasks?
Comment: VPC and RDS are the most costly elements.  Fargate / EC2 should be lower costs for smaller transactions but you may need to consider resilience.  Check out the AWS Cost Explorer but I would guess you would be looking at low hundreds USD per month.  You could look at Batch Fargate instead of Celery to avoid the overhead of running a dedicated EC2 instance for Celery
Comment: the diagram above is out-of-date because now you can submit jobs to Batch via VPC endpoints, so you don't need a lambda function


IAudioVolumeEndpoint setMute will unmute, but never really mute (looks muted while sounds is still heard)

Question: I have a piece of code, which is supposed to mute/unmute sound. I have patched it a lot, so now it enumerate all rendering device to toggle their mute status. However, although it perfectly unmute anything, for muting, the sound mixer will show that devices are muted, however the sound is still playing. On my laptop I have a LED which indicates if sound is muted, and it indactes that it's muted too...
I have had a look at similar C++ code to achieve the same and can't find a difference...
var
  deviceEnumerator: IMMDeviceEnumerator;
  MMDevice: IMMDevice;
  EndpointVolume: IAudioEndpointVolume;

  Muted: BOOL;
  R: Integer;
  MMDC: IMMDeviceCollection;
  DC: UINT;
  I: Integer;
begin
  CoCreateInstance(CLSID_MMDeviceEnumerator, nil, CLSCTX_ALL, IID_IMMDeviceEnumerator, deviceEnumerator);
  if (deviceEnumerator.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, MMDC) = S_OK) then
  begin
    if MMDC.GetCount(DC) = S_OK then
    begin
      for I := 0 to DC - 1 do
      begin
        if (MMDC.Item(I, MMDevice) = S_OK) then
        begin
          MMDevice.Activate(IID_IAudioEndpointVolume, CLSCTX_ALL, nil, @EndpointVolume);

          if EndpointVolume = nil then
          begin
            OutputDebugString('Unable to get endpoint!!!');
          end
          else
          begin
            R := EndpointVolume.GetMute(Muted); // R = S_OK, always
            R := EndpointVolume.SetMute(not Muted, nil); // R = S_OK always, too
          end;

        end;

      end;
    end;
  end
end;

If anyone has an idea about what's wrong... There's not a single call failing, and everything looks like it's muted, so I'm really puzzled...
I also use similar code to raise and lower volume, it works perfectly.
Comment: You say you "patched it a lot." Did you patch it so much that it no longer works? Or did the code ever work at all? If the former, then what change did you make that broke it? Does the comparable C++ code work?
Comment: Actually, "a lot" might be beyond the truth. It never worked for muting. I patched it because initially it would only try to mute/unmute the default device. In an attempt to get it work, I decided to mute/unmute all devices. The comparable C++ code works (I haven't compiled it myself, but I have source and binary, and binary indeed mute the sound). See here: https://blogs.msdn.com/b/matthew_van_eerde/archive/2012/06/18/muting-all-audio-outputs-with-iaudioendpointvolume.aspx?Redirected=true . To me it does the same, and additionally outputs device name.
Answer: This is gonna sound dumb :)  Since you're hearing sound, you're not muting something.  Output the names of the devices you are muting; if the list doesn't match the list from the C++ code, that works, then you know where the problem is.
Comment: Well I'll give it a try later, but basically, there are 2 rendering endpoint on the computer. The C++ code mutes 2 showing their name. My code mutes 2, too (or reports having muted)... And well, it unmutes them properly, and Windows mixers shows them as properly muted... And after using my muting code, the C++ muting code, which shows only unmuted devices, do not show anything anymore when executed (so it considers everything IS muted, though I still hear music)
Answer: I know that I'm super late, but I think I know what is the problem! Maybe this will help somebody in the future! Basically, don't reuse Muted variable as not Muted :
R := EndpointVolume.GetMute(Muted);
R := EndpointVolume.SetMute(not Muted, nil);

Use something like this:
R := EndpointVolume.GetMute(Muted);
Bool bMuted = Muted;
R := EndpointVolume.SetMute(not bMuted, nil);

Or this:
R := EndpointVolume.GetMute(Muted);
R := EndpointVolume.SetMute(Muted = 0, nil);

What I think is happening, you (and me too, in C++!) are inverting BOOL (that is actually signed int) with not or ~ in C++ (like I did). GetMuted returns -1 on Mute ON and 0 on Mute OFF. When you invert 0 into -1 and send it to SetMute, something bugs out. It seems that SetMute is expecting to get 0 for false and 1 for true (not -1!). Undocumented quirks, I guess...
Comment: Interesting, thanks for posting this! If I can find this code again I'll give it a go. I'll likely just send 0 or 1 casted as BOOL for testing.


Modified Req Url in Express middleware ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client

Question: Hey guys I am facing the error Error "[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" when I am trying to modify the req.url in a express middleware.
My middleware
export function ModifyQueryMiddleware(config, Authconfig, Repo ){
    const accessTokenMap = new Map();
    return async (request, res, next) => {

        const accessToken = request.header('authorization') as string;
        if(!accessToken){
            throw new HttpException(res, 403)
        }

        if(!accessTokenMap.get(accessToken)){
            const JWKS = jose.createRemoteJWKSet(new URL(config.jkwsUri));
            try {
                const jwtVerifyResult = await jose.jwtVerify(accessToken.replace('Bearer ', ''), JWKS);
                const {payload} = jwtVerifyResult;

                accessTokenMap.set(accessToken, payload)

                const aumParams = await authentication(payload, authConfig,Repo);

                const queryRestrictionStrategy = QueryRestrictionStrategyFactory(aumParams, request)
                queryBuilder(queryRestrictionStrategy)
                next()
            } catch(err){

            }
        }

        const payload = accessTokenMap.get(accessToken);
        const aumParams = await authentication(payload, authConfig, repo);
        const queryRestrictionStrategy = QueryRestrictionStrategyFactory(aumParams, request)
        queryBuilder(queryRestrictionStrategy)
        next()

    }
}

My queryBuilder:
export function queryBuilder(strategy: QueryRestrictionStrategy){
    const {req, id} = strategy
    if(req.url === '/someurl'){
        req.url = `/someurl?${id}`
    }
    return
}

I am really confused as I don't modify the header of a response instead I am just modifying the query without the querybuilder the middleware works fine. I already looked at a few questions regarding this error however the res was there always modified.
Any help or tips would be really appreciated !
Answer: Your code can call next twice when !accessTokenMap.get(accessToken) is true. You have to return once that part of your code is handled:
if (!accessTokenMap.get(accessToken)) {
  const JWKS = jose.createRemoteJWKSet(new URL(config.jkwsUri));
  try {
    ...
    next();
  } catch(err) {
    next(err); // make sure to pass the error along!
  }
  return;
}


Is it possible to do this "half strikethrough" using CSS (without using images)

Question: I'm doing a site without using any images, to make it responsive and faster, only CSS(3).
I'm trying to do the following effect using CSS

I used to do this using

  Ou

and the CSS (using image):
.strikethrough {
  background: url('strip.gif') repeat-x 50% 50%;
}

.strikethrough span {
  background: #EAEBEC;
  padding: 0 5px;
  display: inline-block;
  margin: 0 auto;
}

Is it possible to do the same using only CSS?
Comment: I'd stick with the image. It's like 200 bytes (if done properly) and is backwards-compatible.
Answer:

    Ou

or
<fieldset style="text-align: center; border: 0; border-top: 1px solid black;">
  <legend>
    Ou
  </legend>
</fieldset>

Comment: is there a way to make it inherit the background of the current page? some pages are white and some pages are light grey, can make it inherit automatically?
Comment: I have added another option to answer.
Comment: Solution 1 is for inline elements and Solution 2 works best with block element.
Answer:

div
{
text-align: center;
}

span
{
display: inline-block;
}

span:before,
span:after {
border-top: 3px solid #EAEBEC;
display: block;
height: 1px;
content: " ";
width: 48%;
position: absolute;
left: 0;
top: 1.2em;
}

span:after
{
right: 0;
left: auto;
}

    OU

Answer: It looks like I'm too late, but here it is anyway. -jsFiddle
Edit- Added code for different style and updated jsFiddle
css
.strikethrough{
  box-shadow:
        0px -10px 0px 0px #EAEBEC inset, inset 0px -11px 0px 0px black;
  background: #EAEBEC;
  padding: 0 5px;
  display: block;
    text-align:center;
}
.strikethrough span{
    background:#EAEBEC;
}

.different{
    background:white;
}
.different .strikethrough{
  box-shadow:
        0px -10px 0px 0px #fff inset, inset 0px -11px 0px 0px black;
  background: #fff;
  padding: 0 5px;
  display: block;
    text-align:center;
}
.different .strikethrough span{
    background:#fff;
}

html

  Ou

  Ou

Comment: small advantage to this method. The text will still be inline with normally formatted text
Comment: is there a way to make it inherit the background of the current page? some pages are white and some pages are light grey, can make it inherit automatically?
Comment: It looks like the background color can be inherited, but not box-shadow color. Check out my updated answer for a working method.


Attach listener to multiple children

Question: I'm trying to get rid of jquery from my page and rewrite some functionalities to pure js.
There are 2 lists with class work, containing a few li elements. Each li element should have an action on click to add class 'active' to it.
In jquery it is very simple:
$('.work li').on('click', function () {
            var that = $(this);
            that.parent().find('li.active').removeClass('active');
            $(this).addClass('active');
        })

Is there a nicer solution in pure js rather than making something like this with nested loops:
    var lists = document.getElementsByClassName('work');
    for(var i=0; i<lists.length; i++){
       var children = lists[i].querySelectorAll('li');
       for(var j=0; j<children.length;j++){
        children[j].addEventListener();
       }
    }

Comment: I think the OP definitely has it the right way round here. If your using a complicated library for a single feature, which is easily achievable in vanilla then your doing something wrong. If you had a greater need, like UI elements or AJAX as well, then I'd say stick with jQuery.
Comment: My page has some threejs in it and currently uses jquery only for this purpose (i've rewritten all other functionalities to pure js, and they work fine). I think there is no sense in keeping a separate library just to be able to assign onclick listeners in a comfortable way + i want to learn something new ;-)
Comment: Now i see how much i don't know about js
Comment: Now you see why JQuery was developed and has become so popular.
Comment: Working directly with the DOM is tedious and requires a lot of searching loops like this. Also, note that there are some differences between browsers for method names and capabilities. They were the two problems that jQuery set out to solve initially. Why are you trying to eliminate it?
Comment: Why would you NOT use jQuery when playing around with the DOM?
Comment: Because jQuery treats the DOM as a humongous, mutable, global object in the middle of your application? By the way, @jalynn2, what are the differences between browsers for method names?
Comment: @mjanisz1 - that's fine, you are on the right track and there is no way to get around the looping. If you are doing a lot of it, you can start to refactor it into common functions, but then you are starting to reinvent jQuery :-)
Comment: jQuery is not huge - it's about 29kb gzipped. Seriously, 29kb bothers you enough to make you want to write loops like that?
Comment: If it bothers you that much, you can always do a custom build - https://github.com/jquery/jquery#how-to-build-your-own-jquery - of jQuery to just include the DOM API and remove everything else.
Comment: @torazaburo - the DOM IS a humongous, mutable, global object in the middle of your application. You can craft code to access it in a controlled way, but there is no changing that fact. I don't remember differences off the top of my head, except with the AJAX objects, but they are out there. I've been using jQuery too long and they have faded from memory.
Comment: jquery can dissapear
Answer:
There are 2 lists with class work, containing few li elements. Each li
  element should have an action on click to add class 'active' to it.

You could create that entire functionality by adding an event listener to all lis returned by the querySelectorAll. The querySelectorAll returns a nodeList and not an array, so need to map it in order to iterate it. However, note that we are still iterating the set.
Example Snippet:

var lists = document.querySelectorAll(".work li"),
    doSomething = function() {
        [].map.call(lists, function(elem) { elem.classList.remove("active") });
        this.classList.add("active");
    };
[].map.call(lists, function(elem) {
    elem.addEventListener("click", doSomething, false);
});
li { cursor: pointer; }
.active { background-color: yellow; }

One

Two

Three

Four

Five

Six

In fact you could also use event delegation and add event listener only on the ul and then use the event.target to handle your routine. This is better than adding an event listener to each and every li, in case there are many of them. There will be only as many handlers as uls.

Is there a nicer solution in pure js rather than making something like
  this with nested loops

Not really. You have to iterate over the set of elements anyway. Nicer in terms of jazzy, yes. Nicer in terms of avoiding the loops, no. Nicer in terms of efficiency, well yes. Compare the above vanilla javascript code with the jQuery one in your question:
$('.work li').on('click', function () { // internally will iterate and add listener to each li
    var that = $(this);
    that.parent().find('li.active').removeClass('active'); // go to parent and then find li
    $(this).addClass('active');
});

.
Comment: thanks! this looks like a tidy solution! i also like the [].map.call for going through the set of elements!
Answer: querySelectorAll() is quite powerful tool.
I've made a JSFiddle for you.
Code is still nice and readable:
for (var item of document.querySelectorAll(".work li")) {
 item.addEventListener("click", function (evt) {
     evt.target.classList.add("active");
 }, false);
}

Another way is (if you still want to iterate using forEach):
Array.prototype.forEach.call(document.querySelectorAll(".work li"), function(item) {
   item.addEventListener("click", function (evt) {
        evt.target.classList.add("active");
   }, false);
});

Here (JSFiddle) we are interating through a NodeList returned by querySelectorAll(".work li") by calling the Array.prototype.forEach method on it.
And here (Jsfiddle) is the full example, that toggles the class:
Array.prototype.forEach.call(document.querySelectorAll(".work li"), function(item) {
   item.addEventListener("click", function (evt) {
        evt.target.toggleActive = !evt.target.toggleActive;
       evt.target.classList[!!evt.target.toggleActive ? 'add' : 'remove']("active");
   }, false);
});

And finally, if there should be only one active element at a time (Jsfiddle):
var currentActiveElement;
Array.prototype.forEach.call(document.querySelectorAll('.work li'), function(item) {
item.addEventListener('click', function(evt) {
  currentActiveElement && currentActiveElement.classList.remove('active');
  currentActiveElement = evt.target;
  currentActiveElement.classList.add('active');
 }, false);
});

Comment: If I understand your question correctly.

`querySelectorAll()` returns an object [NodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList), witch [can not be treated exactely as Array](https://developer.mozilla.org/en-US/docs/Web/API/NodeList#Why_is_NodeList_not_an_Array.3F).
Comment: how come we can do this but not use for each for querySelectorAll?
Answer: You could actually attach click event listener on wrapper element and filter out clicked li element using event.target (or for IE event.srcElement).
Try out below snippet (not production code by any means, it should be enhanced especially for browser compatibility). Good side of this solution is that you don't have to watch for new elements dynamically added to wrapper element...

function clickHandler(e) {
  var elem, evt = e ? e : event;
  if (evt.srcElement) {
    elem = evt.srcElement;
  } else if (evt.target) {
    elem = evt.target;
  }

  // Filter out li tags
  if (elem && ('LI' !== elem.tagName.toUpperCase())) {
    return true;
  }

  console.log('You clicked: ' + elem.innerHTML)
  return true;
}

var lists = document.getElementsByClassName('work');
for (var i = 0; i < lists.length; i++) {
  var children = lists[i].addEventListener('click', clickHandler);
}

1.1

1.2

1.3

1.4

2.1

2.2

2.3

2.4

3.1

3.2

3.3

3.4

Answer: Sure. Why not  just make better use of document.querySelectorAll? It does use the syntax of css, so we can grab both in one go.
Perhaps something like this:
{
 liList = document.querySelectorAll('.work li');
 var i, n = liList.length;
 for (i=0; i<n; i++)
  liList[i].addEventListener(eventName, functionName, useCapture);
}

Comment: this seems the cleanest to me
Answer: People complain about the wordiness of using native DOM methods, but there's no problem a few bits of strategically-placed sugar could not help. Start off by writing it the way you'd like to:
eachClass('work', function(work) {
    eachSelector(work, 'li', function(li) {
        on(li, 'click', function() {
            eachChild(parent(li), active.remove);
            active.add(li);
        });
    });
});

Now you just have to write eachClass, eachSelector, eachChild, parent, and on, something like the following. They'll each be about 2-3 lines. You just have to write them once, and voila, you have your own little library.
function eachClass(cls, fn) {
    [].forEach.call(document.getElementsByClassName(cls), fn);
}

What is active? It's a little object we can create for setting and removing a particular class:
function makeClassSetter(cls) {
    return {
        add: function(elt) { elt.classList.add(cls); },
        remove: function(elt) {elt.classList.remove(cls); }
    };
}
var active = makeClassSetter('active');

And so on. Great programmers are constantly building little frameworks and layers and utilities and mini-languages. That's what makes their code compact, readable, less buggy, and easier to write.
Answer: I too was looking for a concise but useful solution to this.
This is the best approach I came up with:
tag = document.querySelectorAll('.tag');

tag.forEach(element => {
  element.addEventListener("mouseover", aFunction);
});

function aFunction(){
  this.style.background = "grey";
}

querySelectorAll is a powerful method, a foreach is always much shorter and easier to use when the use-case is there.
I prefer naming the functions and adding to them, although I suppose you could easily replace that with another arrow function within the foreach if you prefer

Attach listener to multiple children


How to stop Excel from firing Worksheet_Change before Workbook_BeforeSave?

Question: Update: Issue Resolved A colleague of mine was changing a cell during Workbook_BeforeSave() without disabling events, therefore triggering Worksheet_Change(). Yes, silly, but at least it's our fault, not Excel's
I've noticed that whenever I hit Ctrl+S in Excel, the Worksheet_Change() is fired before Workbook_BeforeSave(). Is it possible to supress this behaviour using VBA code, but without supressing all events (i.e. without Application.EnableEvents = false)?
This happens regardless of what I'm doing. I've read about someone having a similar issue with ComboBoxes, but I'm not editing ComboBoxes, yet Worksheet_Change() fires always before saving.
Any ideas? I'm only trying to figure out how to bypass some code inside Worksheet_Change() when the document is saved, because that code is only supposed to be executed when the user actually changes something, not when the workbook is saved. Saving is by no means changing...
Comment: Is this on all files or just one workbook? If a single workbook dO you have any volatile functions that may be triggerd on the save in that workbook?
Comment: Only the active workbook is affected. And no, I have no volatile functions in the workbook.
Comment: Just tried with a clean workbook, and this problem does not appear. I have no idea what I'm doing wrong in the first workbook, but I'm working on it. Will post whatever I find.
Comment: If you try "rebirthing" the problem workbook [by (1) selecting all sheets, right click, Move or Copy and pick (new book) for "to:book", (2) copying the code in the `ThisWorkBook` module of your problem workbook over] then does it reoccur?
Comment: Question closed. A colleague of mine was changing a cell during `Workbook_BeforeSave()` without disabling events, therefore triggering `Worksheet_Change()`. Yes, silly, but at least it's our fault, not Excel's.
Comment: @brettdj: thank you for your desire to help. I appreciate it. Your first comment, about possible volatile functions, was quite clever.
Comment: Good to hear. I had presumed that the sequence of code firing had been tested given ` Worksheet_Change() is fired before Workbook_BeforeSave()` . All's well that ends well. :)
Answer: It was a coding mistake on our side:
A colleague of mine was changing a cell during Workbook_BeforeSave() without disabling events, therefore triggering Worksheet_Change().
The fix was easy. In Workbook_BeforeSave():
Application.EnableEvents = False
' Some final changes
Application.EnableEvents = True

And that was it :)
Answer: Add a global flag variable.
Input a function that fires when key pressed and if CTRL + S it sets flag to true.
The worksheet_change event should short circuit if this flag is true.
And workbook_aftersave should change it back to false.


Displaying dictionary word with GDB in Jonesforth

Question: In Jonesforth, a dictionary entry is laid out as follows:
<--- DICTIONARY ENTRY (HEADER) ----------------------->
+------------------------+--------+---------- - - - - +----------- - - - -
| LINK POINTER           | LENGTH/| NAME          | DEFINITION
|                        | FLAGS  |               |
+--- (4 bytes) ----------+- byte -+- n bytes  - - - - +----------- - - - -

We can take a peek at one of these entries using GDB. (See this question for details on using GDB with Jonesforth.)
Let's display the first 16 bytes of the dictionary entry for SWAP as characters:
>>> x/16cb &name_SWAP
0x105cc:    -68 '\274'    5 '\005'    1 '\001'    0 '\000'    4 '\004'    83 'S'    87 'W'    65 'A'
0x105d4:    80 'P'    0 '\000'    0 '\000'    0 '\000'    43 '+'    0 '\000'    1 '\001'    0 '\000'

You can kind of see what's going on here.
The first four bytes are the pointer to the previous word in the dictionary:
-68 '\274'    5 '\005'    1 '\001'    0 '\000'

Then comes the length of the name:
4 '\004'

Then we see the characters of the word name, "SWAP":
83 'S'    87 'W'    65 'A'   80 'P'

And finally some padding to align on a 32-bit boundary:
0 '\000'    0 '\000'    0 '\000'

It would be nice if there was a way to format the word entry in a nicer manner.
If we do the following:
>>> x/1xw &name_SWAP
0x105cc:    0x000105bc

we note that name_SWAP is at 0x105cc.
Let's use GDB's printf to display the word entry:
>>> printf "link: %#010x   name length: %i   name: %s\n", *(0x105cc), (char)*(0x105cc+4), (0x105cc+5)
link: 0x000105bc   name length: 4   name: SWAP

OK, that's not bad! We see the link, the name length, and name, all nicely displayed and labeled.
The downside here is that I have to use the explicit address in the call to printf:
printf "link: %#010x   name length: %i   name: %s\n", *(0x105cc), (char)*(0x105cc+4), (0x105cc+5)

Ideally, I'd just be able to say something like:
show_forth_word name_SWAP

and it'd display the above.
What's the best way to go about this? Is this doable with a GDB user-defined command? Or is it something more appropriate for the GDB Python interface?
Answer:
My question is, what's the best way to go about this?

It depends on whether GDB knows about the type of name_SWAP. If it does, the Python pretty-printer is the way to go.
If it doesn't, something as simple as user-defined command is likely easier. Assuming 32-bit mode:
define print_key
 set var $v = (char*)$arg0
 printf "link: %#010x   name length: %i   name: %s\n", *((char**)$v), *($v+4), ($v+5)
end

Comment: @dharmatech Are you saying that `x/1xw &name_SWAP ` works, but `print_key &name_SWAP` doesn't? That's hard to believe.
Comment: @dharmatech I had a missing `$` in `set var ...`. Corrected.
Comment: If I try `print_key name_SWAP` or `print_key &name_SWAP` I get the following: `No symbol table is loaded.  Use the "file" command.`.
Comment: Here's a [screenshot](https://i.imgur.com/knxsiwb.png) of exactly that happening. :-)
Answer: I just used nm , the good old Unix command.
Comment: The idea here is to show the actual data in the dictionary entry. `nm` as well as `objdump` shows the location of `name_SWAP`, but it doesn't show the fields in the dictionary entry (link, name length, name characters, etc.).
Comment: The "Forth" way is to create new Forth words yourself for this.

I am working on a [C to Forth (jonesforth) to C interface](https://github.com/udexon/5CSM/blob/master/Progress_20181203.md).

Do let me know if there is any overlap or opportunities for collaboration.


Fetch the difference in result in Oracle

Question: I have two tables table_one and table_two.
table_one has incomplete records while table_two has all records
I want to fetch the difference in each date id_date, however i cant get results in a date where there is no record to join
SELECT
  ID_DATE,
  CODE,
  RATE,
  SUM(PURCHASES),
  sum(COMMISSION)
FROM (
SELECT
  A.ID_DATE,
  A.CODE,
  A.RATE,
  (B.PURCHASES - A.PURCHASES) PURCHASES,
  (B.COMMISSION - A.COMMISSION) COMMISSION
FROM (SELECT * FROM  TABLE_ONE WHERE   ID_DATE BETWEEN  20201101 AND 20201130 ) A LEFT JOIN
(SELECT  *  FROM TABLE_TWO WHERE   ID_DATE BETWEEN  20201101  AND 20201130 ) B
ON A.ID_DATE  = B.ID_DATE AND   A.CODE = B.CODE AND A.RATE = B.RATE
)  GROUP BY ID_DATE, CODE, RATE

Link to my fiddle for test  click here
I cant get records of id_date 20201111 for example
Comment: I'd try `coalesce(B.PURCHASES, 0)` etc to avoid null issues-
Comment: Why not a RIGHT JOIN? (If table_two is complete.)
Comment: @jarlh i will add that,
Comment: In answer to your [deleted question](https://stackoverflow.com/q/66134453/1509264) you can use [db<>fiddle](https://dbfiddle.uk/?rdbms=oracle_18&fiddle=01c53605ffcd476f6cfc2720605c633a).
Comment: @MT0 I have undeleted, after editing. post to answer
Answer: Is this what you want?
select t2.id_date, t2.code, t2.rate,
    sum(t2.purchases - coalesce(t1.purchases, 0)) as purchases,
    sum(t2.commission - coalesce(t1.commission, 0)) as commission
from table_two t2
left join table_one t1 on t2.id_date = t1.id_date and t2.code = t1.code and t2.rate = t1.rate
where t2.id_date between 20201101 and 20201130
group by t2.id_date, t2.code, t2.rate

Answer: You need to use proper join and it can be achieved using the following query:
SELECT B.ID_DATE,
       B.CODE,
       B.RATE,
       SUM(B.PURCHASES - COALESCE(A.PURCHASES,0)) PURCHASES,
       SUM(B.COMMISSION - COALESCE(A.COMMISSION,0)) COMMISSION
  FROM TABLE_TWO   B
  LEFT JOIN TABLE_ONE   A
ON A.ID_DATE = B.ID_DATE
   AND A.CODE = B.CODE
   AND A.RATE = B.RATE
   AND A.ID_DATE BETWEEN 20201101 AND 20201130
 WHERE B.ID_DATE BETWEEN 20201101 AND 20201130
 GROUP BY B.ID_DATE,
          B.CODE,
          B.RATE
ORDER BY ID_DATE

db<>fiddle demo


Has MongoDB Improved Its Algorithms for Reusing Empty Space?

Question: I'm going through "MongoDB, The Definitive Guide, 2nd edition", and the author states: "As of this writing, MongoDB is not great at reusing empty space, so moving documents
around a lot can result in large swaths of empty data file... If your schema requires lots of moves or lots of churn through inserts and deletes, you
can improve disk reuse by using the usePowerOf2Sizes option".
This book was written when MongoDB was version 2.4, while today its version 3.4. After going through a major version update, i'm curious if Mongo has made revisions to where the usage of usePowerOf2Sizes option is still necessary?
Answer: Well, MongoDB has included a new storage engine WiredTiger which is great improvement and doesn't store the data like earlier MMapV1 used to store where there was predefined size and when the size increased it applies twice the size, kind of how arraylist works in Java.
However MongoDB does provide a compact command to reclaim the empty spaces, similar to memory defragmentation. Really useful when working with MMapV1 and have collection with millions of documents.


Best way to load modules in CodeIgniter MVC

Question: I am new to the CodeIgniter fw of PHP and generally have medium experience with MVC. I am working on a project where using modules will make my life a lot easier.
There is something regarding the way you call the modules that is a bit unclear in my head. The solution I had was to call the full module in the controller and pass the code as a variable in the view and then just echo it. Here is a sample of that logic
<code>// Controller
$var['login'] = // code that calls the module
$this->load->view('index', $var);

// View
<div class='navbar'>
    <?= $login; ?>
</div>
</code>

However after a small search, I found this solution Creating Block/Modules in Code Igniter
(String path of the module (view2) in the controller, pass it to view1 and then call it in the main view): .
Which of the 2 logics is the one that follows the MVC standards in a better way?
UPDATE: I have found the answer on how to do both here: how to load view into another view codeigniter 2.1?
but my question remains the same. Which is the best logic that follows the MVC standards better?
Comment: Did you try HMVC? https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc
Comment: It is unclear what your question is.
Answer: first create model object
like
$model = new mymodel
where u want to call do this
 $this->model->your_function_name($parameter);
Comment: Why to involve models in that?


Using the .NET Simple Membership provider - but authenticating against an external service

Question: I would like to use the Simple Membership provider in my MVC4 application to take advantage of the features that it provides, but I would like to redirect the login method to use an external web service.
I'm having trouble even finding a starting point on line for this. If someone could point me in the right direction I would be very grateful!
Comment: try this link http://weblogs.asp.net/jgalloway/archive/2012/08/29/simplemembership-membership-providers-universal-providers-and-the-new-asp-net-4-5-web-forms-and-asp-net-mvc-4-templates.aspx
Answer: Maybe this will help you start with that.
http://msdn.microsoft.com/en-us/library/bb386424(v=vs.100).aspx


What are differentials with respect to?

Question: If $x=y^2$, then $\frac{dx}{dy}=2y$, which means that the rate of change of $x$ with respect to $y$ equals $2y$.
We can also find the differential of $x$. We get that $dx=2ydy$. But what is this with respect to? It doesn't make any sense to have a rate of change without respect to anything, right?
Comment: $dx$ is an infinitesimal change in $x$, not a rate
Comment: I prefer to think of $dx$ and $dy$ as one-forms on $\mathbb{R}^2$ - take a look at some introductory differential geometry for a more complete picture. e.g. Loring Tu's book Intro to Manifolds
Answer: It means that if $y$ changes by a small amount $dy$, then the corresponding change in $x$ will be $2ydy$. One can divide by $dt$, where $t$ is an arbitrary variable and change the equation to $$\frac{dx}{dt} = 2y \frac{dy}{dt}$$ This shows that the change in $x$ will be the same, no matter what we're differentiating with respect to.
Answer: The statements $dx=2ydy$ and $\frac {dx}{dy}=2y$ are the same.
The first one is the rate of change of $x$ with respect to $y$ so if you change your y from $y_0$ to $y_0+dy$ then the linear approximation to change in $x$ is $dx=2ydy$

What are differentials with respect to?


Foundation cracks in new home construction North Texas

Question: I am currently building a house in north Frisco and I noticed a some cracks from the middle of the foundation and they go down to the side as see in the pictures. I have not yet contacted the builder as I am trying to get more info on the issue to be able to respond. Are these common and should I be alarmed? I had scheduled a private inspector for the pre sheetrock inspection and I may have to schedule an inspection for this as well. Thank you all in advance!

Other pictures: https://ibb.co/8dwsDwz
https://ibb.co/qCv2Lfs
https://ibb.co/7KjZKmb
https://ibb.co/pdF63vf
https://ibb.co/KLj8vrB
https://ibb.co/X2nTgjR
https://ibb.co/SxDJCXV
https://ibb.co/9HQLRh3
Answer: I would be concerned with the through thickness cracks ; at least have an independent inspector look at it. My son had a KB  home ( cable tension slab) in Round Rock , the cracks did not show up for a couple years but then no one would write a mortgage on the home. He was able to find a buyer that did not need a mortgage.
Answer: Concrete is not designed to crack. When it does, it's a mistake. The designer and/or contractor does not know the difference between reinforcing steel and temperature steel.
Get it fixed or withhold payment to the contractor until it's fixed or a structural engineer (not a civil engineer) signs off as "The crack will not get wider."


Autoboxing Concept SCJP

Question: This question is been manipulated from exam labs
public class B{

      public static void main(String args[]){
        byte g =10;
          Byte x = new Byte(g);
          B p= new B();
          p.doStuff(x);
                      p.doStuff(g);
    }
      void dostuff(Number y){
          System.out.println("C");
      }
      void doStuff(short t){
          System.out.println("X");}

      }

Output : XC
In above program , i dont understant why its giving "C" as output?
its giving X because Byte--> byte-->short;
but in case of , byte g=10;  it should again pass through same method and give "X"  as output.
public class B{

          public static void main(String args[]){
          byte b1=12;
          Byte B1=new Byte(b1);

          capture(b1);
          capture(B1);

        }

        static void capture(short x){
          System.out.print("A");
        }

        static void capture(Number x){
          System.out.print("G");
        }
      }

output : AG
Here , also i understand why its A , because short is bigger than byte so it gives A
But , for other output its should be again A , because B1 is Byte ---> byte(Autoboxing) --->pass through short (Widdening). Why its G?
Comment: Its seems output of first example is wrong. Should it be CX ?
Answer: Don't take this for granted, but I think it's because a Byte is a Number, so it doesn't have to do any autoboxing if it chooses that version. Also, if it still chose the other one, there would be no way at all to call the Number version. Therefore, it makes more sense to have such calls call the Number version, which is exactly what java does.

Autoboxing Concept SCJP


No idea why orthographic projection displays nothing, can anyone help? (OpenTK)

Question: I've recently started working with OpenTK, and as always with OpenGL, I'm frustrated by the setup. My code is a bit of a mess right now, but can anyone tell me why the output is blank (background color) with this orthographic projection?
The external calls to a Render() function are functional, and render quads positioned around the current origin. The geometry displays when I use the perspective projection example in the code, but that isn't my goal.
Ignore the stuff about shaders, that's just there arbitrarily (not actually used).
<code>using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Genesis
{
    class Game : GameWindow
    {
        public static Game Inst;

        public Matrix4 ModelViewMatrix;
        public Matrix4 ProjectionMatrix;

        private int ShaderProgram;

        private int VertexShader;
        private int FragmentShader;

        float rot = 0;

        public GameObject Selector;

        public Multiblock BaseIsland;

        private List<GameObject> gameObjects = new List<GameObject>();

        public Game()
            : base(1000, 650, GraphicsMode.Default, Strings.WINDOW_TITLE)
        {
            VSync = VSyncMode.On;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            GL.ClearColor(0.0f, 0.8f, 0.8f, 0.0f);

            GL.Enable(EnableCap.Texture2D);

            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);

            GL.Enable(EnableCap.DepthTest);

            ShaderProgram = GL.CreateProgram();

            VertexShader = GL.CreateShader(ShaderType.VertexShader);
            GL.ShaderSource(VertexShader, ShaderSource.Vertex_Default);
            GL.CompileShader(VertexShader);

            FragmentShader = GL.CreateShader(ShaderType.FragmentShader);
            GL.ShaderSource(FragmentShader, ShaderSource.Fragment_Default);
            GL.CompileShader(FragmentShader);

            GL.LinkProgram(ShaderProgram);

            //GL.UseProgram(ShaderProgram);

            Assets.Init();
            Blocks.Init();

            //INIT
            BaseIsland = new Multiblock("Base Island", 7, 7);
            for(int x = 2; x <= 4; x++)
            {
                BaseIsland.SetBlock(x, 0, Blocks.BLOCK_DIRT);
            }
            for (int x = 1; x <= 5; x++)
            {
                BaseIsland.SetBlock(x, 1, Blocks.BLOCK_DIRT);
            }
            for (int x = 0; x < 7; x++)
            {
                BaseIsland.SetBlock(x, 2, Blocks.BLOCK_GRASS);
            }
            for (int y = 3; y < 7; y++)
            {
                BaseIsland.SetBlock(3, y, Blocks.BLOCK_STONE);
            }
            BaseIsland.SetBlock(2, 5, Blocks.BLOCK_STONE);
            BaseIsland.SetBlock(4, 5, Blocks.BLOCK_STONE);

            Selector = new GameObject(Assets.UI_SELECTOR);
        }

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);

            GL.Viewport(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width, ClientRectangle.Height);

            //ProjectionMatrix = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, Width / (float)Height, 1.0f, 64.0f);
            ProjectionMatrix = Matrix4.CreateOrthographic(Width, Height, 1.0f, 100.0f);
            Console.WriteLine(ProjectionMatrix);
            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadIdentity();
            GL.LoadMatrix(ref ProjectionMatrix);
        }

        protected override void OnUpdateFrame(FrameEventArgs e)
        {
            base.OnUpdateFrame(e);

            if (Keyboard[Key.Escape])
                Exit();

            //TileSelection sel = Input.GetSelectedTile();

            Vector2 mousePos = Input.GetMousePosition();
            float sx = (mousePos.X * Constants.GLOBAL_SCALE) / (Constants.PIXELS_PER_UNIT * 0.83f);
            float sy = (mousePos.Y * Constants.GLOBAL_SCALE) / (Constants.PIXELS_PER_UNIT * 0.83f);
            Selector.Transform.SetPosition(sx, sy);

            //Console.WriteLine("ProjectionMatrix");
            //Console.WriteLine(ProjectionMatrix);

            rot = (rot + 1.0f) % 360;
            Console.WriteLine(rot);
        }

        protected override void OnRenderFrame(FrameEventArgs e)
        {
            base.OnRenderFrame(e);

            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            ModelViewMatrix = Matrix4.LookAt(Vector3.Zero, -Vector3.UnitZ, Vector3.UnitY);
            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadIdentity();
            GL.LoadMatrix(ref ModelViewMatrix);

            GL.Rotate(rot, 0, 1, 0);
            GL.Translate(0, 0, -5);
            GL.Scale(Constants.GLOBAL_SCALE, Constants.GLOBAL_SCALE, 1);

            //GL.UseProgram(ShaderProgram);

            for (int i = gameObjects.Count - 1; i >= 0; i--)
            {
                GL.PushMatrix();

                gameObjects[i].Render();

                GL.PopMatrix();

            }

            SwapBuffers();
        }

        public void OnGameObjectCreated(GameObject obj)
        {
            gameObjects.Add(obj);

            Console.WriteLine("GAMEOBJECT CREATED: " + obj.Name + " - " + obj.Texture);
        }

        public void OnGameObjectDestroyed(GameObject obj)
        {
            gameObjects.Remove(obj);
        }

        [STAThread]
        static void Main()
        {
            using (Game game = new Game())
            {
                Game.Inst = game;
                game.Run(30.0);
                Game.Inst = null;
            }
        }
    }
}
</code>
Comment: To clarify, I know that the geometry is still being rendered somewhere. I just don't know how to properly configure it so that the geometry appears within the viewport (and properly transformed).
Answer: If you want orthographic camera, you should change
camera property in Inspector.
Comment: Could you elaborate? It sounds like you think I'm using Unity, which I'm not. I'm using OpenTK, a graphics framework for Visual Studio. The application is compiled only from code, not from any sort of graphical IDE configuration.


Wget Hanging, Script Stops

Question: Evening,
I am running a lot of wget commands using xargs
cat urls.txt | xargs -n 1 -P 10 wget -q -t 2 --timeout 10 --dns-timeout 10 --connect-timeout 10 --read-timeout 20

However, once the file has been parsed, some of the wget instances 'hang.' I can still see them in system monitor, and it can take about 2 minutes for them all to complete.
Is there anyway I can specify that the instance should be killed after 10 seconds? I can re-download all the URLs that failed later.
In system monitor, the wget instances are shown as sk_wait_data when they hang. xargs is there as 'do_wait,' but wget seems to be the issue, as once I kill them, my script continues.
Answer: I believe this should do it:
wget -v -t 2 --timeout 10

According to the docs:

--timeout: Set the network timeout to seconds seconds.  This is equivalent to specifying
--dns-timeout, --connect-timeout, and --read-timeout, all at the same time.

Check the verbose output too and see more of what it's doing.
Also, you can try:
timeout 10  wget -v -t 2

Or you can do what timeout does internally:
( cmdpid=$BASHPID; (sleep 10; kill $cmdpid) & exec wget -v -t 2 )

(As seen in: BASH FAQ entry #68: "How do I run a command, and have it abort (timeout) after N seconds?")
Comment: It doesn't make any difference. I'm looking at the verbose output, but there's so much that if there was something here I don't think I'll see it.
Comment: Also, `-v` is superfluous. "The default output is verbose." (man wget)
Answer: GNU Parallel can download in parallel, and retry the process after a timeout:
cat urls.txt | parallel -j10 --timeout 10 --retries 3 wget -q -t 2

If the time for an url to be fetched changes (e.g. due to faster internet connection), you can let GNU Parallel figure out the timeout:
cat urls.txt | parallel -j10 --timeout 1000% --retries 3 wget -q -t 2

This will make GNU Parallel record the median time for a successful job and set the timeout dynamically to 10 times that.

Wget Hanging, Script Stops


Should I cover my air conditioner for winter?

Question: Should I cover my air conditioner for winter? It's difficult to find an appropriate cover, but finding a cover for an evaporation cooler is easy (and because they allow for air flow from the outdoors, it makes sense).
See this answer for things to do before winter hits, where it's not clear whether an air conditioner should be covered or not.
I don't want to let water build up inside and given my climate, it will freeze and thaw repeatedly which can be very damaging. On the other hand, I don't want to create a moisture barrier that leads to other problems.
Any official word on this?
Answer: I have never covered mine and this article also seems to recommend not covering it:

Your central air conditioning unit
  consists of a compressor and
  condensing unit placed outdoors in a
  metal housing. These units, built to
  resist the weather, generally do not
  need a cover. In fact, covers can
  cause problems because they trap
  moisture and create an inviting winter
  home for small animals.
Professionals who service the units
  tell me that most of the damage they
  see in spring was caused by rodents
  living in the units and chewing on
  wiring.
If your air conditioner is subject to
  falling ice or other debris, you could
  cover its top with a piece of plywood,
  plastic or metal held in place by a
  weight.
  Reference: http://misterfix-it.com/blog/?page_id=36#cac

They make a great point that a cover would provide a perfect winter home for animals which would cause damage to your air conditioner.
Comment: Our installer was very explicit in saying nothing more then a piece of plywood with a brick on it should go on the unit, and he said that if I did that to make sure I open the outside disconnect. (I did do that last winter since my unit is right where the icicles usually pile up)
Comment: After talking to a friend in the HVAC business, I found out that sometimes people forget the covers, turn the units on in spring, and wind up with a service call when the unit overheads.
Comment: *Overheats! Doh.
Answer: I cover mine in the winter using a single unopened trash bag and some duct tape.  The bag is the right size to cover just the top and not much of the sides.  This allows ventilation on the sides while keeping snow and ice from entering from above.  With the duct tape, it's just a strip down each corner and then I run a band of tape around the perimeter of the bag to reduce the risk of it blowing away.  I think the important tip that Jeff's link mentions is to not completely seal the unit, but simply prevent damage from above.
Answer: Most people who advocate covering mention that debris, ice, and snow can get into your air conditioner in the winter if it's not covered. Plus it'll end up more weather-beaten if left uncovered.
Answer: Never covered mine in the 31 years I've had it and I live-in upstate New York--brutal winters. no need to cover it.It's designed to be outdoors.Around here there's more damage done in the spring with the cotton wood seeds plugging the condenser.
Answer: It is good to cover the top 1/4 to 1/2 of the air conditioner. This stops moisture from entering through the top and then freezing/thawing repeatedly through the winter. First, although paint technology is very advanced, constant expansion and contraction of painted metal will eventually lead to cracking and this rusting of the metal. Secondly, there are threaded connections between the tubing that goes from the compressor and condenser/evaporator cooling coils. Water can enter these threads and expand and contract eventually causing a leak and thus loss of gas.
Covering 1/4 to 1/2 of the unit will keep the interior of the unit under the same temperature/humidity conditions as the outside air. Although this cover will keep the interior of the unit dryer, it will not provide as good a quality of home for critters as if the unit was covered completely. There will still be good ventilation of icy air to make animules look for better digs.


Rating Slider: Design choice for the un-selected state

Question: I have 4 point rating slider question in my survey form. The survey can have multiple questions with sliders. The current design uses different color on the selector handle(circle) to distinguish between selected(blue) and un-selected(grey) states. When the user launches the form, the slider questions are in the un-selected state.

When a slider question is un-selected, the form shows error upon submission. In early usability trials, we found that the user is not able to tell if he has made the choice OR not(because we show the rating handle in both states).
We tried to park the selector handle out side the position markers in the un-selected state. But, this design didn't get favorable reviews.
What would be the best approach to address this issue?
Additional Information:
There are two types of users in the system: survey creators are survey takers. The screen above is shown to the survey takers.
Survey creators want to see the rating scale because it looks flashy. I personally prefer to use radio button group to represent the rating scale as it makes the survey taking easier. I want to hear from the community to get a second/alternative opinion(s).
Comment: Interesting question, it's always been hard to show a "default" state on these
Comment: Your users are correct. If the slider shows a value then that should be its value and there should be no error. You are correct. The control to use is a radio button group. The survey creators are incorrect. That's your real problem. Tell them you don't use a joystick to play piano. Provide evidence that your users are annoyed by the slider, not thrilled on how flashy it is.  Consider ways to add flash around the scale without hurting function (e.g., reinforcing highlighting of selected value).
Answer: I think there are two problems here:
First, you are showing a discrete scale (4 points) using a continuous spectrum scale widget (many points). It should be represented as discrete states, not a continuous spectrum.
Second, you are inventing a new widget for something people have encountered many times. People have seen the four radio buttons laid out horizontally. Most people know how that works. This widget is unfamiliar and requires people to create a new mental model of how it operates. Your usability tests show that they are creating the wrong mental model.
My solution would be to switch to a discrete scale with four radio buttons laid out horizontally. Action is required to answer the question. The default is the null state (nothing selected).
It's not sexy, but it is:

familiar to people
gives four distinct options
requires no action for the null state

Try a usability test and see if it works. If it does, then you're good. If it doesn't then  you have some other problem.
From your clarification to the question, the real problem is the "survey creators." They believe they are right. So they are interpreting the usability data to mean either (a) the users are wrong or (b) the design is wrong. The answer is that the design is wrong. But they're not willing to accept the right design. Your real problem is changing their minds.
Comment: +1. I have added additional information to my question about the background.
Comment: Then you need to do a usability test of the 2 options to show the "survey creators" that one works and the other does not. Give them evidence. They are thinking that users should behave some way and you need to find a non-biased way of showing how people actually behave and what actually works, even when that's not what you want.
Answer: Do you have to use a slider? Why not four stars, with no stars meaning no data entered? Netflix does this well, with tooltips for each star indicating its significance.
IF you must retain a slider, you could make it a five point scale with zero in the middle as a default.
Answer: Given your restrictions - having to use a slider because someone else thinks it looks good - I would suggest that you use a check box to indicate not selected as an addition. If this is not checked, then the scale is disabled, when you check it the scale is enabled.
But, as others have said, this is the wrong tool to use, and your better option would be to tell them to do things properly.
Answer: Assuming that the slider is a must, you could try initially displaying the slider without the knob, and only displaying the knob on mouseover. Then it's pretty clear that no values are selected, and you still get to keep the flash.


How to remove unwanted characters in tcl variable value?

Question: I have extracted a full name and stored it into a variable.
The below is just for illustrative purpose. In reality,the variable $a is extracted from a log file.
like
set a "John Doe"

The issue is that I can't figure out if there any special characters in the full name which is extracted. I basically tried everything.
Using trimleft,trimright or trim for trailing whitespace. This didn't resolve the issue.
Also tried printing ASCII code values, but could only find the same codes as represented in the full name.
I needed some help with ideas or suggestions about how we can go ahead and remove any unwanted characters in the full name.
The only thing which is bugging me I don't know what those unwanted characters are.
Comment: What's a "special character"? What problem are you having?
Comment: I will remove tags. But the special character could be anything. I am not able to figure out yet. I thought initially whitespace, or /t at the starting and end. But that didn't help much.
Comment: What are "non-special" characters? Is there a specific set of characters that are allowed?
Comment: Non special characters can be anything like extra space, or tabs. I thought it had something to do with encoding of the Full name which is fetched from the logs.set fullName [encoding convertto utf-8 $a]

This didn't help.On display in console, i only see the Full name "John Doe" . I dont find anything unusual.
I am having hard time figuring out what or which characters is causing this issue. This name which is fetched from our tcl variable,
is further  used in a SQL query to fetch some records from DB. But we are not getting any hits.
Answer: Without an exact definition of what is a "special character", it is extremely difficult to suggest anything concrete. However, if we assume that we're talking about converting all sequences of non-alphanumeric characters to something defined (such as _) then we can use regsub to do the task:
set b [regsub -all {\W+} $a "_"]

In your case, it turns John Doe into John_Doe. It also turns **{!John . . . %%''   '''(Doe)@@ into _John_Doe_.

The regular expression \W+ matches (maximally) any non-empty sequence of non-word (non-alphanumeric) characters. That's pretty good for cleaning up a very large fraction of weird user inputs. (It's imperfect for names though, as Patrick O'Brien will tell you. Names are plain old tricky.)


query for records that do not exist

Question: SELECT today.status, GROUP_CONCAT(tomorrow.work_order order by line), today.code, today.events
FROM today LEFT JOIN tomorrow
   ON today.code = tomorrow.code
   WHERE today.status like '1%' or
      (today.status like '3%' and tomorrow.work_ordertext is null)
      GROUP BY today.code

I am having issues with the 'tomorrow.work_ordertext is null' statement. tomorrow.code and tomorrow.work_ordertext may not even exist in the table, so I am guessing it shouldn't really be a null statement. I am looking for a way to pull rows from the today table if no records exists on the tomorrow table once the status is like 3 in the today table. Sorry if it sounds confusing.
Answer: SELECT today.status, GROUP_CONCAT(tomorrow.work_order order by line), today.code, today.events
  FROM today LEFT JOIN tomorrow
ON today.code = tomorrow.code
WHERE today.status = 1 or
  (today.status = 3 and isnull( tomorrow.work_ordertext ))
  GROUP BY today.code

I took out the like for the status as it will match 1, 10, 1b, 1somethingweird.
Comment: Sorry for the late reply, but this didn't work. Or at least I am getting a time out error each time.
Comment: Can you a 'desc' on the query and post that?

query for records that do not exist


Stuck on installing Brasero

Question: <code>0% [Connecting to us.archive.ubuntu.com (220.127.116.11)]

 Cannot initiate the connection to us.archive.ubuntu.com:80 (2001:67c:1562::16). - connect (101: Network is unreachable) [IP: 2001:67c:1562::16 80]
0% [Connecting to security.ubuntu.com (22.214.171.124)]
</code>
I'm trying to install Brasero as a burner for my DVD, but it doesn't proceed. I tried installing it from ubuntu software as well as in terminal same result. In Ubuntu Software app it says pending forever.
Answer: It seems your local repository mirror is currently down, for workaround you can try changing the repository to the Main Server, here's how to do it:

Open dash then type Updates, click/open Software & Updates from search result.
On Download From drop down menu selection, choose Main Server.

There will be pop-up asked you to fill your password, once you have type your password click Authenticate button to apply change you've made.

Close the window then.

Stuck on installing Brasero


What is the term for a pop-up box that fades away but remains accessible at all times?

Question: Workday seems to have implemented a really slick feature. A pop-up box appears that has the following features
a) It fades away when not in focus but not quite fully. Transparent I would say
b) It can be dragged around
c) User can work on other items
d) Support for a close, gear, hyperlinks within box
What is the term that describes this pop-up?
Comment: Can you provide a screenshot or some such? I have visited the site but can't find what you are talking about?
Comment: NotePad++ does that also; I hate it; it makes things harder to see and use.
Comment: @Max - I think I have seen this in Notepad++. Its much slicker than that. It pretty much fully disappears with a very light shade remaining when not the window in focus.
Comment: If this feature is implemented in a web application, try to locate it in the code (with Firebug for example). Maybe you can find a name or a framework there. Other than that, jQuery UI supports dragable pop-ups and I think transparency is also supported... But I never really worked with it.
Comment: @Marjan - looks like I already submitted the action in Workday and now cannot go back to that screen. Sorry.
Answer:
What is the term that describes this pop-up?

I dont think there exists a term for this but at best I would describe it as "Windows that enables transparency when out of focus" Netbeans IDE also refers to it as this way and so does notepad++

Which javascript frameworks support this feature?

For the transparancey? I would say the simple old jQuery. For the window elements/gui features (dragging, support for gear, close etc), jQuery UI There are many plugins that are built upon the jQUery UI to provide a more rich gui experiance
Comment: That does not answer my question.
Comment: Well you need to give an image of the box u have in mind. Slick is a very broad word u need to be precise if you want us to understand what ur imagining. Maybe a rough sketch in pain or w.e? Idk but something
Comment: agreed! unfortunately I was not able to redo that piece in Workday to be able to provide that.
Answer:
What is the term that describes this pop-up?

The term is dialog. You can optionally make dialogs modal, draggable, and transparent.  You can put different buttons on them for different actions. And much more.
As has been mentioned, jQuery UI does this quite well. I've used it many times.
Here are some live examples:

https://jqueryui.com/dialog/
http://imperavi.com/redactor/examples/uidialog/
http://salman-w.blogspot.com/2013/05/jquery-ui-dialog-examples.html
Comment: No, none of the examples illustrate the behavior I observed. Again, as I said it was very slick. It was barely visible. The closest I english word I can come up with is "hint". It was a barely visible hint if I needed to get quick access to functionality while I proceeded with my main task.
Answer: It depends on the scenario.

If you're referring to the pop-up you get when you click the "Related Actions" button, I would call this a "tear-off" (click the button, and then drag the handle at the top of the popup window; you "tore it off" from where it was originally anchored to)
If it's in the context of being able to see more specific information about  an otherwise general topic, I believe the correct Workday term for this is "drill-down".

Neither of these terms really has a requirement to be semi-transparent, although "overlay" comes to mind in this case. I personally have not encountered a feature like the one you have described. Of course, Workday is changing things every other day, so it will probably show up sooner or later.


Intersection of lists of tuples - Haskell

Question: I have two lists of tuples both of the form [(a,b),..].
I wish to compare them and get the common elements - but have tried using intersect, but this does not work. Is there a way of using map/filter to output the intersection as a new list of tuples?
Comment: Please show your code, `intersect` should work fine for you
Answer: Try with a list comprehension:
[x | x <- list1, x `elem` list2]

Example:
Prelude> let list1 = [(1,2), (2,3), (3,4)]
Prelude> let list2 = [(1,2), (2,3), (3,5)]
Prelude> [x | x <- list1, x `elem` list2]
[(1,2),(2,3)]

Anyway, intersect should work, it works for me:
Prelude> import Data.List
Prelude Data.List> list1 `intersect` list2
[(1,2),(2,3)]

Comment: Filter would also work: `filter (\`elem\` list2) list1` :)
Comment: In your answer `intersect` compares all elements of the tuple, but I think topic starter wants to find all intersections based on comparison of the first only element of tuple.
Answer: You can use Data.Function.on function to supply function you need to the first (or second) element of the tuple:
import Data.Function (on)
import Data.List (intersectBy)

intersectBy ((==) `on` fst) [(1,2), (2,3), (3,4)] [(1,2), (2,3), (3,5)]
> [(1,2),(2,3),(3,4)]

Comment: I guess this returns the matching tuple from the left list. Can we tell something like `intersectBy ((==) \`on\` fst)` and `select (min \`on\` snd)`?


Unable to execute shell script via java servlet

Question: I'm trying to execute a simple shell script via java servlet using process builder and I'm not getting any output. I searched for number of solution on stack overflow but nothing helped me out yet...
Here is my code that I'm trying to execute..
HTML:
<form method="post" action="SmxServlet">
    <input type="submit" value="Click">
</form>

Shell script:
echo Hello world!, here your args $@ > log.html 2>&1

SmxServlet.java:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        String[] command = {"/bin/bash", "test.sh", "Argument1"};
        ProcessBuilder p = new ProcessBuilder(command);
        Process p2 = p.start();
        try {
            p2.waitFor();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(p2.getInputStream()));
        String line;

        System.out.println("Output of running " + command + " is: ");
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        //RequestDispatcher dispatcher = request.getRequestDispatcher("log.html");
        //dispatcher.forward(request, response);
    }

As out put in console, I'm getting below with no value:
Output of running [Ljava.lang.String;@77f03096 is:

Can anyone out there please help with this? Is there anything that I'm doing wrong?How to fix it? Really appreciate your help!
Comment: Your command doesn't generate any output on the standard output, so Java doesn't receive any. That's because your echo command sends everything to the file `log.html` rather than the standard output stream.
Comment: Did you try with "echo Hello world!" only,to see if it is working?
Comment: What other errors did you get?
Comment: @ErwinBolwidt No, the output is not getting copied to log.html as well.
Comment: @ShivamAggarwal yes I tried only "echo Hello world!" as well but still stuck... I'm not getting any errors.. its just the code is not working.. I'm using eclipse and tomcat 7, in case if they are culprits.
Answer: Your command doesn't generate any output on the standard output, so Java doesn't receive any. That's because your echo command sends everything to the file log.html rather than the standard output stream.
However, there is another problem: the exclamation mark has a special meaning in the shell. If you run your script manually, you'll see an error like bash: !,: event not found
So you need to escape the exclamation mark.
Change the command in test.sh to
echo Hello world\!, here your args $@

to make it work
Comment: Actually nothing is printing in log.html as well and per your suggestion I did made the changes and it still doesn't work. running the test.sh script manually is not giving me any error.


How do I use the rope dart?

Question: Could someone tell me how to use the rope dart properly? I use it, but struggle with finding out how to do different moves consistently with it.
Especially wondering how to "catch" people and pull them in with it. He does it some seldom times, but mostly the target just falls backwards on the ground and gets back up.
Answer: With the rope dart, everything is contextual.
If you are in open conflict, using the rope dart will simply snare a target and yank them toward you and they'll fall to the ground.  If you're close enough to them when they've fallen, you can perform a ground kill on them.
If you are anonymous (not in open conflict), you have a few more options.  You will do this as long as you remain undetected as you do these actions.
When on the ground, using the rope dart and holding the button down, you will pull them toward you.  The longer you hold it, the more you will pull them closer.  When the target is close enough, you will perform a kill on them.  This works best if you're in a stealth location (e.g., bushes, tall grass, etc.) to reduce the chances of being detected after the kill.  If you happen to get detected after the initial pull, you may continue to pull them and will still kill them when close.
When on higher ground, using the rope dart and holding the button down, you will pull them toward you.  When they can no longer be pulled anymore (when they're directly underneath you or blocked by an obstruction), you will start choking them.  Doing this will grant you a silent kill (not alerting anyone).
When on a beam (i.e., a branch, a rope, etc.), using the rope dart and holding the button down, you will perform the same action if you were on higher ground.  If however you move off of the beam while holding the button, you will perform a predator move hanging the target.  You will lose one of your rope darts.
Comment: Not entirely sure, but it seems to differ if you hit them from the front and from the back too. When I'm on the ground, in hiding, and hit them from behind, he seems to consistently pull them back as long as I keep holding Y.
Comment: Well yeah, trying to hit them from the front where they can see you, you'll get detected (forcing open conflict). Getting them from behind (where nobody else can see either you or the target) will generally be safe. Using the rope dart from the grass will still make you detectable (since you are technically in high profile). It's just meant to hide your killed target.
Answer: You can't pull people all the way to you, you can only pull them a small distance toward you. You do this by "shooting" the rope dart, and then pressing on the back movement (S on the PC).
The one exception to this, is when you are located on a branch of a tree. Doing the same move, shooting the rope dart, and then pressing a movement button, will hang your target from the tree branch and kill them.
Comment: I could be wrong, but I thought there was another case where you can use the rope dart to do a hanging kill.  Must it be a tree branch?
Comment: @MarkRogers It'll probably work on a wooden beam or something too as long as it's thin and above an enemy?
Comment: The thing is that I've seen him pull enemies all the way towards me and then finish them off with a dagger. But I can't figure out when. Might be in connection with being in hiding or something, but was hoping someone knew for sure.
Answer: If you are in an open conflict and have at least 3 enemies surrounding you by holding the triangle button you can also perform a double kill.I have done this some times and you don't lose your rope dart
Answer: During open conflict, when you counter an enemy hit "Y" on xbox immediately after you counter and Connor will perform a kill with your rope dart, providing they are your equipped ranged weapon. You will lose one of your rope darts.

How do I use the rope dart?