问:
why no calc() mixin in Compass?
I feel like I'm missing something, Compass provides mixins for everything else that requires browser prefixes. I understand that calc() is widely supported in modern browsers but I can't be the only one that wants to maximize compatibility?

Searching the docs returns nothing:

http://compass-style.org/search/?q=calc

Bourbon has a calc() mixin that only adds -webkit- but it's deprecated and I can't seem to find out why?

http://bourbon.io/docs/#calc

Any help would be appreciated, why is there no calc() mixin in Compass?

答:
If your goal is to include more prefixes to support very old browsers, you should be able to just use calc() in your stylesheet (without the use of a mixin) and Compass will prefix it for you. If you're not getting the prefixes that you want, you need to adjust your desired browser support settings to include the older browsers you wish to support.

Compass Docs - Tuning vendor prefixes:
http://compass-style.org/help/documentation/tuning-vendor-prefixes/

I haven't seen any evidence that Compass ever supported a calc() mixin in the past but if they did, I would assume they removed it due to browser support getting so good for unprefixed native calc(). I'm pretty sure this is why Bourbon removed it from their library.

Have you considered preprocessing your values instead of using calc() at all? That would truly ensure the most compatibility by avoiding situations where either the browser's support for navtive calc() is buggy or totally non-existent.

Title: why no calc() mixin in Compass?


来源: stackexchange

问:
MS VS 2013 Keyboard shortcut
With MS Visual Studio 2013, what are the keyboard shortcuts (if any) for:

"Float"

"Move to Main Document Group"

Thank you.

答: There are no default shortcuts for these commands. You can assign your own shortcuts in Visual Studio keyboard option to Window.Float and Window.MoveToMainDocumentGroup commands.

ContentLicense: CC BY-SA 3.0

Title: MS VS 2013 Keyboard shortcut


问:
angularfire Error: [$injector:unpr] Unknown provider: $firebaseStorageProvider <- $firebaseStorage
I use "https://www.gstatic.com/firebasejs/4.1.1/firebase.js"

and "https://cdn.firebase.com/libs/angularfire/2.0.1/angularfire.min.js"

My app.js

```<code> angular
      .module('angularfireApp', [
        'firebase',
        'ngAnimate',
        'ngCookies',
        'ngResource',
        'ngRoute',
        'ngSanitize',
        'ngTouch'
      ])
</code>```

my controller.js

```<code>angular.module('angularfireApp')
  .controller('ProductsCtrl', function (Auth, $scope, $firebaseObject, $firebaseArray, $firebaseStorage) {
</code>```

Any idea of what the problem is, thanks

答:
Please use the latest version (2.3.0 as of now) of angularfire because they have recently added a service to wrap the functions of $firebaseStorage. Please check the following release notes:

https://github.com/firebase/angularfire/releases

Therefore, change your angularfire reference to the following:

https://cdn.firebase.com/libs/angularfire/2.3.0/angularfire.min.js

You should be fine after that :)

PS - JSFiddle Demo

Body:
I use "https://www.gstatic.com/firebasejs/4.1.1/firebase.js"

and "https://cdn.firebase.com/libs/angularfire/2.0.1/angularfire.min.js"

My app.js

 angular
      .module('angularfireApp', [
        'firebase',
        'ngAnimate',
        'ngCookies',
        'ngResource',
        'ngRoute',
        'ngSanitize',
        'ngTouch'
      ])

my controller.js

