text:
Q: Error Handling Paradigms: Mixing Exceptions and Error Codes I'm currently developing a game engine in C++ using various pieces of middleware including OGRE (graphics), Bullet (physics), and OpenAL (sound), and I'm fairly early on in the project. It's at this point that I'm setting up my error handling mechanisms.
I plan on exposing the engine to the user by containing it within a DLL and exporting a function which will return a pointer to the main engine object. This object will contain methods with which you can access various components of the engine - most objects will be accessed via interfaces so that the user is hidden from the actual implementations.
I'm inclined to use error codes as my error reporting mechanism instead of exceptions since

*

*Passing exceptions through the DLL link increases the complexity of error reporting, forces me to export the exception classes, etc., and

*Error codes are generally more efficient, and for this reason they are common in real-time game engines.

The only issue that arises then is one with constructors - they can't return error codes. I therefore plan on using error codes for all methods, but throwing exceptions when constructors fail. Since I plan on using the factory method pattern to generate objects and pass them to user code, the exceptions would be handled internally by the engine, and the user would just get a null pointer on construction failure. I realize that you usually shouldn't mix exceptions and return codes, but the alternatives don't sound any better:

*

*You could not do anything in the constructor and use some kind of init() method, but there goes RAII.

*You could set a flag and have some kind of isOk() or isInitialized() method, but now you've introduced the possibility of some zombie state where the object exists but failed to initialize, and you might forget to check to make sure it's alive.

I'm aware of the inherent costs and benefits of both systems, and realize that it's generally a bad idea to mix the two. However, since constructors can't have some kind of return value, would it be unreasonable throw exceptions when constructors fail and use error codes elsewhere? Does anyone have a better suggestion?

A: I personally prefer exceptions (and have many good reasons for that). But of course throwing exceptions from DLL code to user code (and vice versa) is a bad idea. So in your situation I would use exceptions within modules (both DLLs and executable) and use error_return-based APIs for DLL exports. When using DLL's error_return-based API I would use exception-based wrappers for those error_return-ing functions.
IMO returning error indicators in any way (by return value or through reference or via per-thread error codes) havily messes the code with endless error-checking branches. My way (and my understanding of C++ way) is returning only in a case of success.

A: In your case, I'd say screw RAII and use Init methods.  Mixing two paradigms not only decreases consistency, it also forces your Engine's consumers to implement Exception handling mechanisms when some would prefer not to.

A: I prefer now to only work with exceptions, but if you still need or want to use error codes with constructors a aproach that I like is to force the user to pass a parameter in constructor:
class Foo {
    public:
        Foo(int &errorCode) {
            //our init code
            rc = SOMETHING_BAD;
        }
};

//on a method or function:
int errorCode;
Foo foo(errorCode);
if(errorCode != RESULT_OK)
{
      //handle it
}

I think this is better than having a IsOk() method or a separated Init method, because it at least force the user to pass a variable as parameter and it is hard to forget to check errors, the downside is that sometime it is boring to declare variables just for that.
My 2 cents.


text:
Q: How do I use AzureStoragePersistence and Outbox at the same time? So I was moving my NSB setup off of SQL server and onto azure service bus and figured I might as well use azure storage for persistence as well. I'm unclear on how to set this up because I'm also using outbox and I can't use azure storage with it. I'm using the web.config for connections strings, and it sort of only lets me set NServiceBus/Persistence once, so ... I'm a bit lost

A: Unfortunately, due to various reasons the outbox is only supported on SQL-Server and RavenDb. Read more about it here : https://docs.particular.net/nservicebus/outbox/
At the bottom of the document there's a note that only those two persisters support the outbox feature.

A: Add to what Dennis said - you cannot use Storage Persistence with the Outbox feature. Outbox feature requires business data and outgoing transaction to participate in the same transaction. This is only possible with Azure SQL server. With Azure Storage persistence this is not an option. Storage supports table batched operations, but not transactions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting list of files in current directory I'm trying to get a script to read the contents of the directory where the script file is located, then identify a couple of specific files based on partial names and zip them.  But I can't get the object.Files property to work.  Can someone tell me what's wrong here?
Set FSO = CreateObject("Scripting.FileSystemObject")
objFolder = FSO.GetParentFolderName(WScript.ScriptFullName)
Set allFiles = objFolder.Files
For Each objFile in allFiles
    Wscript.Echo objFile.Name
Next

A: Your
objFolder = FSO.GetParentFolderName(WScript.ScriptFullName)

assigns a Path (String) to objFolder (type prefix fraud detected!). Use
Set objFolder = FSO.GetFolder(FSO.GetParentFolderName(WScript.ScriptFullName))

instead.


text:
Q: Laravel Chumper/Zipper removing names of files I've recently installed Chumper/Zipper and trying to upload files into a zip file. However, when I open up the zip file all the files uploaded have been renamed and file extensions are removed. For example when I upload an image as image.png it will change to php20V2Wx. Does anyone know how I can fix this?
Method for storing the file
public function store(Request $request)
{

    foreach ( $request->files as $files ){
         \Zipper::make(public_path('tests.zip'))->add($files)->close();
    }

    return response()->download(public_path('tests.zip'));
}

$files  output

Array ( [0] => Symfony\Component\HttpFoundation\File\UploadedFile
  Object (
  [test:Symfony\Component\HttpFoundation\File\UploadedFile:private] =>
  [originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private]
  => favicon.ico [mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private]
  => image/x-icon [size:Symfony\Component\HttpFoundation\File\UploadedFile:private] =>
  5686
  [error:Symfony\Component\HttpFoundation\File\UploadedFile:private] =>
  0 [pathName:SplFileInfo:private] => /tmp/php4tQEul
  [fileName:SplFileInfo:private] => php4tQEul ) )


text:
Q: Compare and find difference between two XML files in SQL I have to find difference between two XML files - Latest File(File1) and previous version(File2). The Updated XML file may have additional nodes or some nodes may be deleted. I have to compare this two XML and need to show differences in SQL Server.
Sample XML file
  <oper-ins-procref index-levels="3" moidref="G2020685" proc-uid="G2195890" qualref="+Q100107[11/2022]" title="Mobile Device Data" titleref="T25409" uid="G2292969" uid-ref="R1396412" version="5.0">
      <qualifier>
        <builddates id="Q100107" suppressed="true" title="Vehicles Built From: 11/2022" />
      </qualifier>
    </oper-ins-procref>
    <oper-ins-procref index-levels="3" loc-qual="Vehicles With: Emergency Assistance" moidref="G2128321" proc-uid="G2163427" qualref="+Q107191+Q106763+Q107192" title="Emergency Call System Data" titleref="T27313" uid="G2162708" uid-ref="R1303108" version="2.0">
      <qualifier title="Vehicles With: Emergency Assistance">
        <territory id="Q107191" suppressed="true" title="USA" />
        <feature-mfc category="POSITIVE" id="Q106763" title="Emergency Assistance">
          <mfc code="hksab" type="T" vl="vltf" />
          <mfc code="hksab" type="T" vl="vlts" />
          <mfc code="hksab" type="C" vl="vlge" />
          <mfc code="hksab" type="C" vl="vlng" />
          <mfc code="hksab" type="C" vl="vl4a" />
          <mfc code="hksab" type="C" vl="vlgh" />
          <mfc code="hksab" type="C" vl="vle1" />
          <mfc code="hksab" type="T" vl="vlfd" />
          <mfc code="hksab" type="C" vl="vldr" />
          <mfc code="hksab" type="C" vl="vlhd" />
          <mfc code="hksab" type="C" vl="vlhe" />
          <mfc code="hksab" type="C" vl="vlf7" />
          <mfc code="hksab" type="C" vl="vlhc" />
          <mfc code="hksab" type="C" vl="vlgw" />
          <mfc code="hksab" type="T" vl="vlth" />
          <mfc code="hksab" type="T" vl="vlg1" />
          <mfc code="hksab" type="T" vl="vlb8" />
          <mfc code="hksab" type="T" vl="vlek" />
          <mfc code="hksab" type="T" vl="vlg4" />
          <mfc code="hksab" type="T" vl="vlra" />
          <mfc code="hksab" type="T" vl="vlrb" />
          <mfc code="hksab" type="C" vl="vltw" />
          <mfc code="hksab" type="C" vl="vltd" />
          <mfc code="hksab" type="C" vl="vltc" />
          <mfc code="hksab" type="T" vl="vlrc" />
          <mfc code="hksab" type="C" vl="vlte" />
          <mfc code="hksab" type="C" vl="vlzj" />
          <mfc code="hksab" type="T" vl="vlrd" />
          <mfc code="hksab" type="T" vl="vltu" />
          <mfc code="hksab" type="T" vl="vlfh" />
        </feature-mfc>
        <territory id="Q107192" suppressed="true" title="United States of America" />
      </qualifier>
    </oper-ins-procref>
  </section>
  <section index-levels="1" moidref="G1594458" title="Environment" titleref="T21858" uid="G2323014">
    <link-target moidref="G1594459" option="off" proc-uid="G2145049" qualref="+Q107200" title="Protecting the Environment" titleref="T21859" uid="G2335850" uid-ref="R1428999">
      <qualifier>
        <territory id="Q107200" suppressed="true" title="Brazil" />
      </qualifier>
    </link-target>
    <link-target moidref="G1594459" proc-uid="G2188330" qualref="+Q107198" title="Protecting the Environment" titleref="T21859" uid="G2335851" uid-ref="R1429000">
      <qualifier>
        <territory id="Q107198" suppressed="true" title="Taiwan" />
      </qualifier>
    </link-target>
    <link-target moidref="G1594459" proc-uid="G2322795" title="Protecting the Environment" titleref="T21859" uid="G2323015" uid-ref="R1419074" />
    <oper-ins-procref index-levels="3" moidref="G1594459" proc-uid="G1727320" qualref="+Q107192" title="Protecting the Environment" titleref="T21859" uid="G2323016" uid-ref="R1419075" version="9.0">
      <qualifier>
        <territory id="Q107192" suppressed="true" title="United States of America" />
      </qualifier>
    </oper-ins-procref>
  </section>

