Why does openFile with WriteMode truncate the file? How not to?

Question: Haskell's openFile has this tidbit in the source:
-- we want to truncate() if this is an open in WriteMode, but only
-- if the target is a RegularFile.  ftruncate() fails on special files
-- like /dev/null.
when (iomode == WriteMode && fd_type == RegularFile) $
  setSize fD 0

This was very surprising, I assumed that the IOModes were merely wrappers around O_WRONLY, O_RDONLY and O_RDWR. Why is this the case? How does one open a file for write only without truncating?
Comment: Yes, that's what `O_WRONLY` means. The distinction between opening a file for writing and opening a file for appending predates Haskell by quite a bit, and is defined at a lower level than any one programming language's semantics.
Answer: I think IOMode was designed like the mode argument in the fopen function.
From man fopen:

w - Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.

If you wanna to open a file for writing only (without truncate it) then you wanna append it usually. So just use AppendMode. If you don't wanna to have position on the end of a file (also you don't wanna to have position on the begin of a file usually) you can use the hSeek to change it.
Comment: That seems legitimate. Interestingly there's no way to fopen write only without truncating either.
Answer: IO modes AppendMode or ReadWriteMode should open the file for writing without truncating it.
Comment: Yes but ReadWriteMode requires read permissions. I only want to write.


How to add a new LinearLayout into an existing one?

Question: Hello im a beginner in Android development.
I have made an LinearLayout to show the different Informations in a goodlooking way.
I want to have a Screen with a ScrollView where I can add as many LinearLayouts I want.
But the Problem is that th Button event does not add any LinearLayouts...
This is my activity_layouttest.xml:

RelativeLayout
-----Button    @+id/spawnbutton
-----LinearLayout
-----------ScrollView     @+id/scrollView1
--------------------LinearLayout:      spawnLayout

This is my Code:

<code>public class LayoutTest extends Activity {

    // declaring Widgets
LinearLayout SpawnLayout;
Button Spawnbtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_layouttest);

    Spawnbtn = (Button) findViewById(R.id.spawnbutton);
    SpawnLayout = new LinearLayout(readtest.this);
             // set On Click Listener to a Button "Spawnbtn which schould add the new
             // Layout to the existion one

    Spawnbtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            dospawn();
        }
    });
}

     // method to create/add new linearLayout

public void dospawn() {

    // create custom Layout components
    String LEHRER = "Lehrer";
    String STUNDEN = "Stunden";
    String KLASSE = "Klasse";
    String ORT = "Ort";
    String INFO = "Info";
    String FACH = "Fach";

            //create new objects
    LinearLayout linlay = new LinearLayout(CONTEXT);
    TextView tvLehrer = new TextView(CONTEXT);
    TextView tvStunden = new TextView(CONTEXT);
    TextView tvKlasse = new TextView(CONTEXT);
    TextView tvOrt = new TextView(CONTEXT);
    TextView tvInfo = new TextView(CONTEXT);
    TextView tvFach = new TextView(CONTEXT);

            //defining each one including the child - parent Layout "linlay"

    linlay.setOrientation(LinearLayout.VERTICAL);
    linlay.setPadding(20, 10, 20, 10);
    linlay.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT));
    Resources res = CONTEXT.getResources();
    tvLehrer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT));

    tvLehrer.setBackgroundColor(res.getColor(R.color.transparent_light));
    tvLehrer.setGravity(Gravity.RIGHT);
    tvLehrer.setPadding(0, 0, 20, 0);
    tvLehrer.setText(LEHRER);
    tvLehrer.setTextColor(res.getColor(R.color.weiss));
    tvLehrer.setTextSize(20);

    tvStunden.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT));
    tvStunden.setBackgroundColor(res.getColor(R.color.transparent_light));
    tvStunden.setGravity(Gravity.LEFT);
    tvStunden.setPadding(20, 0, 0, 0);
    tvStunden.setText(STUNDEN);
    tvStunden.setTextColor(res.getColor(R.color.weiss));

    tvKlasse.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT));
    tvKlasse.setBackgroundColor(res.getColor(R.color.transparent_light));
    tvKlasse.setGravity(Gravity.LEFT);
    tvKlasse.setPadding(20, 0, 0, 0);
    tvKlasse.setText(KLASSE);
    tvKlasse.setTextColor(res.getColor(R.color.weiss));

    tvOrt.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT));
    tvOrt.setBackgroundColor(res.getColor(R.color.transparent_light));
    tvOrt.setGravity(Gravity.LEFT);
    tvOrt.setPadding(20, 10, 0, 10);
    tvOrt.setText(ORT);
    tvOrt.setTextColor(res.getColor(R.color.weiss));

    tvInfo.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT));
    tvInfo.setBackgroundColor(res.getColor(R.color.transparent_light));
    tvInfo.setGravity(Gravity.LEFT);
    tvInfo.setPadding(20, 0, 0, 10);
    tvInfo.setText(INFO);
    tvInfo.setTextColor(res.getColor(R.color.weiss));

    tvFach.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT));
    tvFach.setBackgroundColor(res.getColor(R.color.orange));
    tvFach.setGravity(Gravity.CENTER_HORIZONTAL);
    tvFach.setPadding(0, 10, 0, 10);
    tvFach.setText(FACH);
    tvFach.setTextColor(res.getColor(R.color.schwarz));

            //add the Components to LinearLayout linlay

    linlay.addView(tvLehrer);
    linlay.addView(tvStunden);
    linlay.addView(tvKlasse);
    linlay.addView(tvOrt);
    linlay.addView(tvInfo);
    linlay.addView(tvFach);

            // add the linlay to the LinearLayout which is defined in the activity.

            SpawnLayout.addView(linlay);
}
</code>

I hope you can find the missing Command or sth else.
Thanks
Answer: Your activity code is without any scrollview. Please paste the contents of activity layout (i.e activity_layoutTest.xml). Looking at the code, I think, it may be better for you to use scrollbar with a list adapter. A look at this question may help you : Using a ListAdapter to fill a LinearLayout inside a ScrollView layout


Converting value of interface in Typescript

Question: given an interface of Person i would like to create a new interface HasmapOfPersonsOverTime based on that. im gonna push updates of Person objects (i.e if a person has a birthday i will push the new age number, and the time the person celebrated the birthday as a object into the array on the age property).
... symbolizes the rest of the properties
interface Person {
    age:number;
    name:string;
    ...
}

i would like an interface looking like :
interface HasmapOfPersonsOverTime {
  [id:string]:{
    age:[
          {
            age:number
            time:string
          }
        ]
    },
    name:[
          {
            name:string
            time:string
          }
        ]
    },
    ...
}

and to give an example on how i would like to use it:
const list:HasmapOfPersonsOverTime = {
  "1515":{
    age:[
      {
        age:24,
        time:"2020-03-05T21:53:37"
      },
      {
        age:25,
        time:"2021-03-05T18:22:05"
      }
    ],
    name:[
      {
        name:"bar",
        time:"1996-03-05T21:53:37"
      }
    ],
    ...
  }
}

i have come this far but i cant get type safety on properties. i create "value":string where i want the correct person property.
interface Person {
  age:number;
  name:string;
}
type HasmapOfPersonsOverTime <T extends Object> = Record<string,Record<keyof T, {'value':string,'time':string}[]>>

const list: HasmapOfPersonsOverTime<Person> = {
  "1515":{
    age:[
      {
        value:"24",
        time:"2020-03-05T21:53:37"
      },
      {
        value:"25",
        time:"2021-03-05T18:22:05"
      }
    ],
    name:[
      {
        value:"name",
        time:"1996-03-05T21:53:37"
      }
    ]
  }
}

Answer: You can use the following mapped type, also used with other builtin types such as Pick
type Person = {
  age: number;
  name: string;
};

type OverTime<T> = {
  [K in keyof T]: (Pick<T, K> & { time: string })[];
};

type HashmapOfPersonOverTime = Record<string, OverTime<Person>>;


Image control in WPF Stretches Image When Stretch Set to None

Question: I have an image control inside a grid displaying a 16x16 icon. But for some reason even though I set the properties so it would remain 16x16 it looks stretched.

Code :
<UserControl x:Class="ChatControls.UserListItem"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d" d:DesignHeight="28" d:DesignWidth="132">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="24" MinWidth="24" MaxWidth="24" />
            <ColumnDefinition Width="171*" />
        </Grid.ColumnDefinitions>
        <Image Name="imgIcon" Source="/ChatControls;component/Images/NormalUser.png" VerticalAlignment="Center" HorizontalAlignment="Center" Stretch="None" />

    </Grid>
</UserControl>

