问:
jadclipse Error during DECOMPILATION REPORT
I am using Eclipse Helios Version and imported an existing project into IDE.

This Project is consisting some code in form of Jar files

So I have installed Jad Eclipse plugin .

Now my question is from the IDE  Whenever i click class (Ctrl + Mouse) which is in jar files , instead of java file ,i m getting this

```<code>/*jadclipse*/

/*
    DECOMPILATION REPORT

    Decompiled from: C:\Documents and Settings\Sai\Desktop\work\kiuybon-1.1.jar
    Total time: 0 ms
    Jad reported messages/errors:
    Exit status: 0
    Caught exceptions:
java.io.IOException: Cannot run program "jad" (in directory "C:\Documents and Settings\Sai\.net.sf.jadclipse\1321168101468"): CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at net.sf.jadclipse.JadDecompiler.decompile(JadDecompiler.java:160)
    at net.sf.jadclipse.JadDecompiler.decompileFromArchive(JadDecompiler.java:217)
    at
</code>```

答:
I encountered the same error: jadclipse

```<code> DECOMPILATION REPORT
 Decompiled from: D:\nnn\nnnn\lib\nnn3.1.1.jar
 Total time: 0 ms
 Jad reported messages/errors:
 Exit status: 0
 Caught exceptions:
java.io.IOException: Cannot run program "c:\jad" (in directory "C:\jad\1490924748657"):
         CreateProcess error=5, Access is denied
</code>```

To solve it I did the following steps:

Added my windows profile as the owner of the jad.exe. I was already admin on my machine but doing only this did not solve the problem.

jad.exe > right click > Properties > security > advanced > owner tab >
change owner to > my windows profile

Restart eclipse. Tried debugging again and the problem is solved.

Body:
I am using Eclipse Helios Version and imported an existing project into IDE.

This Project is consisting some code in form of Jar files

So I have installed Jad Eclipse plugin .

Now my question is from the IDE  Whenever i click class (Ctrl + Mouse) which is in jar files , instead of java file ,i m getting this

/*jadclipse*/

/*
    DECOMPILATION REPORT

    Decompiled from: C:\Documents and Settings\Sai\Desktop\work\kiuybon-1.1.jar
    Total time: 0 ms
    Jad reported messages/errors:
    Exit status: 0
    Caught exceptions:
java.io.IOException: Cannot run program "jad" (in directory "C:\Documents and Settings\Sai\.net.sf.jadclipse\1321168101468"): CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at net.sf.jadclipse.JadDecompiler.decompile(JadDecompiler.java:160)
    at net.sf.jadclipse.JadDecompiler.decompileFromArchive(JadDecompiler.java:217)
    at

Body:
I encountered the same error: jadclipse

 DECOMPILATION REPORT
 Decompiled from: D:\nnn\nnnn\lib\nnn3.1.1.jar
 Total time: 0 ms
 Jad reported messages/errors:
 Exit status: 0
 Caught exceptions:
java.io.IOException: Cannot run program "c:\jad" (in directory "C:\jad\1490924748657"):
         CreateProcess error=5, Access is denied

To solve it I did the following steps:

Added my windows profile as the owner of the jad.exe. I was already admin on my machine but doing only this did not solve the problem.

jad.exe > right click > Properties > security > advanced > owner tab >
change owner to > my windows profile

Restart eclipse. Tried debugging again and the problem is solved.


来源: stackexchange

问:
Nginx reload error in mac osx
Greeting,
i have a server installed nginx streaming
i did stop nginx and then did reload it, but it show me below error and was not start:

```<code>nginx -s stop
nginx: [error] open() "/usr/local/var/run/nginx.pid" failed (2: No     such file or directory)
</code>```

i did below command and nothing:

```<code>sudo nginx
nginx: [emerg] open() "/usr/local/var/run/nginx.pid" failed (2: No such file or directory)
</code>```

how i can resolve it?
can anyone give me PID file content so i can creat it (Fake).

Thank you for your help.

答: your nginx does not start, start the nginx use nginx command

ContentLicense: CC BY-SA 3.0

Title: Nginx reload error in mac osx

Body:
Greeting,
i have a server installed nginx streaming
i did stop nginx and then did reload it, but it show me below error and was not start:

nginx -s stop
nginx: [error] open() "/usr/local/var/run/nginx.pid" failed (2: No     such file or directory)

i did below command and nothing:

sudo nginx
nginx: [emerg] open() "/usr/local/var/run/nginx.pid" failed (2: No such file or directory)

how i can resolve it?
can anyone give me PID file content so i can creat it (Fake).

Thank you for your help.


问:
How to query database to fetch a child if its contents contain something?
I have a schema that looks like this. I want a database to return a child (post-ID) and its contents if favoriteBy contains the UID that I am looking for. Is this possible?

UID is defined by this variable:

```<code>private final String UID = FirebaseAuth.getInstance().getCurrentUser().getUid();
</code>```

For reference, to fetch all user posts that were posted by the user, it would be fetched with this Query object:

```<code>databaseReference.child("user-posts").child(UID).limitToFirst(100);
</code>```

答:
Firebase does not provide a lot of filtering tools to query data. So using only your current structure this won't be possible.

Without changing you current posts structure what I would recommend you to do is, whenever a user set a post as favorite you also updates another branch of your firebase database in a way you could easily get this data later.

So you can save the poster ownerUID and postID under the UID that had fav the post.

```<code>favoritedPosts: {
    UID: { //UID you are looking for
        postOwnerUID: {
            postID: true
        }
     }
}
</code>```

Then you would easily get the favorited posts postOwnerUID and postID with something like:

```<code>databaseReference.child('favoritedPosts').child(UID)
</code>```

The above query will return an object with postOwnerUIDs and their postIDs then finally you can iterate this object to retrieve the posts content with the IDs you have now.

```<code>databaseReference.child('user-posts').child(postOwnerUID).child(postID)
</code>```

Body:
I have a schema that looks like this. I want a database to return a child (post-ID) and its contents if favoriteBy contains the UID that I am looking for. Is this possible?

UID is defined by this variable:

private final String UID = FirebaseAuth.getInstance().getCurrentUser().getUid();

For reference, to fetch all user posts that were posted by the user, it would be fetched with this Query object:

databaseReference.child("user-posts").child(UID).limitToFirst(100);

Body:
Firebase does not provide a lot of filtering tools to query data. So using only your current structure this won't be possible.

Without changing you current posts structure what I would recommend you to do is, whenever a user set a post as favorite you also updates another branch of your firebase database in a way you could easily get this data later.

So you can save the poster ownerUID and postID under the UID that had fav the post.

favoritedPosts: {
    UID: { //UID you are looking for
        postOwnerUID: {
            postID: true
        }
     }
}

Then you would easily get the favorited posts postOwnerUID and postID with something like:

databaseReference.child('favoritedPosts').child(UID)

The above query will return an object with postOwnerUIDs and their postIDs then finally you can iterate this object to retrieve the posts content with the IDs you have now.

databaseReference.child('user-posts').child(postOwnerUID).child(postID)


问:
Slim php / Eloquent custom query for hasMany-relation
I'm currently working with Slim php-framework and eloquent-database:
https://www.slimframework.com/docs/cookbook/database-eloquent.html

What I want to do is to use a custom SQL-query to set up a hasMany-relation of two models.

Let's say, I have two models "User" and "Entry".

My User.php looks like this

```<code>class User extends \Illuminate\Database\Eloquent\Model {
    protected $table = 'users';

    public function entries() {
        return $this->hasMany('foo\bar\Entry');
    }
</code>```

}

To fetch the entries I use the following code which works as expected.

```<code>$userentries = User::find(1)->entries
</code>```

But, I'd like the entries to be fetched with a custom SQL-query like

```<code>SELECT e.user_id, e.colB, SUM(e.colC - e.colD) as foobar from entries as e where e.user_id = 1 group by e.colB order by foobar DESC;
</code>```

instead of the default SELECT * from entries where user_id = 1; but still keep the Entry-model associated to the User's entries property. Is that possible?

答:
If I'm understanding your question correctly, you can do this:

```<code>$userentries = User::where('some', 'conditon')->with('entries')->get();
</code>```

So you basically just add with('entries') to your query.

Body:
I'm currently working with Slim php-framework and eloquent-database:
https://www.slimframework.com/docs/cookbook/database-eloquent.html

What I want to do is to use a custom SQL-query to set up a hasMany-relation of two models.

Let's say, I have two models "User" and "Entry".

My User.php looks like this

class User extends \Illuminate\Database\Eloquent\Model {
    protected $table = 'users';

    public function entries() {
        return $this->hasMany('foo\bar\Entry');
    }

}

To fetch the entries I use the following code which works as expected.

$userentries = User::find(1)->entries

But, I'd like the entries to be fetched with a custom SQL-query like

SELECT e.user_id, e.colB, SUM(e.colC - e.colD) as foobar from entries as e where e.user_id = 1 group by e.colB order by foobar DESC;

instead of the default SELECT * from entries where user_id = 1; but still keep the Entry-model associated to the User's entries property. Is that possible?

Body:
If I'm understanding your question correctly, you can do this:

$userentries = User::where('some', 'conditon')->with('entries')->get();

So you basically just add with('entries') to your query.


问:
How to sync with a remote Git repository?
I forked a project on github, made some changes, so far so good.

In the meantime, the repository I forked from changed and I would like to get those changes into my repository. How do I do that ?

答:
Assuming their updates are on master, and you are on the branch you want to merge the changes into.

```<code>git remote add origin https://github.com/<github-username>/<repo-name>.git
git pull origin master
</code>```

Also note that you will then want to push the merge back to your copy of the repository:

```<code>git push origin master
</code>```

Body:
Assuming their updates are on master, and you are on the branch you want to merge the changes into.

git remote add origin https://github.com/<github-username>/<repo-name>.git
git pull origin master

Also note that you will then want to push the merge back to your copy of the repository:

git push origin master


问:
Erroneous "no diffs found" when importing a patch
I've made changes to 2 files. I've run hg diff > 1 followed by revert --all; then I updated the repo to the new revision. Now I'm trying to import my changes back, but it fails

```<code>hg import 1 --no-commit
applying 1
abort: 1: no diffs found
</code>```

The diff file 1 is well-formed and not empty. Fun fact: updating back to the revision for which the patch was created still doesn't let me import it.

What's going on and how to fix it?

答: Check the encoding of your diff file. If it's not in UTF-8, convert it and try again. There may be byte order marks or something similar messing things up.</p>

Body:
I've made changes to 2 files. I've run hg diff > 1 followed by revert --all; then I updated the repo to the new revision. Now I'm trying to import my changes back, but it fails

hg import 1 --no-commit
applying 1
abort: 1: no diffs found

The diff file 1 is well-formed and not empty. Fun fact: updating back to the revision for which the patch was created still doesn't let me import it.

What's going on and how to fix it?


问:
Problems with nodeS CORS
I am trying to display a dicom with NODEJS but the browser throws me this problem

XMLHttpRequest can not load http: // localhost: 8080 / wado?
  RequestType = WADO & studyUID = 1.2.840.113704.1.111.5 ... 26513.429 &
  contentType = application% 2Fdicom & transferSyntax =
  1.2.840.10008.1.2. In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http: // localhost: 3000' is
  therefore not allowed access.

Then install npm the package cors

And here I leave my code part of my code app.js

```<code>Var express = require ('express');
Var cors = require ('cors')
App.use (cors ())

App.listen (3000, function () {
  Console.log ('listening on 3000')
})
</code>```

Also try adding this in app.js

```<code>App.use (function (req, res, next) {
  Res.header ("Access-Control-Allow-Origin", "*");
  Res.header ("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  Next ();
});
</code>```

But the browser still displays the error:

XMLHttpRequest can not load http: // localhost: 8080 / wado?
  RequestType = WADO & studyUID = 1.2.840.113704.1.111.5 ... 26513.429 &
  contentType = application% 2Fdicom & transferSyntax =
  1.2.840.10008.1.2. In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http: // localhost: 3000' is
  therefore not allowed access.

I have doubt because I also use the route index.js which I leave here

```<code>var express = require('express');
var router = express.Router();
var cors = require('cors')
/*var express = require('express');
var router = express.Router();*/
var mysql = require('mysql');
router.use(cors({origin: 'http://localhost:3000'}));
/* GET home page. */
router.get('/', function(req, res, next) {
 res.render('index', { title: 'Express' });
});