This is what I tried so far but the values are getting repeated for the nodes.
DECLARE @XML1 XML
DECLARE @XML2 XML

SET @XML1 = (SELECT TOP 1 Xml FROM TableA NOLOCK WHERE Id=22)

SET @XML2 = (SELECT TOP 1 Xml FROM TableB NOLOCK WHERE Id=34)

--SELECT @XML1, @XML2

--select T.N.value('local-name(.)', 'nvarchar(max)') as NodeName,
--         T.N.value('.', 'nvarchar(max)') as Value
--  from @XML1.nodes('//@*') as T(N)

--  select T.N.value('local-name(.)', 'nvarchar(max)') as NodeName,
--         T.N.value('.', 'nvarchar(max)') as Value
--  from @XML2.nodes('//@*') as T(N)

;with XML1 as
(
select T.N.value('local-name(.)', 'nvarchar(100)') as NodeName,
         T.N.value('.', 'nvarchar(100)') as Value
  from @XML1.nodes('//@*') as T(N)
  ),
XML2 as
(
select T.N.value('local-name(.)', 'nvarchar(100)') as NodeName,
         T.N.value('.', 'nvarchar(100)') as Value
  from @XML2.nodes('//@*') as T(N)
  )

select coalesce(XML1.NodeName, XML2.NodeName) as NodeName,
       XML1.Value as Value1,
       XML2.Value as Value2
from XML1
  full outer join XML2
    on XML1.NodeName = XML2.NodeName
