text:
Q: How to remove everything except words and emoji from text? As a part of text classification problem I am trying to clean a text dataset. So far I was removing everything except text. Punctuation, numbers, emoji - everything was removed. Now I am trying to use emoji as features hence I want to retain words as well emoji.
First I am searching the emoji in the text and separating them from other words/emoji. This is because each emoji should be treated individually/separately. So I search an emoji and pad it with spaces at both its ends.
But I am at loss while figuring out how to combine the known regex for words and emoji. Here is my current code:
import re

def clean_text(raw_text):

    padded_emoji_text = pad_emojis(raw_text)
    print("Emoji padded text: " + padded_emoji_text)

    reg = re.compile("[^a-zA-Z]") # line a

    # old regex to remove everything except words
    letters_only_text = reg.sub(' ', raw_text)
    print("Cleaned text: " + letters_only_text)

    # Code to remove everything except text and emojis
    # How?

def pad_emojis(raw_text):

    print("Original Text: " + raw_text)

    reg = re.compile(u'['
      u'\U0001F300-\U0001F64F'
      u'\U0001F680-\U0001F6FF'
      u'\u2600-\u26FF\u2700-\u27BF]',
      re.UNICODE)

    #padding the emoji with space at both ends
    new_text = reg.sub(r' \g<0> ',raw_text)

    return new_text

text = "I am very #happy man! but my wife is not . 99/33"
clean_text(text)

Current o/p:
Original Text: I am very #happy man! but my wife is not . 99/33
Emoji padded text: I am very #happy man! but     my wife   is not     . 99/33
Cleaned text: I am very  happy man  but   my wife  is not

What I am trying to achieve:
I am very happy man but     my wife   is not

Questions:
1) How do I add the emoji regex to regex compilation along with the words regex? (line a)
2) Also can I achieve what I am seeking in a better way i.e. without having to write a separate function just to separate the emoji and pad them with spaces? I somehow feel this can be avoided.

A: You may join the two steps into one using a single regex and a lambda expression inside a re.sub like this:
import re

emoji_pat = '[\U0001F300-\U0001F64F\U0001F680-\U0001F6FF\u2600-\u26FF\u2700-\u27BF]'
shrink_whitespace_reg = re.compile(r'\s{2,}')

def clean_text(raw_text):
    reg = re.compile(r'({})|[^a-zA-Z]'.format(emoji_pat)) # line a
    result = reg.sub(lambda x: ' {} '.format(x.group(1)) if x.group(1) else ' ', raw_text)
    return shrink_whitespace_reg.sub(' ', result)

text = 'I am very #happy man! but my wife is not . 99/33'
print('Cleaned text: ' + clean_text(text))
# => Cleaned text: I am very happy man but   my wife  is not

See the Python demo
Explanation:

*

*The first regex will look like ([\U0001F300-\U0001F64F\U0001F680-\U0001F6FF\u2600-\u26FF\u2700-\u27BF])|[^A-Za-z] and will match and capture into Group 1 an emoji or will just match any char other than an ASCII letter. If the emoji was captured (see if x.group(1) inside the lambda), the emoji will be returned back enclosed with spaces on both sides, else, the space will be used to replace a non-letter

*The \s{2,} pattern will match 2 or more whitespaces and shrink_whitespace_reg.sub(' ', result) will replace all these chunks with a single whitespace.


text:
Q: Temp directory for all users? This is the Temp directory for my user account:
C:\Users\John\AppData\Local\Temp

Is there a Temp directory that is accessible by all users?

A: There is a temp directory in the Windows directory, i.e., %SYSTEMROOT%\Temp, but its use is deprecated. Applications should use the user-specific temp directories.
You can, however, redirect users' temp directories, so you could have them all point to the same directory, if that's what you are after. You would just change their TMP and TEMP environment variables to point wherever you want. Ensure that all of the affected users can write to this new directory.

A: Not a Temp directory per se, but you could use %PUBLIC% AKA C:\Users\Public as a workaround.
Also, C:\Users\All Users seems to be accessible to all users on the machine.
from a quick search:

The Public folder is located in "C:\Users\Public", in all Windows
  versions. All user accounts registered in Windows have access to it.
  That's why it is named Public. Any file and folder found in
  "C:\Users\Public" is completely accessible to all users

A: (I am using powershell here!)
workaround 1
One can create a temp folder in the publicly shared folder like this:
## "$tmp":         thus you can use $tmp later on to reference it
## "-force":       does not complain if already existing
## " | out-null":  suppresses md standard output
PS C:\> $tmp = "$env:public\tmp" ; md -force $tmp | out-null

It should be accessable by all users.
However the shared folder may be read-only if configured explicitely.
workaround 2
Using $env:windir\Temp or $env:systemroot\Temp (e.g. C:\Windows\Temp) seems deprecated and uglier, but works (e.g. in a Win2012R2 environment) with some extra adjustments...
You can't list its direct content, which may not be bad, depending on your needs:
PS C:\> cd $env:windir\temp
PS C:\Windows\Temp> ls
ls : Der Zugriff auf den Pfad "C:\Windows\temp" wurde verweigert.
In Zeile:1 Zeichen:1
+ ls
+ ~~
    + CategoryInfo          : PermissionDenied: (C:\Windows\temp:String) [Get-ChildItem], UnauthorizedAccessException
    + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand
PS C:\Windows\Temp> md test ; echo "test123" > test\test.txt

Verzeichnis: C:\Windows\temp\test

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       28.09.2018     17:08             20 test.txt

But other users won't be able to see it normally, if they do not have admin rights:
## as other non-admin user:
PS C:\Windows\Temp> cd test
cd : Zugriff verweigert
In Zeile:1 Zeichen:1
+ cd test
+ ~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\Windows\Temp\test:String) [Set-Location], UnauthorizedAccessException
    + FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.SetLocationCommand

cd : Der Pfad "C:\Windows\Temp\test" kann nicht gefunden werden, da er nicht vorhanden ist.
In Zeile:1 Zeichen:1
+ cd test
+ ~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Windows\Temp\test:String) [Set-Location], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand

To solve this one may want to additionally change permissions via Set-Acl

redpajama_set_name: RedPajamaStackExchange


text:
Q: Handle Shake Gestures when UIAlertView is displaying I want to take screenshots when shaking the device and also want this to work when a UIAlertView is visible.
The problem is that the MotionBegan and MotionEnded-methods are not called. I have tried subclassing UIWindow and UIAlertView and overriding the methods in there, but still nothing gets called.
Am I missing something here?
I enable shake gestures by calling
    UIApplication.SharedApplication.ApplicationSupportsShakeToEdit = true;

in AppDelegate.cs.
And it all works perfectly when there is no UIAlertView visible.
What view responds to shake gestures when an UIAlertView is displayed?

A: I would highly recommend not using UIAlertView.

*

*First it is deprecated in iOS9

*Second it is a really messed UIView. Apple does not support subclassing it and things goes really sideways when trying to ResignFirstResponder so you can receive events. Along with a number of other things about it that are strange, no wonder Apple deprecated it.
Use UIAlertController instead, it is available in iOS8/9/10 and acts like a proper UIViewController and looks like the old alerts when used with UIAlertControllerStyle.Alert style and you will not have any problems with MotionBegan/MotionEnded when using it.
So you can either override MotionBegan/MotionEnded on each of UIViewController:
public override void MotionBegan(UIEventSubtype motion, UIEvent evt)
{
    Console.WriteLine("MotionBegin");
    base.MotionBegan(motion, evt);
}

public override void MotionEnded(UIEventSubtype motion, UIEvent evt)
{
    Console.WriteLine("MotionEnded");
    base.MotionEnded(motion, evt);
}

Or create your own UIWindow subclass and and thus you will get globally motion events (you can just post (PostNotificationName) via notification center if other areas of your app need to respond to the motion events.
public class ShakeWindow : UIWindow
{
    public ShakeWindow() : base() { }

    public ShakeWindow(IntPtr handle) : base(handle) { }

    public override void MotionBegan(UIEventSubtype motion, UIEvent evt)
    {
        Console.WriteLine("Window MotionBegin");
        NSNotificationCenter.DefaultCenter.PostNotificationName("ShakeMe", this);
        base.MotionBegan(motion, evt);
    }

    public override void MotionEnded(UIEventSubtype motion, UIEvent evt)
    {
        Console.WriteLine("Window MotionEnded");
        base.MotionEnded(motion, evt);
    }
}

UIAlertController Example using NSNotificationCenter:
var button2 = new UIButton(UIButtonType.RoundedRect);
button2.SetTitle("Alert 2", UIControlState.Normal);
button2.Frame = new CGRect(20, 60, 100, 40);
button2.TouchUpInside += (object sender, EventArgs e) =>
{
    var alert2 = UIAlertController.Create("StackOverflow", "Shake me now", UIAlertControllerStyle.Alert);
    NSNotificationCenter.DefaultCenter.AddObserver(new NSString("ShakeMe"), (obj) =>
    {
        alert2?.DismissViewController(true, null);
    });
    alert2.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, (UIAlertAction obj) =>
    {
        alert2.DismissViewController(true, null);
    }));
    PresentViewControllerAsync(alert2, true);
};
Add(button2);


text:
Q: Product of two functions in $H^1$ Can you help me proving the following statement?

Let $u,v \in H^1(I)$ where $I$ is an open interval in $\mathbb{R}$. Prove that $u \cdot v \in H^1(I)$ and $(u\cdot v)^\prime = (u^\prime \cdot v) + (u \cdot v^\prime)$.

A: Hint: Note that the space $H^1(I)$ is the space of absolutely continuous functions with weak derivative in $L^2(I)$. Hence the product is still absolutely continuous and the Leibniz formula holds.
Hint for higher dimensions: if one of the two functions is assumed to be $C_{c}^{\infty}$, then by Mayer and Serrin (or sometimes it is taken as a definition), for every element $u \in H^{k}$ there exists a sequence of $C^{\infty}$ functions that converge to $u$. Then it's all about using the properties for smooth functions (which hold) and then pass to the limit.


text:
Q: Social.framework doesn't work for Xcode 6.3.2 As a newbie i wanted to try out Facebook and Twitter Post using objective-c
So i added 2 buttons, added actions to it, also added social framework. When i run the code and click on Tweet or Facebook Buttons nothing happens, am i missing something.I am testing it on Simulator, does that make any difference.
Here is my header file SocialSharingViewController.h
#import <UIKit/UIKit.h>