module.exports = router;
</code>```

I'm sorry for my English

答:
For security purpose browsers don't allow cross origin requests under normal conditions.

Your page is loading from localhost:3000, which defines the origin as it is the first request. Your code is trying to load data from another service running on port- 8080, that is different from origin. So basically you need to enable cors on the service running on port 8080 as it is the external source.

Title: Problems with nodeS CORS

Body:
I am trying to display a dicom with NODEJS but the browser throws me this problem

XMLHttpRequest can not load http: // localhost: 8080 / wado?
  RequestType = WADO & studyUID = 1.2.840.113704.1.111.5 ... 26513.429 &
  contentType = application% 2Fdicom & transferSyntax =
  1.2.840.10008.1.2. In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http: // localhost: 3000' is
  therefore not allowed access.

Then install npm the package cors

And here I leave my code part of my code app.js

Var express = require ('express');
Var cors = require ('cors')
App.use (cors ())

App.listen (3000, function () {
  Console.log ('listening on 3000')
})

Also try adding this in app.js

App.use (function (req, res, next) {
  Res.header ("Access-Control-Allow-Origin", "*");
  Res.header ("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  Next ();
});

But the browser still displays the error:

XMLHttpRequest can not load http: // localhost: 8080 / wado?
  RequestType = WADO & studyUID = 1.2.840.113704.1.111.5 ... 26513.429 &
  contentType = application% 2Fdicom & transferSyntax =
  1.2.840.10008.1.2. In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http: // localhost: 3000' is
  therefore not allowed access.

I have doubt because I also use the route index.js which I leave here

var express = require('express');
var router = express.Router();
var cors = require('cors')
/*var express = require('express');
var router = express.Router();*/
var mysql = require('mysql');
router.use(cors({origin: 'http://localhost:3000'}));
/* GET home page. */
router.get('/', function(req, res, next) {
 res.render('index', { title: 'Express' });
});

module.exports = router;

I'm sorry for my English


问:
C#: Have my whole program run in the background
I am working on an app that creates a mock location. Now, after I start it - everything seems to work here - and then go into maps, I always get set right to where I actually am - not where my fake coordinates are. So im thinking, this is due to my program immediately stopping as soon as i push it into the background of the android phone im debugging with.

1) Would u say so too?
2) So, how do I get my program to continue mocking the location, even though its in the background? I already set up a timer, that mocks a new location every 5 seconds. Here is my main activity (which happens to be a bit long, excuse me..)

Any help would be AWESOME!

```<code>  public static double GlobalLongitude = 0.0; // global, cause i need to pull string from void method
    public static double GlobalLatitude = 0.0;

    static readonly string TAG = "X:" + typeof(Activity1).Name;
    Location _currentLocation;
    LocationManager _locationManager;

    string _locationProvider;
    TextView _locationText;
    static TextView txtAdded;
    static Button btnMain;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        _locationText = FindViewById<TextView>(Resource.Id.GpsTest);
        txtAdded = FindViewById<TextView>(Resource.Id.AddedCoordinates);
        btnMain = FindViewById<Button>(Resource.Id.startbutton);

        CountDown();
        InitializeLocationManager();
    } // start here! :D

    private void CountDown()
    {

        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Interval = 5000;
        timer.Elapsed += OnTimedEvent;
        timer.Enabled = true;

    }

    private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e) // txt.Added is here!
    {
         txtAdded.Text = SetMockLocation();
    }

    public void OnLocationChanged(Location location)
    {
        string test = "Null";
        string test2 = "Null";
        bool waitforresult = false;

        _currentLocation = location;
        if (_currentLocation == null)
        {
            _locationText.Text = "Unable to determine your location. Try again in a short while.";
        }
        else
        {
            _locationText.Text = string.Format("Unchanged: {0:f5} {1:f5}", _currentLocation.Latitude, _currentLocation.Longitude);// hh: 53, 10
            //das her wird ausgegeben bei button.click

            test = string.Format("{0:f5}", _currentLocation.Latitude); // to format
            test2 = string.Format("{0:f5}", _currentLocation.Longitude);

            double.TryParse(test, out GlobalLatitude);
            double.TryParse(test2, out GlobalLongitude);

            if (test != "Null")
            {
                waitforresult = true;
            }

            if (waitforresult == true)
            {
                Add700ToCoordinates();
            }
        }

    } // ausgabe der koordinaten

    void InitializeLocationManager()
    {
        _locationManager = (LocationManager)GetSystemService(LocationService);
        Criteria criteriaForLocationService = new Criteria
        {
            Accuracy = Accuracy.Fine
        };
        IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);

        if (acceptableLocationProviders.Any())
        {
            _locationProvider = acceptableLocationProviders.First();
        }
        else
        {
            _locationProvider = string.Empty;
        }
        Log.Debug(TAG, "Using " + _locationProvider + ".");

    }

    protected override void OnResume()
    {
        base.OnResume();
        _locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
        Log.Debug(TAG, "Listening for location updates using " + _locationProvider + ".");
    }

    protected override void OnPause()
    {
        base.OnPause();
        _locationManager.RemoveUpdates(this);
        Log.Debug(TAG, "No longer listening for location updates.");
    }

    public static double Add700ToCoordinates()
    {
        string xy = "Null";

        double FinalCoordinates = (GlobalLatitude + 0.01065);

        btnMain.Click += (sender, e) =>
        {

            xy = FinalCoordinates.ToString();
            xy = xy + " " + GlobalLongitude.ToString();

        };

        return FinalCoordinates;
    }

    public static string SetMockLocation()
    {

        var context = Android.App.Application.Context;
        var locationManager = context.GetSystemService(LocationService) as LocationManager;

        locationManager.AddTestProvider("Test09", false, false, false, false, false, false, false, Power.Low, Android.Hardware.SensorStatus.AccuracyHigh);
        locationManager.SetTestProviderEnabled("Test09", true);

        var location = new Location("Test09");
        location.Latitude = Add700ToCoordinates();
        location.Longitude = GlobalLongitude;
        location.Accuracy = 0; // ob das geht?... ja, aber was beduetet es?
        location.Time = DateTime.Now.Ticks;
        location.ElapsedRealtimeNanos = 100;  // hier das gleiche... was hießt es? :D
        locationManager.SetTestProviderLocation("Test09", location);

        //Check if your event reacted the right way

        locationManager.RemoveTestProvider("Test09");

        return location.Latitude.ToString();
    }

}
</code>```

}

答:
There are probably two things at play here - service and background processing.

You can set the mock locations, probably, as a service that runs in the background. You can do this in the native code.

And if you are using Xamarin or Xamarin Forms you can utilize the MessagingCenter feature to talk/access the service.

You can have native code running services in the background and your PCL/shared code can access from native code information that you need.

You can check on this link for some very helpful example and walkthrough.

Body:
I am working on an app that creates a mock location. Now, after I start it - everything seems to work here - and then go into maps, I always get set right to where I actually am - not where my fake coordinates are. So im thinking, this is due to my program immediately stopping as soon as i push it into the background of the android phone im debugging with.

1) Would u say so too?
2) So, how do I get my program to continue mocking the location, even though its in the background? I already set up a timer, that mocks a new location every 5 seconds. Here is my main activity (which happens to be a bit long, excuse me..)

Any help would be AWESOME!

  public static double GlobalLongitude = 0.0; // global, cause i need to pull string from void method
    public static double GlobalLatitude = 0.0;

    static readonly string TAG = "X:" + typeof(Activity1).Name;
    Location _currentLocation;
    LocationManager _locationManager;

    string _locationProvider;
    TextView _locationText;
    static TextView txtAdded;
    static Button btnMain;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        _locationText = FindViewById<TextView>(Resource.Id.GpsTest);
        txtAdded = FindViewById<TextView>(Resource.Id.AddedCoordinates);
        btnMain = FindViewById<Button>(Resource.Id.startbutton);

        CountDown();
        InitializeLocationManager();
    } // start here! :D

    private void CountDown()
    {

        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Interval = 5000;
        timer.Elapsed += OnTimedEvent;
        timer.Enabled = true;

    }

    private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e) // txt.Added is here!
    {
         txtAdded.Text = SetMockLocation();
    }

    public void OnLocationChanged(Location location)
    {
        string test = "Null";
        string test2 = "Null";
        bool waitforresult = false;

        _currentLocation = location;
        if (_currentLocation == null)
        {
            _locationText.Text = "Unable to determine your location. Try again in a short while.";
        }
        else
        {
            _locationText.Text = string.Format("Unchanged: {0:f5} {1:f5}", _currentLocation.Latitude, _currentLocation.Longitude);// hh: 53, 10
            //das her wird ausgegeben bei button.click

            test = string.Format("{0:f5}", _currentLocation.Latitude); // to format
            test2 = string.Format("{0:f5}", _currentLocation.Longitude);

            double.TryParse(test, out GlobalLatitude);
            double.TryParse(test2, out GlobalLongitude);

            if (test != "Null")
            {
                waitforresult = true;
            }

            if (waitforresult == true)
            {
                Add700ToCoordinates();
            }
        }

    } // ausgabe der koordinaten

    void InitializeLocationManager()
    {
        _locationManager = (LocationManager)GetSystemService(LocationService);
        Criteria criteriaForLocationService = new Criteria
        {
            Accuracy = Accuracy.Fine
        };
        IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);

        if (acceptableLocationProviders.Any())
        {
            _locationProvider = acceptableLocationProviders.First();
        }
        else
        {
            _locationProvider = string.Empty;
        }
        Log.Debug(TAG, "Using " + _locationProvider + ".");

    }

    protected override void OnResume()
    {
        base.OnResume();
        _locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
        Log.Debug(TAG, "Listening for location updates using " + _locationProvider + ".");
    }

    protected override void OnPause()
    {
        base.OnPause();
        _locationManager.RemoveUpdates(this);
        Log.Debug(TAG, "No longer listening for location updates.");
    }

    public static double Add700ToCoordinates()
    {
        string xy = "Null";

        double FinalCoordinates = (GlobalLatitude + 0.01065);

        btnMain.Click += (sender, e) =>
        {

            xy = FinalCoordinates.ToString();
            xy = xy + " " + GlobalLongitude.ToString();

        };

        return FinalCoordinates;
    }

    public static string SetMockLocation()
    {

        var context = Android.App.Application.Context;
        var locationManager = context.GetSystemService(LocationService) as LocationManager;

        locationManager.AddTestProvider("Test09", false, false, false, false, false, false, false, Power.Low, Android.Hardware.SensorStatus.AccuracyHigh);
        locationManager.SetTestProviderEnabled("Test09", true);

        var location = new Location("Test09");
        location.Latitude = Add700ToCoordinates();
        location.Longitude = GlobalLongitude;
        location.Accuracy = 0; // ob das geht?... ja, aber was beduetet es?
        location.Time = DateTime.Now.Ticks;
        location.ElapsedRealtimeNanos = 100;  // hier das gleiche... was hießt es? :D
        locationManager.SetTestProviderLocation("Test09", location);

        //Check if your event reacted the right way

        locationManager.RemoveTestProvider("Test09");

        return location.Latitude.ToString();
    }

}

}


问:
(C) When calling function, store multiple values in array
So, when calling a function I wish to put two values in, then those two values to be saved in an array in the function argument.

i.e

```<code>function(1,2); (calling the function)