Is there any reason for this?
UPDATE 1:
Yes at runtime also :(

Many thanks in advance.
Comment: @H.B. Sorry I have not got to the stage of testing at run time yet, so I assume from this it can change @ runtime?
Comment: The designer is crap so yes, it can change...
Comment: @H.B. yes even at runtime, please see above
Answer: Actually, I've seen that regularly with PNG images. It seems that the default resolution for PNG is 72dpi, while the default screen resolution in WPF is 96dpi. WPF tries to take this into account by rendering png bitmaps scaled to 133% of their pixel size, which is technically correct but normally not what the user wants. You can either use a gif or jpg instead, or you can combine the image with a LayoutTransform scaling it to 0.75 of its size, or just stick with setting the size of the image control explicitly.
Comment: This is it.  I had a PNG source for an image.  Tried a variety of properties to try to get it to display clearly.  Then I saw this.  I opened up the PNG in an editor (Paint.NET is excellent), resized it (kept the same dimensions, but changed the DPI from 72 to 96), and the images appeared exactly as they should with the right size and no blurring.
Answer: I find I often have to explicitly specify the Width and Height of Image controls to get them to appear correctly:
<Image
  Name="imgIcon"
  Source="/ChatControls;component/Images/NormalUser.png"
  VerticalAlignment="Center"
  HorizontalAlignment="Center"
  Width="16"
  Height="16"
/>

Answer: First of all, your XAML definition of your 171* is a bit odd.  Your best approach is to do this:
<Grid.ColumnDefinitions>
  <ColumnDefinition Width="24" />
  <ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>

You need to look into XAML layout passes in order to understand what this is doing.
Secondly, because you're using a dynamic image source (loaded as a URI), it will be streamed so the width during the first layout pass will be 24, but after the image has been streamed, the control will resize dynamically.  If you want to enforce sizing, your best bet is to use a border around the image as a 0 width container. Like this
 <Border Grid.Column="0" Grid.Row="0" BorderThickness="0" BorderBrush="Black">

    <Image
      Source="sampleImages/gecko.jpg"
    Stretch="UniformToFill" />
  </Border>

Enforcing a width and a height around an image is a shorthanded way of doing this.  The other thing you may want to do is to explicitly define the way the source image is loaded like this:
<Image Width="200">
 <Image.Source>
  <BitmapImage DecodePixelWidth="200"
   UriSource="C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Water Lilies.jpg" />
  </Image.Source>
 </Image>

Which will not load the full image but will resize before load as opposed to dynamically.  For further reference review http://msdn.microsoft.com/en-us/library/ms748873.aspx
I agree with the accepted answer, but I don't think it explains why, it just explains that it works.
Answer: It happens because of the image pixels that is dependent on the screen resolution, it should be device independent so that to remains same on any screen resolution
So use this to do so.
<Image Width = "24" Height = "24" RenderOptions.BitmapScalingMode="NearestNeighbor" RenderOptions.EdgeMode="Aliased" Stretch = "None"/>

replace Width and Height with the original size of the image
This'll help you


Inno Setup uninstaller: An attempt was made to access WizardForm before it has been created

Question: I've a problem with WizardForm's, when I trying to uninstall the program I have this error:

Runtime Error:
Internal error: An attempt was made to access WizardForm before it has been created.

I need to create soft abort uninstallation process with loop (e.g. when application is running and user run the uninstall, program must check processes and if application is running, notify user and if user press the cancel button the program abort uninstallation), I've tried with ExitProcess(0); but it isn't gentle.
Code section:
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
begin
  case CurUninstallStep of
    usUninstall:
    begin
      if MsgBox('Close the {#AppName}, before uninstallation.', mbConfirmation, MB_YESNO) = IDYES then
      begin
        { user clicked Yes }
      end
        else
      begin
        MsgBox('Error',mbError,MB_OK);
        CancelWithoutPrompt := true;
        { ExitProcess(0); }
        WizardForm.close;
      end
    end;
  end;
end;

Comment: Maertin Prikryl, the main problem is this error - An attempt was made to access WizardForm before it has been created.
Comment: Martin Prikryl, I want to abort the uninstallation with aborting section, with window - "Abort Uninstallation. Installation canceled by user". I think this can be done with WizardForm.
Answer: Your approach to implementing your problem is wrong, see at the end.
Anyway, to address your immediate issue: The WizardForm is an installer form. It does not exist in an uninstaller. In the uninstaller, you have UninstallProgressForm. See documentation.
But you do not want to call UninstallProgressForm.Close. That's wrong for the reasons given below.

Inno Setup has a built-in mechanism to prevent an (un)installer from proceeding, while an application is running. The AppMutex directive.
Even if you want to build your own solution, use the InitializeUninstall event function, where you can exit the uninstaller easily and cleanly, by returning False. And you can, of course, display any message you like, before you exit. Just use MsgBox function.
All this is covered in my answer to Uninstall fails because program is running. How do I make Inno Setup check for running process prior to attempting delete?


What is the python 'requests' api equivalent to my shell scripts curl command?

Question: I have this curl command I use a shell script:
curl -X POST -H 'Content-Type: application/json' \
--cert /etc/puppetlabs/puppet/ssl/certs/${PEFQDN}.pem \
--key /etc/puppetlabs/puppet/ssl/private_keys/${PEFQDN}.pem \
--cacert /etc/puppetlabs/puppet/ssl/certs/ca.pem \
--data "{ \"name\": \"$GROUP\", \"parent\": \"00000000-0000-4000-8000-000000000000\", \"environment\": \"production\", \"classes\": { \"$CLASS\": {}} }" \
https://${PEFQDN}:4433/classifier-api/v1/groups | python -m json.tool

I want to get away from my shell script as I need to be able to process some complex json that comes back from the REST API. I figure I'd use python and the requests package.  I was looking at this documentation:
http://docs.python-requests.org/en/latest/user/quickstart/
But I do not see where I can specify my certificate info. In my shell script I can pass curl these options: --cert, --key, --cacert. I do not know how to accomplish the same with python's requests API.  Does anyone out know how I can accomplish this?
UPDATE:  Thanks Joran.  Here is my attempt to write a python script to do this:
#!/usr/bin/env python

import requests

# curl https://${PEFQDN}:4433/classifier-api/v1/groups \
# -H "Content-Type: application/json" \
# --cert /etc/puppetlabs/puppet/ssl/certs/${PEFQDN}.pem \
# --key /etc/puppetlabs/puppet/ssl/private_keys/${PEFQDN}.pem \
# --cacert /etc/puppetlabs/puppet/ssl/certs/ca.pem | python -m json.tool

url='https://my-pm.example.com:4433/classifier-api/v1/groups'
headers = {"Content-Type: application/json"}
data={}
cacert='/etc/puppetlabs/puppet/ssl/certs/ca.pem'
key='/etc/puppetlabs/puppet/ssl/private_keys/my-pm.example.com.pem'
cert='/etc/puppetlabs/puppet/ssl/certs/my-pm.example.com.pem'
result = requests.get(url,
        data=data, #whatever data
        headers=headers, #dict {"Content-Type":"application/json"}
        verify=cert,
        cert=(cacert,key) #key/cert pair
        )
print result.json()

And I must be doing something wrong because this is the output I get ...
# ./add-group.py
Traceback (most recent call last):
  File "./add-group.py", line 21, in <module>
    cert=(cacert,key) #key/cert pair
  File "/usr/lib/python2.7/site-packages/requests-2.7.0-py2.7.egg/requests/api.py", line 69, in get
    return request('get', url, params=params, **kwargs)
  File "/usr/lib/python2.7/site-packages/requests-2.7.0-py2.7.egg/requests/api.py", line 50, in request
    response = session.request(method=method, url=url, **kwargs)
  File "/usr/lib/python2.7/site-packages/requests-2.7.0-py2.7.egg/requests/sessions.py", line 451, in request
    prep = self.prepare_request(req)
  File "/usr/lib/python2.7/site-packages/requests-2.7.0-py2.7.egg/requests/sessions.py", line 382, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "/usr/lib/python2.7/site-packages/requests-2.7.0-py2.7.egg/requests/models.py", line 293, in prepare
    self.prepare_headers(headers)
  File "/usr/lib/python2.7/site-packages/requests-2.7.0-py2.7.egg/requests/models.py", line 401, in prepare_headers
    self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items())
AttributeError: 'set' object has no attribute 'items'

What I am doing wrong here?
Thanks
Answer: headers = {"Content-Type: application/json"}

should be changed to
headers = {"Content-Type": "application/json"}

Looks like the requests API is expecting a dictionary, and {"Content-Type: application/json"} is apparently a Python set.
Answer: result = requests.get(url,
        data=data, #whatever data
        headers=headers, #dict {"Content-Type":"application/json"}
        cert=(cacert,key),#key/cert pair
        verify="cert_chain.pem"
        )
print result.json() #depending on version of requests, json may be a function or a property

this link will be helpful
http://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification
Comment: `headers = {"Content-Type: application/json"}` is not the same as `headers = {"Content-Type": "application/json"}` one is a dictionary with one key/value pair, the other is a set with a single string element ...
Comment: Maybe this is obvious enough that it doesn't need to be pointed out, but it should be `post()` instead of `get()`.
Comment: it should work identically regardless of post/get/push
Comment: Thanks Joran, but I still don't get what I am doing wrong in my python script.  I have updated my question with my attempt to write this in python. Please take a look. Thank you


Merging rows in pandas DataFrame

Question: I am writing a script to scrape a series of tables in a pdf into python using tabula-py.
This is fine.  I do get the data. But the data is multi-line, and useless in reality.
I would like to merge the rows where the first column (Tag is not NaN).
I was about to put the whole thing in an iterator, and do it manually, but I realize that pandas is a powerful tool, but I don't have the pandas vocabulary to search for the right tool. Any help is much appreciated.
My Code
filename='tags.pdf'
tagTableStart=2 #784
tagTableEnd=39 #822

tableHeadings = ['Tag','Item','Length','Description','Value']

pageRange = "%d-%d" % (tagTableStart, tagTableEnd)
print ("Scanning pages %s" % pageRange)

# extract all the tables in that page range
tables = tabula.read_pdf(filename, pages=pageRange)

How The data is stored in the DataFrame:
(Empty fields are NaN)

Tag
Item
Length
Description
Value

AA
Some
2
Very Very

Text

Very long

Value

AB
More
4
Other Very
aaaa

Text

Very long
bbbb

Value
cccc