@interface SocialSharingViewController : UIViewController

- (IBAction)postToTwitter:(id)sender;
- (IBAction)postToFacebook:(id)sender;

@end

Here is my .m file SocialSharingViewController.m
#import "SocialSharingViewController.h"
#import <Social/Social.h>

@interface SocialSharingViewController ()

@end

@implementation SocialSharingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)postToTwitter:(id)sender {
    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
    {
        SLComposeViewController *tweetSheet = [SLComposeViewController
                                               composeViewControllerForServiceType:SLServiceTypeTwitter];
        [tweetSheet setInitialText:@"Great fun to learn iOS programming"];
        [self presentViewController:tweetSheet animated:YES completion:nil];
    }
}

- (IBAction)postToFacebook:(id)sender {
    NSLog(@"clicked facebook button");
    if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
        SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];

        [controller setInitialText:@"First post from my iPhone app"];
        [self presentViewController:controller animated:YES completion:Nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

A: A few things come to mind:

*

*Did you connect the buttons in your .xib to the IBAction methods in your code?

*Is -isAvailableForServiceType: legitimately returning NO, preventing them from showing?


text:
Q: How to query latitude and longitude of Windows 10 device in PowerShell? I'm looking for a way to query Windows 10 location service via PowerShell to return the device's current latitude and longitude in decimal notation. Cribbing from http://www.verboon.info/2013/10/powershell-script-get-computergeolocation/ I put together the following function:
    function Get-LatLong()
    {
    # Windows Location API
    $mylocation = new-object -ComObject LocationDisp.LatLongReportFactory

    # Get Status
    $mylocationstatus = $mylocation.status
    if ($mylocationstatus -eq "4")
    {
        # Windows Location Status Returns 4, so we're "Running"

        # Get latitude and longitude from LatLongReport property
        $latitude = $mylocation.LatLongReport.Latitude
        $longitude = $mylocation.LatLongReport.Longitude

        if ($latitude -ne $null -or $longitude -ne $null)
        {

            write-host "$longtitude $latitude"

        }
        Else
        {
            write-warning "Latitude or Longitude data missing"
        }
    }
    Else
    {
        switch($mylocationstatus)
        {
            # All possible status property values as defined here:
            # http://msdn.microsoft.com/en-us/library/windows/desktop/dd317716(v=vs.85).aspx
            0 {$mylocationstatuserr = "Report not supported"}
            1 {$mylocationstatuserr = "Error"}
            2 {$mylocationstatuserr = "Access denied"}
            3 {$mylocationstatuserr = "Initializing" }
            4 {$mylocationstatuserr = "Running"}
        }

        If ($mylocationstatus -eq "3")
        {
            write-host "Windows Loction platform is $mylocationstatuserr"
            sleep 5
            Get-LatLong
        }
        Else
        {
            write-warning "Windows Location platform: Status:$mylocationstatuserr"
        }
    }
} # end function

When I call the function, it returns:

PS C:\windows\system32> Get-LatLong
WARNING: Windows Location platform: Status:Report not supported

Location services are enabled on the device. I am running PowerShell as Admin. Web searching didn't help.

A: If you follow the comment in the code:
https://msdn.microsoft.com/en-us/library/windows/desktop/dd317716(v=vs.85).aspx
It mentions:

[The Location API object model is available for use in the operating systems specified in the Requirements section. It may be altered or unavailable in subsequent versions. Instead, to access location from a website, use the W3C Geolocation API. To access location from a desktop application, use the Windows.Devices.Geolocation API.]

and that the supported platform is:

Minimum supported client
  Windows 7 [desktop apps only]

Conclusion:
I think the answer of how to query location data on Windows 10 is to use the Geolocation API.


text:
Q: Using Similar Triangles to solve for the equation of a line Consider points A=(−10,−4) and C=(8,5). The point B is on the line passing through A and C. The x-coordinate of B is −1. Determine the y-coordinate of the point B.
This question has been asked before. I am very much interested in a visual representation of solving this. It is part of a coursera self-paced no cert calculus course.
I have a very hard time equating the following solution pictorially with the use of similar triangles.
BD/DA = CE/EA where tow letter pairs are line segments.
DA= x-coordinate of D minus x-coordinate of A= −1+10=9
CE= y-coordinate of C minus y-coordinate of E= |5+4|=9
EA= x-coordinate of E minus x-coordinate of A= 8+10=18
so DB/9=918
Therefore, DB =9/2
Since B is above D, the y-coordinate of B is the y-coordinate of D plus the length of DB.
Thus the y-coordinate of B=−4+92=12
I am also fuzzy on Since B is above D, the y-coordinate of B is the y-coordinate of D plus the length of DB. What it was above.
Thanks,
Chris

A: One thing that seems apparent is that since B lies right at the average of the x values of the triangles, then the triangles should be congruent.  Therefore the y value of B should be the average of A and C y values.  $\frac{1}{2}$

A: The last sentence of the fifth paragraph should have read,

Thus the $y$-coordinate of B is $−4+\dfrac92=\dfrac12$.

which is the correct answer.


text:
Q: Why isn't temperature involved in the Schrödinger equation? I am a bit confused with the Schrödinger equation. It describes the state of a system, the system could be of any size (although the equation will be hard to solve) but temperature doesn't play any role there.
So Why isn't temperature involved in the Schrödinger equation? Is it valid only a $T=0$?

A: Temperature is a statistical property of an ensemble of particles/molecules. The Schrödinger equation works from the perspective of a single quantum state.
I'm sure that it might be possible to introduce temperature in one way or another to the Hamiltonian, but there is seldom a need for this when working with a single particle/atom in quantum mechanics.
As pointed out by DanielSank, the temperature of the environment that interacts with a system will very likely enter the Hamiltonian if it is relevant to the studied process.

A: A thermodynamic state characterizes the thermodynamic observables of a system at equilibrium like temperature or pressure. By definition these observables are defined in the thermodynamic limit, i.e, when the number of degrees of freedom of the system are large. In other words, they describe the emergent macroscopic features of the system, rather than describing all possible microscopic features.
The thermodynamic variables can enter the Schrodinger equation or the Newton laws depending on the system you choose. Eg, if you take a particle in a box interacting with the environment then the relevant thermodynamic variables enter the description using the Hamiltonian for the particle, and thus enter both the Schrodinger equation as well as Newton's laws. Open quantum systems where  degree(s) of freedom interact with environment may have temperature and other macroscopic observables characterizing the state of the environment entering into the Hamiltonian for the degree(s) of freedom.
Usually the Hamiltonians we consider in a QM1 course (I think that's where your confusion is coming from) don't have this kind of degree(s) of freedom-environment interaction, so thermodynamic variables don't enter the description.

A: It may help to return to the classical mechanics of particles, whose exposition -- (see, e.g. Landau and Lifshitz, 'Mechanics') is altogether distinct from the exposition of thermodynamics -- in itself a separate discipline.
I would then make the analogy between classical and quantum mechanics, to assert that Schroedinger's equation is the quantum mechanical analog of the classical mechanics of particles, and therefore -- as in the classical case-- thermodynamic considerations, particularly that of temperature, do not enter.

A: Schrödinger's equation makes a microscopic-level description, while temperature is a macroscopic variable.

A: My take on this goes against the accepted answer's approach. One can use Schrödinger equation to model a macroscopic system, for example a crystal. Moreover, one can imagine systems in which the potential term that appears in Schrödinger equation depends on temperature. The result is that the Schrödinger equation involves temperature.
Consider a crystalline solid in which the interatomic distance depends on temperature. The Hamiltonian applied to the state of the system (which is nothing but Schrödinger equation) will involve terms that depend on temperature.
And to answer the last question of santimirandarp, while it is possible to model a system at $T=0K$, Schrödinger's equation is valid at any temperature.
Edit: As have been requested, in order to improve the answer, I respond to a comment by giving more precision, based on Ashcroft and Mermin's book "Solid State Physics", chapters 22 and 23 (only prerequisite is chapter 5 according to the book's plan) as a reference. It is a question of harmonic crystals. These are crystalline solids where the position of atoms or ions is not fixed but is allowed to vary in such a way that in (a time) average, their position is fixed and correspond to a Bravais lattice site. Furthermore, they may not move too far away from their equilibrium position, which is a reasonable assumption to describe many (but not all) properties for many, if not most, solids. This is called the harmonic approximation. As an example, oscillating ions about their equilibrium position, just like a mass on a spring, would satisfy this criteria. According to the book, by making a further approximation, called the adiabatic approximation (which is based on assuming that electrons move much faster than the ions of the solid, which is generally a justified approximation and the result is that the electrons are to be found in their ground state for that particular ionic configuration), statistical mechanics can now usefully enter into play. With the classical treatment, it is shown that the ionic displacement of an ion is worth $\vec u (\vec R) = \sqrt{k_\text{B}T} \vec u (\overline{\vec R})$, this term depends on temperature and enters the Hamiltonian, see page 427. This implies that temperature can enter into the classical mechanic's Hamiltonian. But the case is similar in quantum mechanics in that the Hamiltonian can also depend on the temperature. The details can be found in chapter 23, about page 452 where the harmonic Hamiltonian (which is part of the total Hamiltonian, and hence Schrödinger's equation) is given and depends implicitely on temperature. One way I see to justify this is that its eigenvalues (given on the same page) depend on temperature.
Maye an intuitive way to realize that the Schrödinger's equation depends on temperature in this case is by convincing oneself that the number of phonons is temperature dependent (it is shown in the  book). The phonons can be thought as perturbations in the position of the ions, and these perturbations will affect electrons and the general Hamiltonian, hence Schrödinger equation.
If the example is too hard to grasp, consider the very simple following example. Our new system is now a crystal (say a metallic conductor) and we control its temperature as we wish. Everytime the temperature is below $100K$, we turn on an electromagnetic field. This field will have an influence on the electrons in the conductor and will have corresponding terms in the Hamiltonian (Schrödinger equation) as well. That potential certainly has a dependence on temperature, where the temperature is the one of the studied system. So this confirms that yes, it is quite possible to find systems in which Schrödinger equation involves temperature.
Nevertheless, it is not always possible to introduce temperature into Schrödinger equation. Like others have stated, if the number of particles of the system is too low or if the system is far from thermodynamics equilibrium, the concept of temperature is not defined, in which case it doesn't even make sense to speak of a temperature of the system. It's a different story if the number of particles is high enough and the system is only "slightly out of equilibrium" in which case it may prove useful to define temperature locally, in subregions of the whole system. This has been done by Onsager in 1931 and lead to the reciprocal relations that bear his name but this is going a bit off topic.