angular.module('angularfireApp')
  .controller('ProductsCtrl', function (Auth, $scope, $firebaseObject, $firebaseArray, $firebaseStorage) {

Any idea of what the problem is, thanks


问:
How to handle null or empty value in multi layer project
I am working in Xamarin.android mobile application. I got some problem of crashing the app due to null value set to TextView.Text and ImageView from api call value. I wonder is there any better way to handle null value in any layer of application i.e. DataLayer or UI. As I have setup this structure in my project.
MyApplication.DA (for data access layer) and all my getters and setters are set under here. In this case, I have DA_WebSchoolNews.cs as

```<code> public class NewsServiceRootObject
{
    public List<DA_NewsServiceResult> NewsServiceResult { get; set; }
}

public class DA_NewsServiceResult
{
    public string CreatedDate { get; set; }
    public string Description { get; set; }
    public string Id { get; set; }
    public string Image { get; set; }
    public string PublishDate { get; set; }
    public string ShortDescription { get; set; }
    public string Title { get; set; }
    public string UserName { get; set; }
}
</code>```

In MyApplication.Core, which is shared project I have called webapi service to update data:

```<code> public async void downloadJsonFeedAsync(string url)
    {
        var httpClient = new HttpClient();

        Task<string> contentTask = httpClient.GetStringAsync(url);

        // await! control returns to the caller and the task continues to run on another thread
        string content = await contentTask;
        Console.Out.WriteLine("Response Body: \r\n {0}", content);

        //Convert string to JSON object
        rootObject = Newtonsoft.Json.JsonConvert.DeserializeObject<NewsServiceRootObject>(content);

    }
</code>```

In MyApplication.UI, an UI layer in which I have created activities and fragments views. In my adapter class, I tried to handle null values so that view would not set any null values during run time, which I have done as follows

```<code> DA_NewsServiceResult item = this[position];
        if (string.IsNullOrEmpty(item.Title)|| string.IsNullOrEmpty(item.Description))
        {
            item.Title = "";
            item.Description = "";
        }

            var txtTitle = view.FindViewById<TextView>(Resource.Id.Title).Text = Android.Text.Html.FromHtml(item.Title).ToString();
            var txtDescription = view.FindViewById<TextView>(Resource.Id.Description).Text = Android.Text.Html.FromHtml(item.ShortDescription).ToString();
            var txtDate = view.FindViewById<TextView>(Resource.Id.news_date).Text = GetCustomDateTime(ConvertToDate(item.PublishDate));
</code>```

what is the best way to handle null or empty for string, date time , int or float type data and how. I will appreciate with sample lines of code if applicable. Thank you.

答:
First for String:

```<code>String.IsNullOrEmpty(string);
</code>```

And for DateTime:

```<code>your_date == DateTime.MinValue
</code>```

And for int int and float will never be null because it is a primitive types.

Body:
I am working in Xamarin.android mobile application. I got some problem of crashing the app due to null value set to TextView.Text and ImageView from api call value. I wonder is there any better way to handle null value in any layer of application i.e. DataLayer or UI. As I have setup this structure in my project.
MyApplication.DA (for data access layer) and all my getters and setters are set under here. In this case, I have DA_WebSchoolNews.cs as

 public class NewsServiceRootObject
{
    public List<DA_NewsServiceResult> NewsServiceResult { get; set; }
}

public class DA_NewsServiceResult
{
    public string CreatedDate { get; set; }
    public string Description { get; set; }
    public string Id { get; set; }
    public string Image { get; set; }
    public string PublishDate { get; set; }
    public string ShortDescription { get; set; }
    public string Title { get; set; }
    public string UserName { get; set; }
}

In MyApplication.Core, which is shared project I have called webapi service to update data:

 public async void downloadJsonFeedAsync(string url)
    {
        var httpClient = new HttpClient();

        Task<string> contentTask = httpClient.GetStringAsync(url);

        // await! control returns to the caller and the task continues to run on another thread
        string content = await contentTask;
        Console.Out.WriteLine("Response Body: \r\n {0}", content);

        //Convert string to JSON object
        rootObject = Newtonsoft.Json.JsonConvert.DeserializeObject<NewsServiceRootObject>(content);

    }

In MyApplication.UI, an UI layer in which I have created activities and fragments views. In my adapter class, I tried to handle null values so that view would not set any null values during run time, which I have done as follows

 DA_NewsServiceResult item = this[position];
        if (string.IsNullOrEmpty(item.Title)|| string.IsNullOrEmpty(item.Description))
        {
            item.Title = "";
            item.Description = "";
        }

            var txtTitle = view.FindViewById<TextView>(Resource.Id.Title).Text = Android.Text.Html.FromHtml(item.Title).ToString();
            var txtDescription = view.FindViewById<TextView>(Resource.Id.Description).Text = Android.Text.Html.FromHtml(item.ShortDescription).ToString();
            var txtDate = view.FindViewById<TextView>(Resource.Id.news_date).Text = GetCustomDateTime(ConvertToDate(item.PublishDate));

what is the best way to handle null or empty for string, date time , int or float type data and how. I will appreciate with sample lines of code if applicable. Thank you.

Body:
First for String:

String.IsNullOrEmpty(string);

And for DateTime:

your_date == DateTime.MinValue

And for int int and float will never be null because it is a primitive types.


问:
jQuery not able to update my global variable
I have a function, for navigating between tabs, and also submits a form. The back-end validation is working just as expected, but i'm setting my global variable isValid=false if the user gave invalid input. I'm only validating one form for now, hence the use of data.isValid.

My Jquery Code

```<code>var tabID, relatedTabID, isValid=true;

$('#form').on('submit', function (e) {
    var formData = $('#form').serialize();
    e.preventDefault();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        type: 'POST',
        url: '/roa',
        dataType: 'json',
        data: {inputs: formData, nextTab: relatedTabID, currentTab: tabID}, //also need to pass in related Tab ID, and also tabID
        success: function (data) {
            if (data.value===1){
                if (data.isValid){//if data is valid, return next view
                    $('#tabShow').html((data.view));
                    isValid=true;
                }
                else{//if it isn't target the div id=erros and replace only error section

                    isValid=false;
                    var x=jQuery.parseJSON(data.msg);
                    var errorString = '';
                    $.each( x.errors, function( key, value) {
                        errorString += "<li class='alert alert-danger'>" + value + '</li>';
                    });
                    alert(errorString);
                    $('.something').html(errorString);
                    return false;//prevent navigation
                }
            }
            else{
            $('#tabShow').html((data.view));}
        },
        error: function () {
            alert('error');
        }
    });
});

$(document).on('hide.bs.tab', '.nav-pills a', function (e) {

    tabID = $(e.target).attr('id');
    relatedTabID = $(e.relatedTarget).attr('id');
    $('#form').submit();
    alert(isValid);
    if (tabID==='section2'){
        return false;
    }

});
</code>```

My function $(document).on('hide.bs.tab', '.nav-pills a', function (e) is not able to detect the change in my global variable isValid. I don't really understand the problem here.

My back-end code

```<code>Route::post('/roa', function() {
$m = Request::except('_token');
$name = "form1_sections/" . $m['nextTab'] . "_form";//next view name
$name2 = "form1_sections/" . $m['currentTab'] . "_form";//current view name

parse_str($m['inputs'], $output);
$type= gettype($output);
if ($m['currentTab']=='section2'){//only validation for section2
    $rules = [
        'TB1_course.*' => 'required'
    ];
    $validator=Validator::make($output, $rules);
    if ($validator->passes()){
        return ["view" => view("$name")-> render(), "value"=>1, "type"=>$type, "isValid"=>true];
    }
    return ["view" => view("$name2")->withErrors($validator) -> render(), "value"=>1, "type"=>$type, "isValid"=>false, "msg"=>json_encode([
        'errors' => $validator->errors()->getMessages(),
        'code' => 422
     ])];
}
return ["view" => view("$name") -> render()];
});
</code>```

Even when an error is detected, it should return a value of false. I would like to stop navigation if validation is incorrect. An interesting thing to note is that isValid returns true, even when I display the errors but after that if I try navigating somewhere else, it returns false. Any suggestions?

答:
are you sure that your else was triggered? if yes you might want to do this for your Global variables declare an object and access it.

ex

```<code>var Global = {
     isValid = true
///put all your Global variable here
}
</code>```

then access it using the Global object your problem might be the scoping in js

```<code>Global.isValid = false;
</code>```

Body:
I have a function, for navigating between tabs, and also submits a form. The back-end validation is working just as expected, but i'm setting my global variable isValid=false if the user gave invalid input. I'm only validating one form for now, hence the use of data.isValid.

My Jquery Code

var tabID, relatedTabID, isValid=true;

$('#form').on('submit', function (e) {
    var formData = $('#form').serialize();
    e.preventDefault();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        type: 'POST',
        url: '/roa',
        dataType: 'json',
        data: {inputs: formData, nextTab: relatedTabID, currentTab: tabID}, //also need to pass in related Tab ID, and also tabID
        success: function (data) {
            if (data.value===1){
                if (data.isValid){//if data is valid, return next view
                    $('#tabShow').html((data.view));
                    isValid=true;
                }
                else{//if it isn't target the div id=erros and replace only error section

                    isValid=false;
                    var x=jQuery.parseJSON(data.msg);
                    var errorString = '';
                    $.each( x.errors, function( key, value) {
                        errorString += "
" + value + '
';
                    });
                    alert(errorString);
                    $('.something').html(errorString);
                    return false;//prevent navigation
                }
            }
            else{
            $('#tabShow').html((data.view));}
        },
        error: function () {
            alert('error');
        }
    });
});

$(document).on('hide.bs.tab', '.nav-pills a', function (e) {

    tabID = $(e.target).attr('id');
    relatedTabID = $(e.relatedTarget).attr('id');
    $('#form').submit();
    alert(isValid);
    if (tabID==='section2'){
        return false;
    }

});

My function $(document).on('hide.bs.tab', '.nav-pills a', function (e) is not able to detect the change in my global variable isValid. I don't really understand the problem here.

My back-end code

Route::post('/roa', function() {
$m = Request::except('_token');
$name = "form1_sections/" . $m['nextTab'] . "_form";//next view name
$name2 = "form1_sections/" . $m['currentTab'] . "_form";//current view name

parse_str($m['inputs'], $output);
$type= gettype($output);
if ($m['currentTab']=='section2'){//only validation for section2
    $rules = [
        'TB1_course.*' => 'required'
    ];
    $validator=Validator::make($output, $rules);
    if ($validator->passes()){
        return ["view" => view("$name")-> render(), "value"=>1, "type"=>$type, "isValid"=>true];
    }
    return ["view" => view("$name2")->withErrors($validator) -> render(), "value"=>1, "type"=>$type, "isValid"=>false, "msg"=>json_encode([
        'errors' => $validator->errors()->getMessages(),
        'code' => 422
     ])];
}
return ["view" => view("$name") -> render()];
});

Even when an error is detected, it should return a value of false. I would like to stop navigation if validation is incorrect. An interesting thing to note is that isValid returns true, even when I display the errors but after that if I try navigating somewhere else, it returns false. Any suggestions?

Body:
are you sure that your else was triggered? if yes you might want to do this for your Global variables declare an object and access it.

ex

var Global = {
     isValid = true
///put all your Global variable here
}

then access it using the Global object your problem might be the scoping in js

Global.isValid = false;


问:
Cannot rollback in if block transaction sql
When I executed this stored procedure, I cannot rollback in IF block even the IF statement was right. If the IF statement was right, script still running in the end and there is no rollback at all.

The message: The account id has already used successful register

Msg 3902, Level 16, State 1, Procedure PROC_DANGKY, Line 23

  The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.

Code:

```<code>CREATE PROCEDURE PROC_REGISTER
    @name nvarchar(30),
    @birth datetime,
    @passport nvarchar(9),
    @address nvarchar(50),
    @phone nvarchar(11),
    @email nvarchar(20),
    @account nvarchar(30),
    @password nvarchar(20)
AS
BEGIN TRAN
    BEGIN TRY
        IF (EXISTS(SELECT * FROM CUSTOMER WHERE ACCOUNT = @account))
        BEGIN
            PRINT N'The account id has already been used'
            ROLLBACK TRAN
        END

        INSERT INTO KHACHHANG
        VALUES (@name, @birth, @passport, @address, @phone, @email, @account, @password)
        PRINT N'Successfully registered'
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMsg VARCHAR(2000)
        SELECT @ErrorMsg = N'Error: ' + ERROR_MESSAGE()
        RAISERROR(@ErrorMsg, 16,1)

        ROLLBACK TRAN

        RETURN
    END CATCH
COMMIT TRAN
</code>```

答:
REFORMATTED your query

 Removed rollback after exists

```<code>CREATE PROC PROC_REGISTER
    @name nvarchar(30),
    @birth datetime,
    @passport nvarchar(9),
    @address nvarchar(50),
    @phone nvarchar(11),
    @email nvarchar(20),
    @account nvarchar(30),
    @password nvarchar(20)

AS
 BEGIN TRAN
    BEGIN TRY
        IF (EXISTS(SELECT * FROM CUSTOMER WHERE ACCOUNT = @account))
             PRINT N'The account id has already used'
        ELSE
         BEGIN

             INSERT INTO KHACHHANG VALUES (@name, @birth, @passport,           @address, @phone, @email, @account, @password)
           PRINT N'Successul register'
         END
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMsg VARCHAR(2000)

          SELECT @ErrorMsg = N'Error: ' + ERROR_MESSAGE()
            RAISERROR(@ErrorMsg, 16,1)
             IF @@TRANCOUNT > 0
                  ROLLBACK TRAN
        END CATCH

IF @@TRANCOUNT > 0
    COMMIT TRAN
GO

RETURN
</code>```

Body:
When I executed this stored procedure, I cannot rollback in IF block even the IF statement was right. If the IF statement was right, script still running in the end and there is no rollback at all.

The message: The account id has already used successful register

Msg 3902, Level 16, State 1, Procedure PROC_DANGKY, Line 23

  The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.

Code:

CREATE PROCEDURE PROC_REGISTER
    @name nvarchar(30),
    @birth datetime,
    @passport nvarchar(9),
    @address nvarchar(50),
    @phone nvarchar(11),
    @email nvarchar(20),
    @account nvarchar(30),
    @password nvarchar(20)
AS
BEGIN TRAN
    BEGIN TRY
        IF (EXISTS(SELECT * FROM CUSTOMER WHERE ACCOUNT = @account))
        BEGIN
            PRINT N'The account id has already been used'
            ROLLBACK TRAN
        END

        INSERT INTO KHACHHANG
        VALUES (@name, @birth, @passport, @address, @phone, @email, @account, @password)
        PRINT N'Successfully registered'
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMsg VARCHAR(2000)
        SELECT @ErrorMsg = N'Error: ' + ERROR_MESSAGE()
        RAISERROR(@ErrorMsg, 16,1)

        ROLLBACK TRAN

        RETURN
    END CATCH
COMMIT TRAN

Body:
REFORMATTED your query

 Removed rollback after exists

CREATE PROC PROC_REGISTER
    @name nvarchar(30),
    @birth datetime,
    @passport nvarchar(9),
    @address nvarchar(50),
    @phone nvarchar(11),
    @email nvarchar(20),
    @account nvarchar(30),
    @password nvarchar(20)

AS
 BEGIN TRAN
    BEGIN TRY
        IF (EXISTS(SELECT * FROM CUSTOMER WHERE ACCOUNT = @account))
             PRINT N'The account id has already used'
        ELSE
         BEGIN

             INSERT INTO KHACHHANG VALUES (@name, @birth, @passport,           @address, @phone, @email, @account, @password)
           PRINT N'Successul register'
         END
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMsg VARCHAR(2000)

          SELECT @ErrorMsg = N'Error: ' + ERROR_MESSAGE()
            RAISERROR(@ErrorMsg, 16,1)
             IF @@TRANCOUNT > 0
                  ROLLBACK TRAN
        END CATCH

IF @@TRANCOUNT > 0
    COMMIT TRAN
GO

RETURN


问:
How do I measure the benefits of unit testing?
I'm in the process of pushing my company towards having unit tests as a major part of the development cycle.  I've gotten the testing framework working with our MVC framework, and multiple members of the team are now writing unit tests.  I'm at the point, though, where there's work that needs to be done to improve our hourly build, the ease of figuring out what fixtures you need to use, adding functionality to the mock object generator, etc., etc., and I want to be able to make the case for this work to management.  In addition, I'd like us to allocate time to write unit tests for the most critical pieces of existing code, and I just don't see that happening without a more specific case than "everyone knows unit tests are good".

How do you quantify the positive impact of (comprehensive and reliable) unit tests on your projects?  I can certainly look at the number and severity of bugs filed and correlate it with our increases in code coverage, but that's a rather weak metric.

答: Sonar is a company that makes a very interesting code inspection tool, they actually try to measure technical debt programaticaly, which correlates untested code and developer price per hour.</p>

ContentLicense: CC BY-SA 2.5


问:
Android Files USB Stick Access?
I want access to a file: "/mnt/media_rw/72Ab-289A/myFile.mp3"
This file is located on my USB Stick on my Moto G5 Android 7 Smartphone.

But it's not possible... I can't read the /mnt/media_rw/ folder.

The permissions: WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE are set, so this is not the problem.

I've tried it for 5 hours, with google, Environment.getExternalStorageDirectory(), ContextCompat.getExternalFilesDirs, File.readFiles, and much more... nothing is working.

Is there anyone out there and can help me, with a complete solution?

答:
Ok, found it out.

It's not working with the normal File/Storage commands.

The only way is to use the Documents Framework:
https://developer.android.com/guide/topics/providers/document-provider.html

Title: Android Files USB Stick Access?


问:
UTF-8 encoding problem with servlet and apache HttpClient
I have a servlet that sends a string with utf-8 encoding. Also I have a client written with apache httpcomponents library.

My problem is reading the response in utf-8. Some special characters like ñ or ç are not read correctly. If I test the server with an html page sending a request, the string is correct and the encoding is UTF-8 without BOM.

Some snippets:
Servlet

```<code>response.setContentType ("application/json; charset=UTF-8");
PrintWriter out = response.getWriter ();
out.write (string);
</code>```

Client

```<code>entity = response.getEntity ();
entity.getContentEncoding (); //returns null
resultado = EntityUtils.toString (entity, HTTP.UTF_8); //Some characters are wrong
</code>```

Has anyone had the same problem?

SOLVED:
Sorry guys the client and server were working correctly. I'm writting an android app and it seems that the logcat (where I print the messages) doesn't support utf-8 encoding.

答:
Have you tried

```<code>response.setCharacterEncoding("utf-8");
</code>```

instead of setting the encoding via setContentType? It shouldn't make a difference according to the documentation, but who knows...

Also, make sure you didn't call response.getWriter() anywhere in your code before setting the character encoding, because the latter would not have any effect in that case.

Body:
I have a servlet that sends a string with utf-8 encoding. Also I have a client written with apache httpcomponents library.

My problem is reading the response in utf-8. Some special characters like ñ or ç are not read correctly. If I test the server with an html page sending a request, the string is correct and the encoding is UTF-8 without BOM.

Some snippets:
Servlet

response.setContentType ("application/json; charset=UTF-8");
PrintWriter out = response.getWriter ();
out.write (string);

Client

entity = response.getEntity ();
entity.getContentEncoding (); //returns null
resultado = EntityUtils.toString (entity, HTTP.UTF_8); //Some characters are wrong

Has anyone had the same problem?

SOLVED:
Sorry guys the client and server were working correctly. I'm writting an android app and it seems that the logcat (where I print the messages) doesn't support utf-8 encoding.

Body:
Have you tried

response.setCharacterEncoding("utf-8");

instead of setting the encoding via setContentType? It shouldn't make a difference according to the documentation, but who knows...

Also, make sure you didn't call response.getWriter() anywhere in your code before setting the character encoding, because the latter would not have any effect in that case.


问:
Angular 2, routing URL path to route in the app
I have an Angular 2 app hosted on S3. The routing file looks like this.

```<code>const APP_ROUTES: Routes = [
  { path: 'checkout', component: CheckoutComponent },
  { path: 'thankyou', component: ThankyouComponent },
  { path: 'lander', component: LanderComponent },
  { path: '', component: LanderComponent }
];
</code>```

If the user enters www.example.com/checkout I would like it to take them to the checkout route on the app. I figured it would just do this, but S3 is giving me the error No Such Key. Is there a way to do this in Angular 2, or is it something I need to set in S3?  I think the problem is S3 is going to the example.com bucket and then expecting a folder checkout. How would I have it not do that and just the app along with whatever route is specified after the URL?

答:
```<code>RouterModule.forRoot(APP_ROUTES, { useHash: true })
</code>```

Body:
I have an Angular 2 app hosted on S3. The routing file looks like this.

const APP_ROUTES: Routes = [
  { path: 'checkout', component: CheckoutComponent },
  { path: 'thankyou', component: ThankyouComponent },
  { path: 'lander', component: LanderComponent },
  { path: '', component: LanderComponent }
];

If the user enters www.example.com/checkout I would like it to take them to the checkout route on the app. I figured it would just do this, but S3 is giving me the error No Such Key. Is there a way to do this in Angular 2, or is it something I need to set in S3?  I think the problem is S3 is going to the example.com bucket and then expecting a folder checkout. How would I have it not do that and just the app along with whatever route is specified after the URL?


问:
How to prevent Sql-Injection on User-Generated Sql Queries
I have a project (private, ASP.net website, password protected with https) where one of the requirements is that the user be able to enter Sql queries that will directly query the database. I need to be able to allow these queries, while preventing them from doing damage to the database itself, and from accessing or updating data that they shouldn't be able to access/update.

I have come up with the following rules for implementation:

Use a db user that only has permission for Select Table/View and Update Table (thus any other commands like drop/alter/truncate/insert/delete will just not run).

Verify that the statement begins with the words "Select" or "Update"

Verify (using Regex) that there are no instances of semi-colons in the statement that are not surrounded by single-quotes, white space and letters. (The thought here is that the only way that they could include a second query would be to end the first with a semi-colon that is not part of an input string).

Verify (using Regex) that the user has permission to access the tables being queried/updated, included in joins, etc. This includes any subqueries. (Part of the way that this will be accomplished is that the user will be using a set of table names that do not actually exist in the database, part of the query parsing will be to substitute in the correct corresponding table names into the query).

Am I missing anything?

The goal is that the users be able to query/update tables to which they have access in any way that they see fit, and to prevent any accidental or malicious attempts to damage the db. (And since a requirement is that the user generate the sql, I have no way to parametrize the query or sanitize it using any built-in tools that I know of).

答:
Well, you already have enough people telling you "dont' do this", so if they aren't able to dissuade you, here are some ideas:

INCLUDE the Good, Don't try to EXCLUDE the bad

(I think the proper terminology is Whitelisting vs Blacklisting )
By that, I mean don't look for evil or invalid stuff to toss out (there are too many ways it could be written or disguised), instead look for valid stuff to include and toss out everything else.

You already mentioned in another comment that you are looking for a list of user-friendly table names, and substituting the actual schema table names. This is what I'm talking about--if you are going to do this, then do it with field names, too.

I'm still leaning toward a graphical UI of some sort, though: select tables to view here, select fields you want to see here, use some drop-downs to build a where clause, etc. A pain, but still probably easier.

OwnerDisplayName: Yaakov Ellis

LastEditorDisplayName: Yaakov Ellis

OwnerDisplayName: BradC

LastEditorDisplayName: BradC


问:
Execute sql script inside seed.rb in rails3
I want to execute this sql script inside my seed.rb

```<code>LOAD DATA LOCAL INFILE '/home/list-38.csv'
INTO TABLE list
FIELDS TERMINATED BY ':'
LINES TERMINATED BY '\n'
(email,name,password);
</code>```

I checked this link but unable to figure out the solution.So that once we run rake db:seed

How to seed mysql database by running sql scripts in Ruby Rails platform? it dumps my data into the table.

any queries ..do reply

Thanx

答:
A variation on Fredrik Boström's answer that can load from a file:</p>

```<code># db/seeds.rb

def execute_sql_file(path, connection = ActiveRecord::Base.connection)
  require 'active_support/core_ext/object/blank.rb'
  IO.read(path).split(';').reject(&:blank?).each do |statement|
    connection.execute(statement)
  end
end

execute_sql_file('my.sql')
</code>```

Body:
I want to execute this sql script inside my seed.rb

LOAD DATA LOCAL INFILE '/home/list-38.csv'
INTO TABLE list
FIELDS TERMINATED BY ':'
LINES TERMINATED BY '\n'
(email,name,password);

I checked this link but unable to figure out the solution.So that once we run rake db:seed

How to seed mysql database by running sql scripts in Ruby Rails platform? it dumps my data into the table.

any queries ..do reply

Thanx

Body:
A variation on Fredrik Boström's answer that can load from a file:

# db/seeds.rb

def execute_sql_file(path, connection = ActiveRecord::Base.connection)
  require 'active_support/core_ext/object/blank.rb'
  IO.read(path).split(';').reject(&:blank?).each do |statement|
    connection.execute(statement)
  end
end

execute_sql_file('my.sql')


问:
Big O Notation Confusion (C++)
```<code>int f(const std::vector<int>& v) {
    int result = 0;
    for (int i = 0; i < v.size(); ++i) {                O(N)
        for (int j = v.size(); j >= 0; j -= 2) {        O(N/2)
            result += v.at(i) * j;
        }
    }
    return result;
}
</code>```

The inner for loop is O(N/2), however I am wondering why this is because

For example, if v.size() is 10, then

10 >= 0  ✓

8 >= 0 ✓

6 >= 0 ✓

4 >= 0  ✓

2>= 0 ✓

0 >= 0 ✓

-2 Fails

The inner for loop could be executed 6 times with an input size of 10

What am I missing?

EDIT* I understand that only highest magnitude is taken into consideration. This question was more about coming up with the original O(N/2 + 1)

答:
In a comment, you said:

I understand this, but I am just curious as to how O(N/2) is obtained

Take a look at the following table:

```<code>Size of vector     Number of time the inner loop is executed:
0                  1
1                  1
2                  2
3                  2
...
100                51
101                51
...
2x                 x + 1
2x + 1             x + 1
</code>```

If you take the constant 1 out of that equation, the inner loop is O(N/2).

Title: Big O Notation Confusion (C++)

Body:
int f(const std::vector<int>& v) {
    int result = 0;
    for (int i = 0; i < v.size(); ++i) {                O(N)
        for (int j = v.size(); j >= 0; j -= 2) {        O(N/2)
            result += v.at(i) * j;
        }
    }
    return result;
}

The inner for loop is O(N/2), however I am wondering why this is because

For example, if v.size() is 10, then

10 >= 0  ✓

8 >= 0 ✓

6 >= 0 ✓

4 >= 0  ✓

2>= 0 ✓

0 >= 0 ✓

-2 Fails

The inner for loop could be executed 6 times with an input size of 10

What am I missing?

EDIT* I understand that only highest magnitude is taken into consideration. This question was more about coming up with the original O(N/2 + 1)

Body:
In a comment, you said:

I understand this, but I am just curious as to how O(N/2) is obtained

Take a look at the following table:

Size of vector     Number of time the inner loop is executed:
0                  1
1                  1
2                  2
3                  2
...
100                51
101                51
...
2x                 x + 1
2x + 1             x + 1

If you take the constant 1 out of that equation, the inner loop is O(N/2).


问:
Iterating over asyncio coroutines/Tasks as soon as they are ready
I launch a bunch of requests using aiohttp. Is there a way to get the results one-by-one as soon as each request is complete?

Perhaps using something like async for? Or Python 3.6 async generators?

Currently I await asyncio.gather(*requests) and process them when all of them are completed.

答:
As I understand according to the docs, requests are Futures (or can be easily converted to Future using asyncio.ensure_future).

A Future object has a method .add_done_callback.
So, you can add your callback for every request, and then do gather.

Docs for Future.add_done_callback


问:
TFS Security - Browsr Server
I have set up TFS Security using Active Directory groups and in source control explorer through Visual Studio, users only see Team Projects that they have access to. However if they go to Team Explorer and click on the drop down menu they see almost all the team projects. If they go to web Tfs as well, the behaviour is exactly the same.

How do i restrict them to only see projects in dropdown that they have access to?

Project Collection Valid Users Group - Permissions

Project Collection Test Service Accounts - Permissions

Project Collection Service Accounts - Permissions

Project Collection Proxy Service Accounts - Permissions

Project Collection Build Service Accounts - Permissions

Project Collection Build Administrators - Permissions

--At Project Level--

All Project Valid Users group at Project Level are members of Project Collection Valid Users group

User Access From Collection Level:

答:
You need to add the user/groups to the specific team project but not in Collection level. Thus , the restricted user/groups can only see the specific team projects which they have permissions under the collection.

In Team Explorer you can select the projects which you want to connect/display.

Update:

Add the group under specific team project (Set permissions in
Project level)

Add the same group under the specific collection

Under the collection security set "View Collection Level
Information" to "Deny" for the group (Set permissions in Collection
level)

Then the users in the group will can only access TFS with project permissions.

Title: TFS Security - Browsr Server


问:
I want to check if number starts with 4 or 5 in CGI
I need to write some script in CGI which is new to me. I am trying to do if else with condition numbers starting with 5 or 6. So do one code if number starts with 5 and do another if number starts with 6.</p>

答:
I don't think you understand what CGI is. CGI is simply a set of environment variables that are set up by the webserver, and your program is executed with them. The output of the program becomes the webpage.

So if you want to write a CGI script in Python, PHP, C, Assembly, Whitespace... as long as it can be called and use environment variables, it's fine.

So this is really a language question. Which language are you using?

EDIT You specified Perl in a comment to this answer. I suggest you edit the question.

What's your input number? The Perl script will be run with a whole truckload of extra environment variables. Two of the most important are QUERY_STRING and REQUEST_METHOD. CGI consists of a specification of these environment variables, so any language can be used to write CGI.

Consider perl_cgi.cgi?something=else. The bit following the ? is the QUERY_STRING. You can specify this directly as part of an anchor:

```<code><a href="perl_cgi.cgi?something=else">Run with something equals else</a>
</code>```

or as part of a form (one of GET or POST, defaults to GET):

```<code><form action="perl_cgi.cgi" method="[GET or POST]">
    <input type="text" name="something" value="else"/>
    <input type="submit" value="Submit!"/>
</form>
</code>```

This will run your program with the same query string as above (or a different parameter, if the text box is changed) but REQUEST_METHOD will be either GET or POST depending.

So let's write a Perl CGI script to print the first number of the string we get (we're only passed strings):

