text:
Q: Iredmail on google compute, modsecurity and phpbb3 I was given a week to get the website moved from Godaddy because they did not want to move it to their new server. So I had to start to learn how to move it to a cloud solution.
I did achieve it, after a lot of research and help from STACKOVERFLOW.
Now after a month of tweaking and making lots of mistakes I would like to start this thread to help others. I would also like you to comment and offer advice on alternative or better ways for each issue.
The website is fairly complex having been in existence for 23 years and managed by an amateur enthusiast with the objective to use open source and free software. Security was important as personal data of club members is stored and is accessible to members and club officers through a tailored access system based on email identification and provides role based authorisation. The website also houses a forum based on phpbb, a video library, a searchable archive of 20000 pdf documents, as well as the member services home grown system and an email forwarding facility. Two other, basically static, domains are also supported.
Each of these components requires maintenance and updating. Upgrading the components can be difficult when platform software version changes. The first task was to decide how to move each of them in turn to the new platform. I started with one of the static websites.
So which cloud provider? After rapid research and for no defendable reason versus Amazon, Google was chosen. I had set up an account when they first launched gcloud but set up a new one to take advantage of the £300 credit.
Understanding all the various components including compute engines, storage and networks and their pricing took up a lot of wasted time. Of course, I started off with the most minimal and cheapest but eventually found other components and larger ones were required. This meant learning how to resize disks as a couple of times the instances just died through lack of space! I also found that moving the files from the previous host not easy as there are many different ways to do it. So I should revisit that to see what is the best way. I wasted a lot of time trying to move virtual machines. I wasted time moving everything into storage and then trying to build the new website from that. I eventually decided, probably wrongly, to use the Bitnami phpbb stack. I thought that I would get a stable, secure system quickly since I only had a couple of days left to transfer.; but more of that later.
This first domain was simple but I wanted to check out the security and set up https and DNS transfer. Fathoming the Bitnami apache configuration was another challenge, but I stuck with it and learnt some new and possibly useful techniques. But what a support nightmare!
I had hoped there was good security firewall with Bitnami but I could not find it. I had used a GeoIP system on the previous host but did not have time to rebuild this until over a month after going live. I have now set up nftfw with MaxMind IP service.
The Gcloud firewall also needed configuration to get the various services running and secure, particularly for sending mail and I have yet to get the incoming mail forwarding system working. I use three services for outgoing mail notably Google, SendInBlue and SendGrid because I want to protect the free limits provided by each service and not to have all my eggs in one basket.
The two static websites had been moved; so now for the phpbb. Once again the Bitnami configuration was complex and I have yet to figure out if there is any good reason for it (perhaps separation of code from variable data). I did a DIFF of the old and the new system and copied the different files across and made a multitude of configuration changes to files and databases to eventually get it all working. Yes, I think it would have been easier just to rebuild the phpbb system on the new OS. But I still hoped the Bitnami system would give me a more secure platform in this new (for me) environment.
I employed modsecurity on the previous host but have now had to do some relaxation of rules to get phpbb working. Lots more rabbit holes and lots of unfinished business as there are many warnings still being posted.   I need to make the warnings into errors as soon as practical so as to block any hacks. Has anyone a working modsecurity and phpbb setup?
My next task is to get the incoming mail forwarding system to work. I will probably use Iredmail but am struggling to get it to work.  I have looked at many other systems, some of which offer a similar system to the Cpanel system I am used to. All that is really needed is that a dozen or so mailboxes on the domain need to be forwarded to the personal email accounts of club officers.
Sorry this post is not a specific question, although there are some embedded in it, but I felt the background might help others and me for future such migrations. Hopefully your responses will  be forthcoming!

A: For phpBB + Modsecurity, if you are using CRS ruleset, development version or CRS contains exclusion rules package for phpBB which, if used, should eliminate all false positives related to phpBB. See:
https://github.com/coreruleset/coreruleset/blob/v3.4/dev/rules/REQUEST-903.9007-PHPBB-EXCLUSION-RULES.conf
Also, i suggest you to switch Modsecurity to DetectionOnly mode in which it is only logging warnings and not doing any blocking. Search for SecRuleEngine in modsecurity.conf.


text:
Q: How to install 32 bit Android Studio on 64 bit Windows? The download page at http://developer.android.com/sdk/index.html#Other doesn't show any explicit 32 vs 64 bit downloads, so I'm guessing the installer automatically installs the 64 bit version on 64 bit systems. Is there any way to override this?

A: Since most of Android Studio is written in Java, there isn't much difference between the 64 and 32-bit versions, only the launcher and some DLLs.
In any case:

*

*<android-studio>\bin\studio.exe is the 32-bit launcher.

*<android-studio>\bin\studio64.exe is the 64-bit launcher.

However, the 32-bit launcher cannot actually be started in a x64 Windows installation (it will complain about this fact, and close itself).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Not Finding nearest Places I need to develop an application using Google Maps in Android to locate my current location and need to find nearest mosjid.
i'm getting current location if i click find button nothing happening.. It not show nearby places
package com.soft.mapexample;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.app.Dialog;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity implements
LocationListener{

GoogleMap mGoogleMap;
Spinner mSprPlaceType;

String[] mPlaceType=null;
String[] mPlaceTypeName=null;

double mLatitude=0;
double mLongitude=0;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Array of place types
    mPlaceType = getResources().getStringArray(R.array.place_type);

    // Array of place type names
    mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);

    // Creating an array adapter with an array of Place types
    // to populate the spinner
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
   android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);

    // Getting reference to the Spinner
    mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);

    // Setting adapter on Spinner to set place types
    mSprPlaceType.setAdapter(adapter);

    Button btnFind;

    // Getting reference to Find Button
    btnFind = ( Button ) findViewById(R.id.btn_find);

    // Getting Google Play availability status
    int status =
    GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not
  available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
  requestCode);
        dialog.show();

    }else { // Google Play Services are available

        // Getting reference to the SupportMapFragment
        SupportMapFragment fragment = ( SupportMapFragment)
   getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting Google Map
        mGoogleMap = fragment.getMap();

        // Enabling MyLocation in Google Map
        mGoogleMap.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service
 LOCATION_SERVICE
        LocationManager locationManager = (LocationManager)
  getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location From GPS
        Location location = locationManager.getLastKnownLocation(provider);

        if(location!=null){
                onLocationChanged(location);
        }

        locationManager.requestLocationUpdates(provider, 20000, 0, this);

        // Setting click event lister for the find button
        btnFind.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

            int selectedPosition =
                                   mSprPlaceType.getSelectedItemPosition();
                String type = mPlaceType[selectedPosition];

                StringBuilder sb = new StringBuilder
 ("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
                sb.append("location="+mLatitude+","+mLongitude);
                sb.append("&radius=5000");
                sb.append("&types="+type);
                sb.append("&sensor=true");
                sb.append("&key=API_KEY");

    // Creating a new non-ui thread task to download Google place json data
                PlacesTask placesTask = new PlacesTask();

    // Invokes the "doInBackground()" method of the class PlaceTask
                placesTask.execute(sb.toString());

            }
        });

    }

}

/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try{
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new
InputStreamReader(iStream));

            StringBuffer sb  = new StringBuffer();

            String line = "";
            while( ( line = br.readLine())  != null){
                    sb.append(line);
            }

            data = sb.toString();

            br.close();

    }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
    }finally{
            iStream.close();
            urlConnection.disconnect();
    }

    return data;
}