A: It is quite late to answer this question, but I just stumbled about it, too, so I try to give an answer here.
I also think that it helps to consider firstly classical mechanics. Newton's equation of motion describes the motion of particles at fixed total energy (isolated system, NVE ensemble and 1st law of thermodynamics). If we consider describing let's say 1000 water molecules with Newton's equation and we initialize the system with zero velocities of all the water, the water will convert its potential energy to kinetic energy and some dynamic conversion of these two sources of energy will be started. Transfer of kinetic energy between individual water molecules should always happen by the principle of the 2nd law of thermodynamics, so the entropy of the complete system becomes larger, so that hot particles heat up cool particles. So the temperature is already in our simulations in the form of kinetic energy and we can also define it from that.
Now although we can define it, we cannot directly alter it. The reason for that is that our system is isolated, so there is no way to influence our water molecules from outside! That is the reason why the temperature does not appear as a variable in the Newton equation and also not in the Schrödinger equation, because both equation describe the motion of an isolated system. Inside this system there is temperature fluctuations, as said before, but we cannot change it from outside.
If we would want to change the temperature from outside, we need to include a heat bath/thermostat which heats up and cools down out water molecules by (fictitious) collisions.

A: Schrödinger equation, just like Newton's laws, describes behavior of a single particle. Temperature is an average energy per particle, which is *meaningful only for large collections of particles.

A: This questions is actually quite intriguing and I like to take a different perspective than the other authors, to maybe shine some light on this problem. Therefore, I consider time-dependent problems.
Let's start with the time-dependent Schrödinger equation (TDSE), with Hamiltonian $\hat{H}$ and many-body wave function $|\Psi(t)\rangle$, where the former is the generator of the dynamics and the TDSE reads
$$\text{i}\hbar\partial_t |\Psi(t)\rangle = \hat{H}|\Psi(t)\rangle,  \hspace{0.4cm}|\Psi(t_0)\rangle=|\Psi\rangle$$
with some initial condition $|\Psi(t_0)\rangle$. The latter equation describe the real-time evolution of a quantum many-body system. The natural generalization of the latter to finite temperature is the Liouville-von Neumann (LvN) equation, which turns out be given as
$$\partial_t\hat{\rho}(t)=-\frac{\text{i}}{\hbar}[\hat{H},\hat{\rho}]$$
where $\hat{\rho}(t)$ is the density operator. At zero Kelvin, the LvN-equation is equivalent to the TDSE and the real-time dynamics of $\hat{\rho}$ are equivalently described by $|\Psi(t)\rangle$. However, at finite temperature, the density operator for a system in thermal equilibrium is related to a classical stochastic distribution over quantum mechanical states. The latter can be written in an energy eigenbasis $\{|n\rangle\}$ of the underlying Hilbert space as
$$\hat{\rho}_{th}=\frac{1}{Z_\beta}\sum_n e^{-\beta\varepsilon_n}|n\rangle \langle n|$$
In fact, the Hamiltonian entering the LvN eq. is identical to the Hamiltonian entering the TDSE, however, the nature of the corresponding state is fundamentally different. The density operator is the proper representation of a quantum mechanical system at finite temperature and not a wave function. Temperature does not enter the Hamiltonian at all. Moreover, quantum mechanical expectation values generalize at finite temperature to thermal ensemble averages, where the mean energy is for example given as
$$\langle\hat{H}\rangle=\text{tr}\{\hat{\rho}_{th}\hat{H}\}$$
where "tr" denotes the trace operation. The latter generalizes to time-dependent situations, when $\hat{\rho}(t)$ explicitly time dependent and $\hat{\rho(t_0)}=\hat{\rho}_{th}$, for example. Another important point relates to the time-evolution of the density operator. When the formal solution of the LvN-eq. is considered, it turns out, that ket states are propagated forward in time and bra states propagate backwards in time. This feature in combination with a doubled set of degrees of freedom is present in both quantum statistical dynamics as discussed here and finite temperature quantum field theory as given by Keldysh-Schwinger formalism, real-time path integrals and thermofield dynamics. In contrast, the TDSE leads only to a forward propagation of the wave function, while its adjoint is related to the backward evolution of a quantum mechanical system.
I now pick up environmental aspect mentioned by DanielSank. In fact, such a system-bath problem can actually be investigated from the perspective of the TDSE, when staying at $T=0K$, which is, however, numerically demanding. At finite temperature, this is again not possible due to the stochastic nature of the density operator, whereas temperature does not enter the Hamiltonian at all. Moreover, in those situations, one regularly augments the LvN-equation by an additional term, which takes into account the interaction with the surrondings and their temperature implicitly. This term, called dissipator, leads to an exchange of (thermal)energy from the system with the environment and renders the system dynamics non-unitary. I like to mention, that there exist ways (Liouville space formalism, thermofield dynamics) to express the LvN-equation in a way, that is formally equivalent to the TDSE, however, the basic properties do not change. Fields, where you can approach the microscopic relevance of temperature are from my perspective molecular junctions, heat and charge transport at the nanoscale or especially quantum thermodynamics and open quantum system theory.


text:
Q: how to access returned results from rowSet in Java I'm trying to access what the rowSet variable has returned i.e. it is retreving everything from properties where two conditions are met, BUT:
        JdbcRowSetImpl rowSet = new JdbcRowSetImpl();
        int price = 300000;
        rowSet.setUrl("jdbc:mysql://localhost:3306/litrealty");
        rowSet.setUsername("root");
        rowSet.setPassword("");
        rowSet.setCommand("SELECT * FROM properties WHERE city = ? AND price < ?");
        rowSet.setString(1, l);
        rowSet.setInt(2, price);

        rowSet.execute();

since this piece of code is retreving these informations from the database how can I access it and i.e. put into an array so I can scroll through it then via next/previous buttons?

A: you can use while loop and iterate on your rowset and get the data
it would look something like this:
//Creating and Executing RowSet
JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
rowSet.setUrl("jdbc:mysql://localhost:3306/litrealty");
rowSet.setUsername("root");
rowSet.setPassword("password");

rowSet.setCommand("select Id, Name, Salary from employee");
rowSet.execute();

while (rowSet.next()) {
    System.out.println("Id: " + rowSet.getString(1));
    System.out.println("Name: " + rowSet.getString(2));
    System.out.println("Salary: " + rowSet.getString(3));
}

Instead i would suggest you to use PreparedStatement to fetch data base from database


text:
Q: Logout of User via Command Line? How can I go back to the login screen of Ubuntu via command line?
I often use reboot -n or shutdown -t now while I have terminal open but sometimes I just want to logout without rebooting.


text:
Q: Remove missing values in r I am trying to remove missing values in r:
code:
na.omit(x)

which gives the output omitted 56 entries.
typeof(x)

returns "double"
Now again when I check with the following function it returns true.
anyNA(x)

I am new to R, and am not sure what is going wrong. any suggestions would be fine.

A: We need to update the object after applying the function..  Otherwise, it wouldn't change the values stored in the object
x <- na.omit(x)
anyNA(x)
#[1] FALSE

Suppose, if we wanted to update the values in the object without doing the <-, then we can use the %<>% operator from magrittr which does this
library(magrittr)
x %<>%
  na.omit()

anyNA(x)
#[1] FALSE

data
x <- c(NA, 1:3)

A: You can use this -

new_table <- na.omit(df)


text:
Q: SQL Server Management Studio default query results from "Select top 1000" How do I change the default of SELECT TOP 1000 query results to go to Text instead of Grid?

A: In the menu press 'Query', press 'Results To', Press 'Results to Text' or just press CTRL-T

A: From the Menu:
Tools -> Options
then
From the left hand side of the Options window:
Query Results -> Sql Server
Then set "Default destination for results:" to be "Results to text".
Press OK.


text:
Q: Accessing php file outside root directory via jquery ajax request I read it's good practice to store php files containing potentially security risk stuff outside the root directory.
Now I have php files containing stuff for proccessing a registration/login. Those are outside the root directory.
Now I catch the form content via jquery and send it to this php file.
But this seems not to be possible with js/jquery:
$.ajax({
    type: "POST",
    url: "../php_includes/register.inc.php", //beyond root path
    data: data,
    })
    .done(function(data, status) {
            //...
    });

Do I have a design error or just doing something wrong?
Whats the "best practice" solution here?

A: A "best practise" would reduce the number of entry points to 1. Rather than having index.php, login.php and register.php you have just one file handler.php that handles all incoming requests (aided by rewrite rules).
handler.php bootstraps your application and contains routing information that determines how a request should be handeld. Modules in your application can register routes and that is how that code gets activated.
All your code can be stored outside of the webroot, only handler.php is exposed. And handler.php can be as simple as:
<?php
include(__DIR__ . "/../includes/bootstrap.php");

Rewrite rule to capture all requests:
RewriteEngine on
RewriteRule ^(.*)$ handler.php?path=$1 [QSA]