void function(int x[2]); (declaration of function)
</code>```

with x[0] and x[1] being the two arguments when calling the function (i.e the 1 and 2).

Any help would be appreciated.

答:
You can use compound literals if you have two array members, but no array, and wish to call such a function:

```<code>void function(int x[2]);     // declaration of function

function((int [2]) {1, 2});  // calling the function
</code>```

You can also use variables within the compound literal. Here is a simple example program:

```<code>#include <stdio.h>

void function(int x[2]);

int main(void)
{
    int arg1 = 3;
    int arg2 = 4;

    puts("Calling function with constants in compound literal:");
    function((int [2]) {1, 2});

    puts("Calling function with variables in compound literal:");
    function((int [2]) {arg1, arg2});

    return 0;
}

void function(int x[2])
{
    printf("x[0] = %d, x[1] = %d\n", x[0], x[1]);
}
</code>```

Program output:

Calling function with constants in compound literal:
x[0] = 1, x[1] = 2
Calling function with variables in compound literal:
x[0] = 3, x[1] = 4
```

Body:
So, when calling a function I wish to put two values in, then those two values to be saved in an array in the function argument.

i.e

function(1,2); (calling the function)

void function(int x[2]); (declaration of function)

with x[0] and x[1] being the two arguments when calling the function (i.e the 1 and 2).

Any help would be appreciated.

Body:
You can use compound literals if you have two array members, but no array, and wish to call such a function:

void function(int x[2]);     // declaration of function

function((int [2]) {1, 2});  // calling the function

You can also use variables within the compound literal. Here is a simple example program:

#include <stdio.h>

void function(int x[2]);

int main(void)
{
    int arg1 = 3;
    int arg2 = 4;

    puts("Calling function with constants in compound literal:");
    function((int [2]) {1, 2});

    puts("Calling function with variables in compound literal:");
    function((int [2]) {arg1, arg2});

    return 0;
}

void function(int x[2])
{
    printf("x[0] = %d, x[1] = %d\n", x[0], x[1]);
}

Program output:

Calling function with constants in compound literal:
x[0] = 1, x[1] = 2
Calling function with variables in compound literal:
x[0] = 3, x[1] = 4


问:
How can I perfectly center my image?
So I have an image on my website and I want to perfectly center it. I have tried many things but none have worked.

body{
background-color: black;
}

img {
  position: absolute;
  margin-top: 10%;
  text-align: center;
  height: 40%;
  z-index: -5
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="images/astronaut.png"></code>```

答:
The simplest way to centre an image horizontally is with:</p>

```<code>img {
    display: block;
    margin-right: auto;
    margin-left: auto;
}
</code>```

Title: How can I perfectly center my image?

Body:
The simplest way to centre an image horizontally is with:

img {
    display: block;
    margin-right: auto;
    margin-left: auto;
}


问:
How to configure log4j for a Spark program running inside of Intellij?
I've tried all possible suggestion on google but I still get spark log with INFO level which is too verbose. </p>

```<code>import org.apache.log4j.{Level, LogManager, Logger}
import org.apache.spark.sql.SparkSession

object  tmp {

  def main(args: Array[String]): Unit = {
    val spark =  SparkSession.builder()
      .master("local[*]")
      .getOrCreate()

    spark.sparkContext.setLogLevel("ERROR")

    LogManager.getRootLogger.setLevel(Level.ERROR)
    val rootLogger = Logger.getRootLogger()
    rootLogger.setLevel(Level.ERROR)

    Logger.getLogger("org").setLevel(Level.OFF)
    Logger.getLogger("akka").setLevel(Level.OFF)

    spark.read.json("/home/white/wk/tmp/people.json").show
  }
}
</code>```

答:
You could try to set log level on SparkContext

sc.setLogLevel("ERROR")

Body:
I've tried all possible suggestion on google but I still get spark log with INFO level which is too verbose.

import org.apache.log4j.{Level, LogManager, Logger}
import org.apache.spark.sql.SparkSession

object  tmp {

  def main(args: Array[String]): Unit = {
    val spark =  SparkSession.builder()
      .master("local[*]")
      .getOrCreate()

    spark.sparkContext.setLogLevel("ERROR")

    LogManager.getRootLogger.setLevel(Level.ERROR)
    val rootLogger = Logger.getRootLogger()
    rootLogger.setLevel(Level.ERROR)

    Logger.getLogger("org").setLevel(Level.OFF)
    Logger.getLogger("akka").setLevel(Level.OFF)

    spark.read.json("/home/white/wk/tmp/people.json").show
  }
}


问:
How to Set UITableViewCellStyleSubtitle and dequeueReusableCell in Swift?
I'd like a UITableView with subtitle-style cells that use dequeueReusableCellWithIdentifier.

My original Objective-C code was:

```<code>static NSString *reuseIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
if(!cell)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
}
</code>```

After searching the few UITableView questions here already on SO, I thought to write it in Swift like so:

```<code>tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell")

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
</code>```

But that doesn't let me say I want a subtitle style.  So I tried this:

```<code>var cell :UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
</code>```

Which gives me a subtitle cell, but it doesn't let me dequeueReusableCellWithIdentifier.

I've researched some more and looked at this video tutorial, but he creates a separate subclass of UITableViewCell which I assume is unnecessary as I accomplished this same effect previously in Obj-C.

Any ideas? Thanks.

答:
Since tableView.dequeueReusableCell(withIdentifier:, for:) return a non-nil cell, the if cell == nil check is always be false.
But I found a solution, to makes default style cell become what style(value1, value2 or subtitle) you want, because default style cell's detailTextLabel is nil, so check the detailTextLabel if it's nil, then create new style cell, and give it to dequeue cell, like:

Swift 3:

```<code>var cell = tableView.dequeueReusableCell(withIdentifier: yourCellReuseIdentifier, for: indexPath)