```<code>use CGI;
$cgi=new CGI;
$x=$cgi->param('x');
$firstnum=substr($x, 0, 1);
print "Content-type: text/html\n\n";

print <<"EOF";
<html>
<head>
<title>My sample HTML page</title>
</head>
<body>
<p>The first number of $x is $firstnum</p>
</body>
</html>
EOF
</code>```

This presupposes that this program is run as [program_name]?x=[some string]. It's up to you to make sure that's the case.

That should give you enough. You can check firstnum to see if its 5 or 6, then do different things depending.

Body:
I don't think you understand what CGI is. CGI is simply a set of environment variables that are set up by the webserver, and your program is executed with them. The output of the program becomes the webpage.

So if you want to write a CGI script in Python, PHP, C, Assembly, Whitespace... as long as it can be called and use environment variables, it's fine.

So this is really a language question. Which language are you using?

EDIT You specified Perl in a comment to this answer. I suggest you edit the question.

What's your input number? The Perl script will be run with a whole truckload of extra environment variables. Two of the most important are QUERY_STRING and REQUEST_METHOD. CGI consists of a specification of these environment variables, so any language can be used to write CGI.

Consider perl_cgi.cgi?something=else. The bit following the ? is the QUERY_STRING. You can specify this directly as part of an anchor:

<a href="perl_cgi.cgi?something=else">Run with something equals else</a>

or as part of a form (one of GET or POST, defaults to GET):

<form action="perl_cgi.cgi" method="[GET or POST]">
    <input type="text" name="something" value="else"/>
    <input type="submit" value="Submit!"/>
</form>

This will run your program with the same query string as above (or a different parameter, if the text box is changed) but REQUEST_METHOD will be either GET or POST depending.

So let's write a Perl CGI script to print the first number of the string we get (we're only passed strings):

use CGI;
$cgi=new CGI;
$x=$cgi->param('x');
$firstnum=substr($x, 0, 1);
print "Content-type: text/html\n\n";

print <<"EOF";
<html>
<head>
<title>My sample HTML page</title>
</head>
<body>
<p>The first number of $x is $firstnum</p>
</body>
</html>
EOF

This presupposes that this program is run as [program_name]?x=[some string]. It's up to you to make sure that's the case.

That should give you enough. You can check firstnum to see if its 5 or 6, then do different things depending.


问:
how to access shopify Products via API without api-key and password?
i want to develop a chrome extension to see stats for any store which develop in shopify, can i access any store products without API-Key and Password in shopify?</p>

答:
You could try using the Shopify StoreFront API.

It allows to get information of your shop from from your own website or custom app. Although it doesn't need a API Password, it needs a Api Key that doesn't need to be a secret.