How I want the data:
This is almost as it is displayed in the pdf (I couldn't figure out how to make text multi line in SO editor)

Tag
Item
Length
Description
Value

AA
Some\nText
2
Very Very\nVery long\nValue

AB
More\nText
4
Other Very\nVery long\n Value
aaaa\nbbbb\ncccc

Actual sample output (obfuscated)
    Tag                         Item Length                                        Description                                    Value
0    AA              PYTHROM-PARTY-I     20                                               Some             Current defined values are :
1   NaN                          NaN    NaN                                              texst                                   Byte1:
2   NaN                          NaN    NaN                                                NaN                                        C
3   NaN                          NaN    NaN                                                NaN                                       DD
4   NaN                          NaN    NaN                                                NaN                                      NaN
5   NaN                          NaN    NaN                                                NaN                                       DD
6   NaN                          NaN    NaN                                                NaN                                       DD
7   NaN                          NaN    NaN                                                NaN                                       DD
8   NaN                          NaN    NaN                                                NaN                                      NaN
9   NaN                          NaN    NaN                                                NaN                                   B    :
10  NaN                          NaN    NaN                                                NaN  JLSAFISFLIHAJSLIhdsflhdliugdyg89o7fgyfd
11  NaN                          NaN    NaN                                                NaN       ISFLIHAJSLIhdsflhdliugdyg89o7fgyfd
12  NaN                          NaN    NaN                                                NaN    upon ISFLIHAJSLIhdsflhdliugdyg89o7fgy
13  NaN                          NaN    NaN                                                NaN              asdsadct on the dasdsaf the
14  NaN                          NaN    NaN                                                NaN                               actsdfion.
15  NaN                          NaN    NaN                                                NaN                                      NaN
16  NaN                          NaN    NaN                                                NaN       SLKJDBFDLFKJBDSFLIUFy7dfsdfiuojewv
17  NaN                          NaN    NaN                                                NaN                              csdfgfdgfd.
18  NaN                          NaN    NaN                                                NaN                                      NaN
19  NaN                          NaN    NaN                                                NaN       fgfdgdfgsdfgfdsgdfsgfdgfdsgsdfgfdg
20   BB           PRESENT-AMOUNT-BOX    11                          Lorem Ipsum                                                     NaN
21   CC           SOME-OTHER-VALUE      1                                        sdlkfgsdsfsdf                                        1
22  NaN                          NaN    NaN                                             device                                      NaN
23  NaN                          NaN    NaN  ueghkjfgdsfdskjfhgsdfsdfkjdshfgsfliuaew8979vfhsdf                                      NaN
24  NaN                          NaN    NaN                                dshf87hsdfe4ir8hod9                                      NaN

Answer: Create groups from ID columns then join each rows:
agg_func = dict(zip(df.columns, [lambda s: '\n'.join(s).strip()] * len(df.columns)))

out = df.fillna('').groupby(df['Tag'].ffill(), as_index=False).agg(agg_func)

Output:
>>> out
  Tag        Item Length                   Description             Value
0  AA  Some\nText      2   Very Very\nVery long\nValue
1  AB  More\nText      4  Other Very\nVery long\nValue  aaaa\nbbbb\ncccc

agg_func is equivalent to write:
{'Tag': lambda s: '\n'.join(s).strip(),
 'Item': lambda s: '\n'.join(s).strip(),
 'Length': lambda s: '\n'.join(s).strip(),
 'Description': lambda s: '\n'.join(s).strip(),
 'Value': lambda s: '\n'.join(s).strip()}

Merging rows in pandas DataFrame


Existence of total derivative of a function

Question: Given the function  $ f(x,y) = \sqrt[3]{y}\cdot \arctan(x)$ discuss the existence and continuity of it's partial derivatives and existence of it's total derivative.
Since the partial derivative $ \frac{\partial f}{\partial y} = \frac{\arctan(x)}{3\sqrt[3]{y^2}}$ has discontinuity at $y=0$, I tried to compute the partial  derivative at $(x,0)$ using the limit, which gives: $$ \lim_{t\to0} \frac{f(x,t) - f(x,0)}{t} = \lim_{t\to 0} \frac{\sqrt[3]{t}}{t}\arctan(x) = +\infty.$$
Does this mean that the partial derivative doesn't exist at $(x,0)$? So there's no total derivative at $(x,0)$ and it can be said that the function is not differentiable at $\mathbb{R}^2$ ?
Answer: If x=o the partial derivates at (0.0) are both 0.
If x is not zero then at (x,0) the partial derivate with respect to  the variable y does not exist  and then the function is not differentable at those points .


Swift 3: URLSession / URLRequest Not Working

Question: I am still trying to convert our application from Swift 2 over to Swift 3 because I am being forced to since all of our Apple devices are now running iOS 10.
I have gone through the code conversion and thought I was doing well however, while attempting to debug my JSON issues (posted in another question), I am now dealing with requests not even being sent.
let params: [String:AnyObject] = [
    "email":"\(self.preferences.string(forKey: "preference_email")!)" as AnyObject
]
let requestParams: [String:AnyObject] = [
    "action":"601" as AnyObject,
    "params":params as AnyObject
]

do {
    let requestObject = try JSONSerialization.data(withJSONObject: requestParams, options:[])
    var request = URLRequest(url: URL(string: "http://domain.tld/path/")!)

    request.httpBody = requestObject
    request.httpMethod = "POST"

    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    NSLog("Got here?")

    session.dataTask(with: request) {data, response, error in
        guard let data = data, error == nil else {
            print("error=\(error)")
            return
        }

        NSLog("Got here 3?")

        let object:JSON = JSON(data:data)

        NSLog("Object: \(object)")
    }.resume()

    NSLog("Got here 4?")
} catch {
    NSLog("Got here catch?")
}

NSLog("End of getUser")

The code above yields the following output:
2016-10-04 13:00:12.011969 OneTouch[1589:623015] [DYMTLInitPlatform] platform initialization successful
2016-10-04 13:00:12.264319 OneTouch[1589:622954] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2016-10-04 13:00:12.265321 OneTouch[1589:622954] [MC] Reading from public effective user settings.
2016-10-04 13:00:12.295055 OneTouch[1589:622954] Got here?
2016-10-04 13:00:12.295445 OneTouch[1589:622954] Got here 4?
2016-10-04 13:00:12.295515 OneTouch[1589:622954] End of getUser
(lldb)

Which means that the request isn't even being made. Is there some key that I have to add to the PLIST again? This is starting to get annoying.
Below is my old code and it isn't even working anymore:
let params: [String:AnyObject] = [
    "email":"\(self.preferences.string(forKey: "preference_email")!)" as AnyObject
]
let requestParams: [String:AnyObject] = [
    "action":"601" as AnyObject,
    "params":params as AnyObject
]

do {
    let requestObject = try JSONSerialization.data(withJSONObject: requestParams, options:[])
    let request = NSMutableURLRequest(url: URL(string: "http://domain.tld/path/" as String)!, cachePolicy:NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 20)

    request.httpBody = requestObject
    request.httpMethod = "POST"

    NSLog("Got here?")

    let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {data, response, error in
        if error != nil {
            NSLog("Got here 2?")
        }

        NSLog("Got here 3?")

        let object:JSON = JSON(data:data!)

        NSLog("Object: \(object)")
    })

    NSLog("Got here 4?")

    task.resume()
} catch {
    NSLog("Got here catch?")
}

NSLog("End of getUser")

The code above yields the same output as the other code does!
Comment: "trying to convert our application from Swift 2 over to Swift 3 because I am being forced to since all of our Apple devices are now running iOS 10" ... You don't _have_ to convert to Swift 3. You could use Swift 2.3.
Comment: I tried to Convert to 2.3 however, some of the modules that I am using weren't working so I updated to Swift 3 and now I have the issues cleared up with the modules, or so I hope.
Comment: Where is the breakpoint you are setting when you are looking at the log output?  Are you sure you aren't just pausing it before the network call has had time to complete and call the completion handler?
Comment: So the code above is in a function called getUser() which is called when the application is launched. The breakpoint is on the next line after the getUser() function is called therefore, it should be processing the entire function. Also, it logs "End of getUser" which as at the end of the function so I know the entire function is being processed.
Comment: At least declare your param dictionaries as `[String:Any]` and remove the `as AnyObject` casts and use native `URLRequest` rather than `NSURLRequest`
Comment: vadian: Okay, I changed the parameters. Thank you for the hint. That was my poor excuse to get it to work after converting to Swift 3. Thanks to you I have defined how I wanted it.
Comment: Rob: Okay, so what changed to cause that because before I converted to Swift 3, I could do the exact same thing it was working without a problem. I was able to print the data returned immediately.
Comment: Rob: you are correct, thank you. I removed the break point and do see the response back. This  makes it difficult for me to debug because of the way I am used to debugging code. Is there anyway to get the app to halt and wait for a response?
Comment: You can, theoretically, use semaphores to make it wait, but that's a horrible pattern, even if just debugging. Put your breakpoint inside the completion handler if you want it to stop when the response comes in.
Comment: I tried putting it inside the completionHandler however, the data wasn't there. I supposed I can try it again, but it didn't work before. Thank you!
Answer: If you put a breakpoint immediately after calling getUser, the URLSession task's completion handler, which runs asynchronously (i.e. generally finishes later, unless the request failed immediately or was satisfied by some cached response) may not have had a chance to be called.
If you put a breakpoint inside the dataTask completion handler, you should see your data at that point.

Personally, I'd make sure to give getUser a completion handler so you know when it's done:
func getUser(completionHandler: @escaping (JSON?, Error?) -> Void) {
    let params = [
        "email":"\(preferences.string(forKey: "preference_email")!)"
    ]

    let requestParams: [String: Any] = [
        "action": "601",
        "params": params
    ]

    do {
        let requestObject = try JSONSerialization.data(withJSONObject: requestParams)

        var request = URLRequest(url: URL(string: "http://domain.tld/path/")!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 20)

        request.httpBody = requestObject
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")

        let task = URLSession.shared.dataTask(with: request) {data, response, error in
            guard let data = data, error == nil else {
                completionHandler(nil, error)
                return
            }

            completionHandler(JSON(data: data), nil)
        }

        task.resume()
    } catch {
        completionHandler(nil, error)
    }
}

Then when you call it, you can do something like:
getUser { json, error in
    guard let json = json else {
        print(error)
        return
    }

    // do something with json
    print(json)
}

And just put your breakpoint in getUser's completion handler. And remember that you have no assurances that the completion handler will run on the main queue or not, so you'll want to make sure to dispatch and UI or model updates back to the main queue.
Comment: I really like this approach and will probably go back and implement this later, but not at this time. I did get this working thank you to another response, but this answer seems more appropriate! Thank you.
Comment: @recoilnetworks Could you please document what solved this for you? Struggling with the same problem
Comment: The problem for me was the result was taking longer to come back than I was allowing. So, while the result was coming back, I was attempting to break and print the result before the result was actually returned.
Comment: I'm not seeing where `params` constant is actually used. What was the purpose of this constant?


Adding a context variable with AJAX in Flask

Question: I have a select form that needs to be populated through AJAX. Consider this simple example:
templates/index.html
<!DOCTYPE html>

<select id="elements">
</select>

app.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/get-something/<int:n>')
def get_something(n):
    result = ''
    for i in xrange(n):
        result += "<option value='%s'>%s</option>\n" % (i, i)
    return result

if __name__ == '__main__':
    app.run(debug=True)

That works just fine and is what I did. But, I was wondering if there exists another (better?) way.
For instance, I'd prefer having a context variable to better separate the view from the controller. Something like this:
app.modified.py
@app.route('/get-something/<int:n>')
def get_something(n):
    return dict(elements=xrange(n))

templates/index.modified.html
<select id="elements">
    {% for elem in elements %}
        <option value='{{ elem }}'>{{ elem }}</option>\n
    {% endfor %}
</select>

Unfortunately, that does not work. It says, 'dict' object is not callable.
Any help please? Is this even possible? Notice that I don't want to reload the page, I want the same behavior that you get in the AJAX example.
Answer: Using index.modified, you need to do something like this:
return render_template('index.modified.html',
                       elements=your_dictionary)

Not trying to return a dictionary (which is why you are getting that error).  See http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ii-templates fore more examples
Comment: That would reload tthe page. I don't want that.
Comment: Then you should send Json not html, and parse using JavaScript to construct the select. Use return json.dumps(thedictionary) to send back the dictionary of elements.  I won't change the answer as the problem stated had an issue with templating.
Answer: You should be returning render_template('index.modified.html', elements=xrange(n)) since you want the html.
render_template returns a string which you can then encode as JSON. Ex:
data = render_template('index.modified.html', elements=xrange(n))
return json.dumps({'data': data})


Questions about Blur effect