/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{

    String data = null;

    // Invoked by execute() method of this object
    @Override
    protected String doInBackground(String... url) {
        try{
            data = downloadUrl(url[0]);
        }catch(Exception e){
             Log.d("Background Task",e.toString());
        }
        return data;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(String result){
        ParserTask parserTask = new ParserTask();

        // Start parsing the Google places in JSON format
        // Invokes the "doInBackground()" method of the class ParseTask
        parserTask.execute(result);
    }

}

/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer,
List<HashMap<String,String>>>{

    JSONObject jObject;

    // Invoked by execute() method of this object
    @Override
    protected List<HashMap<String,String>> doInBackground(String...
jsonData) {

        List<HashMap<String, String>> places = null;
        PlaceJSONParser placeJsonParser = new PlaceJSONParser();

        try{
            jObject = new JSONObject(jsonData[0]);

            /** Getting the parsed data as a List construct */
            places = placeJsonParser.parse(jObject);

        }catch(Exception e){
                Log.d("Exception",e.toString());
        }
        return places;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(List<HashMap<String,String>> list){

        // Clears all the existing markers
        mGoogleMap.clear();

        for(int i=0;i<list.size();i++){

            // Creating a marker
            MarkerOptions markerOptions = new MarkerOptions();

            // Getting a place from the places list
            HashMap<String, String> hmPlace = list.get(i);

            // Getting latitude of the place
            double lat = Double.parseDouble(hmPlace.get("lat"));

            // Getting longitude of the place
            double lng = Double.parseDouble(hmPlace.get("lng"));

            // Getting name
            String name = hmPlace.get("place_name");

            // Getting vicinity
            String vicinity = hmPlace.get("vicinity");

            LatLng latLng = new LatLng(lat, lng);

            // Setting the position for the marker
            markerOptions.position(latLng);

            // Setting the title for the marker.
            //This will be displayed on taping the marker
            markerOptions.title(name + " : " + vicinity);

            // Placing a marker on the touched position
            mGoogleMap.addMarker(markerOptions);

        }

    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

@Override
public void onLocationChanged(Location location) {
    mLatitude = location.getLatitude();
    mLongitude = location.getLongitude();
    LatLng latLng = new LatLng(mLatitude, mLongitude);

    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}
}

PlaceJSONParser.Java
package com.soft.mapexample;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class PlaceJSONParser {

/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){

    JSONArray jPlaces = null;
    try {
        /** Retrieves all the elements in the 'places' array */
        jPlaces = jObject.getJSONArray("results");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    /** Invoking getPlaces with the array of json object
     * where each json object represent a place
     */
    return getPlaces(jPlaces);
}

private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
    int placesCount = jPlaces.length();
    List<HashMap<String, String>> placesList = new
ArrayList<HashMap<String,String>>();
    HashMap<String, String> place = null;

    /** Taking each place, parses and adds to list object */
    for(int i=0; i<placesCount;i++){
        try {
            /** Call getPlace with place JSON object to parse the place */
            place = getPlace((JSONObject)jPlaces.get(i));
            placesList.add(place);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return placesList;
}

/** Parsing the Place JSON object */
private HashMap<String, String> getPlace(JSONObject jPlace){

    HashMap<String, String> place = new HashMap<String, String>();
    String placeName = "-NA-";
    String vicinity="-NA-";
    String latitude="";
    String longitude="";

    try {
        // Extracting Place name, if available
        if(!jPlace.isNull("name")){
            placeName = jPlace.getString("name");
        }

        // Extracting Place Vicinity, if available
        if(!jPlace.isNull("vicinity")){
            vicinity = jPlace.getString("vicinity");
        }

        latitude =
jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
        longitude =
jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");

        place.put("place_name", placeName);
        place.put("vicinity", vicinity);
        place.put("lat", latitude);
        place.put("lng", longitude);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return place;
}
}

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<Spinner
    android:id="@+id/spr_place_type"
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:layout_alignParentTop="true" />

<Button
    android:id="@+id/btn_find"
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@id/spr_place_type"
    android:text="@string/str_btn_find" />

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/spr_place_type"
    class="com.google.android.gms.maps.SupportMapFragment" />

</RelativeLayout>

String.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="app_name">LocationNearby</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="str_btn_find">Find</string>

<string-array name="place_type">
    <item>airport</item>
    <item>atm</item>
    <item>bank</item>
    <item>bus_station</item>
    <item>church</item>
    <item>doctor</item>
    <item>hospital</item>
    <item>mosque</item>
    <item>movie_theater</item>
    <item>hindu_temple</item>
    <item>restaurant</item>
</string-array>

<string-array name="place_type_name">
    <item>Airport</item>
    <item>ATM</item>
    <item>Bank</item>
    <item>Bus Station</item>
    <item>Church</item>
    <item>Doctor</item>
    <item>Hospital</item>
    <item>Mosque</item>
    <item>Movie Theater</item>
    <item>Hindu Temple</item>
    <item>Restaurant</item>
</string-array>

</resources>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gasoft.mapexample"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="16" />

<permission
    android:name="com.soft.mapexample.permission.MAPS_RECEIVE"
    android:protectionLevel="signature"/>

<uses-permission
android:name="com.soft.mapexample.permission.MAPS_RECEIVE"/>

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.soft.mapexample.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

            <meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="api_key"/>

</application>

</manifest>

A: Create a API_KEY and use that in your application.
instead of sb.append("&key=API_KEY")
use sb.append("&key="+CREATED_API_KEY)


text:
Q: how to set a background JFrame picture with eclipse I have a problem with my code, I'm farelly new to java programming but the thing is that I want to set a bg picture but the code that I use disapears everything else that I've put in the JFrame..
panel.setSize(950, 600);
panel.setTitle("Nuevo Usuario Otto's");
panel.setResizable(false);
panel.setLocationRelativeTo(null);
try {
    panel.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:\\CELLES_PROYECTO\\darkTrees.jpg")))));
} catch (IOException e) {

    e.printStackTrace();
}
panel.setResizable(false);
panel.pack();
panel.setVisible(true);

A: JLabel does not support child components. Instead, use a JPanel for the content pane, and override its paintComponent method to draw the image.
try {
    final Image backgroundImage = ImageIO.read(new File("C:\\CELLES_PROYECTO\\darkTrees.jpg"));
    setContentPane(new JPanel(new BorderLayout()) {
        @Override public void paintComponent(Graphics g) {
            g.drawImage(backgroundImage, 0, 0, null);
        }
    });
} catch (IOException e) {
    throw new RuntimeException(e);
}

The above example also sets the JPanel's layout to BorderLayout, to match the default content pane layout.


text:
Q: How to parallelize a function which has more than one parameter? I have a particular simulation to perform which takes some time to run in R. Since I want to perform 1000 simulations, I decided to use "parallel" package to distribute these simulations over 4 cores. I know that I can get a resulting vector if I have a function like follows.
results_parallel <- parSapply(cl, c(1000,1000,1000,1000), rnorm)

In here rnorm() has only one parameter as the input, so that I can ask to produce 4000 values using 4 cores.
But my simulation has more than one parameter. My question is, since I have more than one parameter as input, how can I tell which parameter should be calculated using 4 cores? If simulation1(A,B,C,m) is my function where m is the number of simulations, I want to ask each core to to do the simulation 250 times, so that finally I can get 1000 simulations. Can anyone give me a hint?

A: You could try creating a function wrapper that takes a single argument rather multiple ones.
rnorm1 <- function(ls){
  rnorm(n = ls$n, mean = ls$mean, sd = ls$sd)
}

cl <- makeCluster(2)

example_list <- list(
      list(n=1000, mean = 0, sd = 1),
      list(n=1000, mean = 1, sd = 2)
)

results_parallel <- parSapply(cl, example_list, rnorm1)

You would just have to specify the required list of arguments so that it is a list of lists.

A: I'm not sure this is exactly what you're after, but you should be able to add the parameters to be passed to rnorm within your function call. I haven't used parSapply before, but here it is with llply:
doMC::registerDoMC( cores = 4 )
results <- plyr::llply( .data = c(1000,1000,1000,1000),
                        .fun = rnorm, mean = 1, sd = 0.4,
                        .parallel = T
)

Note the parameters mean and sd being passed to rnorm from within the llply call. parSapply should be able to handle this in the same way. For example:
results_parallel <- parSapply( cl,
                               X = c(1000,1000,1000,1000),
                               FUN = rnorm, mean = 1, sd = 0.4
)


text:
Q: UIView Animation: PartialCurl ...bug during rotate? a short question.
I've created an app for the iPad, much like a utility app for the iPhone (one mainView, one flipSideView). The animation between them is UIModalTransitionStylePartialCurl.
shouldAutorotateToInterfaceOrientation is returning YES.
If I rotate the device BEFORE entering the FlipSide, everything is okay and the PartialCurl is displayed okay.
But if I enter the FlipSide and then rotate the device, while the UIElements do rotate and position themselves just fine, the actual "page curl" stays with its initial orientation. it just won't budge :)
Is it a known issue? am I doing something wrong?
Thanks!

A: I too had this issue and somewhat gave up. However, I mentioned my dilemma to a friend, who encouraged me to look into the child VC's logic and I recalled a handy trick that I've used to pass data between parent/child view controllers.
In your flipside view controller, create a "rootViewController" property. In your parent view controller, when you initialize the flipside view controller, you set (where "self" is the rootVC):
flipsideController.rootViewController = self;

You then use this for your flipside VC's shouldAutorotateToInterfaceOrientation method:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return interfaceOrientation == self.rootViewController.interfaceOrientation;
}

Viola! The flipside view no longer rotates underneath the partially curled up parent view!

A: The shortest way of the above code is:
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return interfaceOrientation == self.parentViewController.interfaceOrientation;
}


text:
Q: How do I reference the table being updated in the "set" portion of my update statement? I'm using MySQL 5.5.37.  I want to update a table and I would like to use the value of the specific row I wish to update the in the query clause I use to get an update value.  So for instance, I alias my table like so
update session ts set

and so I would like to reference "ts.id" in the "set" portion of the statement, if that's possible.  I tried
update session ts set user_id = (select q.* from
  (select u.id FROM session t, training_session_org tso, organization o, user u
   where o.user_id = u.id and tso.organization_id = o.id
     and t.id = tso.training_session_id and t.id = ts.id) q);

But I'm getting a
ERROR 1054 (42S22): Unknown column 'ts.id' in 'where clause'

What's the proper way to reference my updated table in the query, if its possible?  Also, I want to do this in one SQL statement, not multiple ones.

A: The problem is that you are using a double subquery and ts.id goes out of the inner query scope, I suspect that you tried to use it for avoiding the error:

You can't specify target table 'ts' for update in FROM clause

but the solution is just omitting the session table from the subquery as you don't need it:
update session set user_id = (select u.id
  from training_session_org tso
  join organization o on o.id = tso.organization_id
  join user u on u.id = o.user_id
  where tso.training_session_id=session.id)

In fact, based on the joins you can even simplify the query further:
update session set user_id = (select o.user_id
  from training_session_org tso
  join organization o on o.id = tso.organization_id
  where tso.training_session_id=session.id)


text:
Q: phone gap vs monotouch for data intensive app We are looking to develop a data intensive application for mobile devices. Our central problem is

*

*We will have to store quite a lot of data on the client

*The client wants the app to work offline

*Our skill set is very much web development C# ASP.Net. Definitely not Objective C

We have thought of three possibilities for dev

*

*Web application using HTML5 local storage leveraging the offline application cache.
We are on a 5MB limit for local storage but this might be down to 2.5MB for certain browsers

*Web application through PhoneGap to create a native app.
Big advantage here is that we can use the file system for storage. The down side is that it will have to go through App Store (for iOS especially) - 30% chuck of revenue for a subscription app to Apple

*We build out the app using MonoTouch for Android and iOS.
Good - C# and .Net we can do this. Bad - no Blackberry
Question
I'm struggling to see any genuine advantages of using MonoTouch over PhoneGap in this instance. What are they? Are they any?
As an example in this instance it would be really useful to save data onto the file system but I believe that phone gap can do this through the File object. Obviously monoTouch would leverage System.IO.
Is there instances where there is definite additional functionality in MonoTouch - particularly functions that are useful to mobile dev e.g. Geolocation or camera type functions?. Or does phone gap pretty much have all these covered.
Cheeky Additional Questions
Is there any other options I have missed or any other major advantages/disadvantages for the three approaches I have outlined that I have forgotten about?
Thanks for everyone's expertise

A: We have just finished a very data intensive app written in MonoTouch. The app accesses SAP data, through a middle tier, and exposes this on the app. It also allows direct updates from the app to SAP, again through the same middle tier.
We are in the process of porting this to Windows Phone and Android using MonoDroid.
It took me a while to convince the boss that MonoTouch was the way forwards, and we tried a few different products beforehand including jQuery mobile, ExtJS and Obj C.
The time I was trying to convince him was the time of the Attachmate acquisition and it looked, at times, like MonoTouch was doomed. Luckily for us (me), Xamarin rose like the proverbial Phoenix from the flames, and they have continued to develop Mono* to what it is today.
As a C# developer (and Mono enthusiast) the main win over Obj C or any of the HTML/JavaScript was the fact that I could use C# to get the job done. The documentation was very good, and when the doco didn't quite cut it (recently been updated) the community did.
The IRC channel is very active, with Xamarin employees and community evangelists always willing to help or provide insight into a problem. As are the mailing lists.
Another plus are the Eco-systems which are growing around MT. MT.Dialog makes developing Table based UI's an absolute breeze compared to the XCode equivalent. Couple with this the .Net BCL which is, admittedly a subset based on Silverlight, but it has everything from Serialization, Email to Cryptography etc... If .Net doesn't cover it, or there isn't a specific Mono* project, you can still use ObjC plugins with your MT code.
I disagree that MT has 'yet to prove itself' as a proven platform. We are using it, and whilst we are a relatively small company, there are lots of larger companies also using it. A few of the apps showcased by Apple in the TV ads here in Aus are, reportedly, written in MT.
In order to remain objective, the 2 'cons' of MonoTouch for me have been that you still need to be able to read ObjC (though, tbh, I don't see this as a con... As a 'C#' developer I have to be able to read and write a plethora of languages anyway) and the fact that, historically, MonoDevelop has been a bit buggy. The major bugs appear to have been squashed and, with it being an open source project, you can always fix them and help the rest of us!
To answer your concerns:

*

*We will have to store quite a lot of data on the client

Use the System.IO classes of .Net in C#. If you are unsure of these, MSDN has oodles of examples (MT hides the iOS implementation of file storage)

*

*The client wants the app to work offline

they can all do this, but a Native app is always going to feel better in my opinion.

*

*Our skill set is very much web development C# ASP.Net. Definitely not Objective C

MonoTouch is C# - play to your strengths and have an app in weeks, not months!
My 2 pennies! I would not hesitate to choose the same route again, again and again.

A: There's a new release of MonoTouch that came out yesterday (Feb 8, 2012) -  5.2.  Lots of new features to make developing iOS apps easier and faster.  Details about it an be accessed from here: http://blog.xamarin.com/
One thing that makes MonoTouch a particularly interesting technology is the ability to develop some pretty darn sophisticated apps that can run without requiring internet connectivity.  That can be a biggie.

A: I have used PhoneGap for a while now (on WP7) but not used MonoTouch, however I am an experienced C# / Silverlight developer.
A few advantages of MonoTouch:

*

*You code results in a native UI, giving the best experience on all platforms

*C# is an 'enterprising-strength' programming language. It is well suited to the development of data intensive applications

*Your current skill sets will serve you well here

*There are numerous applications written with MonoTouch available via the app store.

A few disadvantages of MonoTouch:

*

*You write C# code again the iPhone APIs, therefore to port to Android, you will need to have a separate UI layer for MonoDroid.

Advantages of PhoneGap:

*

*It is starting to look like quite a mature framework, with numerous applications written using PhoneGap across the full range of supported OSs.

*There is good community support for PhoneGap

*It uses HTML5, which many see as the technology of the future. This is a rather broad statement, however, most of the big players (Microsoft, Adobe, ...) are backing it.

Disadvantages of PhoneGap:

*

*It uses JavaScript, probably the most misunderstood language in widespread use!

*The UI is written in HTML. Despite the best efforts of frameworks such as jQuery Mobile it will never feel native.

*Because it has platform specific 'shim' code to provide a consistent API, you will find platform-specific issues. However, I have found that the PhoneGap team fix these quite swiftly.

In summary, a tough choice!
Personally I would go PhoneGap, but not try to emulate the look and feel of any specific OS, rather, create your own UI that works well for your application and use that across all platforms.


text:
Q: Reading a file containing multiple lines of strings, integers and floats I'm trying to read a file containing a line containing a string, integer and float. The data is separated by commas and I've seen a tonne of information about how best to approach this. I've simplified by problem by first trying to read in one line, and then work on implementing multiple lines.
I've managed to read the first two pieces of data. It's the float that's giving me issues.
Here is an example of what it is I'm trying to read:
CHANNEL_1, 0, 0.453
char        CHANNEL_NAME_[BUF_SIZE];
uint32_t    val1_;
double      val2_;
    FILE *fp;
int c;

    fp = fopen("E:\\read_from_file\\config.cfg", "r");

if (fp < 1)
{
    printf("Failed to open file = %d\n", fp);
    fclose(fp);
}

c = fscanf(fp, "%[^,], %u[^,], %lf", CHANNEL_NAME_, &val1_, &val2_);

printf("[%s] [%u] [%lf]\n", CHANNEL_NAME_, val1_, val2_);
printf("C = %d\n", c);

I'm able to print the string and integer correctly, however, it's the float that's giving me issues. It comes out as a random float, something like 34534524524523452345.0000000. I expect to see the float as per above, 0.453.
When I print C, which is the result of the fscanf, I get 2 which is incorrect as I'd expect to read 3, due to 3 data types being read in.
What am I doing wrong?

A: There's no such specifier as "%u[^,]". That format is treated as a separate "%u" followed by a separate "[^,]".
The %[ format only reads strings, it doesn't have any type-prefix (and it's not needed as scanf will stop reading integers at the first non-digit character in the input). Which means you can use only "%u" for the middle specifier:
c = fscanf(fp, " %[^,], %u, %lf", CHANNEL_NAME_, &val1_, &val2_);

Note that I added a leading space in the format string. That's because the "%[" format does not skip leading spaces (like any possible newlines after the previous line).

With the format specifier "%u[^,]", the function actually tries to match the exact sequence "[^,]" in the input, which it won't find, leading to the last value not being read. Hence the value of c being 2 (as fscanf only matched two values, the initial string and the first unsigned integer).


text:
Q: This webpage has a redirect loop I have transfer my site from one domain to another. I have cleared cache & session as well. No htaccess issue. URL changed in database.
Still it redirects to
<my domain>/downloader/downloader & giving error This webpage has a redirect loop
Any idea what still i need to check?


text:
Q: Laravel redirect to blank page after logging in with encrypted user email I have a client which want to save his data encrypted in the database (email, name etc.). He wants to log in with the email too. I made the functionality to log in with encrypted email but the problem is that after log in I am redirected to a blank page with the url /login when I should be redirected to /business-accounts. If I delete manually the /login from the url I am redirected to the /business-accounts which I need to be redirected. Before doing the ecrypted email authentication everything worked fine.
AuthenticatedSessionController.php
public function store(LoginRequest $request)
{
    //check user is validated
    User::all()->filter(function ($user) use ($request) {
        if($user->email == $request->email){

            if($user && $user->status==0){
                throw ValidationException::withMessages([
                    'validation' => 'Account not verified.'
                ]);
            }
            //get user email crypted for login
            $request->merge(['email' => User::find($user->id)->get_email_crypted()]);

            $request->authenticate();

            $request->session()->regenerate();

            //set user session
            UserService::set_session($user);

            return redirect()->intended(RouteServiceProvider::HOME);
        }

    });
}

I printed a dd() before the return and seems like everything is working fine till there.
LoginRequest.php
public function authenticate()
{
    $this->ensureIsNotRateLimited();

    if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
        RateLimiter::hit($this->throttleKey());

        throw ValidationException::withMessages([
            'email' => __('auth.failed'),
        ]);
    }

    RateLimiter::clear($this->throttleKey());
}

RouteServiceProvider.php
 public const HOME = '/business-accounts';

Encryption and decryption is made in the User model with get/setEmailAttribute. In the authenticate() method I could see that it is not entering the if where Auth::attempt is located.
I tried to make it work in PasswordResetLinkController too but all I could get is the same blank page with the url /forgot-password and no email received in the inbox.
My Laravel version is 8.x.
L.E. I dumped something before the return redirect() and I saw that in the browser after the login submit I am redirected back to the /login form, so I am thinking that I am getting in a loop or something.
L.E.2.
I somehow resolved this. The thing that I done was changing the crypting method on the email column. I changed the Laravel cripting method with the openssl_crypt function.
User Model
public function setEmailAttribute($value)
{
    if (!is_null($value)) {
        $this->attributes['email'] = openssl_encrypt($value, "AES-128-ECB", env('EMAIL_ENCRYPT_KEY', false));
    }
}

Where the crypting key is located in .env.
AuthenticatedSessionController.php
public function store(LoginRequest $request)
{
    //check user is validated
    $user = User::where('email', openssl_encrypt($request->email, "AES-128-ECB", env('EMAIL_ENCRYPT_KEY', false)))->first();
    if($user && $user->status==0){
        throw ValidationException::withMessages([
            'validation' => 'Contul nu este verificat'
        ]);
    }

    //set email from request to encrypted email
    $request->merge(['email' => User::find($user->id)->get_email_crypted()]);
    $request->authenticate();

    $request->session()->regenerate();

    UserService::set_session($user);

    return redirect()->intended(RouteServiceProvider::HOME);
}

A: you can take a look in the log file in /storage/logs/laravel.log for the error message
also, you could change the .env file to show_errors = true and it will show the error in the browser

A: Use return redirect()->route('your-route-name'); maybe can help you.


text:
Q: Unable to deploy to Heroku, no changes were made I'm running into a deployment issue with Heroku. Yesterday, I was able to deploy without issues -- this morning, I built a new cluster on MongoDB and pushed a change to git with the new connection string. No other changes were made.
After pushing to git, I ran git push heroku master, and was faced with the below error:
. . .
remote:        added 1812 packages from 857 contributors and audited 932744 packages in 66.192s
remote:
remote:        65 packages are looking for funding
remote:          run `npm fund` for details
remote:
remote:        found 0 vulnerabilities
remote:
remote:
remote:        > client@0.1.0 build /tmp/build_3fd8925946ec2800b115594ca20fb426/client
remote:        > react-scripts build
remote:
remote:        Creating an optimized production build...
remote:        Failed to compile.
remote:
remote:        ./node_modules/simple-react-lightbox/dist/index.es.js
remote:        Cannot find module: 'fast-deep-equal/react'. Make sure this package is installed.
remote:
remote:        You can install this package by running: yarn add fast-deep-equal/react.
. . .

Naturally, the first thing I did was try to run yarn add fast-deep-equal/react as advised, which threw the next error,
error Command failed.
Exit code: 128
Command: git
Arguments: ls-remote --tags --heads ssh://git@github.com/fast-deep-equal/react.git
Directory: /Users/me/my-app
Output:
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I've been debugging for several hours now, and I can't seem to figure out a solution.
What could be going on here?

A: Try running yarn add epoberezkin/fast-deep-equal
Yarn appears to be trying to install the library from the wrong github repository. This is likely the fault of Heroku's error message not telling you the correct module name.

A: In a similar case when I tried to deploy to Heroku I got identical messages. After trying some things (at random) I found the problem is the devDependencies. You would rather transfer all of them to normal dependencies:
npm install <module_name> --save-prod

That solved my error, good luck!


text:
Q: Datatables Where clause with two conditions I want to select records where p_code=10 & p_code=24 only for the user = 4, in my MySQL Datatables view. I used the following code fragment.
$usr = $this->session->userdata('id_user');
if($usr == 4)
        {
        $this->datatables->where('tbl_officer.p_code', 10);
        $this->datatables->where('tbl_officer.p_code', 24);

        } else {
        $this->datatables->where('tbl_officer.usr', $usr);
        }

But the code outs an empty result. If I remove the line, $this->datatables->where('tbl_officer.p_code', 24); the result shows only the officers with p_code=10.
How can I add these two lines with where clause in my code ? Can anyone help ?

A: Use or_where, so you can get both or one of them:
$this->datatables->where('tbl_officer.p_code', 10)->or_where('tbl_officer.p_code', 24);

And you can use where_in too:
$this->datatables->where_in('tbl_officer.p_code', [10, 24]);

A: You need to use or_where to join both statements, like so:
$this->datatables->where('tbl_officer.p_code', 10)->or_where('tbl_officer.p_code', 24);

Without it you will just run two separate queries (one for p_code == 10 and other for p_code == 24) and return the value of the last statement.


text:
Q: Recognise link with password in zoom desktop client How can I directly use a zoom link that includes the password with the zoom desktop client on mac OSX?
For meetings people usually sent me links which are structured like this
 https://zoom.us/j/<some long number>?pwd=<some hash of password>

(I don't get the meeting id/pin, only the link)
If I use the zoom desktop client to join the meeting, it will ask me to enter the meeting id. I can use the link instead, but in the next step it will ask me for the pin. So I have to go back to another application, copy the <some hash of password> part of the link and paste it there. Can this step be simplified?
I also tried to paste the link in my browser instead, but then I have to first cancel the download of the zoom installer (even though it is already installed) before I can click on join the meeting with desktop client. This at least will directly take me to the meeting without having to enter the password separately.
I tried from the command line with zoommtg:, as suggested in superuser.com/questions/1563255, but this needs urls like zoom.us/join?action=join&confno=<your_conference_number>, while I have https://zoom.us/j/<some long number>?pwd=<some hash of password>. With this other url scheme zoommtg only opens the desktop client, but does not join the meeting.`


text:
Q: Setting Opacity on parent  makes children indepedently transparent I have a list of items, and when an item becomes "complete", it's opacity is set to 0.4 to fade it away. Also when an item is completed, the icon gets an orange-yellow completion overlay.
.
The markup for this is something similar to
<Grid Opacity="{x:Bind IsCompleted, Converter={StaticResource BooleanNumberConverter}, ConverterParameter=0.4|1}">
    [...]

    <Canvas>
        <Image />

        <Rectangle
            Visibility="{x:Bind IsCompleted, Converter={StaticResource BooleanVisibilityConverter}}"
            Canvas.Top="0" Canvas.Left="0"
            Width="48"
            StrokeThickness="2"
            Opacity="1"
            Height="48" Stroke="#ffC19954" />

        <Polygon
            Visibility="{x:Bind IsCompleted, Converter={StaticResource BooleanVisibilityConverter}}"
            Opacity="1"
            Canvas.Top="23" Canvas.Left="23" Points="0,25 25,25, 25,0" Fill="#ffC19954" />
    </Canvas>

    [...]
</Grid>

The problem I'm having is that it appears the opacity is applied individually to each descendant, so the orange completion triangle appears semi-tranparent on top of the icon, and you can see the icon underneath. You can also see this where the triangle overlaps the border.
Instead, the desired behaviour is that the triangle should be completely opaque and the grid as a whole should be semi-transparent, as it behaves in CSS:

opacity applies to the element as a whole, including its contents, even though the value is not inherited by child elements. Thus, the element and its children all have the same opacity relative to the element's background, even if they have different opacities relative to one another.

It should look like

(note how the white icon is not visible through the orange triangle)
Is there a way to change how opacity is composited and rendered to achieve this?  Very soon the app's background will be slightly transparent, so I need a solution that will work with that as well.

A: You can get around this by simply doing the inverse.
Put a mask grid, above the item, set a solid color to the grid, set it to 0 opacity, and simply increase its opacity when you want the content behind to fade.
<Grid Name="BaseGrid">
<Canvas>
        <Image />
    [...]
</Canvas>

<Grid Name="MaskGrid" Background="Gainsboro" Opacity="0.2"/>

</Grid>


text:
Q: log4net not saving in Database in ASP.NET I have problem with log4net. In localhost works fine and save in the database (Production1), then in QA not save the log in the same database (Production1)
AssemblyInfo.cs
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]

Web.config
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false" />
  </configSections>
  <!-- Log4Net -->
  <log4net>

    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="wsaopc.log" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="1024KB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="debug" type="log4net.Appender.DebugAppender">
      <immediateFlush value="true" />
      <layout type="log4net.Layout.SimpleLayout" />
    </appender>
    <appender name="sql" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="1" />
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <connectionStringName value="CSLog4Net" />
      <commandText value="INSERT INTO aopc_sce_ws_log (wslog_fecha, wslog_tarea, wslog_nivel,wslog_logger, wslog_mensaje, wslog_excepcion) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
      <parameter>
        <parameterName value="@log_date" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.RawTimeStampLayout" />
      </parameter>
      <parameter>
        <parameterName value="@thread" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%thread" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@log_level" />
        <dbType value="String" />
        <size value="50" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%level" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@logger" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%logger" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@message" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%message" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@exception" />
        <dbType value="String" />
        <size value="2000" />
        <layout type="log4net.Layout.ExceptionLayout" />
      </parameter>
    </appender>
    <logger name="WS">
      <level value="ALL" />
      <appender-ref ref="sql" />
      <appender-ref ref="debug" />
      <appender-ref ref="RollingFileAppender" />
    </logger>
    <logger name="EF">
      <level value="ALL" />
      <appender-ref ref="RollingFileAppenderEF" />
    </logger>
    <logger name="BD">
      <level value="ALL" />
      <appender-ref ref="sql" />
    </logger>
  </log4net>

</configuration>

I review in QA and have the same web.config.


text:
Q: Shredding XML data in SQL2012- How can I get values from nested elements I have a table named Audit.Event which captures user events, one of the columns within that table stores the data as xml, which is structured as such
XML Data
<OrganisationSearchEvent xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <Options>
    <IsAgency>false</IsAgency>
    <IsCharity>false</IsCharity>
    <IsCompany>false</IsCompany>
    <IsEducationalEstablishment>false</IsEducationalEstablishment>
    <IsProgrammeProvider>false</IsProgrammeProvider>
    <Name i:nil="true" />
    <OrganisationIDs xmlns:d3p1="http://schemas.datacontract.org/2004/07/System" i:nil="true" />
    <ProfessionalBodies xmlns:d3p1="http://schemas.datacontract.org/2004/07/System" i:nil="true" />
    <Sectors xmlns:d3p1="http://schemas.datacontract.org/2004/07/System">
      <d3p1:int>21</d3p1:int>
      <d3p1:int>82</d3p1:int>
    </Sectors>
    <SubSector xmlns:d3p1="http://schemas.datacontract.org/2004/07/System" i:nil="true" />
  </Options>
  <Paging>
    <EndRecord i:nil="true" />
    <PageNumber>1</PageNumber>
    <PagingMode>Paged</PagingMode>
    <RecordsPerPage>20</RecordsPerPage>
    <StartRecord i:nil="true" />
    <TotalPages>1</TotalPages>
  </Paging>
</OrganisationSearchEvent>

I need to shred the xml and capture the data in the elements named d3p1:int. So far I have wrote the following query:
Query
SELECT
Data.value('(//d3p1:int)[1]', 'int') AS [SectorID],
FROM [Audit].[EventData]
Cross Apply Data.nodes('//OrganisationSearchEvent/Options/Sectors') as Test(X)
Where EventTypeID = 7
Order By CapturedDateTime Desc

All I would expect to see is
+----------+
| SectorID |
+----------+
|       10 |
|       45 |
|       50 |
|       22 |
|        6 |
+----------+

But instead I get the following error

The name "d3p1" does not denote a namespace.

If I replace "d3p1:int" with just "d3p1", nulls are returned
If I use the following line in the select clause as a test, the correct data for that element is returned.
Data.value('(//Name)[1]','nvarchar(100)') AS [Name]

Could anyone point me in the right direction, am unsure what the actual cause of this is
Thanks

--Edit--
Following Shnugo's suggestion I have tried the following with no luck, I must be missing something!
I am unable to point to the actual XMLdata as shown as this is being stored via the application into a column in the "Autit.EventData" table, what I tried to do is this.
Attempt 1
Declare @xml XML=[Audit].[EventData].[Data]

;WITH XMLNAMESPACES ('http://www.w3.org/2001/XMLSchema-instance' AS d3p1)
SELECT i.value('.','int') AS [SectorID]
FROM @xml.nodes('/OrganisationSearchEvent/Options/Sectors/d3p1:int') as A(i)

But I get the error

The multi-part identifier "Audit.EventData.Data" could not be bound.

I assume I still need to use the table so I tried this next
Attempt 2
;WITH XMLNAMESPACES ('http://www.w3.org/2001/XMLSchema-instance' AS d3p1)
SELECT i.value('.','int') AS [SectorID]
FROM [Audit].[EventData]

Cross Apply Data.nodes('/OrganisationSearchEvent/Options/Sectors/d3p1:int') as A(i)

but this returns nothing
Final Solution
Here is the final query I used to return the correct data
 SELECT
T.C.value('.', 'int') as [SelectedID's]
from Audit.[EventData]
cross apply Data.nodes('/OrganisationSearchEvent/Options/Sectors/*') as T(C)
where EventTypeID = 7
order by CapturedDateTime desc

A: Try it like this:
DECLARE @xml XML=
'<OrganisationSearchEvent xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <Options>
    <IsAgency>false</IsAgency>
    <IsCharity>false</IsCharity>
    <IsCompany>false</IsCompany>
    <IsEducationalEstablishment>false</IsEducationalEstablishment>
    <IsProgrammeProvider>false</IsProgrammeProvider>
    <Name i:nil="true" />
    <OrganisationIDs xmlns:d3p1="http://schemas.datacontract.org/2004/07/System" i:nil="true" />
    <ProfessionalBodies xmlns:d3p1="http://schemas.datacontract.org/2004/07/System" i:nil="true" />
    <Sectors xmlns:d3p1="http://schemas.datacontract.org/2004/07/System">
      <d3p1:int>21</d3p1:int>
      <d3p1:int>82</d3p1:int>
    </Sectors>
    <SubSector xmlns:d3p1="http://schemas.datacontract.org/2004/07/System" i:nil="true" />
  </Options>
  <Paging>
    <EndRecord i:nil="true" />
    <PageNumber>1</PageNumber>
    <PagingMode>Paged</PagingMode>
    <RecordsPerPage>20</RecordsPerPage>
    <StartRecord i:nil="true" />
    <TotalPages>1</TotalPages>
  </Paging>
</OrganisationSearchEvent>';

WITH XMLNAMESPACES('http://schemas.datacontract.org/2004/07/System' AS d3p1)
SELECT i.value('.','int')
FROM @xml.nodes('//d3p1:int') AS A(i);

Without namespaces you might use wildcards like here
SELECT i.value('.','int')
FROM @xml.nodes('//*:int') AS A(i);

Or even the full path
WITH XMLNAMESPACES('http://schemas.datacontract.org/2004/07/System' AS d3p1)
SELECT i.value('.','int')
FROM @xml.nodes('/OrganisationSearchEvent/Options/Sectors/d3p1:int') AS A(i);

This depends on your demands. The general advise is: Be as specific as possible.
About your code: As you want to read all int-elements, you need the .nodes() to return your <d3p1:int>-elements. Your query stops one level to high. And secondly, if you have to deal with namespaces, you have either to use them explicitly or use a wildcard.
UPDATE
Without knowing your actual database it is hard to point you out...
From your question I take, that this:
SELECT
Data.value('(//d3p1:int)[1]', 'int') AS [SectorID],
FROM [Audit].[EventData]
Cross Apply Data.nodes('//OrganisationSearchEvent/Options/Sectors') as Test(X)
Where EventTypeID = 7
Order By CapturedDateTime Desc

together with this
Data.value('(//Name)[1]','nvarchar(100)') AS [Name]

returns the correct data?
If so, the least specific approach might be this:
SELECT
Data.value('.','int') AS SectorID
FROM [Audit].[EventData]
Cross Apply Data.nodes('//*:int') as Test(X)
Where EventTypeID = 7
Order By CapturedDateTime Desc

This should pick any element called int (not the datatype, the element's name!) and list this row-wise...
If you get this to work, you might try to find a more specific XPath, but this should - at least - return the correct values...


text:
Q: Create Project PHP Example using XTFR webservice API Can anyone please help me with create project example using XTRF webservice API. Thanks in advance.
-Vamsi

A: You can see how to create a project in Usage Examples section of the documentation for WebService API. I also suggest reading reference documentation for the individual methods and types used across the example code.


text:
Q: How can i download file inside app folder ?[ after packaging ] This is my current folder structurebefore packaging
WRM_80.. is my downloaded folder.
I have these two lines of code inside index.js  to download and show html in my electron window
fs.createReadStream('./Report.zip').pipe(unzip.Extract({ path: './'+folderName }));
LoginWindow.loadURL(`file://${__dirname}./`+folderName+`/t01s01q01.html`);

in development mode its working fine, file downloaded inside the same folder where my index.js exists. But after packaging the app file is downloading outside app folder. Packaged folder structure is given below  WRM_80.. is my downloaded folder.
after packaging
That's why I can not load that downloaded file into window. How can  I download file inside app folder? If that is not possible, how can I load external file from resources\app location ?

A: By referencing the directory as ./folder_name you are essentially telling the application to download to the working directory. In this case, the working directory is the folder that the program is contained in. While developing and using the electron command, the working directory is the root of your application. However once installed and running as a .exe, the working directory changes to the location of the executable.
To solve this problem, do not use the current working directory. Instead use the user / application data folder to store this information. It is not only a consistent location across development and deployment, but it is also the semantically correct place to store application data.
In Electron you can get the path to the application data folder for your app with:
const {app} = require('electron');
app.getPath('userData')

So your code should look something like this:
var userData = app.getPath('userData');
fs.createReadStream(`${userData}/Report.zip`).pipe(unzip.Extract({ path: `${userData}/${folderName}` }));
LoginWindow.loadURL(`file://${userData}/${folderName}/t01s01q01.html`);


text:
Q: No warning on deleting a forward declared pointer (Visual Studio) Deleting forward declared pointers leads to undefined behavior.
Examples:

*

*https://gist.github.com/jatinganhotra/4144778

*https://stackoverflow.com/a/14382111/399908
However, my Visual Studio (VS2012) compiler doesn't warn me about it.

*

*Is this an unfixed VS2012 compiler bug?

*Did I disable (or never enable) the corresponding warning?

*Is this specific to some project setting?

*Visual Leak Detector hinted me to the problem, but is there some method (pragma, code, macro, ...) to detect this at compile time?

A: The respective warning is C4150.
It should be active by default and it is categorized in warning level 2 (which should be active too, since default warning level is W3 afaik).
Note: Instead of lowering the warning level, try to pragma warnings in specific cases.


text:
Q: How should I implement my lambda handler with my REST API gateway model using non- proxy lambda? I am stuck on how I should begin my lambda handler that will read some data from dynamodb. I have defined my api gateway model with the requests and response models, therefore do I need to state any  status codes in the lambda handler ? Do I use API gateway proxy response event ? Any code examples
in Java would be helpful.
My notes on what I should include in the lambda handler:

*

*access DB

*map over table

*Find attribute

*Return response to api ?

What am I missing ? Thank you.

A: If you decided to use a non-proxy Lambda integration then you need to define an integration response using a regex. Here is an example using nodeJS:
lambda regex
Normally i declare my error messages just like this:
const errorMessages = {
    INTERNAL_SERVER_ERROR: {
        message: "Internal server error!",
        code: 500
    },
    ERROR_BODY_INVALID: {
        message: "Invalid request body",
        code: 400
    }
};

Then throw an error like this
exports.handler = function(event, context, callback) {
   try {
      // do something
   } catch (error) {
        callback(JSON.stringify(errorMessages.INTERNAL_SERVER_ERROR));
   };
}

When a lambda error regex matches then it's mapped to the configured response status code.
P.D. If you are using Java this method does not work and you need to use proxy integration


text:
Q: Map jdbi query result to a map keyed on a column with a list of values Imagine a scenario where I am querying the orders table for a list of users and trying to find their orders. I am trying to get a map, with a keyset of user ids, and a list of order objects.
return type is similar to this - Map<Integer, List>
 JdbiHelper.jdbi(readOnly).withHandle(
                handle -> handle.createQuery(query)
                        .bindList("user_id", userIds).?

The query itself is like :-
SELECT * FROM orders WHERE user_id in (<userIds>)

How do I get a map, with key as user ids and list of order objects as values?
I was trying something along these lines
    JdbiHelper.jdbi(readOnly).withHandle(
                handle -> handle.createQuery(query)
                        .bindList("user_id", userIds)
                        .map((rs, ctx) -> Pair.of(rs.getInt("user_id"), rs))
                        .collect(toMap(Pair::getLeft, Pair::getRight))

but, it didn't work.

A: You need a result mapper, e.g. an OrderMapper which turns a result set into an Order object.
Here is a solution using the Guava ImmutableListMultimap (which maps onto a list or results). Otherwise, you have to write your own Collector that collects the resulting Order objects into a Map<Integer, List<Order>>.
OrderMapper mapper = new OrderMapper();

Multimap<Integer, Order> results = JdbiHelper.jdbi(readOnly).withHandle(
                handle -> handle.createQuery("SELECT * from orders WHERE user_id IN (<user_id>)")
                        .bindList("user_id", userIds)
                        .mapTo(Order.class)
                        .collect(toImmutableListMultimap(Order::getUserId, Functions.identity())));

Or you can register the OrderMapper with Jdbi using Jdbi.registerColumnMapper(new OrderMapper()) and use .mapTo(Order.class) instead of the .map(mapper).
In any case you need a mapper to turn the result set into an Order object.
public class OrderMapper implements ColumnMapper<Order> {

    public Order map(ResultSet r, int columnNumber, StatementContext ctx) throws SQLException {
        return new Order().setUserId(rs.getInt("user_id"),
                ... additional columns ...
        }
    }


text:
Q: How to solve the functional equation $f(x^n+y^n)=f(x^n)+f(y^n)$ for any positive integar $n$? I got some problems when solving the functional equation $f(x+y^n)=f(x)+[f(y)]^n, (x,y\in\mathbf{R}) $ for all positive integar $n$. I tried to solve it as following:
================================================
Let $y=0$, then $f(x)=f(x)+[f(0)]^n$ implies $f(0)=0$;
Let $x=0, y=1$, then $f(1)=[f(1)]^n$ implies $f(1)=0$ or $1$.
Let $x=0$, then $f(y^n)=[f(y)]^n$.
Then the equation can be re-written as
$f(x^n+y^n)=f(x^n)+f(y^n), x, y\in\mathbf{R}$. ------- [1]
According to the continuous solution of Cauchy equation, the solution of the funciton (1) is $f(x)=f(1)x=0$ or $x$.
================================================
However, I want to know about:
(1) Whether my solution above is correct?
(2) Maybe I shall discuss the parity of $n$, or not. And how to solve the equation $f(x^n+y^n)=f(x^n)+f(y^n)$ for a general positive integar $n$.
(3) If all solutions of equation [1] have been found, then does the equation $f(x+y^n)=f(x)+[f(y)]^n$ have other solution which is not the solution of [1]?

A: As Yves Daoust mentions, any such $f$ will be additive. Over $\mathbb{R}$, without some condition $f(x)=cx$ is one solution but not the only one - there are infinitely many pathological solutions. For more information, see this Wikipedia page which gives some insight as to why nonlinear additive functions exist.


text:
Q: How to prevent application.properties property inheritence Suppose I have an src/main/ressources/application.properties containing the following (exemplary) entry:
server.ssl.trust-store=/config/app.jks

and multiple application.properties for multiple enviroments
/config
|---/prod
|   |---/application.properties // overrides "server.ssl.trust-store"
|---/int
    |---/application.properties
/src
|---/main
    |---/resources
        |---/application.properties // contains entry "server.ssl.trust-store"

Both application.properties in /config directory inherits from the src/main/resources/application.properties. In /config/prod/application.properties we want to override the entry. This all works as expected.
Now, my question is: is it possible to inhibit the inheritance of properties?
I tried overwriting it with an empty value, but that didn't worked and was differently interpreted as not setting it at all.
Note: For this particular case I know of the existence of server.ssl.enabled=false (source).

A: You could create a new spring profile, for example, ssl, and add the ssl configurations there
# in application-ssl.properties
server.ssl.trust-store=/config/app.jks

You can then enable these configurations in your apps on demand by "importing" the ssl profile.
# in application-prod.properties
spring.profiles.include=ssl

You would leave out this statements where you wouldn't want to have that value present.
Another way is to directly configure conditional properties in the application.properties
# in common application.properties
spring.myproperty=44 # ... etc, normal app properties
---
spring.config.activate.on-profile=ssl # These configs apply to the ssl profile
server.ssl.trust-store=/config/app.jks


text:
Q: Background Color Changes SolidColorBrush bgColor;

public ModernBTN() {
  InitializeComponent();
  this.Loaded += delegate (object sender, RoutedEventArgs e) {
    bgColor = (SolidColorBrush)Background;
    MouseEnter += EnterAnim;
    MouseLeave += LeaveAnim;
  };
}

private void EnterAnim(object sender, MouseEventArgs e) {
  DoubleAnimation anim = new DoubleAnimation(0, myBtn.Width, TimeSpan.FromMilliseconds(200));
  indicatorBtn.BeginAnimation(WidthProperty, anim);
  ColorAnimation animC = new ColorAnimation(BGHover, TimeSpan.FromMilliseconds(200));
  myBtn.Background.BeginAnimation(SolidColorBrush.ColorProperty, animC);
}

private void LeaveAnim(object sender, MouseEventArgs e) {
  DoubleAnimation anim = new DoubleAnimation(myBtn.Width, 0, TimeSpan.FromMilliseconds(200));
  indicatorBtn.BeginAnimation(WidthProperty, anim);
  ColorAnimation animC = new ColorAnimation(Color.FromArgb(bgColor.Color.A, bgColor.Color.R, bgColor.Color.G, bgColor.Color.B), TimeSpan.FromMilliseconds(200));
  myBtn.Background.BeginAnimation(SolidColorBrush.ColorProperty, animC);
}

Please tell me why bgColor changes to BGHover color if I put bgColor values only in this.Loaded and = (SolidColorBrush) Background.
ModernBtn.xaml xaml code of my button
<UserControl x:Class="ModernButton.ModernBTN"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:ModernButton"
         mc:Ignorable="d"
         d:DesignHeight="100" d:DesignWidth="200" Name="myBtn" Background = '#FF282829'>
<Grid Width="Auto" Height="Auto" Name="mainGrid">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
    <TextBlock Text="{Binding ElementName=myBtn, Path=BtnText}" FontSize="24" Foreground="#FFC7BBBB" TextAlignment="Center" Grid.Row="0" Name="txtBtn" Padding="{Binding ElementName=myBtn, Path=TextPadding}"></TextBlock>
    <Rectangle Grid.Row="1" Fill="Lime" Height="5" Name="indicatorBtn" Width="0"></Rectangle>
</Grid>

A:
bgColor = (SolidColorBrush)Background;

Because SolidColorBrush is a reference type, bgColor and Background will reference the same object after the above line. So, when changes are made to Background (as you do with the animation), this changes will be reflected in bgColor.
An easy way to solve this may be to changebgColor to type Color:
Color bgColor;

public MainWindow()
{
   InitializeComponent();
   this.Loaded += delegate (object sender, RoutedEventArgs e) {
        bgColor = ((SolidColorBrush)Background).Color;
        MouseEnter += EnterAnim;
        MouseLeave += LeaveAnim;
   };
}

private void EnterAnim(object sender, MouseEventArgs e)
{
    ColorAnimation animC = new ColorAnimation(BGHover, TimeSpan.FromMilliseconds(200));
    myBtn.Background.BeginAnimation(SolidColorBrush.ColorProperty, animC);
}

private void LeaveAnim(object sender, MouseEventArgs e)
{
    ColorAnimation animC = new ColorAnimation(bgColor, TimeSpan.FromMilliseconds(200));
    myBtn.Background.BeginAnimation(SolidColorBrush.ColorProperty, animC);
}


text:
Q: Set two smtp servers in config file I am trying to set two smtp servers in web.config file but get error
 Unrecognized configuration section system.net/mailSettings/smtp_1.

How correctly to do that?
<configuration>
  <configSections>
    <sectionGroup name="mailSettings">

    </sectionGroup>
  </configSections>

<system.net>
    <mailSettings>
      <smtp_1 from="no-reply1@web2pdfconvert.com" deliveryMethod="specifiedPickupDirectory">
        <specifiedPickupDirectory  pickupDirectoryLocation="C:\Users\Administrator\Projects\temp\wp" />
        <network host="smtp...." enableSsl="true" userName="..." password="..." port="587"  />
      </smtp_1>
      <smtp_2 from="no-reply2@web2pdfconvert.com" deliveryMethod="specifiedPickupDirectory">
        <specifiedPickupDirectory  pickupDirectoryLocation="C:\Users\Administrator\Projects\temp\wp" />
        <network host="smtp...." port="25" />
      </smtp_2>
    </mailSettings>
  </system.net>
</configuration>

A: MailSettings is not intended for this purpouse: this section is the place in configuration where you can store SMTP params, so you won't need to change them programmatically when you create a new SmtpClient.
If you want you can create your own section but not change the original one, like this:
<configuration>
 <configSections>
   <sectionGroup name="myMailSettings">

   </sectionGroup>
 </configSections>
 <myMailSettings>
  <smtp_1 from="no-reply1@web2pdfconvert.com" deliveryMethod="specifiedPickupDirectory">
    <specifiedPickupDirectory  pickupDirectoryLocation="C:\Users\Administrator\Projects\temp\wp" />
    <network host="smtp...." enableSsl="true" userName="..." password="..." port="587"  />
  </smtp_1>
  <smtp_2 from="no-reply2@web2pdfconvert.com" deliveryMethod="specifiedPickupDirectory">
    <specifiedPickupDirectory  pickupDirectoryLocation="C:\Users\Administrator\Projects\temp\wp" />
    <network host="smtp...." port="25" />
  </smtp_2>
</myMailSettings>
....

and finally don't forget to write some code to use that data!


text:
Q: Objects not getting passed into localstorage - React JS So I'm trying to make a web application where it fetches data from backend API and displays it into frontend (This works) and also having add to cart functionality. I'm trying to store the requested item into localstorage and using state too, When the user clicks on add to cart it should store the item or objects in their localstorage. When I click add to cart this gets added cartItems [object Object](This is not clickable) which is not what I want. I want to store the actual objects in localstorage.
import { Card, Button } from 'react-bootstrap'
import axios from 'axios'

function HomeScreen() {
    const [products, setProducts] = useState([])
    const [cart, setCart] = useState([])
    function handleClick(id) {
        const chosen_product = axios.get(`http://localhost:8000/api/products/${id}`)
        setCart(cart + {chosen_product})
        localStorage.setItem("cartItems", cart)
    }
    useEffect(() => {
        async function getProducts() {
            try {
              const response = await axios.get('http://localhost:8000/api/products/');
              setProducts(response.data);
            } catch (error) {
              console.error(error);
            }
          }
       getProducts()
    },[])
    return (

            {products.map(product => (
                <Card className="my-3 p-3 rounded" key={product.id}>
            <Card.Img src={'http://localhost:8000' + product.image} />
            <Card.Body>
            <Card.Title as="div">
                {product.name}
            </Card.Title>
            <Card.Text as="div">

            </Card.Text>
            <Card.Text as="h3">
            ${product.price}
            </Card.Text>
            <Card.Link>
                <Button onClick={()=>handleClick(product.id)} className="btn-primary">Add to cart</Button>
            </Card.Link>
            </Card.Body>
        </Card>
            ))}

    )
}

export default HomeScreen

A: You need to store things in localStorage as a string. You also need to wait for the API response, axios.get returns a Promise.
async function handleClick(id) {
  try {
    const chosen_product = await axios.get(`http://localhost:8000/api/products/${id}`)
    setCart(cart + {chosen_product}) // This is wrong, can't add array to object
    localStorage.setItem("cartItems", JSON.stringify(cart)) // This is wrong, cart will still be the previous value
  } catch (err) {
    console.error(err)
  }
}

In fact you already have this code structure in getProducts...
Also this code makes no sense:
setCart(cart + {chosen_product})

You can't add an object to an array.
Also setting cart straight after setCart won't work and cart will still be your previous value at that point, simplest solution is to create a variable for your new state.
const newCart = cart.concat(chosen_product);
setCart(newCart);
localStorage.setItem("cartItems", JSON.stringify(newCart));

A: You need to make the object into a JSON string like so:
localStorage.setItem("cartItems", JSON.stringify(cart))

And you can then get the item and parse it like this:
JSON.parse(localStorage.getItem("cartItems"))

And you are back to a Javascript object.

A: You need to stringify the object because
localStorage.setItem("cartItems", JSON.stringify(cart))

and you can parse the item to js object again using JSON.parse
JSON.parse(localStorage.getItem('cartItems'))

A: You need to store the object value after stringifying it.

storage.setItem(keyName, keyValue);

keyName
A DOMString containing the name of the key you want to create/update.
keyValue
A DOMString containing the value you want to give the key you are creating/updating.
Storing:
localStorage.setItem("cartItems", JSON.stringify(cart))

Retrieving:
const val = JSON.parse(localStorage.getItem("cartItems"))


text:
Q: unable to show username in angular i have implemented authentication using jwt tokenization and after login I want to display username on the navbar, but it is not showing anything and giving error on console "ERROR TypeError: Cannot read property 'username' of undefined" but after refreshing the page it is showing the username and still giving the same error on the console.
Here is my code
NavbarComponent.ts

import { Component, OnDestroy } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { User } from '../../shared/user';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { AdminAuthGuard } from '../../guards/admin.auth.guard';
import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent {

  user$: any;

  constructor(private authService: AuthService, private router: Router, private adminGuard: AdminAuthGuard) {
    this.authService.getProfile().subscribe((user) => {
      console.log('fsdf' + user.user.email);
      this.user$ =  user.user;
    });
   }

  onLogoutClick() {
    // console.log('this.user' + this.user$.email);
    this.authService.logout();
    this.router.navigate(['/']);
  }

}

The html code in which i'm printing the username.

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home (current)

        Login

        Register

        Shopping Cart

        {{ user$.username }}

          My Orders
          Profile

          Manage Orders
          Manage Products
          <button class="dropdown-item" (click)="onLogoutClick()">Logout</button>

The authentication service code.Focus on getProfile() method

import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { Http, Headers, RequestOptions } from '@angular/http';
// import { map } from "rxjs/operators";
// import { map } from 'rxjs/operators';

import { switchMap } from 'rxjs/operators';
import { tokenNotExpired } from 'angular2-jwt';
import { User } from '../shared/user';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/observable/of';
@Injectable()
export class AuthService {
  private subject = new Subject<any>();
  domain = 'http://localhost:3000';
  authToken;
  user;
  options;

  constructor(private http: Http) { }

  registerUser(user) {
    return this.http.post(this.domain + '/authentication/register', user).map(res => res.json());
  }

  createAuthenticationHeaders() {
    this.loadToken();
    this.options = new RequestOptions({
      headers : new Headers({
        'Content-Type': 'application/json',
        'authorization': this.authToken
      })
    });

  }

  loadToken() {
    this.authToken = localStorage.getItem('token');
  }
  checkUsername(username) {
    return this.http.get(this.domain + '/authentication/checkUsername/' + username).map(res => res.json());
  }

  checkEmail(email) {
    return this.http.get(this.domain + '/authentication/checkEmail/' + email).map(res => res.json());
  }

  login(user) {
    return this.http.post(this.domain + '/authentication/login', user).map(res => res.json());
  }

  logout() {
    this.authToken = null;
    this.user = null;
    localStorage.clear();
  }
  storeUserData(token, user) {
    localStorage.setItem('token', token);
    localStorage.setItem('user', JSON.stringify(user));
    this.authToken = token;
    this.user = user;
  }

  getProfile() {
    this.createAuthenticationHeaders();
    return this.http.get(this.domain + '/authentication/profile', this.options).map(res => res.json());
  }

  loggedIn() {
    return tokenNotExpired();
  }

}

This is the http routed API which is fetching the user from mongodb database written in Node.js. Focus on get() for '/profile' method, it's returning an Observable.

const User = require('../models/user'); // Import User Model Schema

const jwt = require('jsonwebtoken');
const config = require('../config/database');

module.exports = (router) => {
  /* ==============
     Register Route
  ============== */
  router.post('/register', (req, res) => {
    // Check if email was provided
    if (!req.body.email) {
      res.json({ success: false, message: 'You must provide an e-mail' }); // Return error
    } else {
      // Check if username was provided
      if (!req.body.username) {
        res.json({ success: false, message: 'You must provide a username' }); // Return error
      } else {
        // Check if password was provided
        if (!req.body.password) {
          res.json({ success: false, message: 'You must provide a password' }); // Return error
        } else {
          // Create new user object and apply user input
          let user = new User({
            email: req.body.email.toLowerCase(),
            username: req.body.username.toLowerCase(),
            password: req.body.password
          });
          // Save user to database
          user.save((err) => {
            // Check if error occured
            if (err) {
              // Check if error is an error indicating duplicate account
              if (err.code === 11000) {
                res.json({ success: false, message: 'Username or e-mail already exists' }); // Return error
              } else {
                // Check if error is a validation rror
                if (err.errors) {
                  // Check if validation error is in the email field
                  if (err.errors.email) {
                    res.json({ success: false, message: err.errors.email.message }); // Return error
                  } else {
                    // Check if validation error is in the username field
                    if (err.errors.username) {
                      res.json({ success: false, message: err.errors.username.message }); // Return error
                    } else {
                      // Check if validation error is in the password field
                      if (err.errors.password) {
                        res.json({ success: false, message: err.errors.password.message }); // Return error
                      } else {
                        res.json({ success: false, message: err }); // Return any other error not already covered
                      }
                    }
                  }
                } else {
                  res.json({ success: false, message: 'Could not save user. Error: ', err }); // Return error if not related to validation
                }
              }
            } else {
              res.json({ success: true, message: 'Acount registered!' }); // Return success
            }
          });
        }
      }
    }
  });

  router.get('/checkEmail/:email', (req, res) => {
    if (!req.params.email) {
      res.json({ success: false, message: 'email not provided'});
    } else {
      User.findOne({ email: req.params.email}, (err, user) => {
        if (err) {
          res.json({ success: false, message: err});
        } else {
          if (user) {
            res.json({ success: false, message: 'email taken'});
          } else {
            res.json({ success: true, message: 'email available'});
          }
        }
      });
    }
  });

  router.get('/checkUsername/:username', (req, res) => {
    if (!req.params.username) {
      res.json({ success: false, message: 'username not provided'});
    } else {
      User.findOne({ username: req.params.username}, (err, user) => {
        if (err) {
          res.json({ success: false, message: err});
        } else {
          if (user) {
            res.json({ success: false, message: 'username taken'});
          } else {
            res.json({ success: true, message: 'username available'});
          }
        }
      });
    }
  });

  router.post('/login', (req, res) => {
    if (!req.body.username) {
      res.json({ success: false, message: 'No username was provided'});
    } else {
      if (!req.body.password) {
        res.json({ success: false, message: 'No password was provided'});
      } else {
        User.findOne({ username: req.body.username.toLowerCase() }, (err, user) => {
          if (err) {
            res.json({ success: false, message: err});
          } else {
            if (!user) {
              res.json({ success: false, message: 'No user exist'});
            } else {
              const validPassword = user.comparePassword(req.body.password);
              if (!validPassword) {
                res.json({ success: false, message: 'password invalid'});
              } else {
                const token = jwt.sign({userId: user._id}, config.secret, {expiresIn: '24h'});
                res.json({ success: true, message: 'Success!', token: token, user: {username: user.username}});
              }
            }
          }
        });
      }
    }
  });

// MIDDLEWARE TO INTERCEPT HEADERS
// THIS MIDDLEWARE DECRYPTS THE TOKEN
  router.use((req, res, next) => {
    const token = req.headers['authorization']; // whenever a request coming from angular2 with headers attached it is going to search fot this header
    if (!token) {
      res.json({ success: false, message: 'No token provided'});
    } else {
      jwt.verify(token, config.secret, (err, decoded) => {
        if (err) {
          res.json({ success: false, message: 'invalid token' + err});
        } else {
          req.decoded = decoded;
          next();
        }
      });
    }
  })
// ANY ROUTES COMING AFTER THIS MIDDLEWARE WILL PASS THROUGH THE SAME

// BELOW METHOD TAKES THE DECRYPTED TOKEN FIND THE USER
  router.get('/profile', (req, res) => {
    User.findOne({ _id: req.decoded.userId }).select('username email isAdmin').exec((err, user) => {
      if (err) {
        res.json({ success: false, message: err});
      } else {
        if (!user) {
          res.json({ success: false, message: 'user not found'});
        } else {
          res.json({ success: true, user: user });
        }
      }
    });
  });

  return router; // Return router object to main index.js
}

A: Try using safe navigation operator or *ngIf since you are making a request to your API and getting the data asynchronously. Try as follows,
   {{ user$?.username }}

A: I'm pretty sure this happen to you because you're trying to access user$.username  when username property doesn't exist. To avoid that error you can use a defined type and then initialize, eg.
public $user: UserInterface = {
    username: ''
}

or whether you don't want to use defined types, just add an extra validation to html block using ngIf, eg.
{{ user$.username }}

btw, as a good coding practice, use public method declaration for methods that are shared between code and view, aot build will thanks to you.


text:
Q: How to resize current browser window in Selenium WebDriver with PHP? When I try
$this->size(array('width' => 960, 'height' => 400));

I get "BadMethodCallException: The command 'size' is not existent or not supported yet."
I've also tried this
$win = $this->window("")->size(array('width' => 960, 'height' => 400));

but that just gets me a null object.

A: You may try the methold currentWindow()
$win=$this->currentWindow();
$win->size(array('width' => 960, 'height' => 400));


text:
Q: Is it difficult to prove that nature is chaotic? If we have a Markov coding or another symbolic description of a dynamical system it is usually easy to prove that the system is chaotic (in the sense of of Li-York, Devaney, positive entropy of what ever). My impression is that most (interesting) dynamical systems coming of natural science are in fact chaotic. But this is rigourously proved only for a few systems. What is the reason for this? Is it difficult to find a symbolic coding for systems coming from natural science or are we (as mathematicians) not so much interested in these systems?

A: Even rather simple isolated natural phenomenon are complex. In the sense that although they can in principle be written in mathematical terms, we don't have the time and energy to do it. The question becomes therefore: can we prove chaos when we don't know the exact model ?
Both mathematicians and physicists work about this question. Physicist identify so-called universal models, like KdV equation, KPP, harmonic oscillator, etc ..., with the idea that they are the principal part of more complex models ; in mathematical terms, they are normal forms. Mathematicians, in particular dynamicists, prove that some trajectories are structurally stable, under an initial pertubation and a slight change of the dynamical system.
There is some hope that, for some not-too-complex natural systems, we could prove that, even if we don't know the exact model, it is close enough to a simple system (say Lorenz system), so that it inherits the chaotic behaviour of the latter. This is not very far from Feigenbaum's approach to establish the universality of the constant that bears his name.

A: Most rigorous studies of "natural" systems, whether chaotic or not, are in the context of small perturbations of simple systems. Going beyond that usually requires the help of numerics, and a full "proof" would require rigorous error estimates. This tends to be extremely tedious, raising the question whether it is worth doing (who would read the paper?). Proofs of chaos by perturbation approaches do exist, e.g. Melnikov's method, Silnikov's method.

A: There are a number of real systems that have been extensively studied in the lab that show either classical/ray chaos and quantum/wave chaos.  Typically the measurement involves analyzing the higher order modes or eigenfunctions of the system (in the quantum/wave case).
These examples include the studies of Wada boundaries in ray scattering in a system of 4 reflecting balls (by James Yorke's group--made the cover of Nature, below), the measurement of scars in the bunimovich stadium for high mode number, the level spacings in superconducting microwave resonators and, perhaps the most impressive, in the level spacing of a quartz resonator.  Mark Oxborrow and his group were able to show the switchover from Poisson to Wigner statistics in a quartz resonator where they started with an integrable geometry and made small perturbations (shaving on a tiny bit of one corner).  In their more recent work they were able to correctly identify something like 100k modes for their calculation.[2]  To see this many modes AND correctly identify them is a real tour de force.  It requires extremely high Q resonators and an accurate way to model them.  They also measured parametric correlations predicted by random matrix theory.
Here is a photograph (not simulation) of the Wada basins in the 4 ball scattering problem (from:  https://www.nature.com/articles/20573).

[2]: Measurement of parametric correlations in spectra of resonating quartz blocks P Bertelsen, C Ellegaard, T Guhr, M Oxborrow… - Physical Review Letters, 1999


text:
Q: Convert Excel into HTML I want to display my excel sheet into html view.
I tried using dot net (database method) and facing some problem. For empty cells I am getting default value (for example A1 cell is empty it display as A1). I want to display only data.
Any other easy way to do this?

A: Easiest method is to save excel file as web page.

A: I'd recommend using a library, then it is very simple FlexCel is my provider of choice.