if cell.detailTextLabel == nil {
    cell = UITableViewCell(style: .value1, reuseIdentifier: repeatCellReuseIdentifier)
}

cell.textLabel?.text = "Title"
cell.detailTextLabel?.text = "Detail"

return cell
</code>```

That's works for me.

Hope it's help.

ContentLicense: CC BY-SA 4.0

Body:
I'd like a UITableView with subtitle-style cells that use dequeueReusableCellWithIdentifier.

My original Objective-C code was:

static NSString *reuseIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
if(!cell)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
}

After searching the few UITableView questions here already on SO, I thought to write it in Swift like so:

tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell")

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

But that doesn't let me say I want a subtitle style.  So I tried this:

var cell :UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")

Which gives me a subtitle cell, but it doesn't let me dequeueReusableCellWithIdentifier.

I've researched some more and looked at this video tutorial, but he creates a separate subclass of UITableViewCell which I assume is unnecessary as I accomplished this same effect previously in Obj-C.

Any ideas? Thanks.

Body:
Since tableView.dequeueReusableCell(withIdentifier:, for:) return a non-nil cell, the if cell == nil check is always be false.
But I found a solution, to makes default style cell become what style(value1, value2 or subtitle) you want, because default style cell's detailTextLabel is nil, so check the detailTextLabel if it's nil, then create new style cell, and give it to dequeue cell, like:

Swift 3:

var cell = tableView.dequeueReusableCell(withIdentifier: yourCellReuseIdentifier, for: indexPath)

if cell.detailTextLabel == nil {
    cell = UITableViewCell(style: .value1, reuseIdentifier: repeatCellReuseIdentifier)
}

cell.textLabel?.text = "Title"
cell.detailTextLabel?.text = "Detail"

return cell

That's works for me.

Hope it's help.


问:
putting 3 switches in one
I have for some time been working on a console calendar that counts on its own to a certain date with the correct day of week, date etc, which then allows you to insert data on that day. All that is done, but now I'm adding a function where you can put the dates from start date to end date into a text file. The output will be something like:

```<code>05.06.2016 Tuesday
06.06.2016 Wednesday
07.06.2016 Thursday
01.06.2016 Friday
02.06.2016 Saturday
03.01.2016 Sunday
04.01.2016 Monday
05.01.2016 Tuesday
06.01.2016 Wednesday
07.01.2016 Thursday
01.01.2016 Friday
02.01.2016 Saturday
</code>```

This sent me off to this MainInputSection class of my program, and I had to add parameter so that I could alter the messages from just "Input YEAR" etc to "Input start of YEAR for file" etc.

There are now three switches right next to each other that does almost the same thing, and this section of my program therefore felt a bit simple, repetetive, and hard-coded.

What I'd like is a loop or something that shortens this stuff and makes it less nooby the way it is now in order to get the right Console.WriteLine(); matched with the correct Console.ReadLine(); to fill in the int[] arrayAnswers = { answerYear, answerMonth, answerDay }; correcly, but more professionally. I'm thinking something like a for each loop or something, but I only halfway see a solution like that and I need help.

```<code>public class MainInputSection
{
    public static int[] GetUserInputDate(string mode)
    {
        int answerYear;
        int answerMonth;
        int answerDay;

        Console.ForegroundColor = ConsoleColor.Cyan;
        switch (mode)
        {
            case "calender":
                Console.WriteLine("Input YEAR");
                break;
            case "fileStart":
                Console.WriteLine("Input start of YEAR for file");
                break;
            case "fileEnd":
                Console.WriteLine("Input end of YEAR for file");
                break;
        }
        Console.ResetColor();
        answerYear = Convert.ToInt32(Console.ReadLine());

        Console.ForegroundColor = ConsoleColor.Cyan;
        switch (mode)
        {
            case "calendar":
                Console.WriteLine("Input MONTH");
                break;
            case "fileStart":
                Console.WriteLine("Input start of MONTH for file");
                break;
            case "fileEnd":
                Console.WriteLine("Input end of MONTH for file");
                break;
        }
        Console.ResetColor();
        answerMonth = Convert.ToInt32(Console.ReadLine());

        Console.ForegroundColor = ConsoleColor.Cyan;
        switch (mode)
        {
            case "calendar":
                Console.WriteLine("Input DAY");
                break;
            case "fileStart":
                Console.WriteLine("Input start of DAY for file");
                break;
            case "fileEnd":
                Console.WriteLine("Input end of DAY for file");
                break;
        }
        Console.ResetColor();
        answerDay = Convert.ToInt32(Console.ReadLine());

        int[] arrayAnswers = { answerYear, answerMonth, answerDay };

        return arrayAnswers;

    }
}
</code>```

答:
So what you have to do is, group the common things together inside a method, here all cases should display some text in the console with a color and then call the reset color option, and store the user input to an integer variable. So group them together inside a method and return the integer value from the method. I think the signature of the method should be like the following:

```<code> public static int GetInput(string displayMessage)
 {
     Console.ForegroundColor = ConsoleColor.Cyan;
     Console.WriteLine(displayMessage);
     Console.ResetColor();
     return int.Parse(Console.ReadLine());
 }