The documentation says this (the first point is the important):

Using the Storefront API, you can:

Fetch data about a single product or a collection of products to
  display on any website or device.

Create unique checkout experiences
  with full control over the shopping cart.

Create new customers or
  modify existing ones, including address information.

Allow customers
  to select unique product options.


问:
How to restrict few special characters for address field in PHP without regex?
HTML for address field:

```<code>    <p> <label for="username">Address:</label>
    <input type=text name="address" placeholder="Enter your address">
    </p>
</code>```

I have to check the address entered by the user against these conditions given below:

Only letters, numbers, hash, comma, circular brackets, forward slash, dot and hyphen are allowed.

Starting and ending should not be special characters.

Two consecutive special characters are not allowed.

答:
I think you are looking for html5 input field restrictors. But there exists one only for email address or url address, not for a regular physical address

https://www.w3schools.com/html/html_form_input_types.asp

```<code><form>
  E-mail:
  <input type="email" name="email">
</form>
</code>```

```<code><form>
  Add your homepage:
  <input type="url" name="homepage">
</form>
</code>```

based on your updated restrictions. This is best done with regular expressions

I have to check the address entered by the user against these
  conditions given below: 1) Only letters, numbers, hash, comma,
  circular brackets, forward slash, dot and hyphen are allowed. 2)
  Starting and ending should not be special characters. 3) Two
  consecutive special characters are not allowed.