Question: I am working on a specific blur effect that implies several behaviours. But before I would like to know what you think about those blurring algorithms according to performances and quality :
Kawase blur, Box blur and two pass Gaussian blur.
Next are the effects I am currently working on and I would be glad to have your thoughts on those on the proper way to achieve this. Here is a schematic view followed by my questions.

I would like to blur the content of those 4 spheres using the same offset no mater their position. If I apply the same blur on all objects, far object's content will appear more blurry than ones on the foreground and I want to avoid that. I think that the depth make could help but any precision would help me.
If I blur the whole image and apply the result on the sphere, the white background will bleed onto the sphere shape and I want to avoid that. I also don't want that the blue (3) and yellow (4) sphere merges with the red (1) and green (2) ones. But I would like that the green and red ones merges. Again This could be done using the depth but if you have more precision about how to do it it would be interesting.

Any ideas about those questions would be helpful.
Thanks a lot.
Comment: Regarding the background mixing with your objects during the blur, my recommendation would be to not render on white, but to render on transparent black. When doing the blur, you should blur using pre-multiplied alpha.  That will make the result such that you can apply it to any background color (using standard alpha blending) and it will look correct.  More information here: https://stackoverflow.com/questions/4854839/how-to-use-pre-multiplied-during-image-convolution-to-solve-alpha-bleed-problem
Answer:
If I blur the whole image and apply the result on the sphere, the white background will bleed onto the sphere shape and I want to avoid that. I also don't want that the blue (3) and yellow (4) sphere merges with the red (1) and green (2) ones. But I would like that the green and red ones merges. Again This could be done using the depth but if you have more precision about how to do it it would be interesting.

You will need to blurr in multiple passes to achieve this:
once for the blue and once for the yellow, as well as once for the red and green (together). That is: you need to render to texture, you need three textures in this instance to render to, you need to blur the individual textures and then combine them in another render pass.
If you know beforehand that the green and red spheres may blur together, you can just hardcode it, otherwise you need to come up with a way of determining, which spheres may blur together, and group your spheres to render into the same texture.
If you do this, keep in mind that for combining the three individual blurred textures, you need z-values for correct visibility determination.

I would like to blur the content of those 4 spheres using the same offset no mater their position. If I apply the same blur on all objects, far object's content will appear more blurry than ones on the foreground and I want to avoid that. I think that the depth make could help but any precision would help me.

Yes, you can scale your blur filter with a depth value (where you should "invert" the value to make the blurriness scale to larger effects on closer proximities, i.e. smaller depths). For a box filter, you take ratios of the pixels neighbourhoods, but you need to make sure that those ratios add up to one. For this, you'd ideally increase the ratio for the center pixel based on the proximity and reduce the ratio for the neighbouring pixels accordingly.

performances and quality : Kawase blur, Box blur and two pass Gaussian blur.

As to performance, I can't say anything about the three. As to quality, the Box Filter is rather simple, but that doesn't mean it doesn't suffice for your specific need. Just test them against each other.
Comment: To blur the different sphere separately, I decided to do it the same way is done in screen space subsurface scattering. I am using depth to calculate the difference between the basic depth and the blurred depth. If the difference is to high, I just don't apply blur.

Questions about Blur effect


python scrape links keyword

Question: I'm new to python and I need help for scraping all links with a certain keyword. The problem is that I'm getting the following error:

if "air-max" in link["href"]:
           ^
      IndentationError: expected an indented block.

Here is my code
import requests
import time
from bs4 import BeautifulSoup