A: You wont be able to access any files outside the root directory from the browser (ie. like you're trying to do using Javascript). The entire point of storing files outside the root directory is so that they are not accessible by the client.
It is necessary and safe enough to place registration code inside the document root.

A: You'd rather store security-related stuff like configuration files and alike in an external (non-accessible) directory. But if you need to access information stored in these files, you have to create a controller that will filter the access and provide the information in a secure way if needed.
Apache will not serve files that are not located in the website's root directory.


text:
Q: How to import a GraphQL schema from my express-graphql server to my apollo client via Schema Link So what my problem is that i have created a project and i have 2 separete folders.
One for the server side and one for the client side. I try to make a reddit clone based on ben awad's yt tutorial and a lot have changed since the realease.
So in server side i am using apollo server in addition with express and typegraphql redis and typeorm.
In client side i use apollo client and nextjs in addition with typescript.
So i am in a position where i want to do SSR(Server Side Rendering) in thw client side based on the documentation of nextjs and according to the tutorial the method that is used is depracated. So i have been searching for the past 2 days for a solution but nothing comes up.
I followed this method https://github.com/vercel/next.js/tree/canary/examples/with-apollo/lib but i come up with a problem. In this method i then change the apolloClient file to
import {
  ApolloClient,
  from,
  HttpLink,
  InMemoryCache,
  NormalizedCacheObject,
} from "@apollo/client";
import { SchemaLink } from "@apollo/client/link/schema";
import merge from "deepmerge";
import isEqual from "lodash/isEqual";
import { useMemo } from "react";

export const APOLLO_STATE_PROP_NAME = "__APOLLO_STATE__";

let apolloClient: ApolloClient<NormalizedCacheObject> | null = null;

type SchemaContext =
  | SchemaLink.ResolverContext
  | SchemaLink.ResolverContextFunction;

function createIsomorphicLink(ctx?: SchemaContext) {
  if (typeof window === "undefined") {
    const { schema } = require("../modules/graphql/schema");
    return new SchemaLink({
      schema,
      context: ctx,
    });
  }
  const httpLink = new HttpLink({
    uri: "http://localhost:3000/api/graphql",
    credentials: "same-origin",
  });
  return from([httpLink]);
}

function createApolloClient(ctx?: SchemaContext) {
  return new ApolloClient({
    ssrMode: typeof window === "undefined",
    link: createIsomorphicLink(ctx || undefined),
    cache: new InMemoryCache(),
  });
}

interface InitApollo {
  initialState?: any;
  ctx?: SchemaContext;
}

export function initializeApollo({ ctx, initialState }: InitApollo) {
  const _apolloClient =
    apolloClient ?? createApolloClient(ctx || undefined);

  // If your page has Next.js data fetching methods that use Apollo Client, the initial state
  // gets hydrated here
  if (initialState) {
    // Get existing cache, loaded during client side data fetching
    const existingCache = _apolloClient.extract();

    // Merge the initialState from getStaticProps/getServerSideProps in the existing cache
    const data = merge(existingCache, initialState, {
      // combine arrays using object equality (like in sets)
      arrayMerge: (destinationArray, sourceArray) => [
        ...sourceArray,
        ...destinationArray.filter(d =>
          sourceArray.every(s => !isEqual(d, s))
        ),
      ],
    });

    // Restore the cache with the merged data
    _apolloClient.cache.restore(data);
  }
  // For SSG and SSR always create a new Apollo Client
  if (typeof window === "undefined") return _apolloClient;
  // Create the Apollo Client once in the client
  if (!apolloClient) apolloClient = _apolloClient;

  return _apolloClient;
}

export function addApolloState(
  client: ApolloClient<NormalizedCacheObject>,
  pageProps: { props: any }
) {
  pageProps.props[APOLLO_STATE_PROP_NAME] = client.cache.extract();

  return pageProps;
}

export function useApollo(pageProps: any) {
  const state = pageProps[APOLLO_STATE_PROP_NAME];
  const store = useMemo(
    () => initializeApollo({ initialState: state }),
    [state]
  );
  return store;
}

In this modified example i found he uses prisma and nexus.
So when he uses the SchemaLink he can take the schema from the .ts file that is created in module folder
So i wanted to ask if the is way to take the graphql file that occurs after emmiting the sdl from typegraphql documentation [https://typegraphql.com/docs/emit-schema.html ]and if so, it is possible to make a path in order to import/require it from the server folder that it is created.
PS. I am not using neither prisma nor nexus. I just want to know if there is a way to import a graphql file into typescript cause everything relative i found didnt work.
Edit.. So after all i found out that if i use HttpLink instead of schemaLink i can get the same result. But in terms of optimazation because i use the same domain for the server and client side(Localhost) it would be more preferable to use the schemaLink method.So if anyone knows the answer, the question is still open. For the time now i find a way to solve my problem.


text:
Q: how to host an exe with a dynamic commandline parameter I have an installer exe which takes a channel_id param as a command line parameter and uses it.
The channel_id may be different for different downloads and installs.
I want to host my installer exe on web in such a way that when it's downloaded and executed (by double clicking) the channel_id is passed to it in someway ,which should be equivalent to running the installer exe in cmd with channel_id as below.
cmd> myinstaller.exe channel_id.
How is it possible to do so ?

A: You can include your param in the name of the file. For example, instead of setup.exe, call it setup_XXXX.exe. Then from NSIS you can read and parse $EXEPATH and extract your param from the filename.

A: You can append data to the end of the .exe file.

A: Probably not the most reliable way to do this (if there is any), but you could probably check for the Zone.Identifier. I'm not aware of a way to this natively in NSIS, but you might be able to achieve by parsing the result through the commandline.
Try
nsExec::ExecToLog 'more < "$EXEPATH:Zone.Identifier"'

or
nsExec::ExecToLog 'dir /r "$EXEPATH"'

I've also found several Powershell (and VisualBasic) scripts that allow interacting with Alternate Data Streams, but personally I'm not a big fan of using third party scripting languages.


text:
Q: List item record in random order when it gets removed from list I have got list view table. Whenever i try to delete the item from the list view table, the order of the list becomes random but then when I add an item into the list, the list is sorted. Whenever the list is deleted, I want the rest of the items to be sorted by the student ID. I have tried and haven't had any luck so far.
StudentOrder.xaml
<CollectionViewSource
    Source="{Binding StudentRecords}">
    <CollectionViewSource.SortDescriptions>
    </CollectionViewSource.SortDescriptions>
</CollectionViewSource>

StudentOrder.xaml.cs
void StudentOrder_Loaded(object sender, RoutedEventArgs e)
{
    if (Shows.OrderCurrent == null)
    {
        Show.OrderPresent = StudentID;
        Show.DataOrder = "StudentID";
        Show.Order();
    }
    else
    {
        if (orderLst != null)
        {
            Show.Order();
        }
    }
}

ShowOrders.cs
public override bool Delete()
{
    recordRetriever.StudentOrderRetriever.Delete(_record);
    Record = null;
    Refresh();
    return true;
}

private ObservableCollection<ShowOrder> RandomListSort()
{
    IEnumerable<ShowOrder> arrangeditems = StudentRecords;
    if (Orderreplaced)
    {
        switch (DataOrder)
        {
            default:
                arrangeditems = StudentRecords.OrderBy(s => s.GetType().GetProperty(DataOrder).GetValue(s, null)).ToList();
                break;
        }
    }
    Orderreplaced = false;
    return new ObservableCollection<RandomListSort>(arrangeditems);
}

public override void Refresh()
{
    Refresh();
    StudentRecords = RandomListSort();
}

A: There is no property you set for sorting description. If not you are doing it programatically better set it in the XAML it self as shown below.
<CollectionViewSource
        Source="{Binding StudentRecords}">
<CollectionViewSource.SortDescriptions>
        <scm:SortDescription PropertyName="your Propery from bound source" />
    </CollectionViewSource.SortDescriptions>
</CollectionViewSource>

For more documentation look into below link.
https://msdn.microsoft.com/en-us/library/ms742542(v=vs.110).aspx


text:
Q: Does the Iron Bomber's projectile travel faster than the stock? For some reason I can't quite place my hand on, the Iron Bomber's projectile seems to travel much faster than a normal pill the stock grenade launcher.
Is this a placebo? Does the Iron Bomber's projectile travel faster than the Grenade Launcher, or is the speed still the same?

A: The projectile speed is the same.

It is most likely that you just feel that way because the grenade from Iron Bomber bounces less than the stock Grenade Launcher.


text:
Q: Is there an "if" function in Excel for auto-filling a user ID number based on a separate user ID number that's already been found? I am trying to auto-fill a person's user ID number based on repeat information in the table. I have an excel sheet with people that have two user ID #'s so I would like to auto-fill the second number based on the first. i.e. I have 3 columns. Column 1 = name, column 2 = user ID #1 and column 3 = user ID #2. So if Gerald = 3 and 5, how do I get excel to auto-fill the user ID #2 as 5 every time column 2 = 3. It's the same data repeated over and over. As in I have multiple Gerald entries and I want it to auto-fill everytime he comes up based on his first user ID#. It's all in the same sheet so I don't have to switch tabs or anything.
I've tried going through "if" functions but I don't know how to make the right formula.

A: You can use the VLOOKUP function in Excel to achieve what you're trying to do.
The VLOOKUP function searches for a value in the first column of a table and returns the value in the same row from a specified column. In your case, you want to search for the first user ID # in column 2, find the corresponding name in column 1, and return the second user ID # in column 3.
try this formula
=VLOOKUP(B2,A2:C10,3,FALSE)
This formula assumes that your data starts in cell A2 and goes until cell C10. The first argument (B2) is the value you're searching for, which is the first user ID # in column 2. The second argument (A2:C10) is the range that contains the data you want to search in. The third argument (3) is the column number from the range that you want to return a value from. In this case, it's the third column, which contains the second user ID #. The fourth argument (FALSE) specifies that the VLOOKUP function should perform an exact match search.
You can copy this formula down to the rest of the cells in column 3 to auto-fill the second user ID # based on the first.
This formula assumes that there are no duplicates in the first user ID # column (column 2). If there are duplicates, the formula will only return the first match it finds.


text:
Q: VS2019 installer disappears with no trace VS2019 installer disappears with no trace
Have tried the below link
https://learn.microsoft.com/en-us/visualstudio/install/troubleshooting-installation-issues?view=vs-2019

A: Problem solved after removing the NODE_OPTIONS environment variable. it took more than week to found the solution for this issue.
https://developercommunity.visualstudio.com/content/problem/224084/installer-wont-show-up-when-i-have-node-options-va.html


text:
Q: Is it possible to change cpanel account location/path to different dir? Does anyone know how to change location/path of cpanel account using PHP?
Basically will have a multi-brand store with SSL certs and we want this pointed to one location/directory in root.
I was able to achieve this with a small tweak in httpd.conf file, but we want to automate this and have a php plugin.
Any idea?
Note: We have dedicated servers and it's possible + tested.
Maybe with the help of cPanel API or something?

A: I'm not aware of anything other than tweaking the httppd.conf file.  However, perhaps you could build a post account creation script that hooks into the cpanel account setup. You can view the docs on WHM. I believe you will be after the postwwwacct script.
http://docs.cpanel.net/twiki/bin/view/SoftwareDevelopmentKit/WebHome
I'm not sure your reasoning for moving these to root, unless you have disk partitions set up in such a way that the home directory won't do, but perhaps using a filesystem junction point / link to that account folder would do the trick.

A: You can do that over CPanel API
Look at this as starting point
https://documentation.cpanel.net/display/SDK/Guide+to+the+LiveAPI+System
And with PHP over API functions you can make changes to account location/path similar as you would do that through WHM with Home »Account Functions »Rearrange an Account... But that is only if you have more then one partition. For other methods as Joe Meyer said only tweak httpd.conf or use simbolic links to redirect folders and files (which is most unsecure method)...


text:
Q: how to figure out captive portal URL in java I am trying to update an app that I wrote for Android that will automatically log a user into a captive portal at my university. The app worked fine last year with the portal URL hard coded in, however this year that won't work because they changed the server URL, I know what the URL is, so I simply changed it in my program ... which sort of works
There are two main problems, for me, with this approach.

*

*hard coding is a pain in the ass to do every year, I also want to be able to make  it future proof, so that hard coding the URL won't be necessary

*for some unexplainable reason there are actually buildings on campus that will direct to the OLD authentication server, it truly boggles my mind why it would do that

I would like to be able to make an HTTP request and get the URL of the captive portal that is redirected to, how is that done?

A: Captive portals generally will intercept users' HTTP requests and issue a "fake" redirect to the portal's authentication page. Or they can simply replace the actual response with the login page.
If yours is a redirect-to-login, then simply do something like trying to load http://google.com, which can reasonably be expected to be truly available for at least the next few years. If the response comes in as a redirect to some totally different site, the redirect url is highly likely to be the portal's login page.
If it's a replace-the-response-with-login, then you should try to contact a known page with some known content, and see what you get back. if the response you got doesn't match you should have gotten, then you've gotten the login page and can try tearing apart the response and finding the login form via DOM operations.

A: Captivate portals uses 2 methods.

*

*as described above. http redirect so the gateway takes you to another address.

*ICMP - sending "better route" message
Still from my exprience on cases where non simple redirect happens the approach of expecting the redirect won't work.


text:
Q: Google Spreadsheet opening the last edited cell using script Using the following code allows the last edited cell to open when reopening a google spreadsheet.
function setTrigger() {
  var ss = SpreadsheetApp.getActive();
  ScriptApp.newTrigger("myFunction").forSpreadsheet(ss).onEdit().create();
}

function myFunction() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var sName = sheet.getName();
  var currentCell = sheet.getActiveCell().getA1Notation();
  UserProperties.setProperty("mySheetName", sName);
  UserProperties.setProperty("myCell", currentCell);
}

function onOpen() {
  var lastModifiedSheet = UserProperties.getProperty("mySheetName");
  var lastModifiedCell  = UserProperties.getProperty("myCell");
  SpreadsheetApp.getActiveSpreadsheet().getSheetByName(lastModifiedSheet).getRange(lastModifiedCell).activate();
}

I have a cell which has
=today()

Which updates so the code doesn't open the last row of my spreadsheet, but opens in the cell that updates with today().
How would I update the script to open the spreadsheet at my last edited cell in the last row of the spreadsheet?

A: Can you try this:
function myFunction() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var sName = sheet.getName();
  var currentCell = sheet.getActiveCell().getA1Notation();
  var temp = "";
  if (currentCell != "A1") {temp = currentCell;}
 UserProperties.setProperty("mySheetName", sName);
  UserProperties.setProperty("myCell", temp);
}