This is the regex you need

```<code>/^([a-zA-Z0-9 ]|[a-zA-Z0-9 ][-#,()\/.])*[a-zA-Z0-9 ]$/gm
</code>```

https://regex101.com/r/irDQ1S/1

Body:
HTML for address field:

 Address:
    <input type=text name="address" placeholder="Enter your address">

I have to check the address entered by the user against these conditions given below:

Only letters, numbers, hash, comma, circular brackets, forward slash, dot and hyphen are allowed.

Starting and ending should not be special characters.

Two consecutive special characters are not allowed.

Body:
I think you are looking for html5 input field restrictors. But there exists one only for email address or url address, not for a regular physical address

https://www.w3schools.com/html/html_form_input_types.asp

<form>
  E-mail:
  <input type="email" name="email">
</form>

<form>
  Add your homepage:
  <input type="url" name="homepage">
</form>

based on your updated restrictions. This is best done with regular expressions

I have to check the address entered by the user against these
  conditions given below: 1) Only letters, numbers, hash, comma,
  circular brackets, forward slash, dot and hyphen are allowed. 2)
  Starting and ending should not be special characters. 3) Two
  consecutive special characters are not allowed.

This is the regex you need

/^([a-zA-Z0-9 ]|[a-zA-Z0-9 ][-#,()\/.])*[a-zA-Z0-9 ]$/gm

https://regex101.com/r/irDQ1S/1


问:
Sum for every case of a value in column
A sample of my matrix is given below:

```<code>[ 1  43;
  1  15;
  1  34;
  5  15;
  5  32;
  7   2;
  7  43;
  7  16;
  7  75 ]
</code>```

I want the sum of column 2 for each unique value in column 1. So, it would be:

```<code>[ 1   92;
  5   47;
  7  136 ]
</code>```

It would be possible with a for-loop, but it would be very time consuming. So I am looking for a faster solution.

答:
You can use the following code:

```<code>[C,~,ic] = unique(A(:,1));
result = [C, accumarray(ic,A(:,2))];
</code>```

Also, you can find unique and accumarray in the standard documentation.

Title: Sum for every case of a value in column

Body:
A sample of my matrix is given below:

[ 1  43;
  1  15;
  1  34;
  5  15;
  5  32;
  7   2;
  7  43;
  7  16;
  7  75 ]

I want the sum of column 2 for each unique value in column 1. So, it would be:

[ 1   92;
  5   47;
  7  136 ]

It would be possible with a for-loop, but it would be very time consuming. So I am looking for a faster solution.

Body:
You can use the following code:

[C,~,ic] = unique(A(:,1));
result = [C, accumarray(ic,A(:,2))];

Also, you can find unique and accumarray in the standard documentation.


问:
webpage layout distorts when opening website on a different computer?
basically when i opened my webpage on a different computer, my layout became distorted and some stuff went off the screen and you could not see it.

the PC i designed the website on had a larger screen than my laptop screen .

however when i zoomed out using the web browsers zoom function on my laptop, everything then went back to place again...why is this? how can i fix this?

how would i use media queries if that is the solution ?

below is the code: THANK YOU

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>The Sun</title>
         <style type="text/css">

            * {
                margin: 0;
                padding: 0;
            }
            body {
                background-color: #91928C;
                font-family: 'Titillium Web', Calibri, sans-serif;
                background-image:url(starfield.jpg);
                background-size:cover;

            }
            .nav-section {
                width: 100%;
                padding: 20% 0;

            }

            nav ul {
                position: relative;
                left: 550px;
                bottom: 350px;

                width: 700px;

                background-color: rgba(255, 255, 255, 0.5);
                text-align: center;
                border-radius: 63px;
            }
            nav ul li {
                list-style: none;
                display: inline-block;
            }
            nav ul li a {
                display: block;
                text-decoration: none;
                padding: 40px 60px;
                font-size: 20px;
                text-transform: uppercase;
                font-weight: 300;
                color: #323642;
                transition: background-color 0.5s ease;
            }
            nav ul li a:hover {
                background-color: rgba(255, 255, 255, 0.3);

            }

            .container {

                margin-left:auto;
                margin-right:auto;

            }

            .info {
                position:relative;
                top: -1800px;
                left:550px;
                opacity:1;
                width:700px;
                color: #ffffff;
                }

            .content {
                position: relative;
                bottom: 690px;
                left: 500px;
                background-color:#000000;
                height:1200px;

                width: 800px;
                border: 3px solid white;
                opacity:0.8;

            }

            h1 {
            color:#FFFFFF
            }

        </style>
    </head>
    <body>

        <div class="nav-section">
            <nav>
                <ul>

                     <li><a href="EarthProfile.html">Earth Profile</a></li>
                    <li><a href="EarthInfo.html">Info</a></li>
                    <li><a href="EarthVideo.html">video</a></li>

                </ul>
            </nav>
        </div>

        <div class="container">
        <div class="content">

        </div>
        </div>

        <div class="info">

          <center><img src = "earth.gif" height="800" width="700"></center>
          <br>
          <br>

          <hr> </hr>

          <br>
          <br>

          <p></p>
        </div>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <script type="text/javascript"></script>

    </body>
</html>
</code>```

答:
OKAYSO, to address your stated issue, you're getting different looks across platforms because of the way different browsers display various elements. To establish a solid baseline, use a CSS Reset.

Take a look at what I've changed, this should be enough to get you headed down the right path.

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>The Sun</title>
         <style type="text/css">
            html, body, div, span, applet, object, iframe,
            h1, h2, h3, h4, h5, h6, p, blockquote, pre,
            a, abbr, acronym, address, big, cite, code,
            del, dfn, em, img, ins, kbd, q, s, samp,
            small, strike, strong, sub, sup, tt, var,
            b, u, i, center,
            dl, dt, dd, ol, ul, li,
            fieldset, form, label, legend,
            table, caption, tbody, tfoot, thead, tr, th, td,
            article, aside, canvas, details, embed,
            figure, figcaption, footer, header, hgroup,
            menu, nav, output, ruby, section, summary,
            time, mark, audio, video {
                margin: 0;
                padding: 0;
                border: 0;
                font-size: 100%;
                font: inherit;
                vertical-align: baseline;
            }
            /* HTML5 display-role reset for older browsers */
            article, aside, details, figcaption, figure,
            footer, header, hgroup, menu, nav, section {
                display: block;
            }
            body {
                line-height: 1;
            }
            ol, ul {
                list-style: none;
            }
            blockquote, q {
                quotes: none;
            }
            blockquote:before, blockquote:after,
            q:before, q:after {
                content: '';
                content: none;
            }
            table {
                border-collapse: collapse;
                border-spacing: 0;
            }

            * {
                margin: 0;
                padding: 0;
            }
            body {
                background-color: #91928C;
                font-family: 'Titillium Web', Calibri, sans-serif;
                background-image: url(starfield.jpg);
                background-size: cover;
                background-position: center center;
                width: 100vw;
                height: 100vh;

            }
            .nav-section {
                width: 100%;
            }

            nav ul {
                width: 70%;
                max-width: 700px;
                background-color: rgba(255, 255, 255, 0.5);
                text-align: center;
                border-radius: 63px;
                margin: auto;
            }
            nav ul li {
                list-style: none;
                display: inline-block;
            }
            nav ul li a {
                display: block;
                text-decoration: none;
                padding: 40px 60px;
                font-size: 20px;
                text-transform: uppercase;
                font-weight: 300;
                color: #323642;
                transition: background-color 0.5s ease;
            }
            nav ul li a:hover {
                background-color: rgba(255, 255, 255, 0.3);

            }

            .container {
                margin-left:auto;
                margin-right:auto;
            }

            .info {
                opacity: 1;
                width: 90%;
                margin: auto;
                color: #ffffff;
            }

            .content {
                background-color: #000000;
                height: 1200px;
                width: 80%;
                margin: auto;
                max-width: 1000px;
                border: 3px solid white;
                opacity: 0.8;
            }

            h1 {
                color:#FFFFFF
            }
        </style>
    </head>
    <body>

        <div class="nav-section">
            <nav>
                <ul>

                     <li><a href="EarthProfile.html">Earth Profile</a></li>
                    <li><a href="EarthInfo.html">Info</a></li>
                    <li><a href="EarthVideo.html">video</a></li>

                </ul>
            </nav>
        </div>

        <div class="container">
            <div class="content">
                <div class="info">
                    <img src = "earth.gif" />
                    <hr> </hr>
                    <p></p>
                </div>
            </div>
        </div>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <script type="text/javascript"></script>

    </body>
</html>
</code>```

Your biggest issues were the use of "position" (read up on that!) and fixed dimensions. Use dimensions that are relative to the viewport or parent element going forward.

Good luck!

Body:
basically when i opened my webpage on a different computer, my layout became distorted and some stuff went off the screen and you could not see it.

the PC i designed the website on had a larger screen than my laptop screen .

however when i zoomed out using the web browsers zoom function on my laptop, everything then went back to place again...why is this? how can i fix this?

how would i use media queries if that is the solution ?

below is the code: THANK YOU

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>The Sun</title>

Earth Profile

Info

video

Body:
OKAYSO, to address your stated issue, you're getting different looks across platforms because of the way different browsers display various elements. To establish a solid baseline, use a CSS Reset.

Take a look at what I've changed, this should be enough to get you headed down the right path.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>The Sun</title>
         <style type="text/css">
            html, body, div, span, applet, object, iframe,
            h1, h2, h3, h4, h5, h6, p, blockquote, pre,
            a, abbr, acronym, address, big, cite, code,
            del, dfn, em, img, ins, kbd, q, s, samp,
            small, strike, strong, sub, sup, tt, var,
            b, u, i, center,
            dl, dt, dd, ol, ul, li,
            fieldset, form, label, legend,
            table, caption, tbody, tfoot, thead, tr, th, td,
            article, aside, canvas, details, embed,
            figure, figcaption, footer, header, hgroup,
            menu, nav, output, ruby, section, summary,
            time, mark, audio, video {
                margin: 0;
                padding: 0;
                border: 0;
                font-size: 100%;
                font: inherit;
                vertical-align: baseline;
            }
            /* HTML5 display-role reset for older browsers */
            article, aside, details, figcaption, figure,
            footer, header, hgroup, menu, nav, section {
                display: block;
            }
            body {
                line-height: 1;
            }
            ol, ul {
                list-style: none;
            }
            blockquote, q {
                quotes: none;
            }
            blockquote:before, blockquote:after,
            q:before, q:after {
                content: '';
                content: none;
            }
            table {
                border-collapse: collapse;
                border-spacing: 0;
            }

            * {
                margin: 0;
                padding: 0;
            }
            body {
                background-color: #91928C;
                font-family: 'Titillium Web', Calibri, sans-serif;
                background-image: url(starfield.jpg);
                background-size: cover;
                background-position: center center;
                width: 100vw;
                height: 100vh;

            }
            .nav-section {
                width: 100%;
            }

            nav ul {
                width: 70%;
                max-width: 700px;
                background-color: rgba(255, 255, 255, 0.5);
                text-align: center;
                border-radius: 63px;
                margin: auto;
            }
            nav ul li {
                list-style: none;
                display: inline-block;
            }
            nav ul li a {
                display: block;
                text-decoration: none;
                padding: 40px 60px;
                font-size: 20px;
                text-transform: uppercase;
                font-weight: 300;
                color: #323642;
                transition: background-color 0.5s ease;
            }
            nav ul li a:hover {
                background-color: rgba(255, 255, 255, 0.3);

            }

            .container {
                margin-left:auto;
                margin-right:auto;
            }

            .info {
                opacity: 1;
                width: 90%;
                margin: auto;
                color: #ffffff;
            }

            .content {
                background-color: #000000;
                height: 1200px;
                width: 80%;
                margin: auto;
                max-width: 1000px;
                border: 3px solid white;
                opacity: 0.8;
            }

            h1 {
                color:#FFFFFF
            }
        </style>
    </head>
    <body>

        <div class="nav-section">
            <nav>
                <ul>

                     <li><a href="EarthProfile.html">Earth Profile</a></li>
                    <li><a href="EarthInfo.html">Info</a></li>
                    <li><a href="EarthVideo.html">video</a></li>

                </ul>
            </nav>
        </div>

        <div class="container">
            <div class="content">
                <div class="info">
                    <img src = "earth.gif" />
                    <hr> </hr>
                    <p></p>
                </div>
            </div>
        </div>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <script type="text/javascript"></script>

    </body>
</html>

Your biggest issues were the use of "position" (read up on that!) and fixed dimensions. Use dimensions that are relative to the viewport or parent element going forward.

Good luck!


问:
Arbitrary document ordering in CouchDB/PouchDB
I’m building what can be treated as a slideshow app with CouchDB/PouchDB: each “slide” is its own Couch document, and slides can be reordered or deleted, and new slides can be added in between existing slides or at the beginning or end of the slideshow. A slideshow could grow from one to ≲10,000 slides, so I am sensitive to space- and time-efficiency.

I made the slide creation/editing functionality first, completely underestimating how tricky it is to keep track of slide ordering. This is hard because the order of each slide-document is completely independent of the slide-doc itself, i.e., it’s not something I can sort by time or some number contained in the document. I see numerous questions on StackOverflow about how to keep track of ordering in relational databases:

Efficient way to store reorderable items in a database

What would be the best way to store records order in SQL

How can I reorder rows in sql database

Storing item positions (for ordering) in a database efficiently

How to keep ordering of records in a database table

Linked List in SQL

but all these involve either

using a floating-point secondary key for reordering/creation/deletion, with periodic normalization of indexes (i.e., imagine two documents are order-index 1.0 and 2.0, then a third document in between gets key 1.5, then a fourth gets 1.25, …, until ~31 docs are inserted in between and you get floating-point accuracy problems);

a linked list approach where a slide-document has a previous and next field containing the primary key of the documents on either side of it;

a very straightforward approach of updating all documents for each document reordering/insertion/deletion.

None of these are appropriate for CouchDB: #1 incurs a huge amount of incidental complexity in SQL or CouchDB. #2 is unreliable due to lack of atomic transactions (CouchDB might update the previous document with its new next but another client might have updated the new next document meanwhile, so updating the new next document will fail with 409, and your linked list is left in an inconsistent state). For the same reason, #3 is completely unworkable.

One CouchDB-oriented approach I’m evaluating would create a document that just contains the ordering of the slides: it might contain a primary-key-to-order-number hash object as well as an array that converts order-number-to-primary-key, and just update this object when slides are reordered/inserted/deleted. The downside to this is that Couch will keep a copy of this potentially large document for every order change (reorder/insert/delete)—CouchDB doesn’t support compacting just a single document, and I don’t want to run compaction on my entire database since I love preserving the history of each slide-document. Another downside is that after thousands of slides, each change to ordering involves transmitting the entire object (hundreds of kilobytes) from PouchDB/client to Couch.

A tweak to this approach would be to make a second database just to hold this ordering document and turn on auto-compaction on it. It’ll be more work to keep track of two database connections, and I’ll eventually have to put a lot of data down the wire, but I’ll have a robust way to order documents in CouchDB.

So my questions are: how do CouchDB people usually store the order of documents? And can more experienced CouchDB people see any flaws in my approach outlined above?

答: Thanks to a tip by @LynHeadley, I wound up writing a library that could subdivide the lexicographical interval between strings: Mudder.js. This allows me to infinitely insert and move around documents in CouchDB, by creating new keys at will, without any overhead of a secondary document to store the ordering. I think this is the right way to solve this problem!</p>


问:
Get the years before the current year in dropdown using Javascript
I have a working code which loads the 10 years after of the current year in the dropdown, havig the current year as the selected item. What I need to add is the 10 years BEFORE the selected or current year.

Here's the code

```<code><select id="year" class="" style="width: 100%; display:inline-block;" value="" ></select>

<script>
    var currentYear = new Date().getFullYear()
    max = currentYear + 10
    var options = "";
    for (var year = currentYear ; year <= max; year++) {
        options += "<option>" + year + "</option>";
    }
    document.getElementById("year").innerHTML = options;
</script>
</code>```

答:
Create option using createElement and append it to select.

var currentYear = new Date().getFullYear()
    max = currentYear + 10
    var option = "";
    for (var year = currentYear-10 ; year <= max; year++) {

        var option = document.createElement("option");
        option.text = year;
        option.value = year;

        document.getElementById("year").appendChild(option)

    }
    document.getElementById("year").value = currentYear;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="year" class="" style="width: 100%; display:inline-block;" value="" ></select></code>```

Body:
I have a working code which loads the 10 years after of the current year in the dropdown, havig the current year as the selected item. What I need to add is the 10 years BEFORE the selected or current year.

Here's the code

<select id="year" class="" style="width: 100%; display:inline-block;" value="" ></select>

Body:
Create option using createElement and append it to select.

var currentYear = new Date().getFullYear()
    max = currentYear + 10
    var option = "";
    for (var year = currentYear-10 ; year <= max; year++) {

        var option = document.createElement("option");
        option.text = year;
        option.value = year;

        document.getElementById("year").appendChild(option)

    }
    document.getElementById("year").value = currentYear;

<select id="year" class="" style="width: 100%; display:inline-block;" value="" ></select>


答:
Consider using filter_var()

http://php.net/manual/en/function.filter-var.php

```<code>function addressFilter($address)
{
    $invalidChars = ['%', '&']; // Array of invalid characters

    foreach ($invalidChars as $invalidChar) {
        if (strpos($address, $invalidChar) !== false) {
            return false;
        }
    }

    return $address;
}

$address = filter_var($_POST['address'], FILTER_CALLBACK, ['options' => 'addressFilter']);
</code>```

Title: How to restrict few special characters for address field in PHP without regex?

Body:
Consider using filter_var()

http://php.net/manual/en/function.filter-var.php

function addressFilter($address)
{
    $invalidChars = ['%', '&']; // Array of invalid characters

    foreach ($invalidChars as $invalidChar) {
        if (strpos($address, $invalidChar) !== false) {
            return false;
        }
    }

    return $address;
}

$address = filter_var($_POST['address'], FILTER_CALLBACK, ['options' => 'addressFilter']);


问:
DB multiple table update while permanent access
I have a set of tables in a MySql database which contain a set of related data (50 000 rows total, so low volume), which are accessed all the time (7 million/day) . Periodically (let's say once a day) I need to update ALL the data in all the tables (full refresh).

I'm considering 2 possibilities:

use transactions, but I'm not sure how it will work with reads/locks

use versioning: adding a version column in all tables and set all rows on the same "publication" with the same version. The next publication will have a version+1, then the lower version rows can be deleted. The current version is stored in a parameter table allowing the reading query to always pick the latest available version.

Anybody has experimented with both solutions? Or any different/better solution?

Thanks

答:
Replacing an entire table

```<code>CREATE TABLE new LIKE real;
populate `new` with the new stuff   --  the slow part
RENAME TABLE real TO old,
             new TO real;  -- atomic and fast.
</code>```

Replacing an entire database:  Do the above for each table, but hold off to do the RENAMEs until all the other work is done.  Then do all of them in a single RENAME TABLE statement.

No locking, no transactions, no nothing.

Body:
Replacing an entire table

CREATE TABLE new LIKE real;
populate `new` with the new stuff   --  the slow part
RENAME TABLE real TO old,
             new TO real;  -- atomic and fast.

Replacing an entire database:  Do the above for each table, but hold off to do the RENAMEs until all the other work is done.  Then do all of them in a single RENAME TABLE statement.

No locking, no transactions, no nothing.


问:
What is the Visual Studio(2017) shortcut to rename a bookmark?
I want to know if there is a default shortcut to rename a bookmark in Visual Studio(2017) or what the equivalent command is to manually create the shortcut.

I was looking a command like Edit.BookmarkRename.

答: In the Bookmarks tool window, press F2 to rename the selected bookmark.


问:
How to access previous row values from partitioned data in pandas dataframe
I have a dataframe with X and Y column as shown below.

I need to add another column Z which is the mean of the current and previous 2 rows of column Y. Also when X value changes, mean should be recalculated as shown. I know I can use the shift function for the entire dataframe to calculate the mean, but how do I recalculate the mean as and when X value changes.

```<code>X   Y   Z
a   1   1
a   2   1.5
a   3   2
a   4   3
b   10  10
b   20  15
b   30  20
</code>```

答:
You need to use groupby with rolling:

```<code>df['Z'] = df.groupby('X')['Y'].rolling(3,min_periods=1).mean().reset_index(drop=True)
</code>```

Output:

```<code>   X   Y     Z
0  a   1   1.0
1  a   2   1.5
2  a   3   2.0
3  a   4   3.0
4  b  10  10.0
5  b  20  15.0
6  b  30  20.0
</code>```

Body:
I have a dataframe with X and Y column as shown below.

I need to add another column Z which is the mean of the current and previous 2 rows of column Y. Also when X value changes, mean should be recalculated as shown. I know I can use the shift function for the entire dataframe to calculate the mean, but how do I recalculate the mean as and when X value changes.

X   Y   Z
a   1   1
a   2   1.5
a   3   2
a   4   3
b   10  10
b   20  15
b   30  20

Body:
You need to use groupby with rolling:

df['Z'] = df.groupby('X')['Y'].rolling(3,min_periods=1).mean().reset_index(drop=True)

Output:

   X   Y     Z
0  a   1   1.0
1  a   2   1.5
2  a   3   2.0
3  a   4   3.0
4  b  10  10.0
5  b  20  15.0
6  b  30  20.0