headers = {"Content-Type": "application/x-www-form-urlencoded;
charset=UTF-8","X-Requested-With": "XMLHttpRequest","User-Agent":
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/56.0.2924.87 Safari/537.36"}

for i in range(0,4):
url = "https://www.aw-lab.com/shop/uomo/scarpe?p={}".format(i)
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")

all_links = soup.find_all("a")
for link in all_links:
if link.has_key('href'):
if "air-max" in link["href"]:
    print(link["href"])

Comment: You have to indent your code. Make sure you follow the style, check if you have spaces or tabs everywhere in correct places.
Answer: You need another indentation level after link.has_key('href'):. Also, be consistent; always use spaces (preferred) or always use tabs. This may not always be true, but, in general, if there is a COLON : at the end of a line, then the next line should be indented one level further.
for i in range(0,4):
    url = "https://www.aw-lab.com/shop/uomo/scarpe?p={}".format(i)
    r = requests.get(url)
    soup = BeautifulSoup(r.content, "html.parser")

    all_links = soup.find_all("a")
    for link in all_links:
        if link.has_key('href'):
            if "air-max" in link["href"]:
                print(link["href"])

Answer: Please use  an IDE like spyder IDE or jupyter notebook for development.
import requests
import time
from bs4 import BeautifulSoup

headers = {"Content-Type": "application/x-www-form-urlencoded;
charset=UTF-8","X-Requested-With": "XMLHttpRequest","User-Agent":
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/56.0.2924.87 Safari/537.36"}

for i in range(0,4):
    url = "https://www.aw-lab.com/shop/uomo/scarpe?p={}".format(i)
    r = requests.get(url)
    soup = BeautifulSoup(r.content, "html.parser")

all_links = soup.find_all("a")
for link in all_links:
    if link.has_key('href'):
        if "air-max" in link["href"]:
            print(link["href"])

python scrape links keyword


Sharing Local GWT Project with the rest of the world?

Question: As you all probably know, when you create a GWT project (I use Eclipse..not that it matters), and you run it as a web application, you get the application URL, for instance:
http://127.0.0.1:8888/StockWatcher.html?gwt.codesvr=127.0.0.1:9997
My question is, I would like to let my friend, which is on a different computer, this URL so he can also check the application, so I changed the 127.0.0.1's to my own IP, but it doesnt do the trick, what am I missing here?
Thanks,
Answer: If you want to share your app with rest of the world, you need to deploy it on some sort of web server. You can pick many of them, f.e. Apache Tomcat, Jetty, JBoss, GlassFish ... Basically, your application needs some sort of container to run in.
I will now briefly describe deploying GWT app to Tomcat:

You must have globaly accessible IP (and also domain name)
Install Apache Tomcat, see the documentation
Eclipse with Google plugin created for you folder structure containg /war folder
Copy /war folder to to Tomcat webapps (by default /Apache Tomcat X/webapps. You might want to rename your war folder, say to "StockWatcher"
Add necessary libraries to /lib folder (but Tomcat will complain about missing classes, not difficult to find out what's wrong here)
Restart tomcat and type URL like: http://your_url:your_port/YourApp/YourApp.html

I see that you did StockWatcher tutorial, these steps should cover basics. Try it on localhost first. Maybe getting globaly accessible IP is what you were originaly looking for.
Answer: The URL you pasted is the "development mode" (or "hosted mode") URL for debugging your app. For deployment, you need to compile your project (in Eclipse there's a red-colored button, and see the GWT website for more details).
If all you want is for your friend to access your debugging development run, see GWT's docs about that
Answer: pass the parameter -bindAddress 0.0.0.0 to bind the embedded server from eclipse to all network cards. compile your app with the red icon in eclipse and paste the url from the dev console without gwt.codesrv at the end
Answer: In Eclipse,
Run > Debug Configurations...
Select your project on the left panelunder Web Applications > Project Name
Select the Arguments Tab on the right panel
Under "Program Arguments:" append the argument "-bindAddress a.b.c.d" where a.b.c.d is the IP of your machine.
Restart/Run jetty
Now the URL can be accessed from a different machine on the network


login loop on admin account, guest works fine

Question: As you can tell I am having some issues. I am a gamer, and not having write privileges would be a death sentence to any gamer. With this guest account when I log. I have tried 2-3-4 fixes, Even did another fsck, another issue, not this one. My point is. there is something wrong with either admin, GUI, or something in between. Cause I can log in terminal or shell whatever it is called. But not with GUI.
Answer: likely the problem lies with the "hidden" files and directories in your home directory.  These all start with a "." and basically hold configuration information, which may be outdated after an update.  The guest account starts fresh, so doesn't have that problem.  Search this site for "login loop" and there are many solutions -- basically just put all the "dot" files into a temporary directory, so they don't intefere with login and see if that works.  They should be recreated as needed, like the guest account does, but if you really need something you put aside, it is always in the temporary directory to bring out.


How do I find if my video driver is working

Question: I use xserver-xorg-video-nouveau driver software and I want to check if it is working.
I checked a box in the Driver Manager, but I am not sure it works.
Answer: Go to System Settings... > System > Details Under 'Graphics', you will see something like GeForce GTX 760/PCIe/SSE2 I'm using the same drivers, and that's what shows up for me.
Another way to verify that they're in use is to open your terminal and type in lspci -vnn | grep -i VGA -A 12. Look for the line that says Kernel driver in use If it says nvidia, you have the driver installed. To make sure that you have hardware 3D acceleration, type in glxinfo | grep OpenGL | grep renderer If it says anything other than MESA, you're in luck.
To get CUDA up and running for 3D rendering and such, type in one final command: sudo apt-get install nvidia-modprobe. This enables CUDA for the full experience. Once that's all finished, restart your computer.


Terraform template variables from other Terraform resources

Question: I have Terraform that is using a templated bash script to set my user data section for an AWS launch configuration.
data "template_file" "user_data" {
  template = "${file("${path.module}/user-data.tpl")}"

  vars {
    file_system_id = "${aws_efs_mount_target.my_efs_alpha.dns_name}"
  }
}

The file_system_id variable then needs to be used in my template:
sudo mount -t nfs -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2 $$$${file_system_id}:/ /mnt/efs
Bash will interpret a single dollar sign as a bash variable. As I understand it, Terraform will interpret a double-dollar-sign as a Terraform variable. For added fun, the dollar signs in the template need to be escaped with another dollar sign -- hence the 4 dollar signs in front of file_system_id.
Looking at the user data in my Launch Config over in AWS Console, Terraform does not appear to be making any effort to replace my $$$${file_system_id) with the variable value from my template_file definition. Rather, it just shows up in the user data section as literally $${file_system_id}.
So, the question is, how do I get my EFS DNS name (or whatever other value I want) to replace the file_system_id variable in my template? What have I missed?
Comment: so what's wrong to use `${file_system_id}` directly in user_data.tpl?
Comment: Well, that's some humble pie for me. I figured that since it was an escape character, and since I've found cases where I need to escape the '$' with double dollar signs to get Terraform variable replacement to work, that this would be a similar case. Indeed, it looks like the single dollar sign works here. Feel free to submit your comment as an answer and I'll approve it.
Answer: As BMW mentioned, you don't need to escape the dollar signs. ${file_system_id} works just fine.
Terraform's variable-replacement in templates will run first so you don't need to worry about how Bash will parse it until after the variables are replaced.


HttpInvokerServiceExporter is deprecated in spring 5. Is there any replacement? Will it be available in spring 6?

Question: HttpInvokerServiceExporter is deprecated in spring 5. I want to call  spring remote bean via HTTP protocol. Is there any replacement? HttpInvokerServiceExporter has a vulnerability of RCE also so i need to use some replacement of HttpInvokerServiceExporter.
RMI skeleton
@Configuration
public class RMIServer {

    @Bean
    DTBookingService bookingService() {
    return new DTBookingServiceImpl();
    }

    @Bean(name = "exporter")
    RmiServiceExporter exporter(DTBookingService implementation) {
        Class<DTBookingService> serviceInterface = DTBookingService.class;
        RmiServiceExporter exporter = new RmiServiceExporter();
        exporter.setServiceInterface(serviceInterface); //interface
        exporter.setService(implementation); //bean
        exporter.setServiceName("bookingService"); //bean name
        exporter.setRegistryPort(1099);
        try {
            exporter.prepare();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return exporter;
    }
}

RMI Stub to call remote bean
import javax.naming.Context;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.rmi.RmiProxyFactoryBean;

@Configuration
public class RMIClientConfig {

    @Bean
    RmiProxyFactoryBean service() {
        RmiProxyFactoryBean proxyFactoryBean = new RmiProxyFactoryBean();
        proxyFactoryBean.setServiceUrl("rmi://localhost:1099/bookingService");
        proxyFactoryBean.setServiceInterface(DTBookingService.class);
        return proxyFactoryBean;
    }
}

Now i am trying to call bean via  HttpInvokerServiceExporter via http protocol instead of rmi://(RmiServiceExporter). Please suggest if any replacement of HttpInvokerServiceExporter.
Answer: According to
https://docs.spring.io/spring-framework/docs/6.0.7/javadoc-api/
the whole package branch org.springframework.remoting is not available for Spring 6.


Connect to PostgreSQL server with "cert" authentication method using QSqlDatabase

Question: I need to communicate with PostgreSQL database from my Qt application, but the server uses "cert" authentication method, so I need to pass my certificates to the server.
The only solution I see for now is to obtain PGconn* like this:
QSqlDatabase db;
//.....
PGconn* conn = (PGconn*)db.driver()->handle()->data();

and do some work with it. Or even reject QSqlDatabase and use libpq directly.
Is there any other way to do this without using libpq from my code? For example, something like this:
//hypothetic QSqlDatabase methods:
QSqlDatabase db;
//.....
db.SetSslCert("/path/to/my/cert.crt");
db.SetSslKey("/path/to/my/cert.key");
//.....

Comment: `QSqlDatabase` is pretty limited - I wouldn't be surprised if there's no way to do this directly.
Answer:
I need to pass my certificates to the server.

There's no function in Qt for that because there's no equivalent function in libpq for that either. It happens automatically, as described in  Client Certificates inside SSL support from libpq documentation
Excerpt:

If the server requests a trusted client certificate, libpq will send
  the certificate stored in file ~/.postgresql/postgresql.crt in the
  user's home directory. The certificate must be signed by one of the
  certificate authorities (CA) trusted by the server. A matching private
  key file ~/.postgresql/postgresql.key must also be present

(in Windows, ~/.postgresql is going to be %APPDATA%\postgresql)
The same will happen for a Qt application since the Qt's QPSQL driver is built on top of libpq. The fact that the connection uses SSL and certificates is essentially transparent even for the driver itself.
EDIT: if ~/.posgresql is not convenient as when they are multiple certificates, alternatives exist:

The location of the certificate and key files can be overridden by the
  connection parameters sslcert and sslkey or the environment variables
  PGSSLCERT and PGSSLKEY

The connection parameters are set through QSqlDatabase::setConnectOptions. Despite its doc mentioning only an handful of postgresql-specific parameters, it actually will accept any parameter, so anything supported by libpq will work.
Comment: Thanks, that works. But what if I need to connect to the database under different roles, each has it's own *.crt and *.key file? Is there any solution except replacing files in `~/.postgresql/` before each connection?
Comment: @Sergey: this can be overwritten through environment variables or connection parameters, see my edit


KO Single page app. Async data calls randomly failing/not binding

Question: I've got a single screen with multiple dropdowns. Each get populated via a web api call.
I'm in an active directory environment. I'm using the Durandal SPA framework.

At the moment I do the loading of my dropdowns on the activate of my view. EG.
  activate: function (data) {
            var id = data.id || undefined;
            userRole(data.mode || 'usr');

            // i added this as i was thinking i dont need to initialize the "static" dropdowns every time
            // I'm testing my code without this as we speak.
            if (!hasBeenInit) {
                lookupInit(id);
                hasBeenInit = true;
            }
        },
   }

[A] It seems like randomly, depending on the amount of server load (I'm guessing) my dropdowns wont get populated..
[B] Some of the dropdowns are dependant on the value of another.
I've I've achieved this by making use of the knockout subscribe event. and updating my observable collections.
Javascript
userInfo.BuildingCode.subscribe(function (value) {
        vm.userInfo.FloorCode(undefined);
        http.get('api/Floor', { id: value }, false)
            .done(function (response) {
                console.log('api/Floor');
                vm.lookups.allFloors(response);
                console.log(vm.lookups.allFloors());
            });
    });

html
<select data-bind="options: lookups.allFloors, optionsText: 'FloorName', optionsValue: 'FloorCode', value: $root.userInfo.FloorCode"></select>

If I had to select the building value for example, the floor dropdown must get new values.
The API call does happens, it seems like the observable array gets updated, but the values don't seem to be reflecting on the view.
Chrome console log
api/Floor main-built.js:14
[Object, Object, Object]

api/Floor main-built.js:14
[Object, Object, Object]

api/Floor main-built.js:14
[Object, Object, Object, Object, Object]

What can i do to ensure my lookups/dropdowns get populated each and every call. As well as their execution order stays as specified.
I've tried something like this, but it just feels wrong. I've also added an async false overload to the  durandal http helper, but it didnt seem to work... any ideas? :\
   http.get('api/employmenttype')
            .done(function (response) {
                console.log('api/employmenttype');
                vm.lookups.allEmploymentTypes(response);
            })
            .then(function () {
                http.get('api/actionlist')
                    .done(function (response) {
                        console.log('api/actionlist');
                        vm.lookups.allActionListOptions(response);
                    })
                    .then(function () {  ... } );

UPDATE
I investigated my async call overload. Ended up being the culprit, once i fixed it, my data seemed to load constantly. The only side effect is that none of my server side data sets loads asynchronously. (Which i'm hoping I wont get crucified for).
Answer: Assuming that lookupInit is a async call make sure to return the promise. So activate becomes something along the line.
activate: function (data) {
    var id = data.id || undefined;
    userRole(data.mode || 'usr');

    // i added this as i was thinking i dont need to initialize the "static" dropdowns every time
    // I'm testing my code without this as we speak.
    if (!hasBeenInit) {
        hasBeenInit = true;
        return lookupInit(id);
    }
    return true;
},

I'm still digesting the other part(s) of the question, but thought that might get you started already.
Update: The value of vm.userInfo.FloorCode is reset to undefined, but in the select there's no optionsCaption: 'Please select...' defined. It might be that ko won't update the option values because is can't find a corresponded value.
Comment: Yes, the standard they have at the client is that defaults get added to the value set, thus i couldn't/didn't add a caption. I'll have a look at  your suggestion. I investigated my async call overload. Ended up being the culprit, once i fixed it, my data seemed to load constantly... although it feels slightly wrong making the majority of the api calls async false. Would this be standard practice when dealing with server side data?
Comment: Don't get me wrong here. I was NOT suggesting to set `async=false`, instead I was suggesting returning the promise, so that Durandal knows  during `activate` when it's allowed to do further composing.
If the default it added to the value set, make sure to set the value for default instead of `undefined` e.g. `vm.userInfo.FloorCode('WhatEverDefaultValueIsReturned')`;


Count all values in a 2D matrix greater than a value for a 3D array

Question: Given a 3D arr
np.random.seed(0)
arr=np.random.rand(4,3,3)

The arr is a below
0.54881,0.71519,0.60276
0.54488,0.42365,0.64589
0.43759,0.89177,0.96366

0.38344,0.79173,0.52889
0.56804,0.92560,0.07104
0.08713,0.02022,0.83262

0.77816,0.87001,0.97862
0.79916,0.46148,0.78053
0.11827,0.63992,0.14335

0.94467,0.52185,0.41466
0.26456,0.77423,0.45615
0.56843,0.01879,0.61764

I would like to calculate total cell that greater than 0.7 at the last two axis.
Which should give the answer of
3,3,5,2

Extension from the suggestion made from this OP, I reckon this can be achieved as below
[(darr>0.7).sum() for darr in arr]

But, I wonder, whether there is another approach to avoid the list comprehension.
Answer: You can sum over multiple axes.
(arr > 0.7).sum(axis=(1, 2))
array([3, 3, 5, 2])


Show that $\exp \biggl(\sum_{n=1}^\infty (-1)^{n-1} \frac{z^n}{n} \biggr) = 1+z \ $ for $\ \lvert z \rvert < 1$

Question: I am working on the following exercise:

Show that $$\exp \biggl(\sum_{n=1}^\infty (-1)^{n-1} \frac{z^n}{n} \biggr) = 1+z$$
for all $z \in \mathbb{C}$ with $\lvert z \rvert < 1$.
Hint: $\frac{d}{dz} \frac{f(z)}{1+z} = ?$

I do not get how this hint is supposed to help. Following the hint I would have to use the quotient rule
$$\frac{u^\prime v - uv^\prime}{v^2}$$
, to evaluate $\frac{d}{dz} \frac{f(z)}{1+z}$, so I calculated the derivative
$$\frac{d}{dz} \exp \biggl(\sum_{n=1}^\infty (-1)^{n-1} \frac{z^n}{n} \biggr) = \biggl(\sum_{n=1}^\infty(-1)^{n-1}z^{n-1}\biggr) \exp \biggl(\sum_{n=1}^\infty (-1)^{n-1} \frac{z^n}{n} \biggr).$$
But I still can not see what this should be good for, when I use this on the quotient rule. Could you give me a hint?
Answer: We have, for $|z|<1$,
$$
\frac{d}{{dz}}\frac{{f(z)}}{{1 + z}} = \frac{{f(z)\left( {\sum\limits_{n = 1}^\infty  {( - 1)^{n - 1} z^{n - 1} } } \right)(1 + z) - f(z)}}{{(1 + z)^2 }} = f(z)\frac{{(1 + z)\sum\limits_{n = 1}^\infty  {( - 1)^{n - 1} z^{n - 1} }  - 1}}{{(1 + z)^2 }}
\\
 = f(z)\frac{{\sum\limits_{n = 1}^\infty  {( - 1)^{n - 1} z^{n - 1} }  - \sum\limits_{n = 1}^\infty  {( - 1)^n z^n }  - 1}}{{(1 + z)^2 }} = f(z)\frac{{1 - 1}}{{(1 + z)^2 }} = 0.
$$
Thus $f(z)/(1+z)$ is a constant, which must be $f(0)/(1+0)=1$. Hence $f(z)=1+z$.
Comment: The radius of convergence of the series appearing in $f(z)$ is $1$. Thus you need $|z|<1$ when you differentiate it term-wise.
Comment: Thanks for your answer. Could you please expalin where you use that $\lvert z \rvert < 1$?
Answer: $$\exp[\sum_{n=1}^{\infty}(-1)^{n-1}\frac{z^n}{n}]= \exp[\ln(1+z)]=1+z, |z|<1.$$
Answer: Hint: What is the power series for $ln(z) $ ?


Sketch set $|z-1| = 1$ and the corresponding image of the map $w = z^2$

Question: Dear MSE-community!
I have begun on a journey through Gamelin's Complex Analysis. In the first chapter, there is an exercise, which claims that $|z-1| = 1|$ corresponds to $r = 2\cos\theta$ if you change to polar coordinates. How exactly do you change to polar coordinates so you get $r = 2\cos\theta$?
I have myself tried to solve this exercise:
$$|z-1|=1 \iff (x-1)^2+y^2=1$$
So the domain is a circle with center $(1,0)$ and radius $1$. To obtain the image under the map $w = z^2$ we compute:
$$
z^2 = (x^2-y^2) + i(2xy)$$ which yield, when plugged into the equation of the domain: $$(x^1 - y^2 - 1)^2 + (2xy)^2 = 1 \iff x^4 - 2x^2y^2 - 2x^2 + y^4 + 2y^2 + 4x^2y^2 = (x^2+y^2)^2 + 2(y^2-x^2) + 1 = 1 \iff
|z|^4 - 2\text{Re}(z^2) = 0 \iff |z|^4 = 2\text{Re}(z^2)$$

I do not understand how the image $|z|^4 = 2\text{Re}(z^2)$ is sketched out, or translated into polar form.
All help is appreciated, thanks!
Comment: $$(x-1)^2+y^2=1\to x^2+y^2=2x$$ which is to say that $$r^2=2r\cos\theta\to r=2\cos\theta$$
Answer: Starting with $r=2 \cos \theta,$
$\displaystyle r=\frac{2x}{r}$
$r^2 = 2x$
$x^2 +y^2-2x +1 = 1$
$(x-1)^2 + y^2 =1$
$|z-1|=1.$
Here is some Mathematica code to plot the image (a cardiod) of $w=z^2$ (in red) along with the circle (in blue).
<code>Q = ( (x - 1)^2 + y^2 == 1);
S = ImplicitRegion[Q, {x, y}];
a = Region[S, Frame -> True];

f = Evaluate[{x^2 - y^2, 2 x y}] &;
F = TransformedRegion[a, f];
b = Region[F, BaseStyle -> Red, Frame -> True];

Show[a, b, PlotRange -> {{-2.5, 4.5}, {-3, 3}}, AspectRatio -> 6/7]
</code>

We have made use of the mapping:
$w=z^2$
$\eta + i \xi = (x+iy)^2 = x^2 -y^2 + i\, 2xy.$
Answer: As $|z-1|=1$, $z=1+\cos t+i\sin t$ for some $t$.
Here $r\cos\theta=1+\cos t$ and $r^2=(1+\cos t)^2+\sin^2 t=2+2\cos t=2(1+\cos t)=2r\cos\theta$.
So, $|z-1|=1$ can be written as $r=2\cos\theta$ in polar coordinates.

Note that $z=1+\cos t+i\sin t=2\cos^2\frac t2+2i\cos\frac t2\sin\frac t2$
$\omega=z^2=(2\cos^2\frac t2+2i\cos\frac t2\sin\frac t2)^2=4\cos^2\frac t2(\cos t+i\sin t)=2(1+\cos t)(\cos t+i\sin t)$
Here $r=2(1+\cos t)$ and
So, $r\cos\theta=2(1+\cos t)\cos t=r(\frac r2-1)$ and hence $r=2(1+\cos\theta)$, which describes a cardioid.

We have three sets of lengths and angles.
The first set measures a point on the circle from the centre of the red circle (i.e., $1$), with the length being $1$ and the angle being $t$.
The second set measures the same point on the circle from the origin, with the length $r$ and angle $\theta$. We can actually use simple geometry to show that $\theta=\frac t2$ and  $r=2\cos\theta$.
The third set measures a point on the blue cardioid (which is corresponding to the point on the circle) from the origin, with the length and the angle again denoted by $r$ and $\theta$. Notice that $r$ and $\theta$ in the second and the third set are different.

There is a problem in OP's approach. When we are talking about $z=x+iy$, we have $(x-1)^2+y^2=1$. But if we want to find the locus of $\omega$, we have to consider the graph of $Y$ against $X$, where $\omega=X+iY$. It means that we have to find an equation connecting $X$ and $Y$ with $X=x^2-y^2$, $Y=2xy$ and $(x-1)^2+y^2=1$. It is not correct to do the substitution getting $(x^2-y^2-1)^2+(2xy)^2=1$.
Comment: Instead of the locus of the square of $z$, your equation is the locus of the square root of $z$. I used different symbols $z=x+iy$ and $\omega=X+iY$ to distinguish the two points.
Comment: I kind of figured I did something wrong with that substitution but what exactly does my substitution represent?
Comment: If $z=\omega^2$ and $\omega=X+iY$, then $z=(X^2-Y^2)+i(2XY)$. For $z=x+iy$, we have $(x-1)^2+y^2=1$. Therefore, $(X^2-Y^2-1)^2+(2XY)^2=1$ is the equation of the locus of $\omega$ with $\omega^2=z$.  Using different symbols for the real and imaginary parts of $z$ and $\omega$ help us to see the clear picture.
Comment: I know that's *how* I did the substitution but I don't understand the point you are trying to make :(
Comment: Another comment on your value for $r$: you got $r = 2(1 + cos\ t)$ but when I try to obtain $r$ I get $r^2 = 2(1 + cos\ t)$ via $z^2 = (1 + cos\ t + i\sin\ t)^2 \implies r^2 = (1 + cos\ t)^2 + (sin\ t)^2 \iff r^2 = 2(1 + cos\ t)$.

What am I doing wrong?
Comment: $\omega=2(1+\cos t)(\cos t+i\sin t)$ is already in polar form with $|\omega|=2(1+\cos t)$ and $\arg(\omega)=t$.
Comment: $\omega=z^2=(1+\cos t+i\sin t)^2$ implies that $|\omega|=|(1+\cos t+i\sin t)^2|=|(1+\cos t+i\sin t)|^2=(1+\cos t)^2+(\sin t)^2=2(1+\cos t)$. Again, it is $r=2(1+\cos t)$.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/94070/discussion-between-iaenstrom-and-cy-aries).
Comment: @iaenstrom I just added a figure and some notes to my answer. See if they can help.
Answer: From your equation $(x-1)^2 + y^2 = 1$, use the substitution $x = r \cos \theta, y = r \sin \theta$. Expanding and rearranging that equation will give you $r = 2\cos \theta$.


C# XAML Creating StackPanel in BackGroundWorker

Question: This is my first question here. I'm begining with XAML and C#, hope I can explain my problem and get some help.
I'm afraid that my approach is not possible to implement, but maybe I could get some help with a workaround.
I need to print lots of cards. The process is running but freezes the main thread. I would like to do this bulk printing inside a BackgroundWorker and report progress in the main thread.
I found some examples of how to do it and I created all the stuff necessary to run the backgroundworker.
The problem is that for each card, I create an stackpanel where I build the picture and finally print it using a FixedDocument and a printdialog.
Code crashes in the first line of the class accreditation_graphic
<code>        void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
        {
        ObservableCollection<accreditation_field> _acc_list;
        _acc_list = _param_acc_list;

        accreditation_graphic _graphic = new accreditation_graphic();

        // The sender is the BackgroundWorker object we need it to
        // report progress and check for cancellation.
        //NOTE : Never play with the UI thread here...
        foreach (accreditation_field _acc in _acc_list)
        { [...] }
        [...]
    }
</code>
The class is:
<code>    class accreditation_graphic
{
    private StackPanel _stack = new StackPanel();

    public accreditation_graphic()
    {

    }
</code>
[...]
And the thread finishes with no error in: private StackPanel _stack = new StackPanel();
Is there any way to create an stackpanel in a backgroundworkers?
Thanks.
Comment: See [this question](http://stackoverflow.com/q/2763323/1136211). It is however possible to create UI elements in a different thread, provided that you set it to STA (single thread apartment). But it won't be (easily) possible to use those elements in the UI thread. They are completely separated.
Answer: The correct approach is to use your background worker thread to create the data that will be displayed on the UI but not the actual UI elements. You can use the progress report mechanism to report that data to the UI thread. Have the code on the UI thread pick that data and use it to generate the actual UI elements.
An even better solution: replace StackPanel with ItemsContainer (or an inheritor of ItemsContainer) and use data binding. Briefly here are some more details:

In XAML use an ItemsContainer or a class inherited from ItemsContainer.
In XAML set the ItemsSource of the ItemsContainer via data binding to an observable collection stored in a view model (that is whatever you set the DataContext of the control / page to).
In XAML use a data template to visualize each element from the ItemsSource.
Use the progress report mechanism to bring the data from the background thread and transfer it to the observable collection that is the source of the data binding.

BTW, if you are just starting with C# / XAML take the time to learn about databinding and MvvM, it will be worth your time.
Another suggestion: look at the new async / await in C#. You should use that instead of the background worker.


Will files and data be deleted when I update from 10.10 to 11.04?

Question:
Possible Duplicate:
Will there be data loss for upgrade?

I am thinking to update from 10.10 to 11.04.
Will any files or data be deleted?
Thanks in advance.
Answer: At the end of the upgrade, you can choose to keep all your files, including previous kernel version and old libraries. So, an upgrade wont delete any of your files, but you may remove the old libraries and programs, at your choice.


Is it possible to prove $\sum_{k=0}^n \binom{n\vphantom{k}}{k} \binom{k}{m} = \binom{n\vphantom{k}}{m} 2^{n-m}$ combinatorially?

Question: $$\sum_{k=0}^n \binom{n}{k} \binom{k}{m} = \binom{n}{m} 2^{n-m}$$
So for the proof, I have to use a real example, such as choosing committees, binary sequences, giving fruit to kids, etc. I have been thinking hard on it, but I don't fully understand it to do so.  Any help is really appreciated.
Comment: I think it is a binomial identity
Comment: You could make the summation start at $k=m$ with no difference.
Answer: Say you have n people and a large empty ship. There are needed exactly m people (crew) to operate the ship, and there could be any number of passengers. In how many ways can you select the crew and the passengers from the group of n people?
First way: Select the crew first in $\binom{n}{m}$ ways. For every one of the remaining $n-m$ people you have 2 choices: either to select him as a passenger or not. So overall you have $\binom{n}{m}2^{n-m}$ ways of filling the ship.
Second way: Select first which people will get on the ship (not making distinction between crew and passengers yet). Then select which of them will be the crew. If you had made your mind that $k$ people will get on the ship then you could select them in $\binom{n}{k}$ ways, and then select the crew members between them in $\binom{k}{m}$ ways. Since $k$ could be any number from $m$ to $n$ you should take the sum over $k$ of the above product. Starting the summation from a smaller value of $k$ is ok since $\binom{k}{m}=0$ for $k<m$.
Comment: +1, though I would prefer not to be a passenger if the crew is randomly selected!
Answer: Start with an $n$-element set $N$, say $\{1,2,\dots,n\}$. The $k$-th term in the sum on the left side of your equation counts the number of ways of choosing, first, a $k$-element subset $K$ of $N$, and then an $m$-element subset $M$ of $K$.  So the whole sum counts the ways of making such choices, $M$ and $K$ such that $M\subseteq K\subseteq N$, if you allow $K$ to be of any size (but $M$ still has to have $m$ elements).  The right side of your equation counts the same thing, because there are $\binom nm$ possibilities for $M$ and, once you've chosen $M$, choosing $K$ amounts to choosing a subset of the $(n-m)$-element set $N-M$ to serve as the rest of $K$ (meaning to serve as $K-M$).


Proving $\int_{0}^\pi \frac{2\cos 2\theta + \cos 3\theta}{5+4\cos\theta} = \frac{\pi}{8}$

Question: Given that $$\int_{|z|=1|}\frac{z^2}{2z+1} dz = \frac{i\pi}{4}$$,
show $$\int_{0}^\pi \frac{2\cos 2 \theta + \cos 3\theta}{5+4\cos\theta} = \frac{\pi}{8}$$.
I saw the bounds of the latter integral and thought that I should try and parametrize using $z = e^{2i\theta}$ where $\theta \in [0,\pi]$.
This doesn't seem to simplify easily.
i saw this thread: Show that $\int_0^\pi\frac{2\cos(2\theta)+\cos(3\theta)}{5+4\cos(\theta)}d\theta=\frac{\pi}{8}$
and the top answer says:
$$\begin{align}
\int_0^\pi \frac{2\cos(2\theta)+\cos(3\theta)}{5+4\cos(\theta)}\,d\theta&=\frac12\text{Re}\left(\oint_{|z|=1}\frac{2z^2+z^3}{5+2(z+z^{-1})}\,\frac{1}{iz}\,dz\right)\\\\\end{align}$$
which I don't understand.
How does multiplying a half to the integral with contour $|z|=1$ (parametrized by $z = e^{i\theta}, \theta\in [0,2\pi]$) give the LHS?
I tried looking at it by taking the latter integral and using the substitution $u=\pi + \theta$, in hopes that the integrand simplifies to stay the same but it doesn't, so I can't see why the integral with bounds $0,\pi$ is half the integral that would have bounds $0,2\pi$ (since we would use the parametrization $z=e^{i\theta}$).
Comment: Do you want $\cos\theta$ or $\cos2\theta$ in your integral?
Comment: @LordSharktheUnknown $\cos 2\theta$, sorry.
Comment: It still has $\cos\theta$ in the title.
Comment: Let $z= \cos (\theta)+i \sin( \theta )$, rationalise the denominator, equate imaginery parts and use a symmetry arguement to halve the interval.
Answer: With $\theta\to-\theta$
$$
I=\int_0^{-\pi} \frac{2\cos(2\theta)+\cos(3\theta)}{5+4\cos(\theta)}\,(-)d\theta=\int_{-\pi}^0 \frac{2\cos(2\theta)+\cos(3\theta)}{5+4\cos(\theta)}\,d\theta
$$
\begin{align}
2I
&=\int_{-\pi}^\pi \frac{2\cos(2\theta)+\cos(3\theta)}{5+4\cos(\theta)}\, d\theta\\
&=\int_{|z|=1} \frac{{\bf Re\,}(2z^2+z^3)}{5+2(z+z^{-1})}\,\dfrac{1}{iz} dz,\\
&={\bf Re\,}\int_{|z|=1} \frac{2z^2+z^3}{5+2(z+z^{-1})}\,\dfrac{1}{iz} dz,\\
&={\bf Re\,}\dfrac{1}{i}\int_{|z|=1} \frac{z^2}{2z+1}\, dz,
\end{align}
Note that $\overline{z}=\dfrac{1}{z}$ so $\overline{dz}=d\overline{z}=-\dfrac{dz}{z^2}$ and $\dfrac{\overline{dz}}{\overline{iz}}=-\dfrac{dz}{-i\overline{z}z^2}=\dfrac{dz}{iz}$ and also ${\bf Re\,}(z+\overline{z})=z+\overline{z}$. The rest is simple.
Answer: Note that
$$2\int^\pi_0 \cos(n\theta)f(\cos \theta ) d\theta = \int^{\pi}_{-\pi} \cos(n\theta)f(\cos\theta ) d \theta $$
Now you can use that $\gamma(t) = e^{i t}$ where $t \in [-\pi , \pi )$ to prove
$$\Re \oint_{|z|=1} z^n f\left(\frac{z+z^{-1}}{2} \right) \frac{dz}{iz} = 2\int^\pi_0 \cos(n\theta)f(\cos \theta ) d\theta $$
Or any linear combination
$$\Re \oint_{|z|=1} (az^n+bz^m) f\left(\frac{z+z^{-1}}{2} \right) \frac{dz}{iz} = 2\int^\pi_0 (a\cos(n\theta)+b \cos(m\theta))f(\cos \theta ) d\theta $$
So we have by choosing $n=2,m=3,a=2,b=1$
$$\Re \oint_{|z|=1} \frac{z^3+2z^2}{5+2(z+z^{-1})} \frac{dz}{iz} =2\int^{\pi}_{0}\frac{\cos(3t)+2\cos(2t)}{5+4\cos(t)}dt $$
Note that
$$\frac{z^3+2z^2}{5+2(z+z^{-1})} \frac{1}{z} = \frac{z^2(z+2)}{(z+2)(2z+1)} = \frac{z^2}{2z+1}$$
So we deduce that
$$2\int^{\pi}_{0}\frac{\cos(3t)+2\cos(2t)}{5+4\cos(t)}dt =-i \Re \oint_{|z|=1}  \frac{z^2}{2z+1} = \frac{\pi}{4}$$


Using flash player i.e. watching a video in fullscreen (Mozilla), freezes computer

Question: this has happened to me twice now, today and yesterday. I've just installed Ubuntu 14.04 (some time ago) 64bit and I use noscript in Firefox.
I was watching youtube not in fullscreen and my screen froze but the sound kept on playing with no problem. At first I couldn't do anything but after mashing a lot of button combinations my mouse started working (the mashing did not result in anything but the mouse showing) I tried to shut the tab down with youtube and it worked, kind of. The sound stopped but the computer was still frozen apart from the cursor.
Today I was watching a stream in fullscreen and the same thing happened. Screen froze, sound kept on playing and after mashing button combinations (stuff like alt+f4, esc, alt+tab etc.) my cursor appeared but I could do nothing anyway.
I tried to find a solution but I only found posts from 2013, 2014 etc.
Answer:
Adobe Flash player support and updates for linux platform has been stopped. Therefore you might experience some problems.
As an alternative you should disable Flash plugin.

Press CTRL+SHIFT+A
Go to the PLUGIN section, and disable Shockwave flash player.
Reload the Youtube video. Now It will use HTML 5 player to play it.

I hope HTML5 player wont cause any trouble!


jQuery.print-preview not working in IE9

Question: I have this issue with a plug-in called jQuery.print-preview. It works fine in FF, Safari, etc.. For some reason (I think) it conflicts with Google's custom search plug-in in IE9. If I add a meta tag to tell IE to use IE7 it works fine. But this is not really satisfying because the page renders a bit different under IE7.
I have put all the files in my test folder:
http://tinyurl.com/blnlaym
Hopefully you can help me.
Kind regards,
Jurgen
Comment: For some reason the conflict is there when I use jquery-1.9.0.min.js. If I switch to jquery 1.5.2 everything works just fine. For now I leave it like that but it would be great if somebody could tell me why 1.9 does not work in IE9.

Jurgen
Answer: Sigh, I just discovered that the whole problem was due to the sequence of loading several scripts. It was by accident I mixed up the order. I did that before in an attempt to solve this but apparently I overlooked something.
Okay, consider this one solved.
Jurgen

jQuery.print-preview not working in IE9


In Spring framework can we write jdbc in jsp

Question: Hello friends i want to know whether writing jdbc connection in jsp is it a good way or not in spring frame work.
Comment: never put jdbc in jsp, bad practice. this has nothing to do with spring framework, it is bad practice in general.
Comment: Its not a good way. You are breaking the MVC pattern.
Comment: You can, but why would you want to do that?
Comment: Looks like I am back in 1996 and not 2013
Comment: in my web application i am dynamically changing the values on a click so i want to do it using jdbc in jsp .
Comment: with out using jdbc in jsp can i render a page dynamically. i am new to spring please provide a example
Answer: Not it's not a good way.
This is really a bad design. You are using spring-mvc so I guess you are using the MVC pattern. In the MVC pattern the V(iew) is your jsp and the only responsability of the view is to display a M(odel). This M(odel) comes from the C(ontroller) and must not be built/fetched from the View.
More information on the MVC pattern : http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller


Pipe successfully sorting data but tests are returning incorrect results

Question: I am using a pipe to sort a a json array with two datetime columns in either ascending or descending order (triggered by the boolean isDescending, however the unit test doesn't seem to care about the order each object is in the array. Like in the test all 4 cases return true, even though the returned array should have the items in reverse order compared to dummyData[]. What am I doing wrong
sortpipe.ts
export class SortByPipe implements PipeTransform {

  transform(data: iRepositories[], args?: ISortByPipe): iRepositories[] {
    if ( !args.column)
    {
      return data;
    }
    return data.sort((a, b) => {
      if (args.isDescendingOrder)
      {
        return a[args.column] > b[args.column] ? -1 : 1;
      }
      else
      {
        return a[args.column] > b[args.column] ? 1 : -1;
      }
    });
  }

}

sortpipe.spec.ts
describe('SortByPipe', () => {

  let pipe: SortByPipe;

  beforeEach(() => {
    pipe =  new SortByPipe();
  });

  const dummyData = [
    { id: 1, created_at: '2014-01-24T13:40:11Z', updated_At: '2015-01-24T13:40:11Z' },
    { id: 2, created_at: '2015-01-24T13:40:11Z', updated_At: '2016-01-24T13:40:11Z' },
    { id: 3, created_at: '2016-01-24T13:40:11Z', updated_At: '2017-01-24T13:40:11Z' },
  ];

  it('create an instance', () => {
     expect(pipe).toBeTruthy();
  });

  // this is correct
  it('should return in the same order as the original data (sort by created_at date)', () => {
    const args: ISortByPipe = {column: 'created_at', isDescendingOrder: false};
    expect(pipe.transform(dummyData, args)).toEqual(dummyData);
  });

  // this is correct
  it('should return in the same order as the original data (sort by last commit date)', () => {
    const args: ISortByPipe = {column: 'updated_At', isDescendingOrder: false};
    expect(pipe.transform(dummyData, args)).toEqual(dummyData);
  });

  // this should be false but its returning true
  it('should return in descending order (sort by created_at date)', () => {
    const args: ISortByPipe = {column: 'created_at', isDescendingOrder: true};
    expect(pipe.transform(dummyData, args)).toEqual(dummyData);
  });

  // this should be false but its returning true
  it('should return in descending order (sort by last commit date)', () => {
    const args: ISortByPipe = {column: 'updated_At', isDescendingOrder: true};
    expect(pipe.transform(dummyData, args)).toEqual(dummyData);
  });
})

Answer: Array.prototype.sort sorts in-place so it sorts the array you pass in.  It returns the same array out of convenience but it is not making a copy of the input.  This means, after you call your transform, the order of dummyData has been changed.  You should make a copy in your pipe to keep it safe.
Answer: try like this
let sortarray = [...data];
sortarray = sortarray.sort((a, b) => {
      if (args.isDescendingOrder)
      {
        return a[args.column] > b[args.column] ? -1 : 1;
      }
      else
      {
        return a[args.column] > b[args.column] ? 1 : -1;
      }
    });
return sortarray;


Python: how do I resolve AttributeError: 'module' object has no attribute 'face_recognition_model_v1'

Question: I have downloaded the file and placed it in the same directory from where I am running my code. But here facerec = dlib.face_recognition_model_v1(face_rec_model_path) I am still getting this Atribute error. i have given the full to where it is but still error.
this is my code, I am not able to identify where the problem is ?
import sys
import os
import dlib
import glob
from skimage import io

predictor_path = '/home/irum/Desktop/DLIB-recognition/shape_predictor_68_face_landmarks.dat'
face_rec_model_path = '/home/irum/Desktop/DLIB-recognition/dlib_face_recognition_resnet_model_v1.dat'
faces_folder_path = '/home/irum/Desktop/DLIB-recognition/att_faces/ERSHIAN'

# Load all the models we need: a detector to find the faces, a shape predictor
# to find face landmarks so we can precisely localize the face, and finally the

# face recognition model.
detector = dlib.get_frontal_face_detector()
sp = dlib.shape_predictor(predictor_path)
facerec = dlib.face_recognition_model_v1(face_rec_model_path)

win = dlib.image_window()

# Now process all the images
for f in glob.glob(os.path.join(faces_folder_path, "*.png")):
    print("Processing file: {}".format(f))
    img = io.imread(f)

    win.clear_overlay()
    win.set_image(img)

    # Ask the detector to find the bounding boxes of each face. The 1 in the
    # second argument indicates that we should upsample the image 1 time. This
    # will make everything bigger and allow us to detect more faces.
    dets = detector(img, 1)
    print("Number of faces detected: {}".format(len(dets)))

    # Now process each face we found.
    for k, d in enumerate(dets):
        print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
            k, d.left(), d.top(), d.right(), d.bottom()))
        # Get the landmarks/parts for the face in box d.
        shape = sp(img, d)
        # Draw the face landmarks on the screen so we can see what face is currently being processed.
        win.clear_overlay()
        win.add_overlay(d)
        win.add_overlay(shape)

        face_descriptor = facerec.compute_face_descriptor(img, shape)
        print(face_descriptor)

        dlib.hit_enter_to_continue()

Comment: The error message is telling you that `dlib` doesn't have an attribute called `face_recognition_model_v1`.  I don't know what dlib is so I can't tell you any more than that, but you could check the dlib.py file you downloaded and check there.
Answer: update dlib. Run this command: pip install dlib==19.4.0
Answer: You need to install dlib.
Run
pip install dlib
Comment: have you tried the latest dlib? run pip install dlib==19.4.0.
Comment: Requirement already satisfied: dlib in /usr/local/lib/python2.7/dist-packages/dlib-19.2.0-py2.7-linux-x86_64.egg


OpenCV symbols are undefined using gcc 5.1

Question: I have a very basic program to test that OpenCV works.
#include <opencv2/opencv.hpp>

int main() {
    cv::namedWindow("Window", CV_WINDOW_AUTOSIZE);

    cv::VideoCapture video_capture;
    video_capture.open(0);

    while (true) {
        cv::Mat image;
        video_capture.read(image);

        cv::imshow("Window", image);

        if (cv::waitKey(1) == 27) {
            break;
        }
    }

    return 0;
}

And a CMakeLists.txt file that finds OpenCV like so:
find_package(OpenCV REQUIRED)
...
target_link_libraries(Project ${OpenCV_LIBS})

This works on Mac OSX 10.10 using OpenCV 2.4.10 and clang 602.0.49, but If I try to use gcc 5.1 by putting set(CMAKE_CXX_COMPILER /usr/gcc-5.1.0/bin/g++-5.1.0) in my CMakeLists.txt, I get the following error:
Undefined symbols for architecture x86_64:
  "cv::namedWindow(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)", referenced from:
      _main in main.cpp.o
  "cv::imshow(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, cv::_InputArray const&)", referenced from:
      _main in main.cpp.o

What's the problem and how do I fix it?
Comment: It might be the [new ABI](https://gcc.gnu.org/gcc-5/changes.html#libstdcxx).
Comment: I want to use C++ 11 though.
Comment: So? Have you read what they wrote about the new ABI and how to fix problems in case linking fails for symbols including `std::__cxx11::`?
Comment: @DanielFrey so I just have to recompile opencv using gcc 5.1?
Comment: No. Just add `#define _GLIBCXX_USE_CXX11_ABI 0` before including any other headers.
Comment: @DanielFrey I was assuming a recompile was needed. This [answer](http://stackoverflow.com/a/12546314/1180117) suggests use of preprocessor will create runtime issue. Is that different from this one ?
Answer: Please recompile your OpenCV using the same version of gcc that you use to compile the above code. This problem should hopefully disappear. From the official gcc pages,

If you get linker errors about undefined references to symbols that involve types in the std::__cxx11 namespace or the tag [abi:cxx11] then it probably indicates that you are trying to link together object files that were compiled with different values for the _GLIBCXX_USE_CXX11_ABI macro. This commonly happens when linking to a third-party library that was compiled with an older version of GCC. If the third-party library cannot be rebuilt with the new ABI then you will need to recompile your code with the old ABI.
Comment: With versions of gcc before 6, this can be accomplished by calling cmake with CXXFLAGS set to "-std=c++11" or "-std=c++14": `CXXFLAGS="-std=c++11" cmake ..`
Answer: We had this problem testing in a CentOS 7.9 container with gcc 5.3.1. We tried many solutions as shown here, here, and here, and although none worked as-is, the associated discussion and comments -- especially about using linker verbosity ('-Wl,--verbose') to understand what it's trying to do -- contributed pieces of the puzzle. After a day of struggle we solved it by downloading a later version of libstdc++ (6.0.21 vs 6.0.19) to /usr/lib64 and breaking the libstdc++.so symlink to point at the newer version. This allowed older OpenCV libs to link and -- so far -- has not broken anything else.
Note that we only changed the libstdc++ .so -- downloading various rpms, trying to upgrade the container, adding -D_GLIBCXX_USE_CXX11_ABI=0 build flag, etc - none of those worked.
We found it odd the issue didn't occur in our testing with gcc4 and gcc6-9 -- only with gcc5. As far as I can tell, after gcc 5 was released in 2015 time-frame, it wasn't long before this issue had significant attention, and updated versions of libstdc++ came along soon after.


Mongodb shopping cart, how to check and update inventory

Question: I read the documentation concerning the ways to implement a shopping cart with mongodb, but I have doubts about the flow.
With this implementation each time a user enters the products in the cart, the amount paid reserved to the customer is not available to other buyers until the user performs checkout or shopping cart expires.
This approach is a problem because, by experience, the majority of users do not buy the end, leaving for a period those products reserved only to him and therefore not affordable.
This translates into a loss of sales.
E.g:

there is a product with 5 quantities in db
a client "A" puts the product in the basket with amount 5
then in the db are 0 products available
another client "B" enter the site and can not buy that product
in the end the customer "A" leave the site leaving the cart full.
The shopping cart will automatically clear after an hour.

Result: an hour for that product can not be purchased by anyone!
I think a better approach is to inspect and updates only on the actual amount at checkout.
In this way you are not lost sales for too long.
The problem with this approach is the implementation at the atomic updates of the amount.
What do you think about this approach?
Are you planning an implementation?
Answer: If I was you, I'd use multiple records in the same collection for each product put in the cart, but with a 10 min TTL on an index for documents of type "in-cart" (see mongo TTL docs). Then, using db.col.aggregate(...) you can sum these records and deduct the count from the total available. If a user leaves without buying, the TTL will auto delete de document. If he buys, you can really deduct from the total available using doc.update and $inc with negative value and delete the associated in-cart documents.
product document:
<code>{
  type: 'product'
  product_id: 123,
  available: 4
}
</code>
in-cart document(s) as many as "in progress shopping" or abandonned carts:
<code>{
  type: 'in-cart'
  product_id: 123,
  customer_id: 1,
  taken: 2
}

{
  type: 'in-cart'
  product_id: 123,
  customer_id: 2,
  taken: 1,
}
</code>