where coalesce(XML1.Value, '') <> coalesce(XML2.Value, '')
```


text:
Q: Does a function space construction always decrease the connectivity of a space? This question is kind of dual to this question, where I asked if smashing with a space $Y$ always increases (which means ''$\geq$'') the connectivity of a space $X$ and the answer was "yes".
The connectivity of a pointed space $X$ is the maximal number $\operatorname{con}(X)$ such that $\pi_i(X)=0$ for all $0\leq i\leq\operatorname{con}(X)$.
Let $X$ and $Y$ be pointed CW complexes and equip the set $\operatorname{Hom_\bullet} (Y,X)$ of pointed continuous maps with the compact-open topology.

Is it true that $\operatorname{con}(\operatorname{Hom_\bullet} (Y,X))\leq \operatorname{con}(X)$ if $X$ is connected?

This is particullary interesting when $Y=S^1$ where $\operatorname{Hom_\bullet} (S^1,X)=\Omega(X)$ but then $\pi_n(\Omega(X))=\pi_{n+1}(X)$ and the statement is true in this case.

A: I'm not sure, what is the "(conceptually) right" answer for this (and even what is the right question).
But if $\dim Y\le\operatorname{con}X$ and $X$ is connected, then

*

*$\operatorname{map}(Y,X)$ is connected;

*$\operatorname{con}\operatorname{map}(Y,X)\ge\operatorname{con}X-\dim Y$ (because $\pi_i\operatorname{map}(Y,X)=\pi_0\operatorname{map}(Y,\Omega^i X)$, for example).

And I don't think there is an easy estimate in the direction you want. For example, $\operatorname{con}(S^1\times S^1)=0$ but $\operatorname{con}\operatorname{map}(S^2,S^1\times S^1)=+\infty$ (maps from $S^2$ can be lifted to the universal cover -- which is contractible).


text:
Q: Is there any way to reduce the cost of deactivate_slab.isra.82 in alloc_skb on Debian I have a UDP heavy workflow which bottlenecks due to deactivate_slab.isra.82 called by __alloc_skb (15+% of CPU time). The alloc method seems to be being called inside the Intel card driver most frequently (I assume for the RX path) but also by my send syscalls.
I can only push about 1.1Gbps on a 10G server due to this bottleneck, I'm wondering if there are any kernel parameters I can tweak to reduce this overhead, perhaps something to expand the size of free lists for SKBs so that the kernel-malloc path isn't hit as frequently.
I already noticed that slub_debug is enabled by default on Debian which was slowing my application even further (from 850Mbps to 1.1Gbps).

A: This was my misunderstanding in the slub_debug option, the correct way to turn it off is "slub_debug=-", " slub_debug=off" disabled the slab debug check but not all the debugging code.
After properly disabling the debug mode I see significant performance gains for my UDP heavy workloads and there is no obvious single kernel function causing a bottleneck anymore.


text:
Q: Sending data from Fragment to Fragment using Interface, by setting Fragment Layouts dynamically. Saved instance of Fragment NOT working I am sending data from one fragment to another, using interface. This works absolutely fine. Now I am trying to use onSaveInstanceState() to save the value in
a Fragment and retrieving in onCreate(). however i'm getting null in Bundle of onCreate(). P.S. everything works fine when i set the Fragment directly into the activity layout in xml. but when i set the fragment through java code into the activity, the onSaveInstanceState is failing. It is not saving the last known value. Please help.  Pasting the code below. You can try it out to know the exact issue.
Fragment_A :
public class Fragment_A extends Fragment implements View.OnClickListener {

Button btnAdd;
int counter = 0;
Communicator comm;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(savedInstanceState != null){
        counter = savedInstanceState.getInt("counter", 0);
    }
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_a, container, false);
    return view;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    comm = (Communicator) getActivity();
    btnAdd = (Button) getActivity().findViewById(R.id.btnAdd);
    btnAdd.setOnClickListener(this);
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("counter", counter);
}

@Override
public void onClick(View v) {
    counter++;
    comm.sendData(counter);
}
}

interface Communicator{
    void sendData(int i);
}

=====
Activity :
public class Activity_InterComm extends Activity implements Communicator{

FragmentManager manager;
FragmentTransaction transaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_intercomm);

    Fragment_A fragment_1 = new Fragment_A();
    Fragment_B fragment_2 = new Fragment_B();

    manager = getFragmentManager();
    transaction = manager.beginTransaction();

    transaction.add(R.id.frag_a, fragment_1, "Frag1");
    transaction.add(R.id.frag_b, fragment_2, "Frag2");
    transaction.commit();
}

@Override
public void sendData(int i) {
    manager = getFragmentManager();
    Fragment_B fragment_b = (Fragment_B) manager.findFragmentById(R.id.frag_b);
    fragment_b.setData("Button has been clicked " + i + " times");
}
}

=====
Fragment_B :
public class Fragment_B extends Fragment {

TextView txtMessage;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_b, container, false);
    return view;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    txtMessage = (TextView) getActivity().findViewById(R.id.txtMessage);
}

public void setData(String message){
    txtMessage.setText(message);
}
}

activity_intercomm.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<!--<fragment
    android:id="@+id/frag_a"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginBottom="8dp"
    android:layout_weight="1"
    android:name="android.learning.com.fragintercomm.Fragment_A"/>

<fragment
    android:id="@+id/frag_b"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:name="android.learning.com.fragintercomm.Fragment_B"/>-->

<LinearLayout
    android:id="@+id/frag_a"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginBottom="8dp"
    android:layout_weight="1"
    android:background="@color/colorAccent"
    android:orientation="vertical"/>

<LinearLayout
    android:id="@+id/frag_b"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginBottom="8dp"
    android:layout_weight="1"
    android:background="@color/colorPrimaryDark"
    android:orientation="vertical"/>

</LinearLayout>

A: the soluion I found was using getView() instead of getActivity() while initializing the button in Fragment_A. use btnAdd = (Button) getView().findViewById(R.id.btnAdd); instead of btnAdd = (Button) getActivity().findViewById(R.id.btnAdd);.
However, you can't use getView() in Fragment_B. The Textview freezes and, onSaveInstanceStat() doesn't work. Please suggest a solution.


text:
Q: Close Vaadin notification when click outside of the message box setDelayMSec( -1 ) means that the message is displayed until the user clicks on the message box. Can I close to message box when user clicks anywhere outside?

A: Try to add a tag that uses the entire screen, with this:
public void createAndShowNotification(String caption, String description, Notification.Type type) {
    description += "";
    Notification notif = new Notification(caption, description, type, true);
    notif.setDelayMsec(-1);
    notif.show(Page.getCurrent());
}

A: No, when you use setDelayMSec(-1) then you have to click in the message box to close it.
If the user should be able to close it by clicking anywhere outside the box, you have to set a positive number.
Of course you can set a very high number, so that it does (almost) not autocloses...
https://vaadin.com/book/vaadin7/-/page/application.notifications.html


text:
Q: Non Unique Username with ASP.Net Identity 2.0 I have a situation where my username is not unique. Email is used as username and one email can have many different passwords in the database and all are legitimate.
How do I use ASP.NET Identity 2.0 in this situation.
var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);

Above line expects only one user in the database. If the multiple records are returned - it returns failure. That is exactly what is expected it to do but this logic doesn't work for me.
How do I override this logic?
Alternatively, I am ready to customize this login but the problem is - I am not sure what all things are done as a part of PasswordSignInAsync. Like adding to cookies etc.
Please help.

A: I made it work. I had to use Username + password combination as a unique Username.
These are different situations in industry for different types of needs.


text:
Q: EntitySqlException on CreateQuery and type mismatch I have this situation. I call CreateQuery with this query and I get Exception.
string sql = "SELECT VALUE CP
                FROM CIC_PRODUZIONE_OPERAZIONI_View AS CP
                WHERE  CP.CD_PLANT = 5
                   AND CP.CD_POSTI = 10946
                   AND (CP.FL_STATE IN {N'D',N'N',N'M'})
                   AND EXISTS (SELECT 1
                               FROM CIC_OPERAZIONI AS C
                               WHERE CP.CD_CIC_PRODUZIONE = C.CD_CIC_PRODUZIONE
                                  AND C.CD_POSTI = 10894
                                  AND C.AFCDOPER = (SELECT VALUE TOP (1) D.AFCDOPER                                                                     FROM CIC_OPERAZIONI AS D
    WHERE D.CD_CIC_PRODUZIONE = CP.CD_CIC_PRODUZIONE
      AND D.AFCDOPER > CP.AFCDOPER
    ORDER BY D.AFCDOPER))
    ORDER BY CP.AFCDPROD, CP.FL_STATE, CP.AFESPSAP, CP.AFESPMOD, CP.AFCDOPER";

    ObjectQuery<T> entities = CreateQuery<T>(sql);

This is the Exception:

EntitySqlException: The argument types 'Edm.Decimal' and
  'Transient.collection[Edm.Decimal(Nullable=True,DefaultValue=,Precision=4,Scale=0)]'
  are incompatible for this operation.

The problem seems to be when I try to select the TOP value.
Any suggestion?
EDIT
I undestand that the problem is on the right side of the expression because the subquery get an ICollection<decimal> and on the left I have a decimal field.
...
C.AFCDOPER = (SELECT VALUE TOP (1) D.AFCDOPER                                                                     FROM CIC_OPERAZIONI AS D
        WHERE D.CD_CIC_PRODUZIONE = CP.CD_CIC_PRODUZIONE
          AND D.AFCDOPER > CP.AFCDOPER

...
how could it be possible to get the "First" of that collection to avoid to get in exception?

A: Did you try ?
Select Top(1) D.AFCDOPER   FROM CIC_OPERAZIONI AS D

I think this will work without the world "VALUE" .


text:
Q: Ajax Function Syntax understanding I am new to Ajax.I am bit confused looking at this below example.
$.ajax({
    url: "test.html",
    cache: false,
    success: function(html){
        $("#results").append(html);
    }
});

Please help me to understand this function.How it is executed.
I can see that,the below  block code is passed as argument
{
    url: "test.html",
    cache: false,
    success: function(html){
        $("#results").append(html);
    }
}

this is passed as a argument to the function Ajax().

A: The success callback is invoked when the AJAX call returns with no errors...
I think you should read jQuery AJAX documentation

A: That's a typical way to call javascript functions, since Javascript does not have keyword arguments.
What happens is you pass an object (POJO) with parameters to your method then inside method you can access arguments and use them.
So in this way you can eliminate huge function arguments and also give client the ability pass whatever argument it's interested in.
So in ajax method the implementation code will read parameters that it needs and them executes the implementation logic. Of course if you need to know what parameters are exactly expected and accepted you should refer to JQuery ajax method call. (http://api.jquery.com/jquery.ajax/)
I hope this little info helps you to better understand how it works.


text:
Q: Prove that a function can be represented as Infinite Darboux sums $f$ is positive and decreasing monotonously.
Both $\int _0^\infty f(x)dx$  and $\sum_{n=1}^\infty f(nk)$ converges.
Prove that:
$$\lim_{k^+\to 0} k\sum_{n=1}^\infty f(nk)= \int _0^\infty f(x)dx$$
What I tried to do:
I feel as if I can "see" the proof but I'm unable to write it.
It's like I'm being asked to prove that Upper Darboux Sum converges to the integral when the intervals become narrow (lets assume $k$ is the width of Darboux's rectangles)
Or maybe something regards Riemann sums?
Only that all of these sentences where taught for finite intervals. Maybe show somehow the tail is approximately zero?
Someone, Help?
:-)

A: If you have no problem with infinite "Darboux sums", you can simply observe that, since $f$ is monotonically decreasing,
$$k\sum_{n=1}^\infty f(nk)\tag{1}$$
is a lower Darboux sum for the integral $\int_0^\infty f(x)\,dx$, and $(1)$ is also an upper Darboux sum for the integral $\int_k^\infty f(x)\,dx$. That yields
$$\int_0^\infty f(x)\,dx - k\cdot f(0) \leqslant \int_k^\infty f(x)\,dx \leqslant k\sum_{n=1}^\infty f(nk) \leqslant \int_0^\infty f(x)\,dx.\tag{2}$$
Letting $k \searrow 0$ in $(2)$ shows $\lim\limits_{k\searrow 0} k\sum\limits_{n=1}^\infty f(nk) = \int_0^\infty f(x)\,dx$.
If you don't want to argue with infinite Darboux sums, you can still argue that for every $N\in \mathbb{N}$, the finite sum
$$S_N = k\sum_{n=1}^N f(nk)$$
is a lower Darboux sum for the integral $\int_0^{Nk} f(x)\,dx$ and an upper Darboux sum for the integral $\int_{k}^{(N+1)k} f(x)\,dx$, so
$$\int_0^{(N+1)k} f(x)\,dx - kf(0) \leqslant S_N \leqslant \int_0^{Nk} f(x)\,dx \leqslant \int_0^\infty f(x)\,dx.\tag{3}$$
Letting $N\to\infty$ for $S_N$ in $(3)$ shows
$$\int_0^{(N+1)k}f(x)\,dx - kf(0) \leqslant k \sum_{n=1}^\infty f(nk) \leqslant \int_0^\infty f(x)\,dx\tag{4}$$
for all $N\in\mathbb{N}$. Now letting $N \to \infty$ on the left hand side of $(4)$, we again obtain $(2)$. And once more, squeezing yields
$$\lim_{k\searrow 0} k\sum_{n=1}^\infty f(nk) = \int_0^\infty f(x)\,dx.$$


text:
Q: TFS question - joining table row based on the highest date value I am hoping I can get some help with my TFS query. I am trying to join a table based on the highest date value with a State = 'Ready for QA'.
Here is what I have currently:
SELECT a.Id, a.ChangedDate, b.Id, b.[Changed Date], b.State, CASE WHEN b.[Changed Date] < a.ChangedDate AND b.State = 'Ready for QA' OR b.Id IS NULL THEN a.ChangedDate ELSE b.[Changed Date] END AS 'Ready'
  FROM [Tfs_AdmiCollection].[dbo].[tbl_WorkItemCoreLatest] a
LEFT JOIN (SELECT id, State, MAX(ChangedDate) AS 'Changed Date' FROM [Tfs_AdmiCollection].[dbo].[tbl_WorkItemCoreWere] WHERE State = 'Ready for QA' GROUP BY Id, State) b ON a.Id = b.Id
  WHERE a.IterationId = 312
    AND a.State = 'Ready for QA'
    AND a.WorkItemType = 'Bug'
ORDER BY Ready

SELECT * FROM [Tfs_AdmiCollection].[dbo].[tbl_WorkItemCoreWere]
WHERE Id = 24809

SELECT * FROM [Tfs_AdmiCollection].[dbo].[tbl_WorkItemCoreLatest]
WHERE Id = 24809

In the Image, I only want to use the ChangedDate from table b in my CASE when the highest date value = 'Ready for QA'. Can anyone explain the best way to accomplish this? Thanks in advance!


text:
Q: Programmatically determine dimensions of image files in bundle I have a large number of image files in my iPhone app bundle (~3000) and I want to determine the dimensions at runtime rather than store this data in the database or an xml manifest for the images.
Is there a way to do this programmatically?

A: UIImage has the size property that returns the dimensions of the image, however I wouldn't recommend loading all 3000 of your images in your iPhone app.  Pre-generating that information at build time would give you much better results.  Failing that you might possibly use some sort of naming convention for your images that encodes the image size in the file name, however this is really not that different to storing the information in some sort of database or XML file ;)

A: The file Unix utility uses the header information on the file to determine the size.  It basically requires loading in the first block of the file and sifting through the information (varies by file type but presumably you'll only have one to implement since you control the images).

A: As of iOS 4, it is possible to access image properties without actually loading image in memory.
You'll need ImageIO.framework and #import < ImageIO/ImageIO.h>
NSURL *imageFileURL = [NSURL fileURLWithPath:imagePath];

CGImageSourceRef imageSource = CGImageSourceCreateWithURL((CFURLRef)imageFileURL, NULL);

if (imageSource == NULL)
{
    // Error loading image ...
}

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:NO], (NSString *)kCGImageSourceShouldCache, nil];

CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, (CFDictionaryRef)options);

NSNumber *mImageWidth;

NSNumber *mImageHeight;

if (imageProperties)
{
    mImageWidth = (NSNumber *)CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth);

    mImageHeight = (NSNumber *)CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);

    CFRelease(imageProperties);
}


text:
Q: Jquery FAQ toogle with "dd" and "dt", click to close the answers When I click on the question the answer comes up, I click back on the question the answer hides. What I was looking for was to insert a close text link at the end of the answer that would close the answer. Can you please help me?
Here is the script I use now:

Also, I wanted the questions to look like links and when on mouseover the cursor should appear instead of the "I".

A: Here is your working code

Question?

Answer.Close Text

A: jQuery
$('.faq dd').hide();
$('close').hide().appendTo('.faq dt');
$('.faq dt').click(function() {
    $(this).next().slideToggle('slow');
    $(this).find('span').toggle();
});

CSS
.faq dt {
   cursor: pointer;
}

jsFiddle.


text:
Q: Calculating sha256 of S3 StreamingBody differs from sha256sum returned checksum So the gist is: I am using boto3 to get_object from S3. The response body contains a "StreamingBody" object. When I calculate the sha256 sum of it like this:
sha256 = hashlib.sha256()
for line in file_to_extract_from.iter_lines():
    sha256.update(line)

print("sha256: {0}".format(sha256.hexdigest()))

It returns 16aba5393ad72c0041f5600ad3c2c52ec437a2f0c7fc08fadfc3c0fe9641d7a3
However, when I calculate it using my Linux inbuilt sha256sum, it returns b7f1ee9373416a49835747455ec4d287bcccc5a4bf8c38156483d46b35ce4dbd instead. I wonder what is wrong with my configuration?
EDIT: After asking this question I realised that S3 is only returning me the content of the file and its calculating the hash based on that, where as on my linux I'm calculating the hash for the whole file. Is there a way to calculate a hash for the whole file from S3?

A: I was being stupid. My file on my linux system had a new blank line at the end of the file, which AWS seems to overwrite. Once I removed the blank line from my local machine, I ended up getting the correct checksum.


text:
Q: Is it possible to have more than one authentication cookie for one web site? Is it possible to have more than one authentication cookie for one web site?
As it turned out it is not possible.
I have the following situation:
2 Web sites (same domain):

*

*A

*B

2 Authenticationn cookies:

*

*Website A has authentication cookie A

*Website B has authentication cookie B

Both cookies have sliding expiration enabled. Cookie A is shared between both sites.
When you login on web site A and B you have the two cookies for web site B.
Will the shared cookie A be refreshed regarding sliding expiration when I access web site B?
EDIT: The answer is no.

A: If you are just using the built-in forms-authentication, then no.
However, if you create your own (which I would recommend against), then you would be able to.

A: short answer no, however you can either stuff extra data into the cookie, or define another one with different name, but you have to manage in both cases
to be able to answer better, more details are needed about the problem you are trying to solve


text:
Q: Adding formatting to rich edit controls using win32 api I am creating a rich edit text box like so:
const char *testText = "Hello \\bworld!";

LoadLibrary("riched20.dll");

hwndoutbox = CreateWindowEx(
    ES_SUNKEN,
    RICHEDIT_CLASS,
    testText,
        WS_BORDER | WS_VISIBLE | WS_CHILD,
        0, 40, 300, 300,
        hwnd, 0, hInstance, NULL);

The intended result is to display 'Hello World' with the 'World' in bold.
What am I doing wrong?
I have a hunch that \b might be an escape code for something, but i cant find much info to back that up

A: You need to go and have a look at the specification for RTF. For a start, RTF data has a header, and you aren't including that.
In fact, Wikipedia's page on RTF (here) might have been a good place for you to start. It includes this example text:
{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard
This is some {\b bold} text.\par
}

... which is a string with a bold word.
The "rich edit control" is a control designed to render RTF.


text:
Q: Angular router-outlet content overlaid on top of mat-toolbar In my app.component.html, I placed a mat-toolbar above a router-outlet like so:
<mat-toolbar color="primary">
  Tattoo Share!
</mat-toolbar>
<router-outlet></router-outlet>

The problem is the router-outlet content is overlaid on top of the toolbar. This content should be beneath the toolbar. How should I correct this? I tried placing things inside block elements such as div to no avail. There is also this CSS on mat-toolbar:
mat-toolbar { position: fixed }

A: You should use CSS in the styles.css to put a margin-bottom equals to the height of the toolbar in itself. Also use an ID so it won't apply to other toolbars
mat-toolbar#over-router {
    margin-bottom: 40px; // check the actual height in the browser
}

A: You can use flex layout.

     <app-toolbar></app-toolbar>

         <router-outlet></router-outlet>

.home-main {
  height: 100%;
  display: flex;
  flex-direction: column;
}

A: Got it to work using some CSS on my toolbar:
mat-toolbar {
  position: fixed;
  top: 0;
  z-index: 1;
}


text:
Q: Why does my component render twice when using React's Context API and the useEffect hook? I'm trying to understand how the Context API works together with React hooks (specifically useEffect and useReducer).
I am unsure as to why one of my components (ContactListPage) seems to be rendering twice.
A minimal example to demonstrate:
index.js
ReactDOM.render(
  <ContactContextProvider>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </ContactContextProvider>,
  document.getElementById("root")
);

contact-context.js
export const ContactContext = createContext();

function reducer(state, action) {
  switch (action.type) {
    case "FETCH_CONTACTS": {
      return { ...state, contacts: action.payload };
    }
    default:
      throw new Error();
  }
}

export const ContactContextProvider = (props) => {
  const [state, dispatch] = useReducer(reducer, { contacts: [] });
  const store = React.useMemo(() => ({ state, dispatch }), [state, dispatch]);

  return (
    <ContactContext.Provider value={store}>
      {props.children}
    </ContactContext.Provider>
  );
};

ContactListPage.js
export default function ContactListPage() {
  const { state, dispatch } = useContext(ContactContext);
  console.log(state);

  useEffect(() => {
    const fetchData = async () => {
      try {
        // Make Ajax request for contacts here
        dispatch({
          type: "FETCH_CONTACTS",
          payload: [{ name: "Bob" }]
        });
      } catch (error) {
        // handle error
      }
    };
    fetchData();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  return (

List of Contacts

  );
}

Here is the app running in a CodeSandbox.
When the ContactListPage component first renders, the following is logged to the console:
Object {contacts: Array[0]}
Object {contacts: Array[1]}

This makes sense to me. Initially the contacts array is empty, then in the useEffect hook in the ContactListPage component, I dispatch an action to add a contact, so the component is re-rendered with the updated list of contacts.
The problem comes when I navigate away from this view (I'm using React Router), then I navigate back. In this case I see:
Object {contacts: Array[1]}
Object {contacts: Array[1]}

I would have expected the console.log statement to only fire once, as the contacts array hasn't changed.
I've spent all afternoon Googling this. None of the other answers I could find on SO worked for me.
So, my question is: Why does the console.log statement always fire twice?

N.B. To reproduce this in the CodeSandbox:

*

*Click on the Add Contact link and observe the first output in CodeSandbox's console.

*Click on the Contacts List link and observe the second output in CodeSandbox's console.

A: It is because your component is mounting again when you change your route. So when you go from contact list to add contact:
Your reducer already set it to name:bob
And now again when your come back to your component list component. Two things is happening component is rendering because of useContext inital state(hooks also cause rerendering) and another one is causing because of your useEffect i.e you are dispatching your FETCH_CONTACTS when component is mounted.
If you see console on first load:

Object {contacts: Array[0]}
Object {contacts: Array[1]}

Observe console return two statement first state is when contact is empty and second state is when contact is updated using reducer]
Now when you come from add contact page the console shows this:
Object {contacts: Array[1]}
Object {contacts: Array[1]}

Both has same value first one coming from context intital state and second one is coming again as reducer is again updating value.
If you want to see yourself add console more for clarity. Check here how component is mounting and unmounting: https://codesandbox.io/s/elegant-ishizaka-enck6?file=/src/components/ContactListPage.js:478-492

A: So the useEffect implementation here takes place when the component is rendered for the first time. Thats when you get the result:
Object {contacts: Array[0]} Object {contacts: Array[1]}

Since you are still in the app, the action dispatched at the first render of the component is saved in the state. Since you have navigated away component .i.e. the component is not longer in dom, when you load component again in dom, hence after the initial render, the useEffect takes place and renders your component after the effect is completed because you are dispatching another action to the reducer even though you have the value.
Since a new action is dispatched, that is considered as a state change and that is when you see following:
Object {contacts: Array[1]} Object {contacts: Array[1]}

You can test this by add console.log at this line in your reducer:
Now you can add something like a check or a flag that can confirm that the data has been loaded and you don't have to make the fetch again.
So I have added following check in your useEffect:
 if (state.contacts.length === 0) {
      fetchData();
 }

And Eureka !!! One less render.
I have tried out and modified your sandbox on this link. So it is nice to have these check incase you want to minimise unnecessary call and renders on the app.


text:
Q: Can I create a butterfly animation effect with translate3D (css), or another css animation on a single image or element? I have an image of a butterfly, something like this.

I am trying to figure out if there is any way to make it look like its wings are opening and closing with a 3D CSS transform/translate or animation, but without having to split the image up into parts (it can be a background image of a div though if that helps).

A: Yes, using background applied to two elements where each one will show only one half and then you simply rotate both on the Y axis.

.box {
  width:300px;
  margin:20px;
  display:flex;
  perspective:500px;
}
.box::before,
.box::after{
  content:"";
  padding-top:56%; /* ratio based on your image */
  flex:1; /* half the main element size */
  background-image:url(https://i.imgur.com/DgMoHC5.jpg);
  background-size:200% 100%; /* twice bigger than the pseudo element to get half the image*/
  animation:left 1s linear infinite alternate;
  transform-origin:right;
}
.box::after {
  background-position:right; /* get the right part of the image */
  animation-name:right;
  transform-origin:left;
}

@keyframes left{
  to {transform:rotateY(60deg)}
}
@keyframes right{
  to {transform:rotateY(-60deg)}
}

A more realistic animation with some translation:

.box {
  width: 300px;
  margin: 20px;
  display: flex;
  perspective: 500px;
}

.box::before,
.box::after {
  content: "";
  padding-top: 56%;
  flex: 1;
  background-image: url(https://i.imgur.com/DgMoHC5.jpg);
  background-size: 200% 100%;
  animation: left 0.5s linear infinite alternate;
  transform-origin: right;
}

.box::after {
  background-position: right;
  animation-name: right;
  transform-origin: left;
}

@keyframes left {
  from {
    transform: translateZ(80px) rotateY(-30deg)
  }
  to {
    transform:translateZ(0px) rotateY(50deg)
  }
}

@keyframes right {
  from {
    transform: translateZ(80px) rotateY(30deg)
  }
  to {
    transform:translateZ(0px) rotateY(-50deg)
  }
}


text:
Q: Why is the object not defined in this environment? I have very little understanding of how environments work in R.
Here is my code
push = function(l, x)
{
  assign(l, append(eval(as.name(l)), x), envir=parent.frame())
}

main = function()
{
    mylist = list("hello")
    push("mylist","World")
}

main()

This code returns the error
Error in eval(expr, envir, enclos) : object 'mylist' not found

*

*Why does it return this error?

*How to fix that?

A: The eval is not taking place with respect to the parent frame of the push call, only the assign is.
One could pass the parent.frame() to eval or adopt the following style which seems clearer.  (main is unchanged.)
push = function(l, x, envir = parent.frame())
{
    envir[[l]] <- append(envir[[l]], x)
}

or pass the objects themselves and return them to avoid dealing with environments:
push <- function(l, x) append(l, x)
main <- function() {
  mylist <- list("Hello")
  push(mylist, "World")
}
main()


text:
Q: Couldn't find Post without an ID / ActiveRecord::RecordNotFound I know this is a very basic solution however, I am just not seeing it right now. I am getting a 'Couldn't find Post without an ID' error within CommentsController#create.
I created a 'New Comment' button under the post which should then redirect to the comment form. From there once a user inputs their comments and clicks the 'Create Comment' button the comment should be displayed under the original post. Thank you in advance.
Comments Controller
Class CommentsController < ApplicationController
  before_filter :authenticate_user!

  def new
  @comment = Comment.new
  end

  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment].permit(:commenter, :body))

    respond_to do |format|
      if @comment.save
        format.html { redirect_to @post, notice: 'Comment was successfully created.' }
        format.json { render json: @comment, status: :created, location: @comment }
      else
        format.html { render action: "new" }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end

  end

def destroy
    @post = Post.find(params[:post_id])
    @comment = @post.comments.find(params[:id])
    @comment.destroy
    redirect_to post_path(@post)
end

def show
  @comment = Comment.new
end

end

Post/Show

        <% if @post.image.url %>
            <%= image_tag @post.image.url(:medium) %>

        <% elsif @post.video.url %>
            <%= video_tag @post.video.url(:medium), controls: true, type: "video/mp4" %>
        <% end %>

           Likes:
           <%= @post.get_likes.size%>

        <%=link_to image_tag('like.jpg', :border => 0), likes_post_path(@post) %>
        <%=link_to image_tag('unlike.jpg', :border => 0), dislikes_post_path(@post) %>

<%= @post.description %>

        <% user = @post.user %>

<%= link_to(user.name, user_path(user)) if @post.user %>

        <%= link_to 'New Comment', new_comment_path, class: "btn btn-danger btn-sm active" %>

<% if @post.user == current_user %>
            <%= link_to edit_post_path(@post) do %>

            Edit
          <% end %>
        <% end %>
        <%= link_to 'Back', posts_path %>

Comments / _form
<%= form_for [@post, Comment.new] do |f| %>
  <% if @comment.errors.any? %>

<%= pluralize(@comment.errors.count, "error") %> prohibited this comment from being saved:

      <% @comment.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

    <%= f.label :body %>

    <%= f.text_area :body %>

    <%= f.submit class: "btn btn-danger btn-sm" %>

<% end %>

Routes
 resources :comments
 resources :posts do
    resources :comments
end

Comments / Show

<%= notice %>

  Post:
  <%= @comment.post_id %>

  Body:
  <%= @comment.body %>

<%= link_to 'Edit', edit_comment_path(@comment) %> |
<%= link_to 'Back', comments_path %>

Rake Routes
post_comments GET     /posts/:post_id/comments(.:format)          comments#index
                         POST    /posts/:post_id/comments(.:format)          comments#create
        new_post_comment GET     /posts/:post_id/comments/new(.:format)      comments#new
       edit_post_comment GET     /posts/:post_id/comments/:id/edit(.:format) comments#edit
            post_comment GET     /posts/:post_id/comments/:id(.:format)      comments#show

A: I recommend making the following changes:
Routes:
Remove the first resources :comments. Leave the following:
resources :posts do
  resources :comments
end

Posts/Show view:
You should be using new_post_comment_path instead of new_comment_path. Run rake routes to see why.
CommentsController#new:
Define @post in your new action:
def new
  @post = Post.find(params[:post_id])
  @comment = Comment.new
end

Finally, in Comments/_form:
Change <%= form_for [@post, Comment.new] do |f| %> to <%= form_for [@post, @comment] do |f| %>. Although I believe <%= form_for @comment do |f| %> should work.
I recommend going through the Rails Guides for additional information and explanations.

A: I believe that in def new of the comments controller, you also need to set @post, not just @comment


text:
Q: Empty file when saving signed PDFs from DocuSign Connect I'm getting blank PDFs when saving signed PDF documents from DocuSign from Connect event notification.
As I understand it the PDFBytes value is Base64 encoded, so this is my code to convert that into a string:
XmlNode docs = xmldoc.SelectSingleNode("//a:DocumentPDFs", mgr);
                foreach (XmlNode doc in docs.ChildNodes)
                {
                    string documentName = doc.ChildNodes[0].InnerText;
                    string documentId = doc.ChildNodes[2].InnerText;
                    string byteStr = Encoding.UTF8.GetString(Convert.FromBase64String(doc.ChildNodes[1].InnerText));
                    System.IO.File.WriteAllText(LOGPATH + envelopeId.InnerText + "_" + documentId + "_" + documentName, byteStr);
                }

However, this produces empty PDFs. Has anyone had any success with this?

A: No need to encode the bytes after converting the Base64 string. Try this
byte[] fileBytes = Convert.FromBase64String(doc.ChildNodes[1].InnerText);
string filePath = LOGPATH + envelopeId.InnerText + "_" + documentId + "_" + documentName + ".pdf";
System.IO.File.WriteAllBytes(filePath , fileBytes);


text:
Q: how to change properties file according to rest api or unit test call from src/test/resources and src/main/resources I am creating a spring mvc application and during normal flow of an api, properties for database are taken from "application.properties" file in src/main/resources folder. Then I wrote the unit test cases for the same and created a file with the same name i.e. "application.properties"  in src/test/resources folder. The test cases were running fine earlier but now for the normal flow,now they are taking parameters from src/test/resources instead of taking only from src/main/resources .

File Structure :
  DemoProject
|-src/main/resources/application.properties
|-src/test/resources/application.properties

this is my hibernamteConfiguration file:
import java.util.Properties;
import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class HibernateConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.akshay.pojos" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
     }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("driver"));
        dataSource.setUrl(environment.getRequiredProperty("url"));
        dataSource.setUsername(environment.getRequiredProperty("user"));
        dataSource.setPassword(environment.getRequiredProperty("password"));
        return dataSource;
    }
     @Bean
     public Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("format_sql"));
        properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hbm2ddl.auto"));
        return properties;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
       HibernateTransactionManager txManager = new HibernateTransactionManager();
       txManager.setSessionFactory(s);
       return txManager;
    }
}


text:
Q: laravel 5.3 login with facebook I am implementing login with facebook in my laravel 5.3 project. It seems to work as I get all the data recorded to the database from a facebook user, but my project sees my auth state as not logged. Also it does not redirect me to the dashboard, but displays a white page with the callback link. Why?
It redirects a user to the fagebook page to login
public function redirectToProvider()
{
    return Socialite::driver('facebook')->redirect();
}

Callback Handler
public function handleProviderCallback()
{
    try{
        $socialUser = Socialite::driver('facebook')->user();
    }
    catch(\Exception $e) {
        return redirect('/dashboard');
    }

    $user = User::where('facebook_id', $socialUser->getId())->first();
    if(!$user){
        User::create([
            'facebook_id' => $socialUser->getId(),
            'name' => $socialUser->getName(),
            'email' => $socialUser->getEmail(),
        ]);

        auth()->login($user);
        return redirect()->to('/dashboard');
    }
}

My auth()->login seems not to work, and redirect also. What may be the problem? Thank you!
routes:
Route::get('dashboard', ['as' => 'dashboard', 'uses' => 'PageController@getDashboard']);

Route::get('auth/facebook', 'Auth\RegisterController@redirectToProvider');
Route::get('auth/facebook/callback', 'Auth\RegisterController@handleProviderCallback');

A: The behaviour seems correct for the way you have coded the callback handler. I believe what you want to happen is if the user exists then you want to log them in, your current code doe's nothing if the user exists so you need to make sure if the user exists that they are logged in.
I would change the code as follows:
$user = User::where('facebook_id', $socialUser->getId())->first();

if(!$user){
    User::create([
        'facebook_id' => $socialUser->getId(),
        'name' => $socialUser->getName(),
        'email' => $socialUser->getEmail(),
    ]);
}

if(Auth::loginUsingId($user->id)){
    return redirect()->intended('/dashboard');
}

This way if there is a user they will still be logged in rather than the handler doing nothing


text:
Q: how show error message csv file does not exist
if i added a csv file name inccorrectly i wnat to show error message entered csv file does not exist please write the correct csv file name.how it make?

class Command(BaseCommand):
help = 'Load a company csv file into the database'

def add_arguments(self, parser):
    parser.add_argument('filename.csv', type=str)

def handle(self, *args, **options ):
    if Company.objects.exists():
        print("Data already loaded!!")
    with open('companies.csv', 'r') as file:
        reader = csv.reader(file)
        for row in reader:
            create= Company.objects.get_or_create(
            name=row[0],
            hr_name=row[1],
            hr_email=row[2],
            hr_verified=row[3],
            user_id=row[4],
            primary_phone=row[5],
            comments=row[6],
            )

A: This is more of a Python question than a Django question. You can do it with a try/catch throwing FileNotFoundError exception when an incorrect file is given.
def handle(self, *args, **options ):
    if Company.objects.exists():
        print("Data already loaded!!")
    try:
        with open('companies.csv', 'r') as file:
            reader = csv.reader(file)
            ....
    except FileNotFoundError:
        # Yoour error message goes here

A: *

*You can use a try except:

try:
    with open(filename, "r") as file:
       # ...
except FileNotFoundError as e:
    print("Please write the correct cvs file name")

*You can check if it exists the file:

import os

if not os.path.exists(filename):
    print("Please write the correct csv file name")


text:
Q: Where does a math person go to learn quantum mechanics? My undergraduate advisor said something very interesting to me the other day; it was something like "not knowing quantum mechanics is like never having heard a symphony."  I've been meaning to learn quantum for some time now, and after seeing it come up repeatedly in mathematical contexts like Scott Aaronson's blog or John Baez's TWF, I figure I might as well do it now.
Unfortunately, my physics background is a little lacking.  I know some mechanics and some E&M, but I can't say I've mastered either (for example, I don't know either the Hamiltonian or the Lagrangian formulations of mechanics).  I also have a relatively poor background in differential equations and multivariate calculus.  However, I do know a little representation theory and a little functional analysis, and I like q-analogues!  (This last comment is somewhat tongue-in-cheek.)
Given this state of affairs, what's my best option for learning quantum?  Can you recommend me a good reference that downplays the historical progression and emphasizes the mathematics?  Is it necessary that I understand what a Hamiltonian is first?
(I hope this is "of interest to mathematicians."  Certainly the word "quantum" gets thrown around enough in mathematics papers that I would think it is.)

A: I took undergraduate quantum mechanics as the only Physics class I took in college.  You're in better shape knowing linear algebra well and not knowing any physics than you would be the other way around.  So one option is just to take a normal quantum mechanics course or read a normal undergrad text (we used the one with Schrodinger's cat on the cover).

A: I disagree (though not particularly strongly) with the comments claiming that you should learn classical mechanics first.  You don't need much physics background to learn to do basic calculations with wave functions, and to pick up ideas like observables-as-differential-operators.  If you want a list of good web resources and textbooks together with good organizing commentary, I recommend looking at Gerardus 't Hooft's page: Theoretical physics as a challenge.  You can safely ignore the paragraphs in the beginning about his page being only for people who want to win the Nobel prize in physics.

A: I think learning QM makes only sense if one knows the basics of Lagrange- and Hamilton-Jacobi-mechanics, where I found the old but very beautifull and readable "Classical Mechanics" by Goldstein very good. It needs no preknowledge and covers the development of early QM from that too. The formalism in classical mechanics described there in a very nice way is THE fundamental piece on which field theory and quantum field theory is built on. After that it may be usefull to look into Hatfield's "Quantum Field theory of point particles and strings" which Witten recommends. Then there is a tourist guide and lectures from an IAS summer school on that.

A: It doesn't stress the physical intuition very much, but I learned a lot of basic quantum from the first chapter of Nielsen and Chuang. If you're planning on doing quantum computing or QIT stuff, you'll likely need the book anyway, although there's probably better resources if you're not.

A: I agree with Scott firmly here. The Lagrangian and Hamiltonian formulation of mechanics is a beautiful subject with immediate doorways to symplectic geometry, but unnecessary for the appreciation of the basic postulates of QM ("The Universe is a vector space..."). Honestly, if Qiaochu wants to appreciate this clean formulation and not worry about "perturbative expansions of blah blah blah," this is sufficient.
I am also a huge fan of Griffith's "Introduction to Quantum Mechanics" as a first book. It can be read without serious knowledge of electromagnetism and classical mechanics. I know that the MIT physics undergraduate curriculum does not require Lagrangian/Hamiltonian Classical Mechanics before their 3 term QM sequence. This means for Qiaochu that 8.01 and 8.02 is sufficient, 18.03 is more important, and I have heard of many a MIT student taking 8.05 without 8.04, but don't expect a physics professor to say that to you. (My apologies for the MIT-speak)
The problem with learning "grown-up" mechanics (at MIT 8.07 or Sussman's 6.946J, which I recommend highly) before QM is that this path leads more naturally to understanding more differential-geometric concepts and consequently takes serious time. This is fine for a physicist and is probably a wise move before taking GR, but for a growing mathematician, I would advise understanding smooth manifold theory before trying to learn the more sophisticated and elegant approach to mechanics. This inevitably entails a much more firm grounding in ODE theory and I recommend V.I. Arnold's ODEs book for that.
Once you have these two perspectives in hand you can then sit back and wonder how the QM Universe-as-a-Hilbert-space viewpoint and the GR Universe-as-a-C^2-manifold description can ever be reconciled.

A: Dan Dugger has wonderful mostly-finished notes on this here:
http://pages.uoregon.edu/ddugger/qftbook.pdf
It's written for topologists, very clearly, and he does a great job of giving both physical and "mathematical" explanations/intuitions.
Really well done.

A: It could be just my own personal bias, but I think it is difficult to learn quantum mechanics without first learning classical mechanics. I recommend taking a 1 semester course, either graduate or advanced undergraduate, in classical mechanics and then taking a quantum mechanics course. I also think it would be a mistake to start with an overly mathematically-oriented QM course. You want to learn how physicists think and how they use this stuff to come up with real physical predictions. Otherwise, you're just learning math packaged as "physics". You shouldn't have much trouble later figuring out how to translate the physics back into math. But if you focus too much on the math at the beginning, you make it less likely you'll ever understand the physics.

A: For a good introduction requiring minimal background you could try D.J. Griffiths, Introduction to Quantum Mechanics, but keep in mind that it is aimed at physics or engineering students.
Also a good book is Landau and Lifshitz, Quantum Mechanics, but you also need to read a at least a  good part of Mechanics, by the same authors in order to understand it.

A: A concise introduction to quantum probability, quantum mechanics, and quantum computation (36 pages) by Greg Kuperberg: http://www.math.ucdavis.edu/~greg/intro-2005.pdf

A: I recommend against Shankar, he is not conceptually very careful.
One can, in fact, learn the foundations of QM without knowing Classical Mechanics at all, and I recommend reading the first six chapters of Dirac, The principles of quantum mechanics, to get a feeling for the physical concepts.  although he is not mathematically rigorous, he never even clearly defines what space his operators are operating on, this is an advantage for once.
Then, in order to get the same conceptual clarity from a mathematician, and better mathematical rigour, I always recommend Anthony Sudbery Quantum Mechanics and the Particles of Nature.
If you are reading QM for "culture", as I gather you are, the books which work well as intro texts for professionals are really irrelevant, so forget Sakurai, Gottfried, Landau, et hoc genus omne.  I except Feynman, but only after reading the above two, you could benefit from the chapters in his undergrad Lectures on Physics and benefit from his book on Path Integrals and QM (joint with Hibbs).
I recommend against Mackey or von Neumann, they have no physical insight, Varadarajan is even worse.

A: Take a class!  I took the core graduate Quantum Mechanics class offered by the Physics department at my school (using Sakurai's book), and it was one of the best classes I ever took.

A: To sum up and structure what others have said (and add my grain of salt):
a. there are a few core "quantum" concepts to learn. The normal route follows the historical one up to the 1960s (skipping too physical considerations for you), and this is indeed done well in Takhtajan's book (chapters 1 to 5). It does go through classical mechanical aspects, and requires some knowledge of undergrad math (linear algebra, Hilbert spaces, multivariate calculus, ODEs & PDEs, and a little differential geometry).
Of course  be aware that this reference still does skip a lot of issues that physicists are aware of, a good physics textbook for beginners is Physics of Atoms and Molecules by Bransden and Joachain. To which one must add more recent aspects, not covered neither there or in Takhtajan, from the 1980s-1990s as in Preskill's notes. Beyond that there is field theory and ever more physics, but the basic stuff is in those three references.
b. you can then take any one mathematical aspect and push it very far. It could be the geometry, or functional analysis, or representation theory, or semiclassical limit, or complexity theory... Then it's not quantum mechanics per se anymore, but explains why some objects are labelled quantum, or studied in a certain way.
c. don't be blinded by the math if you talk to physics or engineering friends: it can look all very neat but yet a key thing to know is that most quantum systems just cannot be solved explicitely , which is why physicists introduce all sorts of approximations and asymptotics, and use computers. It's not about lack of rigor, it's dealing with non-solvable systems (e.g. only the H atom and H2+ ion can can be solved explicitely, already the He atom has a too little symmetry group to do that).

A: 1)  I !ike Winitzki's style a lot.
He is a mathematical physicist of Russian origin and seems to write in a way that will appeal to you. His homepage is
http://homepages.physik.uni-muenchen.de/~winitzki/
Here are the first four relevant handouts on Quantum Mechanics
http://homepages.physik.uni-muenchen.de/~winitzki/QM_notes_1.pdf
http://homepages.physik.uni-muenchen.de/~winitzki/QM_notes_2.pdf
http://homepages.physik.uni-muenchen.de/~winitzki/QM_notes_3.pdf
http://homepages.physik.uni-muenchen.de/~winitzki/QM_notes_4.pdf
2)  An element of the tensor product of two vector spaces is not necessarily a tensor product of two vectors, but sometimes a sum of such. This might be considered a mathematical shenanigan
but if you start with the state vectors of two quantum systems it exactly corresponds to the notorious notion of entanglement which so displeased Einstein (not to mention Podolski and Rosen).
This is one of the most beautiful facts I have ever learned. So you are absolutely right in wanting to study Quantum Mechanics: it is incredibly exciting, beautiful and intellectually rewarding.

A: This is a question, not an answer, but: Has anyone here read Singer's "Linearity, symmetry and prediction in the hydrogen atom"?  I'm a sucker for a good example, and it seems like this could be a good grounding for the daunting task of understanding quantum mechanics.

A: Igor Dolgachev's course notes "Introduction to Physics" starts with an introduction to classical mechanics and develops quantum mechanics from a mathematical point of view.  It's a good place to start if you're strong mathematically but are having a difficulty understanding physicists' notations and perspectives.

A: Takhtajan's fairly recent "Quantum Mechanics for Mathematicians" should suit the bill.

A: I've just finished teaching the first semester of a year-long "Quantum Mechanics for Mathematicians" course.  Some of the references I found most useful are

*

*A good, clear, physics textbook.  Shankar's "Principles of Quantum Mechanics" that many have mentioned fits the bill.

*Faddeev and Yakubovskii, "Lectures on Quantum Mechanics for Mathematics Students" is short and to the point.  Takhtajan's "Quantum Mechanics for Mathematicians" is at a higher level that I was aiming for, but quite good.

*The first 60 or so pages of Folland's "Quantum Field Theory" are an excellent introduction to physics in general and QM in particular (and the rest of the book is a great QFT textbook).
Finally, I should point out that I've put up my course notes, which try to cover basic QM from a representation theory point of view, at the lowest level possible, they're here.

A: There's quite a variety of resources available for learning quantum mechanics. Since you're interested in the mathematical perspective, my suggestion would be to start with one of the mathematically-oriented quantum field theory books.
Physics courses about quantum mechanics contain many "real-world" applications which may be of less interest to someone without the previous background.
Quantum field theory is really what is used in all mathematics constructions you keep hearing about, and it's possible to learn the necessary quantum mechanics on the way.
In a major research university, you also have quite a number of options of finding interesting people and asking them directly. Though the courses in the physics departments would be structured for physicists, a lecturer in one of those courses could be a good place to get loaded with references.
Let me note that the physics and mathematics departments in Cambridge, Massachusetts, have a reputation for constructing effective bridges between physics and mathematics. Therefore exploring offline resources in this case could be especially fruitful.

A: When I was in college, the books I was taught from were Sakurai's "Modern quantum mechanics" and Townsend's "A modern approach to quantum mechanics". Though, they are clearly physics books, they both take a non-historical more mathematical approach starting with the two-dimensional vector space of a spin 1/2 particle. They don't assume any classical mechanics, neither Newtonian, Lagrangian or Hamiltonian. The first chapter of Sakurai for example gives a nice intro to the basic ideas of quantum mechanics. If what you're interested in is quantum field theory from a mathematical point of view, I'd suggest Folland's recent book "Quantum field theory". Also, if you decide to go for classical mechanics from an advanced mathematical perspective, you could try Abraham and Marsden's "Foundations of Mechanics".

A: Try this book:

*

*Geometry of Quantum Theory. Varadarajan, V.S. This is a book about the mathematical foundations of quantum theory. Its aim is to develop the conceptual basis of modern quantum theory from general principles using the resources and techniques of modern mathematics.

A: I got a lot out of Anthony Sudbery's "Quantum Mechanics and the Particles of Nature: An Outline for Mathematicians". My favourite part was solving for the energy levels of the hydrogen atom using a bit of linear algebra and not a single partial differential equation. Beautiful! I remember the discussion of spin being particularly lucid too (and which you may find easy depending on how good your representation theory is). You may be able to find it in a library but it's hard to buy. It's not a hard-core pure math axiomatic approach to QM. It assumes undergrad stuff like linear algebra, really elementary differential equations and maybe a tiny bit of of group theory.

A: It does not seem that anyone has mentioned Hannabuss's An introduction to quantum theory .  Although I have personally not lectured from it, it seemed good to us when we considered a quantum theory course for maths undergraduates in Edinburgh.  (Alas, there was opposition from the physicists and the course ended up not being given.)  At this level quantum mechanics is an application of linear algebra, so well suited for mathematics students.  Having said that, I echo others' answers where they suggest trying to develop a "physical" intuition as well.

A: I had taught myself Quantum Theory from the excellent book by J.J. Sakurai called "Modern Quantum Mechanics". Its a great book to build the conceptual foundations strongly but lacks examples.
Then I had read the 2-volume book on Quantum Mechanics by Cohen-Tanoudji et. al.
This book will give enormous number of examples of using Quantum Theory especially about using two-state system formalism.
It is extremely detailed to say the least and very clear, though at times lacks the elegance of the book by Sakurai. In terms of contents it subsumes the books by Shanker or Sakurai many times over.
The trickiest part of Quantum Theory is to get grips on the theory of angular momentum and spherical harmonics and Wigner's D-matrices. This is masterfully covered in the classic book by Edmonds. The pinnacle point of this journey is to understand and use Wigner-Eckart Theorem which Sakurai also does pretty well.
One can also look at the book by Giamarchi and the books by Frank Wilczek for some sophisticated issues.  Especially about understanding the subtleties that happen when one tries to do Quantum Theory in 1 and 2 spatial dimensions.

A: I would highly recommend Shankar's "Principles of Quantum Mechanics", a book from which I learnt quantum mechanics in 12th grade (no, this says nothing about my abilities, but instead goes to show how fantastically good Shankar is in explaining the principles of quantum mechanics to a high school student interested in self-studying it before college). This, followed by Feynman's Volume III, were my first taste of quantum mechanics before I even started undergraduate studies in physics.

A: Hi Qiaochu,
  Try Roger Penrose's great volume Road to Reality: a Complete Guide to the Laws of the Universe. It is meant to be popular science, but written in a completely rigorous way and take you far and deep into the cutting edge mathematical physics. Also it's a great way to build physics intuition without bogged down by the formalism.

A: As far as I can tell, this has not been suggested yet. I very highly recommend Quantum Theory, Groups and Representations:
An Introduction by Peter Woit. It's available for free here. It is extremely well written and takes a fully mathematical (or as close as it can get) approach to QM and QFT. It is quite comprehensive and emphasizes symmetry groups and their representations.

A: I second what Noah says. You don't have to take mechanics first, just linear algebra. I would recommend reading Shankar's Principles of Quantum Mechanics. It's better than Griffiths' book for a math person.

A: Charles already posted Takhtajan's book, which is my first choice --- it's geared towards early graduate students.  A more elementary book, geared towards math undergrads, is by Fadeev (who is, incidentally, Takhtajan's adviser, and Takhtajan's book can be understood as some sort of sequel).
The book Mirror Symmetry by Hori et al. includes a whirlwind overview of quantum mechanics and quantum field theory.  It's not mathematical in the sense that it contains no proofs and even fewer definitions, but it doesn't require any particular background.

A: For a short, well-written and fairly basic introduction to QM you can check Gillespie's classic "A Quantum Mechanics Primer". You won't need any previous background.
If you want to get a grasp / read a summary about what the book has to offer, you may visit my post:

Gillespie's A Quantum Mechanics Primer (I)

A: I agree with the comment saying take a course if you can.
That said, for self study, I found Bohm's quantum theory (dover ; cheap) very usable, given an engineering undergrad education.  It is old fashioned, and very verbose (perhaps too much), but also doesn't skimp on the math.

A: Matt Leifer once told me people should start (for a "conceptual" background) with John Polkinghorne's Quantum Theory: A Very Short Introduction.  Then, to delve into the concepts in depth, I would recommend getting (when it is released in a month or two) Q-PSI: Quantum Processes, Systems, and Information by Ben Schumacher and Michael Westmoreland (Cambridge U. Press).  I've been using it to teach undergrad. QM for a bit over a year.  I would supplement it with J.J. Sakurai's Modern Quantum Mechanics (not Advanced Quantum Mechanics - they're completely different books) and, to truly appreciate a different viewpoint, Quantum Paradoxes: Quantum Theory for the Perplexed by Yakir Aharonov and Daniel Rohrlich.
If you get interested in the quantum information side of things (which is highly mathematical), pick up Protecting Information: From Classical Error Correction to Quantum Cryptography by Susan Loepp and Bill Wootters and the "bible" of QI, Quantum Computation and Quantum Information (known popularly as "Mike and Ike") by Michael Nielsen and Isaac Chuang.

A: I happen to know about what appears to be a most appropriate book to teach quata to mathematicians : DANIEL T. GILLESPIE : A QUANTUM MECHANICS PRIMER, An Elementary Introduction to the Formal Theory of Non-relativistic Quantum Mechanics. Open University, England, 1973, ISBN 0 7002 2290 1. I taught quanta from it to several generations of mathematicians.

A: David Mermin wrote a quantum textbook with a similar audience in mind (no diff. eqs. required): http://www.amazon.com/Quantum-Computer-Science-David-Mermin/dp/0521876583

A: Quantum Mechanics and Quantum Field Theory: A Mathematical Primer.
I haven't read it (yet), though, but, given the Preface, it was written specifically for math students seeking a mathematically-rigorous introduction to QM and QFT.

A: I think there are some excellent recommendations above. I learned quantum mechanics for real from Shankar, I think it's a great choice. Griffiths is also a great physics text. I would also recommend these following less famous books:
Physical chemistry and materials science textbooks. I would also highly recommend newer textbooks in physical chemistry as a perhaps less obvious place to look for excellent introductions to quantum mechanics - as Dirac famously said once, it's really the foundation for all of chemistry. An excellent physical chemistry is Physical Chemistry by Berry, Rice and Ross. Presumably there are also good introductions in materials science books, although I don't have any to recommend.
Not Feynman. In my opinion Feynman's Lectures in Physics is great for insight, but it's a terrible idea to learn anything from it the first time - remember that when Feynman actually lectured, most of the freshmen and sophomores (the intended audience) dropped the course, and were replaced by senior students!
Weyl (group theory). I'm surprised no one's mentioned Hermann Weyl's textbook "Theory of groups and quantum mechanics". It's an oldie but goodie, and perhaps best appreciated with someone with a good background in group theory.
Lieb (analysis). I recommend Elliott Lieb's Analysis GSM textbook - on the surface, it looks like it's about functional analysis, but it's secretly also a text on quantum mechanics!

There are some subjects that none of the introductory quantum mechanics texts I've read ever do a satisfactory job of explaining, and I think are really worth following up after Shankar or another such book. The most important ones I think are:

*

*Many-body phenomena. This is really where some of the strangest predictions of quantum mechanics come from, like the EPR paradox and spin statistics. Levine's Physical Chemistry is an excellent place to start. Another great book is Blaizot and Ripka's Quantum Theory of Finite Systems, which does a superb job with boson and fermion statistics.

*Dynamics (time-dependent quantum mechanics. I cannot recommend Tannor's Introduction to Quantum Mechanics: A Time-dependent Perspective enough as a really fantastic resource for learning how practicing physicists and chemists actually do these calculations, beyond the really simplistic calculations presented in most introductory texts. That could also work as a first textbook.

You know, I'm in the building next to you. Maybe you should come by and talk sometime. :)

A: A great starting point are the lecture notes for physics 219 at Caltech:
http://www.theory.caltech.edu/people/preskill/ph229/#lecture
If you pick up any QM textbook that doesn't contain "no cloning theorem", "entanglement",
"EPR (Einstein-Poldolsky-Rosen)", "threshold theorem", "quantum cryptography", "Shor's algorithm", or the word "Channel" in it then it is out-of-date.  (Similarly, don't take a QM course that doesn't have most of these words on the sylibus.)
The quantum information community has really made abstract quantum theory interesting in the last 20 years or so. 20 years ago it would seem heretical that one could study quantum theory from an abstract point of view without specific interest in a particular physical system.  Now there are at multiple papers on the quant-ph arXiv every day that do just that.  The surprising fact: there are lots of interesting research problems available even in the finite-dimensional Hilbert space case.  ("Interesting" here means that solutions of such problems appear quite frequently in Physical Review Letters, Journal of Mathematical Physics, Communications of Mathematical Physics, Nature, ect.)
Note: QM can get technical much faster than classical mechanics does. If you want to actually analyze atoms besides hydrogen then it's going to be a quite a while before you can do it rigorously.  It's analysis.  Reed and Simon's "Methods of Mathematical Physics" books are a must if you want to go in that direction.
BTW, if you want to understand what a Hamiltonian is, go get a hold of Arnold's GTM book on classical mechanics.  It is clearly the best.

A: I wonder why no one mentioned von Neumann's Mathematical Foundations of Quantum Mechanics.
It is a little outdated and contains some minor errors but besides that it is one of the best books i have ever read.
I would especially recommend it for people who study mathematics since it's written from this point of view and not in the sometimes strange physicists language (aka no bra-ket notation, no inexact use of mathematical facts etc).
Since he is using (and for the first time formulating(!)) the theory of separable Hilbert spaces this is already accessible to anyone who knows linear algebra and even more so if you know some functional analysis.
Most importantly von Neumann was a genius who could structure his thoughts in an extremely clear, highly logical fashion which makes it very enjoyable to read this book.

A: To  me the answer to your question is   clear:
Mackey's Mathematical Foundations of Quantum Mechanics
either in conjunction with, or
followed by Dirac's Principles of Quantum Mechanics.
After those perhaps   Weyl's book `The theory of groups and quantum mechanics'.