I added a temp variable and am doing a check (assuming only A1 has the today() function) before updating temp. Seems to work.


text:
Q: Akka Http Swagger setup - 406 application/octet-stream when referencing other file I'm trying to set up Swagger in a Scala project and running into issues referencing schemas in another file.
My folder structure for this is (the swagger folder has all the swagger-ui stuff):

*

*docs

*

*swagger.yml

*models

*

*test_model.yaml

*swagger

*

*index.html

*swagger-ui.css etc....

My swagger file references the index.html file and it loads fine.  All schemas that I define inside the swagger.yml file are loading and showing up correctly.  However, when I try to reference a file inside models such as test_model.yaml.  I get a 406 error on it loading the test_model.yaml file
Resource representation is only available with these types:
application/octet-stream

My akka set up for the routes for this is:
path("swagger") {
      getFromFile("docs/swagger/index.html") } ~
      getFromDirectory("docs/swagger") ~
      getFromDirectory("docs")

The first two seem to do what I expect.  My swagger ui page loads correctly and all of my routes/schemas defined in swagger.yml load fine.  However, when I use
$ref: './models/test_model.yaml#/components/schemas/Test'

It throws a 406 error when trying to load the test_model.yaml file.  The schemas are all defined correctly and if I keep them defined in the original swagger.yml file and reference them inside there it works fine.  It is only when I put them into an outside file.

A: Ok I finally got it working.  I had to add a custom ContentResolver for these routes to map the type for these files to application/yaml instead of the default resolver mapping them to Octet.


text:
Q: Edit the catalog page for specific category I am using Magento 1.8.1 and I am working on SEO. I need to put micro-data (schema code) for some category on that page only. I don't understand how to put the data for specific page because if I put any data in template page, it will update on all categories.
For example: I need to put data only for this page.

A: As I understand it, you want to add some code to only appear on a specific category view. You can add Javascript to the description field in the General Information tab of the category:

You can also add a template to before_body_end block of the page:

You can add additional layout directives here. This layout update:
<reference name="before_body_end">
    <block type="core/template" name="seocode" template="seocode/seocode.phtml" />
</reference>

means render out your custom block (seocode) and template file (seocode.phtml) in the before_body_end block. The before_body_end block can be found in the page templates; i.e. page/1column.phtml or page/2columns-left.phtml.


text:
Q: JPA Hibernate - Mapping Embedded Collections to a Single Table I have a table with lot of fields such as
Account
OrderNo
Term
LegNo
LegSymbol
LegSymbolType
LegExchangeType
etc etc
The primary key of the above table is a composite key comprising of Account, OrderNo & LegNo
The data in the DB would look  something like this
1234 1 2 1 AAA BBB CCC
1234 1 2 2 DDD EEE FFF
The bolded ones are Account,Order,LegNo respectively.
While designing the entity for the above table, we want to group all the Leg related information (All bolded columns ) in a separate class and all other info in a entity
So, the main Order Entity will contain the Embedded object Leg. (I assume Leg wont be defined as an entity since it is not a separate table as such).
@Entity
@Table(name="xxx")
public class Order implements Serializable {

    ... All order specific fields & it's getters/setters

}

@Embeddable
public class Leg implements Serializable {

  private long legNo;
  private String legSymbol;

  ...
  ...
}

I assume Order Entity would hold the account, orderNo,Term info and the OrderLeg embedded object would the other info like the above.
We can have multiple legs for the same order as shown in the above record. Hence we might need to have collection of legs inside the Order entity.
Can we achieve this functionality as we have only one table in place ? We cannot change the schema of the table or create a new table as it is out of our control.
I tried using the @ElementCollection in the Order Entity on List of Legs but it looks like, when I try to persist a new order, the Leg details are not being taken as part of the query.
If I have hibernate.hbm2ddl.auto=create as part of the persistence.xml, it deletes the existing schema and alters the existing order table to hold only the order infos and creates a separate leg table to hold the leg infos which is not desired.
@Entity
@Table(name="xxx")
public class Order implements Serializable {

**@ElementCollection
private List<Leg> a = new ArrayList<Leg>();**
}

The values set to Leg class such as LegNo, LegSymbol etc  is not included in the insert query at all and I always get an exception since the LegNo is a mandatory field in the table.
Please advise..


text:
Q: dnsmasq does not hand out IP addresses I am trying to learn about networking, specifically, what I am currently trying is creating a private network that runs behind a NAT that connects to my main router.
The way I've though of it is as follows:
                                 +---------------------------------------------------+
                                 |10.0.0.0/24                                        |
                                 |                               +-------+           |
                          +------+---------------------------+   |Switch |   +-----+ |
                          |Raspberry Pi                      |   |       +---+     | |
                          |                                  |   |       |   +-----+ |
                          |                              eth1+---+       |           |
    +-----------------+   |                          10.0.0.1|   |       |           |
    |Router           |   |                                  |   |       |   +-----+ |
    |192.168.100.1    +---+eth0              dnsmasq settings|   |       +---+     | |
+---+dhcp:            |   |192.168.100.5   range: 10.0.0.2/24|   |       |   +-----+ |
    |192.168.100.2/24 |   |              gateway:    10.0.0.1|   +-------+           |
    |                 |   |                                  |                       |
    +-----+------+----+   +------+---------------------------+                       |
          |      |               |                                                   |
          |      |               +---------------------------------------------------+
          |      |
          |      +------------------------------------+ Other devices
          |
          |       +---------------+
          |       |pi-hole        |
          +-------+192.168.100.3  |
                  |               |
                  +---------------+

Now I think I've set up the raspberry pi correctly. The configs are as follows:
/etc/dnsmasq.conf
domain=local.pi
local=/local.pi/

no-hosts
addn-hosts=/etc/hosts.d

localise-queries

no-poll
no-resolv
cache-size=10000

log-async
log-queries=extra
log-facility=/var/log/dnsmasq/dnsmasq.log

local-ttl=2

server=192.168.100.3
server=9.9.9.9

domain-needed
bogus-priv

interface=eth1
dhcp-authoritative
dhcp-range=10.0.0.2,10.0.0.254,1h
dhcp-option=option:router,10.0.0.1
dhcp-leasefile=/etc/dhcp.leases

However, the dnsmasq doesn't seem to hand out any ip addresses, as evident by the logs:
Sep 30 22:37:25 dnsmasq[3296]: started, version 2.76 cachesize 10000
Sep 30 22:37:25 dnsmasq[3296]: compile time options: IPv6 GNU-getopt DBus i18n IDN DHCP DHCPv6 no-Lua TFTP conntrack ipset auth DNSSEC loop-detect inotify
Sep 30 22:37:25 dnsmasq-dhcp[3296]: DHCP, IP range 10.0.0.2 -- 10.0.0.254, lease time 1h
Sep 30 22:37:25 dnsmasq[3296]: using nameserver 9.9.9.9#53
Sep 30 22:37:25 dnsmasq[3296]: using nameserver 192.168.100.3#53
Sep 30 22:37:25 dnsmasq[3296]: using local addresses only for domain local.pi
Sep 30 22:37:33 dnsmasq-dhcp[3296]: no address range available for DHCP request via eth1