</code>```

And you can use the method like the following:

```<code>public static int[] GetUserInputDate(string mode)
{
    int answerYear = 0;
    int answerMonth = 0;
    int answerDay = 0;
    switch (mode)
    {
        case "calender":
            answerYear = GetInput("Input YEAR");
            answerMonth = GetInput("Input MONTH");
            answerDay = GetInput("Input DAY");
            break;
        case "fileStart":
            answerYear = GetInput("Input start of YEAR for file");
            answerMonth = GetInput("Input start of MONTH for file");
            answerDay = GetInput("Input start of DAY for file");
            break;
        case "fileEnd":
            answerYear = GetInput("Input end of YEAR for file");
            answerMonth = GetInput("Input end of MONTH for file");
            answerDay = GetInput("Input end of DAY for file");
            break;
    }

    int[] arrayAnswers = { answerYear, answerMonth, answerDay };

    return arrayAnswers;

}
</code>```

Title: putting 3 switches in one

Body:
I have for some time been working on a console calendar that counts on its own to a certain date with the correct day of week, date etc, which then allows you to insert data on that day. All that is done, but now I'm adding a function where you can put the dates from start date to end date into a text file. The output will be something like:

05.06.2016 Tuesday
06.06.2016 Wednesday
07.06.2016 Thursday
01.06.2016 Friday
02.06.2016 Saturday
03.01.2016 Sunday
04.01.2016 Monday
05.01.2016 Tuesday
06.01.2016 Wednesday
07.01.2016 Thursday
01.01.2016 Friday
02.01.2016 Saturday

This sent me off to this MainInputSection class of my program, and I had to add parameter so that I could alter the messages from just "Input YEAR" etc to "Input start of YEAR for file" etc.

There are now three switches right next to each other that does almost the same thing, and this section of my program therefore felt a bit simple, repetetive, and hard-coded.

What I'd like is a loop or something that shortens this stuff and makes it less nooby the way it is now in order to get the right Console.WriteLine(); matched with the correct Console.ReadLine(); to fill in the int[] arrayAnswers = { answerYear, answerMonth, answerDay }; correcly, but more professionally. I'm thinking something like a for each loop or something, but I only halfway see a solution like that and I need help.

public class MainInputSection
{
    public static int[] GetUserInputDate(string mode)
    {
        int answerYear;
        int answerMonth;
        int answerDay;

        Console.ForegroundColor = ConsoleColor.Cyan;
        switch (mode)
        {
            case "calender":
                Console.WriteLine("Input YEAR");
                break;
            case "fileStart":
                Console.WriteLine("Input start of YEAR for file");
                break;
            case "fileEnd":
                Console.WriteLine("Input end of YEAR for file");
                break;
        }
        Console.ResetColor();
        answerYear = Convert.ToInt32(Console.ReadLine());

        Console.ForegroundColor = ConsoleColor.Cyan;
        switch (mode)
        {
            case "calendar":
                Console.WriteLine("Input MONTH");
                break;
            case "fileStart":
                Console.WriteLine("Input start of MONTH for file");
                break;
            case "fileEnd":
                Console.WriteLine("Input end of MONTH for file");
                break;
        }
        Console.ResetColor();
        answerMonth = Convert.ToInt32(Console.ReadLine());

        Console.ForegroundColor = ConsoleColor.Cyan;
        switch (mode)
        {
            case "calendar":
                Console.WriteLine("Input DAY");
                break;
            case "fileStart":
                Console.WriteLine("Input start of DAY for file");
                break;
            case "fileEnd":
                Console.WriteLine("Input end of DAY for file");
                break;
        }
        Console.ResetColor();
        answerDay = Convert.ToInt32(Console.ReadLine());

        int[] arrayAnswers = { answerYear, answerMonth, answerDay };

        return arrayAnswers;

    }
}

Body:
So what you have to do is, group the common things together inside a method, here all cases should display some text in the console with a color and then call the reset color option, and store the user input to an integer variable. So group them together inside a method and return the integer value from the method. I think the signature of the method should be like the following:

 public static int GetInput(string displayMessage)
 {
     Console.ForegroundColor = ConsoleColor.Cyan;
     Console.WriteLine(displayMessage);
     Console.ResetColor();
     return int.Parse(Console.ReadLine());
 }

And you can use the method like the following:

public static int[] GetUserInputDate(string mode)
{
    int answerYear = 0;
    int answerMonth = 0;
    int answerDay = 0;
    switch (mode)
    {
        case "calender":
            answerYear = GetInput("Input YEAR");
            answerMonth = GetInput("Input MONTH");
            answerDay = GetInput("Input DAY");
            break;
        case "fileStart":
            answerYear = GetInput("Input start of YEAR for file");
            answerMonth = GetInput("Input start of MONTH for file");
            answerDay = GetInput("Input start of DAY for file");
            break;
        case "fileEnd":
            answerYear = GetInput("Input end of YEAR for file");
            answerMonth = GetInput("Input end of MONTH for file");
            answerDay = GetInput("Input end of DAY for file");
            break;
    }

    int[] arrayAnswers = { answerYear, answerMonth, answerDay };

    return arrayAnswers;

}


问:
get_absolute_url and reverse outside of templates
"...If you need to use something similar to the url template tag in your code, Django provides the following function: reverse()...."

I looked at the docs for get_absolute_url()  and reverse, as well as the example given:

a href="{{ object.get_absolute_url }}">{{ object.name }} /a>

What I am not seeing, or understanding, is how are we passing the kwargs (name, self, ID, whatever) to the model method so it knows which one of 100 instances to return the url for, particularly where I need to use it in text, outside the template system?

a href="name_of_object.get_absolute_url ">text name of object

Do I have to put the full name of the object in the href?

How would I use a variable like self or object or modelname instead?

Can I rewrite gau to take kwargs as well as self?

If I do that, can I put the () on the end of gau to take in the kwargs? We can’t do that in the template.

Can I use:

a href="self.get_absolute_url(**kwargs) ">text name of object ?

or

a href="object.get_absolute_url(self, **kwargs) ">text name of
  object ?

And if so, do I need to add anything to the definition of gau on my model to make sure those kwargs are passed to return?

Or do I just treat it like a regular outside link, and thus have to hard code it?

Thanks.
--update--

@ChidG: Thanks for such a complete answer, and my apologies for taking so long to get back to you. I'd like to clarify my use case a little, and see if that changes your answer any.     If I have ten articles using the same template, each article is still unique, and their links to different urls are not going to be in the same place on each article. So there is no way for me to put a single (or multiple) url tag in the template that will be useful to all ten articles.  That's what I meant by using gau / the url tag outside the template. I want to do a simple search and replace that will turn the affected text into links. Otherwise, I'd have to do them one at a time by hand, which I assumed couldn't be the way this has to be done. What am I missing?

答:
When Django's docs say 'outside of the template system', they mean in Python code, in a views.py or models.py (or whatever.py) file. The examples you have given all appear to be HTML (they feature a tags, so it looks like you are talking about HTML).

If it's HTML, then it's not outside the template system, so the Python functions you've mentioned won't work. You need to use the Django template tags.

Regarding this question:

What I am not seeing, or understanding, is how are we passing the kwargs (name, self, ID, whatever) to the model method so it knows which one of 100 instances to return the url for, particularly where I need to use it in text, outside the template system?

{{object.get_absolute_url}} (or object.get_absolute_url() in pure Python) does not require a kwarg, because the get_absolute_url method on the model already knows how to generate the correct URL with whatever kwargs are needed. If it doesn't already know how to do that (because of your specific URL configuration), you can write a custom get_absolute_url method which will enable that.

Whenever you return an HTML file from a Django view (unless you're doing something unconventional), you are using the template system. When you're using the template system, you reference Django context variables using {{ }} and custom tags using {% %}. So to insert a URL into a template, whether it's into an a tag or just into the text, you will use curly brackets and it will be {{ object.get_absolute_url }} or using the url tag itself, {% url 'whatever_url_name' kwarg=value %}

Do I have to put the full name of the object in the href?

You have to put whatever the context variable is that refers to the object in the template context.

How would I use a variable like self or object or modelname instead?

You can use whatever name you like for the context variable. If you're using Django's class based views it will be object by default for a single object view, but you can change it to whatever you like using the context_object_name attribute on the view.

Can I rewrite gau to take kwargs as well as self?

That is unnecessary. get_absolute_url returns a full URL, and all it needs is the model instance. The model instance must be able to find its own url using its own get_absolute_url method without any further kwargs.

Can I use:

The correct syntax is clearly demonstrated in the Django docs for get_absolute_url that you've linked to:

```<code><a href="{{ object.get_absolute_url }}">{{ object.name }}</a>
</code>```

Body:
When Django's docs say 'outside of the template system', they mean in Python code, in a views.py or models.py (or whatever.py) file. The examples you have given all appear to be HTML (they feature a tags, so it looks like you are talking about HTML).

If it's HTML, then it's not outside the template system, so the Python functions you've mentioned won't work. You need to use the Django template tags.

Regarding this question:

What I am not seeing, or understanding, is how are we passing the kwargs (name, self, ID, whatever) to the model method so it knows which one of 100 instances to return the url for, particularly where I need to use it in text, outside the template system?

{{object.get_absolute_url}} (or object.get_absolute_url() in pure Python) does not require a kwarg, because the get_absolute_url method on the model already knows how to generate the correct URL with whatever kwargs are needed. If it doesn't already know how to do that (because of your specific URL configuration), you can write a custom get_absolute_url method which will enable that.

Whenever you return an HTML file from a Django view (unless you're doing something unconventional), you are using the template system. When you're using the template system, you reference Django context variables using {{ }} and custom tags using {% %}. So to insert a URL into a template, whether it's into an a tag or just into the text, you will use curly brackets and it will be {{ object.get_absolute_url }} or using the url tag itself, {% url 'whatever_url_name' kwarg=value %}

Do I have to put the full name of the object in the href?

You have to put whatever the context variable is that refers to the object in the template context.

How would I use a variable like self or object or modelname instead?

You can use whatever name you like for the context variable. If you're using Django's class based views it will be object by default for a single object view, but you can change it to whatever you like using the context_object_name attribute on the view.

Can I rewrite gau to take kwargs as well as self?

That is unnecessary. get_absolute_url returns a full URL, and all it needs is the model instance. The model instance must be able to find its own url using its own get_absolute_url method without any further kwargs.

Can I use:

The correct syntax is clearly demonstrated in the Django docs for get_absolute_url that you've linked to:

<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>


答: Generally git pull is enough, but I'm not sure what layout you have chosen (or has github chosen for you).

Title: How to sync with a remote Git repository?

Body:
I forked a project on github, made some changes, so far so good.

In the meantime, the repository I forked from changed and I would like to get those changes into my repository. How do I do that ?

ContentLicense: CC BY-SA 2.5


问:
How to create a fully transparent Navigation Bar?
I want to change the Navigation Bar fully transparent like on the picture below.

I tried <item name="android:windowTranslucentNavigation">true</item> but it is not fully transparent (more like 50%).

Is there a solution? Because i found nothing to it, but I saw some apps that used it like Nova. And its even in googles guidelines https://material.google.com/layout/structure.html#structure-system-bars

答:
use following code in onCreate of your Activity:

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow(); w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            }
</code>```

and in your styles.xml:

```<code><item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:windowTranslucentNavigation">false</item>
</code>```

Body:
use following code in onCreate of your Activity:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow(); w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            }

and in your styles.xml:

<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:windowTranslucentNavigation">false</item>


问:
Visual Studio Code: format is not using indent settings
When using the Format Code command in Visual Studio Code, it is not honoring my indent settings ("editor.tabSize": 2). It is using a tab size of 4 instead. Any ideas why this is happening?

Thanks!

答:
If @Maleki's answer isn't working for you, check and see if you have an .editorconfig file in your project folder.

For example the Angular CLI generates one with a new project that looks like this

```<code># Editor configuration, see http://editorconfig.org
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
max_line_length = off
trim_trailing_whitespace = false
</code>```

Changing the indent_size here is required as it seems it will override anything in your .vscode workspace or user settings.

Body:
If @Maleki's answer isn't working for you, check and see if you have an .editorconfig file in your project folder.

For example the Angular CLI generates one with a new project that looks like this

# Editor configuration, see http://editorconfig.org
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
max_line_length = off
trim_trailing_whitespace = false

Changing the indent_size here is required as it seems it will override anything in your .vscode workspace or user settings.


问:
java.lang.NullPointerException: uri - Turning on Location through Alert Dialog
Hi i'm developing a program which gets the user's current location and sends it to one of the users preferred contacts. Now some user might have their locations turned off so i've added a dialog alert which asks them to enable their location by pressing yes. When Yes is clicked the program crashes and i get the error:

```<code> Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }} to activity {com.example.michael79.handydoc/com.example.michael79.handydoc.emergencyActivity}: java.lang.NullPointerException: uri
</code>```

Here is my code:

```<code>public class emergencyActivity extends AppCompatActivity implements LocationListener {

private static final int REQUEST_CODE =1;

TextView t1;
LocationManager locationManager;
String mprovider;
//Context context=this;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_emergency);

    t1=(TextView) findViewById(R.id.textContact);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    mprovider = locationManager.getBestProvider(criteria, false);
    displayLocationSettingsRequest(this);
    if (mprovider != null && !mprovider.equals("")) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Location location = locationManager.getLastKnownLocation(mprovider);
        locationManager.requestLocationUpdates(mprovider, 15000, 1, this);

        if (location != null)
            onLocationChanged(location);
        else
            Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
    }

}
    public void getContact(View v){
        Uri uri = Uri.parse("content://contacts");
        Intent intent = new Intent(Intent.ACTION_PICK, uri);
        intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
        startActivityForResult(intent, REQUEST_CODE);
    }
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if(resultCode != Activity.RESULT_CANCELED) {
            Uri uri = intent.getData();
        String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME};
        Cursor cursor = getContentResolver().query(uri, projection,
                null, null, null);
        cursor.moveToFirst();
        int numberColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
        String number = cursor.getString(numberColumnIndex);
        int nameColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
        String name = cursor.getString(nameColumnIndex);
        Toast.makeText(getApplicationContext(), "Number" + number + " Name" + name, Toast.LENGTH_LONG).show();
        t1.setText(number);
        //Log.d(TAG, "ZZZ number : " + number +" , name : "+name);
    }

};

public  void sendAlert(View v){
    String phoneNo = t1.getText().toString();
    String sms = "I need your help please i'm in distress";

    try {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNo, null, sms, null, null);
        Toast.makeText(getApplicationContext(), "SMS Sent!",
                Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(),
                "SMS faild, please try again later!",
                Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
}

@Override
public void onLocationChanged(Location location) {
    TextView cord = (TextView) findViewById(R.id.textView26);
    cord.setText("Current Longitude:" + location.getLongitude()+"  Current Latitude:"+location.getLatitude());

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
private void displayLocationSettingsRequest(Context context) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
            .addApi(LocationServices.API).build();
    googleApiClient.connect();

    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(10000 / 2);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
    builder.setAlwaysShow(true);

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    Log.i("show", "All location settings are satisfied.");
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    Log.i("show", "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");

                    try {
                        // Show the dialog by calling startResolutionForResult(), and check the result
                        // in onActivityResult().
                        status.startResolutionForResult(emergencyActivity.this, REQUEST_CODE);
                    } catch (IntentSender.SendIntentException e) {
                        Log.i("show", "PendingIntent unable to execute request.");
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    Log.i("show", "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
                    break;
            }
        }
    });
}
</code>```

I checked how to fix the issue but the solutions i get dont fix them.

答:
```<code>private static final int REQUEST_CODE =5;
private static final int STATUS_REQUEST_CODE =2;

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if(requestCode!=RESULT_CANCELED) {
            if(requestCode==REQUEST_CODE) {

            Uri uri = intent.getData();
            String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME};
            Cursor cursor = getContentResolver().query(uri, projection,
                    null, null, null);
            cursor.moveToFirst();
            int numberColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
            String number = cursor.getString(numberColumnIndex);
            int nameColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
            String name = cursor.getString(nameColumnIndex);
            Toast.makeText(getApplicationContext(), "Number" + number + " Name" + name, Toast.LENGTH_LONG).show();
            t1.setText(number);
            //Log.d(TAG, "ZZZ number : " + number +" , name : "+name);
        }
    }

};

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    Log.i("show", "All location settings are satisfied.");
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    Log.i("show", "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");

                    try {
                        // Show the dialog by calling startResolutionForResult(), and check the result
                        // in onActivityResult().
                        status.startResolutionForResult(emergencyActivity.this, STATUS_REQUEST_CODE);
                    } catch (IntentSender.SendIntentException e) {
                        Log.i("show", "PendingIntent unable to execute request.");
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    Log.i("show", "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
                    break;
            }
        }
    });
}
</code>```

After sometime of reading and also testing and fixing i created a request code for the status.startResolutionForResult() and changed the condition statement in the onActivityResult() which fixed my problem

Body:
Hi i'm developing a program which gets the user's current location and sends it to one of the users preferred contacts. Now some user might have their locations turned off so i've added a dialog alert which asks them to enable their location by pressing yes. When Yes is clicked the program crashes and i get the error:

 Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }} to activity {com.example.michael79.handydoc/com.example.michael79.handydoc.emergencyActivity}: java.lang.NullPointerException: uri

Here is my code:

public class emergencyActivity extends AppCompatActivity implements LocationListener {

private static final int REQUEST_CODE =1;

TextView t1;
LocationManager locationManager;
String mprovider;
//Context context=this;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_emergency);

    t1=(TextView) findViewById(R.id.textContact);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    mprovider = locationManager.getBestProvider(criteria, false);
    displayLocationSettingsRequest(this);
    if (mprovider != null && !mprovider.equals("")) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Location location = locationManager.getLastKnownLocation(mprovider);
        locationManager.requestLocationUpdates(mprovider, 15000, 1, this);

        if (location != null)
            onLocationChanged(location);
        else
            Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
    }

}
    public void getContact(View v){
        Uri uri = Uri.parse("content://contacts");
        Intent intent = new Intent(Intent.ACTION_PICK, uri);
        intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
        startActivityForResult(intent, REQUEST_CODE);
    }
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if(resultCode != Activity.RESULT_CANCELED) {
            Uri uri = intent.getData();
        String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME};
        Cursor cursor = getContentResolver().query(uri, projection,
                null, null, null);
        cursor.moveToFirst();
        int numberColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
        String number = cursor.getString(numberColumnIndex);
        int nameColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
        String name = cursor.getString(nameColumnIndex);
        Toast.makeText(getApplicationContext(), "Number" + number + " Name" + name, Toast.LENGTH_LONG).show();
        t1.setText(number);
        //Log.d(TAG, "ZZZ number : " + number +" , name : "+name);
    }

};

public  void sendAlert(View v){
    String phoneNo = t1.getText().toString();
    String sms = "I need your help please i'm in distress";

    try {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNo, null, sms, null, null);
        Toast.makeText(getApplicationContext(), "SMS Sent!",
                Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(),
                "SMS faild, please try again later!",
                Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
}

@Override
public void onLocationChanged(Location location) {
    TextView cord = (TextView) findViewById(R.id.textView26);
    cord.setText("Current Longitude:" + location.getLongitude()+"  Current Latitude:"+location.getLatitude());

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
private void displayLocationSettingsRequest(Context context) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
            .addApi(LocationServices.API).build();
    googleApiClient.connect();

    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(10000 / 2);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
    builder.setAlwaysShow(true);

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    Log.i("show", "All location settings are satisfied.");
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    Log.i("show", "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");

                    try {
                        // Show the dialog by calling startResolutionForResult(), and check the result
                        // in onActivityResult().
                        status.startResolutionForResult(emergencyActivity.this, REQUEST_CODE);
                    } catch (IntentSender.SendIntentException e) {
                        Log.i("show", "PendingIntent unable to execute request.");
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    Log.i("show", "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
                    break;
            }
        }
    });
}

I checked how to fix the issue but the solutions i get dont fix them.

Body:
private static final int REQUEST_CODE =5;
private static final int STATUS_REQUEST_CODE =2;

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if(requestCode!=RESULT_CANCELED) {
            if(requestCode==REQUEST_CODE) {

            Uri uri = intent.getData();
            String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME};
            Cursor cursor = getContentResolver().query(uri, projection,
                    null, null, null);
            cursor.moveToFirst();
            int numberColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
            String number = cursor.getString(numberColumnIndex);
            int nameColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
            String name = cursor.getString(nameColumnIndex);
            Toast.makeText(getApplicationContext(), "Number" + number + " Name" + name, Toast.LENGTH_LONG).show();
            t1.setText(number);
            //Log.d(TAG, "ZZZ number : " + number +" , name : "+name);
        }
    }

};

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    Log.i("show", "All location settings are satisfied.");
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    Log.i("show", "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");

                    try {
                        // Show the dialog by calling startResolutionForResult(), and check the result
                        // in onActivityResult().
                        status.startResolutionForResult(emergencyActivity.this, STATUS_REQUEST_CODE);
                    } catch (IntentSender.SendIntentException e) {
                        Log.i("show", "PendingIntent unable to execute request.");
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    Log.i("show", "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
                    break;
            }
        }
    });
}

After sometime of reading and also testing and fixing i created a request code for the status.startResolutionForResult() and changed the condition statement in the onActivityResult() which fixed my problem


问:
Extend text on hover
I'm  using two initials and I want that if a user hovers it it will show the rest of the text but I can't make it to display the rest of the text correctly: the part of the first letter it's being displayed next to the text of the second initial.

jsfiddle

```<code>#logo .short{
        position: relative;
        margin-top: 0;
        padding: 0 10px;
        font-size: 36px;
        display: inline-block;
        text-transform: uppercase;
      transition: all .3s ease-out;
}
  .short:after{
   position: relative;
    margin-left: -20px;
    content: "est1";
    opacity: 0;
    -webkit-transition: all .3s ease-out;
}

 .short:hover:after{
        opacity: 1;
        display: inline-block;
      margin-left: -10px;
 }
#logo span{
    position: relative;
    transition: margin .3s ease-out;
}
span:hover{
        margin-left: 20px;
}
span:after{
   position: relative;
    margin-left: -20px;
    content: "est2";
    opacity: 0;
    -webkit-transition: all .3s ease-out;
 }

span:hover:after{
  opacity: 1;
  margin-left: -10px;
 }
</code>```