A: Assuming that you know enough representation theory, I suggest Folland's QFT book right from the start. It covers what you need to know about classical mechanics in the first (or second) chapter, and then there is a chapter about non-relativistic quantum mechanics—this is the best introduction to the subject you will find around, since it explains in a rational way why the state space is a Hilbert space, why observables are represented as self-adjoin operators, etc.
In case your knowledge of representation theory is lacking, I suggest you take some time to learn more about it; it will pay off to see how spin comes out of rotational symmetries of the system, and later on, how to derive relativistic wave equations from relativistic symmetry (which is something you can find in the Weinberg book too, but Folland's explanation is better for a mathematician, modulo learning the Mackey machine).
If you are willing to study some C*-algebras, another suggestion is Strocchi's An Introduction to the Mathematical Structure of Quantum Mechanics. It does not assume any background in physics, but it is quite heavy on the math side (it is used in a third year course in QM for mathematicians at the SNS of Pisa.) It does present the subject from what is usually referred to as the algebraic point of view, that is, you assume, after some considerations, that you can get a C*-algebra of observables out of the set of all measurement instruments. This algebra is commutative for classical mechanics, while for quantum mechanics it is not (this underlines the fundamental role of the uncertainty principle in quantum mechanics).

A: I really enjoyed "Road to Reality" by Roger Penrose.  He wrote it for "general audience", and for a while it was selling in the big bookstores like Barnes and Noble, but I suspect that his definition of "general audience" is what most mathematicians mean: graduate level sophistication without research experience in the subject.

A: There is a wonderful book by David Morin called "Introduction to Classical Mechanics". This book treats mechanics in a problems-oriented format; worked exercises dominate the book, making it very hands on.   This was written for the honors freshman mechanics class at Harvard, and the math is simple but rich.  It is basically a mix of differential equations and Euclidean geometry (and physics) and yet are problems there to challenge everybody.  The book moves efficiently and he covers Lagrangians by Chapter 6.  He explains the least action principle in a simple and natural way using only basic calculus.
In my opinion, you can learn quantum mechanics straight from a variety of sources, but it will seem unmotivated.  Then again, Fenynman says "I think I can safely say that nobody understands quantum mechanics."

A: Quantum Mechanics, Enrico Fermi's work is helpful.I think mathematicians study quantum mechanics,to learn how physics is processed with math,the way and the insight physicists do work with math,and the physical interpretation as well.It is an excellent book although the content is somehow oldfashioned.

A: There are two recent texbooks that are very beautiful, full of pictures, if very unorthodox. They use category as foundation, and only treat finite-dimensional quantum mechanics. They are most suited for quantum information theory and philosophy and foundations of quantum mechanics.

*

*Bob Coecke and Aleks Kissinger, Picturing Quantum Processes: A First Course in Quantum Theory and Diagrammatic Reasoning (Cambridge, United Kingdom ; New York, NY, USA: Cambridge University Press, 2017).

*Christiaan Johan Marie Heunen and Jamie Vicary, Categories for Quantum Theory: An Introduction, Oxford Graduate Texts in Mathematics, 28, First edition (Oxford ; New York, NY: Oxford University Press, 2019).

First book is very slow and easy both in its physics and math. Second book is brisker in math, and more suited for mathematicians.


text:
Q: How to add md-icon in md-option? I am new to angularJS, Can anyone answer me how to add md-icon in md-option?
I tried <md-option>ABC <md-icon>delete</md-icon></md-option> but it will give output like this when selected
"ABCdelete"
any solution of this ??

A: Just as any other child element
<md-option ng-repeat="size in sizes" value="{{size}}">
<md-icon>clear</md-icon>
{{size}}
</md-option>

A: You have to tell md-icon which icon you need to use.
Use like this :
<md-icon md-svg-src = '<url_of_an_image_file>'></md-icon>

A: Here's a small example showing the use of <md-icon> inside an <md-option> directive, just to prove it works. I believe you may be missing a stylesheet or script reference which is causing it to display text instead of the actual icon.

angular.module('app', ['ngMaterial', 'ngAnimate', 'ngAria'])
  .controller('ctrl', function() {
    this.commuteTypes = [{
        description: 'Walk',
        icon: 'directions_walk'
      },
      {
        description: 'Bus',
        icon: 'directions_bus'
      },
      {
        description: 'Drive',
        icon: 'directions_car'
      }
    ];

    this.commuteType = null;
  });
<link href="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.1.18/angular-material.min.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <md-select placeholder="Commute" ng-model="$ctrl.commuteType">
      <md-option ng-repeat="commute in $ctrl.commuteTypes" ng-value="commute">
        <md-icon>{{ commute.icon }}</md-icon> {{ commute.description }}
      </md-option>
    </md-select>


text:
Q: How to add a blank space between header and a ion-card in ionic 2 with some color? I want to add a grayspace of between header and the first card starting.
And want to remove the line highlighting on the card's top area in the screen, I have mentioned it the screenshot provided.
.html
<ion-header>

  <ion-toolbar>

    <ion-title>Ion Cards</ion-title>
  </ion-toolbar>
</ion-header>
<ion-content>

  <ion-card>

  <ion-item>
    <ion-avatar item-start>

    </ion-avatar>

Marty McFly

November 5, 1955

  </ion-item>

  <ion-card-content>

Wait a minute. Wait a minute, Doc. Uhhh... Are you telling me that you built a time machine... out of a DeLorean?! Whoa. This is heavy.

  </ion-card-content>

  <ion-row>
    <ion-col>
      <button ion-button icon-left clear small>
        <ion-icon name="thumbs-up"></ion-icon>

12 Likes

      </button>
    </ion-col>
    <ion-col>
      <button ion-button icon-left clear small>
        <ion-icon name="text"></ion-icon>

4 Comments

      </button>
    </ion-col>
    <ion-col center text-center>
      <ion-note>
        11h ago
      </ion-note>
    </ion-col>
  </ion-row>

</ion-card>

</ion-content>

enter image description here

A: Add the bottom-border in the header.
ion-header {
border-bottom: 10px solid gray;
}

A: In ionic  is having background white
You can change background in
<ion-header>

  <ion-toolbar>

    <ion-title>Ion Cards</ion-title>
  </ion-toolbar>
</ion-header>
<ion-content style="background:lightgray;">

  <ion-card>

  <ion-item>
    <ion-avatar item-start>

    </ion-avatar>

Marty McFly

November 5, 1955

  </ion-item>

  <ion-card-content>

Wait a minute. Wait a minute, Doc. Uhhh... Are you telling me that you built a time machine... out of a DeLorean?! Whoa. This is heavy.

  </ion-card-content>

  <ion-row>
    <ion-col>
      <button ion-button icon-left clear small>
        <ion-icon name="thumbs-up"></ion-icon>

12 Likes

      </button>
    </ion-col>
    <ion-col>
      <button ion-button icon-left clear small>
        <ion-icon name="text"></ion-icon>

4 Comments

      </button>
    </ion-col>
    <ion-col center text-center>
      <ion-note>
        11h ago
      </ion-note>
    </ion-col>
  </ion-row>

</ion-card>

</ion-content>

A:
and change header
<ion-header style="border-bottom: 5px solid gray;">
  <ion-toolbar>

    <ion-title>Ion Cards</ion-title>
  </ion-toolbar>
</ion-header>


text:
Q: Html background color width adjust based on content text I have an h1 tag in which I want to apply a background color, with the max-width property. But the background color should not be applied based on content width. Can anyone help to resolve this?
Current output:

Expected output:
Should remove red mark background color without changing the HTML content(in css with max-width property). Use only css:

h1 {
  background-color: yellow;
  max-width: 200px;
}
<!DOCTYPE html>

This paragraph testing 123

A: i faced this problem in client project, I searched many option but its not working properly, then finally I found this solution using "SELECTION" text you can set background cover on Text using JavaScript it support in all browser.

$(document).ready(function () {
  let resEle = document.querySelector("h1");
    $("h1").hover(
        function () {
            window.getSelection().selectAllChildren(this);
        },
        function () {
            window.getSelection().removeAllRanges(this);
        }
    );
});
h1 {
  max-width: 200px;
}

h1::selection{
  background:yellow;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>

This paragraph testing 123

A:

h1 {
  max-width: 200px;
}
h1>span {
  background-color: yellow;
}
<!DOCTYPE html>

This paragraph testing 123

I thing you can put span tag inside H1 tag

A: Since display:block behavior always trying to stretch of its container width so your body has 100%. But when you put max-width:200px it becomes limited by 200px regardless of content inside. With your mention not changing html its not so good but you can try max-width to content Width. So try tweak html or change max-width

h1 {
  background-color: yellow;
  max-width: min-content;
}
<!DOCTYPE html>

This paragraph testing 123

A: As you don't want to change HTML content,

*

*Decrease max-width value

h1 {
  max-width: 150px;
  background-color: yellow;
}

This paragraph testing 123

*Set width in percentage wise with media query for Responsive Design

h1 {
  background-color: yellow;
  width: 30%;
}

This paragraph testing 123

*Set max-width: min-content

h1 {
  background-color: yellow;
  max-width: min-content;
}

This paragraph testing 123

*Increase / Decrease Font Size

h1 {
  background-color: yellow;
  max-width: 200px;
  font-size: 40px;
}

This paragraph testing 123