That last message continually repeats as clients request an IP. The following is the output of tcpdump:
# tcpdump -v
tcpdump: listening on eth1, link-type EN10MB (Ethernet), capture size 262144 bytes
23:14:53.372604 IP (tos 0x0, ttl 64, id 17534, offset 0, flags [none], proto UDP (17), length 384)
   0.0.0.0.bootpc > 255.255.255.255.bootps: BOOTP/DHCP, Request from b8:27:eb:64:2b:f2 (oui Unknown), length 356, xid 0x37bc3a64, secs 11906, Flags [none]
   Client-Ethernet-Address b8:27:eb:64:2b:f2 (oui Unknown)
   Vendor-rfc1048 Extensions
     Magic Cookie 0x63825363
     DHCP-Message Option 53, length 1: Discover
     Client-ID Option 61, length 7: ether b8:27:eb:64:2b:f2
     SLP-NA Option 80, length 0""
     NOAUTO Option 116, length 1: Y
     MSZ Option 57, length 2: 1472
     Vendor-Class Option 60, length 56: "dhcpcd-6.11.5:Linux-4.14.34-hypriotos-v7+:armv7l:BCM2835"
     Hostname Option 12, length 14: "test-client"
     T145 Option 145, length 1: 1
     Parameter-Request Option 55, length 15:
       Subnet-Mask, Classless-Static-Route, Static-Route, Default-Gateway
       Domain-Name-Server, Hostname, Domain-Name, MTU
       BR, NTP, Lease-Time, Server-ID
       RN, RB, Option 119
23:15:07.057241 IP (tos 0x0, ttl 64, id 26091, offset 0, flags [none], proto UDP (17), length 384)
   0.0.0.0.bootpc > 255.255.255.255.bootps: BOOTP/DHCP, Request from 00:e0:4c:23:c2:22 (oui Unknown), length 356, xid 0x1b0502bb, secs 8250, Flags [none]
   Client-Ethernet-Address 00:e0:4c:23:c2:22 (oui Unknown)
   Vendor-rfc1048 Extensions
     Magic Cookie 0x63825363
     DHCP-Message Option 53, length 1: Discover
     Client-ID Option 61, length 7: ether 00:e0:4c:23:c2:22
     SLP-NA Option 80, length 0""
     NOAUTO Option 116, length 1: Y
     MSZ Option 57, length 2: 1472
     Vendor-Class Option 60, length 56: "dhcpcd-6.11.5:Linux-4.14.34-hypriotos-v7+:armv7l:BCM2835"
     Hostname Option 12, length 14: "gateway"
     T145 Option 145, length 1: 1
     Parameter-Request Option 55, length 15:
       Subnet-Mask, Classless-Static-Route, Static-Route, Default-Gateway
       Domain-Name-Server, Hostname, Domain-Name, MTU
       BR, NTP, Lease-Time, Server-ID
       RN, RB, Option 119#
^C
2 packets captured
2 packets received by filter
0 packets dropped by kernel

What am I missing?
The end goal is that all those in the 10.0.0.0/24 range will connect to the rest of the internet behind a nat.


text:
Q: Error when calling quit() on a QCoreApplication within a QThread In an effort to create a Qt event loop in a separate thread, from within a DLL which is called by a main application written in Java, I have done the following, based on a suggestion I read here, which works rather well:
// Define a global namespace. We need to do this because the parameters
// passed to QCoreApplication must have a lifetime exceeding that of the
// QCoreApplication object
namespace ToolThreadGlobal
{
    static int argc = 1;
    static char * argv[] = { "MyVirtualMainApplication.exe", NULL };
    static QCoreApplication *coreApp = nullptr;
    static ToolThread *toolThread = nullptr;
};

//! The ToolThread class differs from a standard QThread only
//! in its run() method
class ToolThread : public QThread
{
    //! Override QThread's run() method so that it calls
    //! the QCoreApplication's exec() method rather than
    //! the QThread's own
    void run() { ToolThreadGlobal::coreApp -> exec(); }
};

class ThreadStarter : public QObject
{
    Q_OBJECT

public:
    //! Constructor
    ThreadStarter()
    {
        // Set up the tool thread:
        if (!ToolThreadGlobal::toolThread)
        {
            ToolThreadGlobal::toolThread = new ToolThread();
            connect(ToolThreadGlobal::toolThread, &ToolThread::started,
                    this, &ThreadStarter::createApplication, Qt::DirectConnection);
                    // The thread's 'started' event is emitted after the thread
                    // is started but before its run() method is invoked. By
                    // arranging for the createApplication subroutine to be
                    // called before run(), we ensure that the required
                    // QCoreApplication object is instantiated *within the
                    // thread* before ToolThread's customised run() method
                    // calls the application's exec() command.
            ToolThreadGlobal::toolThread->start();
        }
    }

    //! Destructor
    ~ThreadStarter()
    {
        // Ensure that the thread and the QCoreApplication are cleanly
        // shut down:
        ToolThreadGlobal::coreApp -> quit();
        delete ToolThreadGlobal::coreApp;
        ToolThreadGlobal::coreApp = nullptr;
        delete ToolThreadGlobal::toolThread;
        ToolThreadGlobal::toolThread = nullptr;
    }

    //! Function to return a pointer to the actual tool thread:
    ToolThread* getThread() const { return ToolThreadGlobal::toolThread;  }

private:
    //! Create the QCoreApplication that will provide the tool
    //! thread's event loop
    /*! This subroutine is intended to be called from the tool
        thread itself as soon as the thread starts up.
    */
    void createApplication()
    {
        // Start the QCoreApplication event loop, so long as no
        // other Qt event loop is already running
        if (QCoreApplication::instance() == NULL)
        {
            ToolThreadGlobal::coreApp = new QCoreApplication(ToolThreadGlobal::argc,
                                                             ToolThreadGlobal::argv);
        }
    }
};

To use this, a subroutine called from the main Java applications' thread just needs to create a ThreadStarter object
which will automatically create a ToolThread with a QCoreApplication running inside it:
itsThreadStarter = new ThreadStarter();
itsToolThread = itsThreadStarter -> getThread();

We can then instantiate a QObject class in the usual way, move it to the thread and call its methods asynchronously using QMetaObject::invokeMethod:
itsWorker = new Worker();
itsWorker -> moveToThread(itsToolThread);

QMetaObject::invokeMethod(itsWorker, "doSomethingInteresting");

When we're done, we just delete the ThreadStarter object and everything is cleaned up nicely. Apart from the annoying message saying
WARNING: QApplication was not created in the main() thread

on startup, it seems to meet all my requirements.
Except… (and here, at last, is my question).
Occasionally - and without any pattern that I've been able to discern so far - I get an error during the shutdown process. Usually it occurs at the line
        delete ToolThreadGlobal::coreApp;

but sometimes at the line
    ToolThreadGlobal::coreApp -> exec();

(which of course is executed in the thread's run() method and doesn't return until after ToolThreadGlobal::coreApp -> quit(); has been fully executed).
Often the error message is a simple access violation; sometimes it's a rather more involved:
ASSERT failure in QObjectPrivate::deleteChildren(): "isDeletingChildren already set, did this function recurse?", file ..\qtbase\src\corelib\kernel\qobject.cpp, line 1927

I assume it's because, once I issue the quit() command to the QCoreApplication, I should be waiting for a little while for it to close down the event loop properly before deleting it - just as one would usually call quit() and then wait() on an ordinary QThread before deleting it. However, QCoreApplication doesn't seem to have the equivalent of a wait() command, and I can't implement a QTimer to force a delay because it wouldn't work once I've closed down the event loop with quit(). I'm therefore at a loss what to do. I have an inkling that, as QCoreApplication is a QObject, I could call its deleteLater() method but I can't see where I should call it from.
Is there an expert out there who understands the ins and outs of QCoreApplication and QThread well enough to suggest a solution to this? Or is there a fundamental flaw in the way that I have designed this?

A: This seems to have worked for me...
Firstly, I add a static 'cleanup' function to my global namespace:
namespace ToolThreadGlobal
{
    static int argc = 1;
    static char * argv[] = { "MyVirtualMainApplication.exe", NULL };
    static QCoreApplication *coreApp = nullptr;
    static ToolThread *toolThread = nullptr;
    static void cleanup() { coreApp->deleteLater();  coreApp = nullptr; }
};

Then, from my ThreadStarter::createApplication slot I connect the QCoreApplication's aboutToQuit signal to it:
    void createApplication()
    {
        // Start the QCoreApplication event loop, so long as no other Qt event loop
        // is already running
        if (QCoreApplication::instance() == NULL)
        {
            ToolThreadGlobal::coreApp = new QCoreApplication(ToolThreadGlobal::argc,
                                                             ToolThreadGlobal::argv);
            connect(ToolThreadGlobal::coreApp, &QCoreApplication::aboutToQuit,
                    ToolThreadGlobal::cleanup);
        }
    }

Then the 'ThreadStarter' destructor is reduced to just five lines (including the addition of calls to QThread::quit() and QThread::wait() which should have been there the first time around):
    ~ThreadStarter()
    {
        // Ensure that the thread and the QCoreApplication are cleanly shut down:
        ToolThreadGlobal::coreApp -> quit();
        ToolThreadGlobal::toolThread -> quit();
        ToolThreadGlobal::toolThread -> wait();
        delete ToolThreadGlobal::toolThread;
        ToolThreadGlobal::toolThread = nullptr;
    }

When the ThreadStarter destructor calls QCoreApplication::quit(), the QCoreApplication calls the cleanup function while its event loop is still running. This schedules the QCoreApplication to delete itself once it is good and ready, and in the meantime resets the global pointer to NULL so that the rest of the application knows that a new QCoreApplication can be instantiated when needed.
I guess this leaves a very small risk that there could be a conflict if the main application immediately creates a new QCoreApplication and tries to run exec() on it while the old QCoreApplication is still in the process of cleaning itself up. I don't think that is likely to happen in the context where I'm using it.


text:
Q: Not taking reference from node_modules while creating angular 6 from VS-2017 I have created one angular 6 application using visual studio 2017.

Here is the screenshot for my visual studio project (Angular).