答:
Place the span tag outside of the header tag and simply style the span tag :after as follows:

```<code>span:hover:after{
  opacity: 1;
  margin-left: 0px;
 }
</code>```

see snippet below

#logo .short{
     position: relative;
     margin-top: 0;
     padding: 0 10px;
     font-size: 36px;
     display: inline-block;
     text-transform: uppercase;
      transition: all .3s ease-out;
}
  .short:after{
   position: relative;
    margin-left: -20px;
    content: "est1";
    opacity: 0;
    transition: all .3s ease-out;
    -webkit-transition: all .3s ease-out;
}

 .short:hover:after{
     opacity: 1;
     display: inline-block;
      margin-left: -10px;
 }
#logo span{
 position: relative;
 transition: margin .3s ease-out;
}
span:hover{
  margin-left: 20px;
}
span:after{
   position: relative;
    margin-left: -20px;
    content: "est2";
    opacity: 0;
    -webkit-transition: all .3s ease-out;
 }

span:hover:after{
  opacity: 1;
  margin-left: 0px;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
   <h1 class="short">
    T
   </h1>
    <span>t</span>
</code>```

Title: Extend text on hover

Body:
I'm  using two initials and I want that if a user hovers it it will show the rest of the text but I can't make it to display the rest of the text correctly: the part of the first letter it's being displayed next to the text of the second initial.

jsfiddle

#logo .short{
        position: relative;
        margin-top: 0;
        padding: 0 10px;
        font-size: 36px;
        display: inline-block;
        text-transform: uppercase;
      transition: all .3s ease-out;
}
  .short:after{
   position: relative;
    margin-left: -20px;
    content: "est1";
    opacity: 0;
    -webkit-transition: all .3s ease-out;
}

 .short:hover:after{
        opacity: 1;
        display: inline-block;
      margin-left: -10px;
 }
#logo span{
    position: relative;
    transition: margin .3s ease-out;
}
span:hover{
        margin-left: 20px;
}
span:after{
   position: relative;
    margin-left: -20px;
    content: "est2";
    opacity: 0;
    -webkit-transition: all .3s ease-out;
 }

span:hover:after{
  opacity: 1;
  margin-left: -10px;
 }

Body:
Place the span tag outside of the header tag and simply style the span tag :after as follows:

span:hover:after{
  opacity: 1;
  margin-left: 0px;
 }

see snippet below

#logo .short{
     position: relative;
     margin-top: 0;
     padding: 0 10px;
     font-size: 36px;
     display: inline-block;
     text-transform: uppercase;
      transition: all .3s ease-out;
}
  .short:after{
   position: relative;
    margin-left: -20px;
    content: "est1";
    opacity: 0;
    transition: all .3s ease-out;
    -webkit-transition: all .3s ease-out;
}

 .short:hover:after{
     opacity: 1;
     display: inline-block;
      margin-left: -10px;
 }
#logo span{
 position: relative;
 transition: margin .3s ease-out;
}
span:hover{
  margin-left: 20px;
}
span:after{
   position: relative;
    margin-left: -20px;
    content: "est2";
    opacity: 0;
    -webkit-transition: all .3s ease-out;
 }

span:hover:after{
  opacity: 1;
  margin-left: 0px;
 }

<a id="logo">
   <h1 class="short">
    T
   </h1>
    <span>t</span>
</a>


问:
How to convert lowercase string to uppercase string without toUppercase() function
```<code>function alpha()
{
    var a=prompt("Enter String: ");

    for(var b=[i=0];c=a.charCodeAt(i);)
    {
        b[i++]=String.fromCharCode(c|(c>96 && c<123));
    }
    alert(b.join(""))
}
console.log(alpha());
</code>```

<p>So far some letters in the code change when I run this but for some reason it is not changing the string characters to all uppercase. (Example of output; I type "hi" into the prompt and the alert outputs "i" so the h disappears for some reason. </p>

答:
Just for interest's sake, here's a way to do it in one statement without arrays or a loop (at least, not an explicit loop):

var input = 'ABCdefGHIjkl123.'  // or you could prompt("Enter String: ")

var output = input.replace(/[a-z]/g, function(m) {
  return String.fromCharCode(m.charCodeAt(0) - 32)
})

console.log(output)```

Body:
function alpha()
{
    var a=prompt("Enter String: ");

    for(var b=[i=0];c=a.charCodeAt(i);)
    {
        b[i++]=String.fromCharCode(c|(c>96 && c<123));
    }
    alert(b.join(""))
}
console.log(alpha());

So far some letters in the code change when I run this but for some reason it is not changing the string characters to all uppercase. (Example of output; I type "hi" into the prompt and the alert outputs "i" so the h disappears for some reason.


问:
Javascript - Promise pending
I'm learning work with promises and i want to select data from a table and add this to an array and send this array to next then.

I do this but it return [Promise {<pending>}]:

```<code>    var p1 = new Promise(function(resolve, reject) {
      var stamp = req.params.stamp;
      var part = [];
      part.push(request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'"));
      resolve(part);
      // or
      // reject ("Error!");
    });

    p1.then(function(value){
      console.log(value);
    }, function(reason){
      console.log(reason);
    });
</code>```

I think that i have to wait for promise but how?

UPDATE

Now i want to iterate the array part and do a select to another array.
After that i have to create a new array with this stucture:

```<code>-PARTS
      - part
            - u_order
            - u_familia
            - u_part
            - u_type
            - articles (article from each part)
</code>```

And i try this but cannot access to array articles

```<code>var p1 = new Promise(function(resolve, reject) {
      var stamp = req.params.stamp;
      request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'").then((data)=>resolve(data));
      // or
      // reject ("Error!");
    });

    p1.then(function(value){
      var stamp = req.params.stamp;
      console.log(value.length);
      for(var i= 0; i<value.length; i++)
      {
        console.log(value[i]);
        request.query("SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='"+stamp+"' and st.u_posic = '"+value[i].u_order+"'").then((data)=>resolve(data));
      }

    }, function(reason){
      console.log(reason);
    });

    p1.then(function(part, articles){
      var parts = [];
      console.log("PART: " +part.length);
      for(var j= 0; j<part.length; j++)
      {
        console.log(part[j].u_order);
        console.log(part[j].u_familia);
        console.log(part[j].u_part);
        console.log(part[j].u_type);
        console.log(articles[j]);
      };
    });
</code>```

Thank you

答:
You can do the following:</p>

```<code>var stamp = req.params.stamp;
var p1 = request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'");

p1.then((value) => {
    console.log(value.length);
    var promise_arr = [];
    for(var i= 0; i<value.length; i++)
    {
        console.log(value[i]);
        promise_arr.push(request.query("SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='"+stamp+"' and st.u_posic = '"+value[i].u_order+"'"));
    }
    //Since request.query returns a promise we need to resolve all of the promises using Promise.all
    return Promise.all(promise_arr);
}, (reason) => {
    console.log(reason);
}).then((part) => { //This is where you receive result form Promise.all
    var parts = [];
    console.log("PART: " +part.length);
    for(var j= 0; j<part.length; j++)
    {
        console.log(part[j].u_order);
        console.log(part[j].u_familia);
        console.log(part[j].u_part);
        console.log(part[j].u_type);
        console.log(articles[j]);
    };
})
</code>```

Title: Javascript - Promise pending

Body:
I'm learning work with promises and i want to select data from a table and add this to an array and send this array to next then.

I do this but it return [Promise {<pending>}]:

    var p1 = new Promise(function(resolve, reject) {
      var stamp = req.params.stamp;
      var part = [];
      part.push(request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'"));
      resolve(part);
      // or
      // reject ("Error!");
    });

    p1.then(function(value){
      console.log(value);
    }, function(reason){
      console.log(reason);
    });

I think that i have to wait for promise but how?

UPDATE

Now i want to iterate the array part and do a select to another array.
After that i have to create a new array with this stucture:

-PARTS
      - part
            - u_order
            - u_familia
            - u_part
            - u_type
            - articles (article from each part)

And i try this but cannot access to array articles

var p1 = new Promise(function(resolve, reject) {
      var stamp = req.params.stamp;
      request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'").then((data)=>resolve(data));
      // or
      // reject ("Error!");
    });

    p1.then(function(value){
      var stamp = req.params.stamp;
      console.log(value.length);
      for(var i= 0; i<value.length; i++)
      {
        console.log(value[i]);
        request.query("SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='"+stamp+"' and st.u_posic = '"+value[i].u_order+"'").then((data)=>resolve(data));
      }

    }, function(reason){
      console.log(reason);
    });

    p1.then(function(part, articles){
      var parts = [];
      console.log("PART: " +part.length);
      for(var j= 0; j<part.length; j++)
      {
        console.log(part[j].u_order);
        console.log(part[j].u_familia);
        console.log(part[j].u_part);
        console.log(part[j].u_type);
        console.log(articles[j]);
      };
    });

Thank you

Body:
You can do the following:

var stamp = req.params.stamp;
var p1 = request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'");

p1.then((value) => {
    console.log(value.length);
    var promise_arr = [];
    for(var i= 0; i<value.length; i++)
    {
        console.log(value[i]);
        promise_arr.push(request.query("SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='"+stamp+"' and st.u_posic = '"+value[i].u_order+"'"));
    }
    //Since request.query returns a promise we need to resolve all of the promises using Promise.all
    return Promise.all(promise_arr);
}, (reason) => {
    console.log(reason);
}).then((part) => { //This is where you receive result form Promise.all
    var parts = [];
    console.log("PART: " +part.length);
    for(var j= 0; j<part.length; j++)
    {
        console.log(part[j].u_order);
        console.log(part[j].u_familia);
        console.log(part[j].u_part);
        console.log(part[j].u_type);
        console.log(articles[j]);
    };
})


问:
Updating a column after new values is added in ORACLE
I am having some troubles creating a trigger which will get the current point a person have, check to see what award he will be under, then update his reward title. So this is the scenario:

```<code>     PersonTable
    | Person (PK) | RewardTitle (FK) | Score|
    | A           | Beginner         | 0    |
    | B           | MidRange         | 17   |
    | C           | Professional     | 32   |

     RewardTable
    | RewardTitle (PK) | BottomScore | UpperScore| Reward        |
    | Beginner         | 0           | 9         | Free food     |
    | MidRange         | 10          | 19        | Free games    |
    | Professional     | 20          | 100       | Unlimited time|
</code>```

The situation is, I want to update Person A so that he nows have 11 points then find out which RewardTitle does his new point belong to, and change his RewardTitle accordingly, so since he has 11 points, his RewardTitle will now be MidRange.

I attempted to create a trigger which tries to find the RewardTitle he belongs to then update this value accordingly, but I kept on getting an error saying:

```<code>    Person is mutating, trigger/function may not see it
</code>```

and I understant the problem, but I cannot think of any other ways to achieve the result. I have tried using

```<code>    pragma autonomous_transaction;
</code>```

but it still did not work, here is my attempt below:

```<code>    UPDATE PersonTable
    SET Score = 11
    WHERE Person = 'A';

    DELIMITER //
    CREATE OR REPLACE TRIGGER person_upd_trigger
    AFTER UPDATE ON PersonTable
    FOR EACH ROW
    DECLARE
        temp_variable VARCHAR(120);
    BEGIN
        SELECT r.RewardTitle INTO temp_variable
        FROM PersonTable p, RewardTable r
        WHERE :NEW.Person = p.Person
        AND p.Score BETWEEN r.BottomScore AND r.UpperScore;

        UPDATE PersonTable
        SET RewardTitle = temp_variable
        WHERE :NEW.Person = Person;
   END;
</code>```

I will be very grateful for all the help I could get, I am quite new to Oracle SQL. Thankyou

答:
You can't update the same table you are already updating in a BEFORE TRIGGER (if supposedly allowed would cause an infinite loop). Instead, you need to re-write your trigger as:

In order to this to work you should change your trigger definition to BEFORE

```<code>CREATE OR REPLACE TRIGGER person_upd_trigger
BEFORE UPDATE ON PersonTable -- declare it as BEFORE
FOR EACH ROW
DECLARE
    temp_variable VARCHAR(120);
BEGIN
    SELECT r.RewardTitle INTO temp_variable
    FROM RewardTable r
    WHERE :NEW.Score BETWEEN r.BottomScore AND r.UpperScore;

    -- here you are setting the new value, no need for an update.
    :NEW.RewardTitle := temp_variable;
END;
</code>```

Body:
I am having some troubles creating a trigger which will get the current point a person have, check to see what award he will be under, then update his reward title. So this is the scenario:

     PersonTable
    | Person (PK) | RewardTitle (FK) | Score|
    | A           | Beginner         | 0    |
    | B           | MidRange         | 17   |
    | C           | Professional     | 32   |

     RewardTable
    | RewardTitle (PK) | BottomScore | UpperScore| Reward        |
    | Beginner         | 0           | 9         | Free food     |
    | MidRange         | 10          | 19        | Free games    |
    | Professional     | 20          | 100       | Unlimited time|

The situation is, I want to update Person A so that he nows have 11 points then find out which RewardTitle does his new point belong to, and change his RewardTitle accordingly, so since he has 11 points, his RewardTitle will now be MidRange.

I attempted to create a trigger which tries to find the RewardTitle he belongs to then update this value accordingly, but I kept on getting an error saying:

    Person is mutating, trigger/function may not see it

and I understant the problem, but I cannot think of any other ways to achieve the result. I have tried using

    pragma autonomous_transaction;

but it still did not work, here is my attempt below:

    UPDATE PersonTable
    SET Score = 11
    WHERE Person = 'A';

    DELIMITER //
    CREATE OR REPLACE TRIGGER person_upd_trigger
    AFTER UPDATE ON PersonTable
    FOR EACH ROW
    DECLARE
        temp_variable VARCHAR(120);
    BEGIN
        SELECT r.RewardTitle INTO temp_variable
        FROM PersonTable p, RewardTable r
        WHERE :NEW.Person = p.Person
        AND p.Score BETWEEN r.BottomScore AND r.UpperScore;

        UPDATE PersonTable
        SET RewardTitle = temp_variable
        WHERE :NEW.Person = Person;
   END;

I will be very grateful for all the help I could get, I am quite new to Oracle SQL. Thankyou

Body:
You can't update the same table you are already updating in a BEFORE TRIGGER (if supposedly allowed would cause an infinite loop). Instead, you need to re-write your trigger as:

In order to this to work you should change your trigger definition to BEFORE

CREATE OR REPLACE TRIGGER person_upd_trigger
BEFORE UPDATE ON PersonTable -- declare it as BEFORE
FOR EACH ROW
DECLARE
    temp_variable VARCHAR(120);
BEGIN
    SELECT r.RewardTitle INTO temp_variable
    FROM RewardTable r
    WHERE :NEW.Score BETWEEN r.BottomScore AND r.UpperScore;

    -- here you are setting the new value, no need for an update.
    :NEW.RewardTitle := temp_variable;
END;


问:
How can I implement unit tests in big and complex classes?
I'm implementing unit tests in a finance system that involves several calculations. One of the methods, receives an object by parameter with more than 100 properties, and based on this object's properties, it calculates the return.
In order to implement unit tests for this method, I need to have all of this object filled with valid values.

So...question: today this object is populated via database. On my Unit Tests (I'm using NUnit), I'd need to avoid the database and create a mock object of that, to test only the method's return. How can I efficiently test this method with this huge object? Do I really need to manually fill all of the 100 properties of it?
Is there a way to automatize this object creation using Moq (for example)?

obs: I'm writing unit tests for a system that is already created. It's not feasible to re-write all the architecture at this moment.

Thanks a million!

答:
I'd take this approach:

1 - Write unit tests for every combination of the 100 property input parameter object, leveraging a tool to do this for you (e.g. pex, intellitest) and ensure they all run green. At this point refer to the unit tests as integration tests rather than unit tests, for reasons that become obvious later.

2 - Refactor the tests into SOLID chunks of code - methods that do not call other methods can be considered genuinely unit testable as they've no dependencies on other code. The remaining methods are still only integration testable.

3 - Ensure ALL the integration tests are still running green.

4 - Create new unit tests for the newly unit testable code.

5 - With everything running green you can delete all/some of the superfluous original integration tests - up to you, only if you feel comfortable doing so.

6 - With everything running green you can start to reduce the 100 properties needed in the unit tests to only those strictly needed for each individual method. This will likely highlight areas for additional refactoring, but anyway will simplify the parameters object. That in turn will make future code maintainers efforts less buggy, and I'd wager that historic failures to address the size of the parameter object when it had 50 properties is why it is now 100. Failing to address the issue now will mean it'll grow to 150 parameters eventually, which lets face it, nobody wants.


问:
C# null check chain in method call
I suppose method call chain below.

```<code>void DoSomething()
{
    ObjectA a = CreateA();
    if (a != null)
    {
        a.Foo();
    }
}

ObjectA CreateA()
{
    ObjectB b = CreateB();
    if (b != null)
    {
        ObjectA a = b.ToA();
        return a;
    }
    return null;
}
</code>```

If method call depth get deeper, null checking will be more overlapped.
Is there any good solution for this?

Modified

I changed example code. It can't solve my problem that change CreateA to constructor.
The problem is only unnecessary null check chaining overlapping.

```<code>void SetImage()
{
    UISprite image = GetSprite();
    if (image  != null)
    {
        image.spriteName = "hat";
    }
}

UISprite GetSprite()
{
    UISprite image = GetComponent<UISprite>();
    if (image  != null)
    {
        image.width = 100;
        image.height = 100;
        return image;
    }
    return null;
}
</code>```

答:
Starting with C# 6.0 you can use Null-Conditional Operator, which lets you make null-checking implicitly:

```<code>var result = possiblyNull?.MethodThatCanReturnNull()?.SomeProperty;
</code>```

This construct will produce a null result if any element in the chain produces null.

Title: C# null check chain in method call

Body:
I suppose method call chain below.

void DoSomething()
{
    ObjectA a = CreateA();
    if (a != null)
    {
        a.Foo();
    }
}

ObjectA CreateA()
{
    ObjectB b = CreateB();
    if (b != null)
    {
        ObjectA a = b.ToA();
        return a;
    }
    return null;
}

If method call depth get deeper, null checking will be more overlapped.
Is there any good solution for this?

Modified

I changed example code. It can't solve my problem that change CreateA to constructor.
The problem is only unnecessary null check chaining overlapping.

void SetImage()
{
    UISprite image = GetSprite();
    if (image  != null)
    {
        image.spriteName = "hat";
    }
}

UISprite GetSprite()
{
    UISprite image = GetComponent<UISprite>();
    if (image  != null)
    {
        image.width = 100;
        image.height = 100;
        return image;
    }
    return null;
}

Body:
Starting with C# 6.0 you can use Null-Conditional Operator, which lets you make null-checking implicitly:

var result = possiblyNull?.MethodThatCanReturnNull()?.SomeProperty;

This construct will produce a null result if any element in the chain produces null.