As you can see I have added one new component and service named as Todo.
When I am adding todo.service.ts I need to add some references of angular modules so that I can avail HttpClient, HttpHeaders, HttpParams , catchError, tap, map features.
But here seems like I am not able to refer the path to the angular module package which we can easily refer while creating project using cli command because there we have node_modules folder where we have all packages and importing file using below command
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { catchError, tap, map } from 'rxjs/operators';
but here in VS-2017 I am not able to refer the package.
It give me an error like "can not find modules"
Here is the screen shot for the same.

Please suggest me what to do here how to refer to angular packages while creating angular project in VS-2017.
Note there is no error in referring to the package because the same code is working while creating project using angular CLI command.

A: Navigate to directory where package.json file is placed
Run
npm install

If still the issue persists
Install required package using npm:
npm i <package-name> --save

A: Do this ,
Replace /common/http to common only
Same for operators

A: I got the solution..

*

*You can rename or deleted the existing node_modules folder.

*Then create new project using angular-cli command.

*Then paste the copy the node_modules(step 2) to my .NET folder (step1).

Now, it start working.
Thanks for your all suggestion guys..


text:
Q: Custom room Socket.io NodeJS I am making an application with sockets and the need arises to broadcast information, but only to people who are inside a room.
This is my code from the server.ts
// Dependencies
import express from 'express'
import http from 'http'
import socket from 'socket.io';
import {connect, disconnect, orderChanged} from './sockets/socket';
import {config} from 'dotenv';

config ();

// Main class
export default class server {

    _private static instance: server
    public app: express.Application
    public port: number
    http: http.Server private
    public io: socket.Server

    // Initialize variables and methods
    // Singleton pattern implementation
    private constructor () {

        this.app = express ()
        this.port = Number (process.env.SRV_PORT)
        this.http = new http.Server (this.app)
         this.io = new socket.Server (this.http, {
            cors: {
                origin: true,
                credentials: true
            }
        })
        this.listenSockets ();
    }

    // Return the instance running Singleton pattern
    public static get instance () {
        returns this._instance || (this._instance = new Server ())
    }

    // Method to start the server
    start (callback: any) {
        this.http.listen (this.port, callback)
    }

    private listenSockets (): void {
        console.log ('Listening Sockets');

        this.io.on ('connection', client => {
            console.log ('Connected to room', client.rooms, '-', client.id);
            // User disconnected
            disconnect (client);
            connect (client);
        });
    }
}

Since node starts, an instance is created in DP Singleton and the socket listener is launched
When an operation happens in the database, anywhere in the app, I send it to call and send information to the front-end which is correctly received by the front-end and does what it has to do. Example url / edit-products
import server from '../core/server';

// Socket broadcast, new information
const __id = String (req.headers.id);
const updatedData = await getNewData (__id);
Server.instance.io.emit ('data changed', updatedData);

The problem is that this information is sent indiscriminately to all users connected to the socket. Now, I have a unique ID that brings multiple users together in a MongoDB model. You could use that ID to broadcast only to users with that ID. There is a logic that implies that if the user connects from Mexico, add it to an Array of people in MongoDB, otherwise it will add it to another MongoDB document, then they are two different IDs.
I would love the room to be that ID.
I saw that I could use the socket's join () method, but that function derives from the connected client, not from the server itself. I try to issue the information like this
// Socket broadcast, new information
const __id = String (req.headers.id);
const updatedData = await getNewData (__id);
Server.instance.io.in (updatedData._id) .emit ('data changed', updatedData);

But at no point did I set up that "ROOM". When the user login, he could add it but I don't know how to create a custom room, he tried something like this
const user = await UserModel.find (_data);
Server.instance.io.join (user.channel._id);

But that function within io does not exist.
It exists this way, but it doesn't work for me
Server.instance.io.on ('user-join', (socket: Socket) => {
   console.log (plug);
   socket.join (uuid);
});
Server.instance.io.emit ('user join');

What could I do?

A: .join() is a method on an individual socket.  That's how you use it as socket.join(roomName).  When the first user joins a room, the room is created automatically and other users can also join it.  When the last user leaves the room, the room is removed automatically from the server.  So, you join a user's socket to a room - you don't join something to the server.

Similarly, when you tried this:
Server.instance.io.on ('user-join', (socket: Socket) => {
   console.log (plug);
   socket.join (uuid);
});

That doesn't work because you don't listen for incoming messages from a socket on the server (except for the connection message - which introduces the socket object).  You listen for incoming client messages on a socket itself:
Server.instance.io.on ('connection', (socket: Socket) => {
    socket.on('user-join', () => {
        // you will have to find the room name that goes with this socket
        socket.join(someRoomName);
    });
});

Also, note that this code:
private listenSockets (): void {
    console.log ('Listening Sockets');

    this.io.on ('connection', client => {
        console.log ('Connected to room', client.rooms, '-', client.id);
        // User disconnected
        disconnect (client);
        connect (client);
    });
}

looks problematic.  Why would you disconnect a client when they connect?  You don't show those functions disconnect() and connect() so it's unclear what they actually do - I would guess they keep track of connected clients somehow.  If you're just trying to clean up any state that might have been previously left hanging, then you should be doing something like this:
private listenSockets (): void {
    console.log ('Listening Sockets');

    this.io.on ('connection', client => {
        console.log ('Connected to room', client.rooms, '-', client.id);
        client.on('disconnect', () => {
            // User disconnected
            disconnect(client);
        });

        // user connected now
        connect(client);
    });
}

You don't have to worry about inaccurate housekeeping on whether a socket is connected or not.  You will always get a disconnect event for a socket when it disconnects.  This is for two reasons.  For a browser window that closes or a page that the user navigates away from, the browser cleans up all objects associated with that page, including the open socket.io connection.  This will always close the socket and cause a disconnect event.  Second, socket.io uses ping and pong messages to regularly check if an existing connection is still working.  If it's not, it will get disconnected.  The client may or may not retry to open a new connection depending upon the circumstance.  But, any disfunctional connection (one that isn't respond to ping messages) will get closed by the server and a disconnect event will occur for that too.  So, those two circumstances make sure that a disconnect event always happens.

Server.instance.io.emit ('data changed', updatedData);  The problem is that this information is sent indiscriminately to all users connected to the socket.

This sends to all users connected to your server and is how it was designed.
To send to a single socket, you would use:
 socket.emit(...);

where socket is what you're code calls client, the object you get from the connection event.
To send to all sockets who have joined a room, you would use:
 io.in(roomName).emit(...)

where io is the socket.io server instance.
And, there are many, many more variations of .emit() depending upon exactly what you're trying to send to.

Now, I have a unique ID that brings multiple users together in a MongoDB model. You could use that ID to broadcast only to users with that ID. There is a logic that implies that if the user connects from Mexico, add it to an Array of people in MongoDB, otherwise it will add it to another MongoDB document, then they are two different IDs. I would love the room to be that ID.

I don't completely follow what you're trying to do, but it seems like inside your connect(client) function, you could just call client.join(uniqueIDForMultipleUsers) and that would create a room with this uniqueID and add this client to that room.  In the future, you can send to everyone in that room with io.in(uniqueIDForMultipleUsers).emit(...).

But at no point did I set up that "ROOM". When the user login, he could add it but I don't know how to create a custom room, he tried something like this

You don't create rooms manually.  You just use socket.join(roomName) and the socket.io infrastructure automatically creates the room if it doesn't already exist.  Similarly when the last socket in a room either leaves the room or disconnects, the room is automatically removed.  So you just don't have to manage the room creation or deletion yourself.  In fact, a room object is not something you ever deal with directly - it's a housekeeping item inside of the socket.io server that contains a list of sockets that are currently in the room.  A socket can be in as many rooms as it wants to be.  You use these on the server:
socket.join(roomName);     // add a client's socket to a room
socket.leave(roomName);    // remove a client's socket from a room
io.in(roomName).emit(...); // broadcast a message to every socket in a room

What is sometimes a bit confusing about the above logic is that socket.join() and socket.leave() are socket methods, but they actually modify a data structure in the server (where the list of rooms/sockets are kept).  For whatever reason, that's just how they chose to originally design the API.  Logically, it's more like io.join(socket, roomName) since it's modifying something on the server.  But, since the socket knows the server object it's part of, they can leave that off and just do socket.join(roomName).


text:
Q: In Spring, does @Controller accept requests only after completing any other beans' @PostConstruct methods? I have to initialize something with DAO using @PostConstruct.
And before completing it, @Controller SHOULD NOT accept any request.
Is it default behaviour? Or need any other configuration?


text:
Q: Embedding Times New Roman in XSL-FOP I recently discovered that the commercial printing company that my office uses does not have referenced fonts on their printers.  The PDFs I produce using the Apache FOP Library by default set fonts to referenced during the XSL-FO transformation.  Three of the standard fonts (Times New Roman, Courier and DejaVu) will not embed despite my efforts to force them. I have tried everything on this link and even the older method described here. Thank you in advance for any input you can provide.
Example of my attempts to modify the fop.xconf

  <afp-font name="Times Roman" type="raster" codepage="T1V10500" encoding="Cp500">
    <afp-raster-font size="6" characterset="C0N20060" base14-font="TimesRoman"/>
    <afp-raster-font size="7" characterset="C0N20070" base14-font="TimesRoman"/>
    <afp-raster-font size="8" characterset="C0N20080" base14-font="TimesRoman"/>
    <afp-raster-font size="9" characterset="C0N20090" base14-font="TimesRoman"/>
    <afp-raster-font size="10" characterset="C0N20000" base14-font="TimesRoman"/>
    <afp-raster-font size="11" characterset="C0N200A0" base14-font="TimesRoman"/>
    <afp-raster-font size="12" characterset="C0N200B0" base14-font="TimesRoman"/>
    <afp-raster-font size="14" characterset="C0N200D0" base14-font="TimesRoman"/>
    <afp-raster-font size="16" characterset="C0N200F0" base14-font="TimesRoman"/>
    <afp-raster-font size="18" characterset="C0N200H0" base14-font="TimesRoman"/>
    <afp-raster-font size="20" characterset="C0N200J0" base14-font="TimesRoman"/>
    <afp-raster-font size="24" characterset="C0N200N0" base14-font="TimesRoman"/>
    <afp-raster-font size="30" characterset="C0N200T0" base14-font="TimesRoman"/>
    <afp-raster-font size="36" characterset="C0N200Z0" base14-font="TimesRoman"/>
  </afp-font>

A: If they do not have to receive a "pdf" per se, you can convert it to PCL, which is nothing more than a description of how to print the file. According to wikipedia it is the "DeFacto standard for printer languages." Ghostscript can do this for you http://www.ghostscript.com/ its free open source etc. etc...
http://sourceforge.net/projects/ghostscript/forums/forum/5451/topic/3096129 -- helpful instructions on how to do the pdf to pcl conversion :)
I hope this is helpful, i feel your pain :)


text:
Q: bigquery longterm storage table list As per the GCP documentation :

Long-term storage:
If a table is not edited for 90 consecutive days, the price of storage for that table automatically drops by approximately 50 percent. There is no degradation of performance, durability, availability, or any other functionality when a table is considered long term storage.

Is there any way to list out all the tables which falls under this criteria in a Bigquery dataset?

A: One way is to use some Bash magic. I've knocked this up quickly using Cloud Shell, which has jq pre-installed. It works by:

*

*Listing all datasets

*Listing each table in each dataset

*For each table, call bq show to grab the metadata information about the table

*Using jq pull out the id and numLongTermBytes from each table

*The numerical value for numLongTermBytes is how much storage is in long term. If it's 0, then it's active storage.

Not sure how this would work with partitions & clustered tables (you'll need to test), but should be enough to get you started at least. You could of course write a neater Python script or something, but I like the 'simplicity' of Bash :)
Noted that this is somewhat of a fragile/brittle solution.
bq ls --format=json | jq -r '.[].id' | xargs -n 1 -P 4 -i bq ls --format=json {} | jq -r '.[].id' | xargs -n 1 -P 4 -i bq show --format=json {} | jq -r '.id + "," + .numLongTermBytes'


text:
Q: Insert a csv file into Azure SQL from an Azure Blob I have an asp.net (c#) site in Azure and an accompanying Azure SQL database.  I need to upload 1gb+ csv files and get them parsed and into my Azure SQL database.  I can get the csv files into an Azure blob.  I now have the URL to the blob (newGuid.txt).
Either from SQL or from the web app, how do I parse this csv and get it inserted into my Azure SQL database? (the csv has 36 columns if that helps)
I can't figure out how to reference the URL to use SqlBlukCopy.  I initially thought I would BULK INSERT but Azure SQL doesn't allow that.  I can't download the files locally and use BCP for each one.

A: I agree this is an old question, but as gets traction, here is the answer:
You can use Azure Data Factory to move data from Blob Storage (and many more data sources) to Azure SQL Database (and many other data sinks).
There is nothing simpler today to achieve your goal. Here are some tutorials:

*

*Move data by using Copy Activity

*Move data to and from Azure Blob

*Move data to and from SQL Server running on-premises or on Azure VM (IaaS)
You can configure a data pipeline to just run once. Or run on specific time, or run on a schedule. You can make it copy single file, or using file pattern to get more files, etc.


text:
Q: react-router only goes to index route I'm running into a situation in react where my application on recognizes the index route.  my code in my app.js looks like this:
import React from 'react'

import { render } from 'react-dom'

import { Router, Route, Link, IndexRoute } from 'react-router'

class App extends React.Component {
    render() {
        return (

                Hello There App

        );
    }
}

class About extends React.Component {
    render() {
        return (

                Hello There About

        );
    }
}

class Error extends React.Component {
    render() {
        return (

                Hello There Error

        );
    }
}

React.render((
  <Router>
    <Route path="/" component={App}>
      <IndexRoute component={About}/>
      <Route path="*" component={Error}/>
    </Route>
  </Router>
), document.body)

There were some similar links I checked out:
React Router only recognises index route
and
React router only works with root path
But these didn't push me along.  I'm running an express server and I have a route there too:
app.use(ecstatic({ root: __dirname + '/public', handleError:true }));
app.get('/', function(request, response){
    response.sendfile("./public/index.html");
});

With or without the app.get("/"... I run into the same issue.  It's also worth noting that I tried it this way as well: https://github.com/rackt/react-router but my routes didn't work that way either.  I'm going on 4 days with this issue with endless research, hopefully one of you can point me in the right direction.
package.json:
"dependencies": {
    "body-parser": "~1.14.1",
    "browserify": "^10.2.6",
    "cors": "^2.7.1",
    "ecstatic": "~0.8.0",
    "express": "~4.0.0",
    "history": "^1.13.1",
    "mongoose": "~4.2.6",
    "react": "~0.13.3",
    "react-dom": "^0.14.3",
    "react-router": "^1.0.0",
    "reactify": "^1.1.1",
    "socket.io": "^1.3.7",
    "uglify-js": "^2.4.24",
    "watchify": "^3.2.3"
  },
  "license": "public domain",
  "devDependencies": {
    "babelify": "^6.1.2"
  }

A: Make your routes look like:
<Router>
  <Route path="/" component={App}>
    <IndexRoute component={Index}/>
    <Route path="*" component={Error}/>
  </Route>
</Router>

the other part you are missing is { this.props.children } in your app component, where the nested route components should be mounted.
Check out the master-detail example, where the NotFound route is used.
And on your server I would redirect everything * to index.html not only /:
app.get('*', function(request, response){
    response.sendfile("./public/index.html");
});


text:
Q: Theorem without numbering Is it possible to have single theorems without numbering? I would like to be able to switch them off individually with asterisk-* or have a nono-theorem environment.
\newtheorem{theorem}{Theorem}
\newtheorem{nono-theorem}{Theorem}[]

A: (It's more of a comment.)
You can define a  new theorem with a star:
\documentclass{article}

\usepackage{lipsum}
\usepackage{ntheorem}
\newtheorem{theorem}{Theorem}
\newtheorem*{theorem-non}{Theorem}

\begin{document}

\begin{theorem}
\lipsum[1]
\end{theorem}
\begin{theorem-non}
\lipsum[1]
\end{theorem-non}

\end{document}

A: Using the amsthm package, you can switch numbering on and off for individual theorems just by defining environments with nearly identical names (as with equation environments):
\documentclass{article}
\usepackage{amsthm}
\theoremstyle{plain}

\newtheorem*{theorem*}{Theorem}
\newtheorem{theorem}{Theorem}

\begin{document}
\begin{theorem}  A numbered theorem.    \end{theorem}
\begin{theorem*} An unnumbered theorem. \end{theorem*}
\end{document}

A: An alternative I've used goes as follows. Include this at the top of your file:
\def\theorem{\par\noindent{\bf Theorem.\ } \ignorespaces}
\def\endtheorem{}

Then create a theorem with:
\begin{theorem}

\end{theorem}

Nice for things like
\def\problemstatement{\par\noindent{\bf Problem Statement.\ } \ignorespaces}
\def\endproblemstatement{}

or
\newcommand{\bBox}{\hbox{\vrule width1.3ex height1.3ex}}
\def\proof{\par\noindent{\bf Proof.\ } \ignorespaces}
\def\endproof{{\ \hspace*{\fill}\bBox \parfillskip 0pt}\smallskip\noindent}


text:
Q: Problem with PHP sessions in WordPress with non-default permalinks I'm experiencing a weird problem that occurs when I change the default permalinks in WordPress.
When I place this code in my functions.php file in my theme (or even in the root index.php file in WordPress) and navigate between and updating a few pages (for example the /about page), my counter often runs twice.
This problem is reproduced on every server I tried and on any theme or WordPress installation. Another thing that makes my brain even more confused is that it does not occur in Safari, Internet Explorer (6, 7 & 8), but only in Firefox. I'm using Firefox 3.6.8 and has tried it in both Mac OS X and Windows XP.
session_start();

$counter = $_SESSION['wp_action_counter'];

if( !isset($counter) ){
$counter = 0;
}

$counter++;

echo $counter;

$_SESSION['wp_action_counter'] = $counter;

My .htaccess rules looks like this
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

I'm curious why this happens and is ever thankful to the one who can help me solve the problem.

A: If it is incrementing twice, this two requests are going to your server, check the server log, or install firebug and watch the net tab, this way you can get sure what's really going on, instead off assuming what it could be (a link is prefetched, a php-generated image is being requested..).

A: Just an idea... is there a broken image, script, css (or something like) path that starts a second request? I had that problem a time ago and IE cached the resulting 404 but FF always re-requestet the broken image. The image-path was rewritten to my index path that triggered a counter...

A: I have finally found out what is the problem.
When I have <?php wp_head(); ?> in my header, WordPress adds this line:
<link rel='next' title='About' href='http://mysite.dev/about/' />

This link is prefetched and this is the cause why the counter runs twice. Adjusting the output of wp_head(); or removing it solves the problem.

A: You can find information on how to control the output in your header here:
http://wpquicktips.wordpress.com/2010/08/30/keep-a-track-of-what-happens-in-your-header-and-footer/


text:
Q: android: how to hide bottom buttons on dialog fullscreen I'm trying to hide navigation buttons when a dialog is shown fullscreen.
I've manage to do it following this example: Android fullscreen dialog
however, whenever i touch a button they appear again.
is there any  way to hide them properly?

thanks

A: The following snippet hides the navigation bar and status bar:
window.decorView.apply {
    // Hide both the navigation bar and the status bar.
    // SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
    // a general rule, you should design your app to hide the status bar whenever you
    // hide the navigation bar.
    systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN
}

From https://developer.android.com/training/system-ui/navigation
Nonetheless for your case you need two things to happen.

*

*First, set windowFullScreen to true to allow the dialog to paint every pixel in the screen. (i.e. Use any FullScreen theme).

*Then, on you dialog, set the systemUiVisibility to View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION.
This will stop the navigationBar from ever showing until you reset the flags or dismiss the dialog.
The complete snippet:
class SomeActivity {

    fun showDialog() {
        FullScrenDialog()
            .apply {
                setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_NoTitleBar_Fullscreen)
            }
            .show(supportFragmentManager, "TAG")
    }

}

class FullScrenDialog : DialogFragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        dialog.window?.decorView?.systemUiVisibility = View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
        return inflater.inflate(R.layout.dialog, container)
    }

}

A: Please try below code for dialog:
final Dialog dialog = new Dialog(this);
        dialog.setCancelable(false);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.getWindow().setGravity(Gravity.CENTER);
        dialog.setContentView(R.layout.dialog_logout);
        Window window = dialog.getWindow();
        window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
        window.getDecorView().setSystemUiVisibility(uiOptions);
        dialog.show();

Output is:

I hope it works for you.