问:
Internet inconsistency in cordova app
I am developing a mobile app using cordova, and I am facing a problem for now 2 days I can't resolve, I am trying to load a simple php file hosted on a server :

```<code><?php
    echo 'Salut'
?>
</code>```

And I am trying to read the content while using an ajax call :

```<code>$.ajax({
    type: 'get',
    url: 'https://mydomain.so/index.php',
    dataType: 'text',
    success: function (data) { alert(data); },
    error: function (x, e) {
        if (x.status == 0) {
            alert('You are offline!!\n Please Check Your Network.');
        } else if (x.status == 404) {
            alert('Requested URL not found.');
        } else if (x.status == 500) {
            alert('Internel Server Error.');
        } else if (e == 'parsererror') {
            alert('Error.\nParsing JSON Request failed.');
        } else if (e == 'timeout') {
            alert('Request Time out.');
        } else {
            alert('Unknow Error.\n' + x.responseText);
        }
    }
});
</code>```

But the text show with alert is "You are offline", I do not understand because on the same html page there is a video youtube that I can watch. And I do not know why it's telling me I am offline while I can watch the video...
Someone know why I can't read php file but I can watch youtube video ?

Edit: Now I can read my php file inside of my onDeviceReady() function, but if I try to to do while clicking a button, it shows x.status==0, I tried to add :

```<code>header('Access-Control-Allow-Origin: *');
</code>```

in my php file but it's not working :s

Edit2: It's working fine, I was changing the location outside of the success function, I put it inside and it's working perfectly.
So I had to add https in my meta tag(before data:) and set new location inside of the ajax request.

```<code><meta http-equiv="Content-Security-Policy" content="default-src 'self' https: data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
</code>```

答:
It could be possible to get a status code of 0 if you have sent an AJAX call and a refresh of the page was triggered before getting the AJAX response. The AJAX call will be cancelled and you will get this status.

or

If you are calling ajax using submit button or on anchor tag, you probably prevent the default behaviour of submit or anchor tag.

If it is related CORS add following line in your php file.

```<code>header('Access-Control-Allow-Origin: *');
</code>```

Hope it helps you

Title: Internet inconsistency in cordova app

Body:
I am developing a mobile app using cordova, and I am facing a problem for now 2 days I can't resolve, I am trying to load a simple php file hosted on a server :

<?php
    echo 'Salut'
?>

And I am trying to read the content while using an ajax call :

$.ajax({
    type: 'get',
    url: 'https://mydomain.so/index.php',
    dataType: 'text',
    success: function (data) { alert(data); },
    error: function (x, e) {
        if (x.status == 0) {
            alert('You are offline!!\n Please Check Your Network.');
        } else if (x.status == 404) {
            alert('Requested URL not found.');
        } else if (x.status == 500) {
            alert('Internel Server Error.');
        } else if (e == 'parsererror') {
            alert('Error.\nParsing JSON Request failed.');
        } else if (e == 'timeout') {
            alert('Request Time out.');
        } else {
            alert('Unknow Error.\n' + x.responseText);
        }
    }
});

But the text show with alert is "You are offline", I do not understand because on the same html page there is a video youtube that I can watch. And I do not know why it's telling me I am offline while I can watch the video...
Someone know why I can't read php file but I can watch youtube video ?

Edit: Now I can read my php file inside of my onDeviceReady() function, but if I try to to do while clicking a button, it shows x.status==0, I tried to add :

header('Access-Control-Allow-Origin: *');

in my php file but it's not working :s

Edit2: It's working fine, I was changing the location outside of the success function, I put it inside and it's working perfectly.
So I had to add https in my meta tag(before data:) and set new location inside of the ajax request.

<meta http-equiv="Content-Security-Policy" content="default-src 'self' https: data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">

Body:
It could be possible to get a status code of 0 if you have sent an AJAX call and a refresh of the page was triggered before getting the AJAX response. The AJAX call will be cancelled and you will get this status.

or

If you are calling ajax using submit button or on anchor tag, you probably prevent the default behaviour of submit or anchor tag.

If it is related CORS add following line in your php file.

header('Access-Control-Allow-Origin: *');

Hope it helps you


来源: stackexchange

问:
setting up qt creator to work with tortoise svn on windows
I was wondering how one would set up qt creator 2.1.0 to work with tortoise svn on windows 7. I have been using tortoise for quite some time now and would like for it to work. I have tried to find some tutorials online and been unsuccessful.

Thanks!

答:
I use QT Creator and Tortoise for testing and playing around with svn.

You have to install Tortoise including the "command line client tools" option.
Open QT Creator, go to Tool / Options / Version Control / SVN.
Insert "C:\Program Files\TortoiseSVN\bin\svn.exe" to "Subversion Command"

Create a new project (if you have none)

Create an Repository with Tortoise --> https://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-quick-start.html

If you want to use your original project folder as local working copy -->
https://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-import.html#tsvn-dug-import-in-place

If you have checked out your project once and reopen it the QTCreator, QT Creator will realize that your project has a svn VersionControl. You can see the revision in [] after the name of your project.
Now you can checkout an update your Repository with QTCreator: Press Tools > Subversion.

I know - this post is 5 years old. I've been looking for a tutorial how to use tortoise "with" QTCreator for a long time. This is the conclusion of my research. Hope it'll help other newbies having the same problem.

ContentLicense: CC BY-SA 3.0


问:
Sum of value per X grouped by Y
```<code>declare @table table (Customer  char(1), Transaction char(3), Discount float);
insert into @table values
('A', '001', '10.1'),
('A', '001', '10.1'),
('A', '002', '20.2'),
('B', '003', '30.3'),
('B', '004', '40.4')
</code>```

I am trying to do something like this:

```<code>SELECT Customer, (SELECT SUM(Discount) WHERE Transaction IS DISTINCT)
FROM @table
GROUP BY Customer
</code>```

And the result should look like:

```<code>Customer    Total Discount
--------------------------
A                   30.3
B                   70.7
</code>```

So basically I need club all the discounts for every customer per transaction, because they are sometimes repeated in my data.

答:
First take DISTINCT value from your temp table based on 3 columns.Then SUM discount value based on GROUP BY Customer</p>

```<code>  SELECT A.Customer, SUM(A.Discount) as Total_Discount
  FROM
   (
     SELECT DISTINCT Customer, Transaction, Discount FROM @table
   ) A
  GROUP BY A.Customer
</code>```

Title: Sum of value per X grouped by Y

Body:
declare @table table (Customer  char(1), Transaction char(3), Discount float);
insert into @table values
('A', '001', '10.1'),
('A', '001', '10.1'),
('A', '002', '20.2'),
('B', '003', '30.3'),
('B', '004', '40.4')

I am trying to do something like this:

SELECT Customer, (SELECT SUM(Discount) WHERE Transaction IS DISTINCT)
FROM @table
GROUP BY Customer

And the result should look like:

Customer    Total Discount
--------------------------
A                   30.3
B                   70.7

So basically I need club all the discounts for every customer per transaction, because they are sometimes repeated in my data.

Body:
First take DISTINCT value from your temp table based on 3 columns.Then SUM discount value based on GROUP BY Customer

  SELECT A.Customer, SUM(A.Discount) as Total_Discount
  FROM
   (
     SELECT DISTINCT Customer, Transaction, Discount FROM @table
   ) A
  GROUP BY A.Customer


问:
Deploying webapp and worker to Heroku from github
I have a web app which I setup the continuous deployment from github. However I'm planning to add some worker roles to this app and I'm wondering couple of things. I'm using Node.js.

In my mind, I had the design like:

Procfile would have the # of web and worker dynos.

Worker type can be a different deployment, but all I can see is it has a different start command. How does this work with the package management? What if the stuff that I require in the worker role is different than the stuff in the web app?

So my questions are?

Any chance that I can use the same repository and structure it in a way that the worker and web code is maintained in the same location? Can I have /web and /worker folders in the root which have different app.js and package.json files so I have them in the same repo, but their dependencies are managed differently. How can I make this work when deploying to Heroku?

I have some 3rd party libraries which I've installed to the web app via build packs, but I want them to be present in the worker roles. These are necessary for some of the computations that I want to do, so I'm planning to use the worker role for dequeue and process. Any way to install build packs on the worker role?

What's the right way of managing this through the Procfile? Can I set the number of worker roles I want in the proc file or do I need to scale up / down using the command line and that's the only option that I have?

答:
Looks like this is entirely possible. All you need to do is have a global package.json file to manage your dependencies (you can't manage separate dependencies with worker and web role). If the package.json is not enough to make heroku detect that you're using Node.Js which was a problem I've faced; add the buildpack of heroku/nodejs and you should be ok. Whatever buildpack is installed, it will be available on the worker role.

Regarding the different directories, this is what I have now:

```<code>/web
/worker
/package.json
/Procfile
</code>```

And my procfile is:

```<code>web: npm start --prefix /web
worker: npm start --prefix /worker
</code>```

which seemed to fix the startup problem. There isn't any way of setting the #of dynos in the Procfile.

Body:
Looks like this is entirely possible. All you need to do is have a global package.json file to manage your dependencies (you can't manage separate dependencies with worker and web role). If the package.json is not enough to make heroku detect that you're using Node.Js which was a problem I've faced; add the buildpack of heroku/nodejs and you should be ok. Whatever buildpack is installed, it will be available on the worker role.

Regarding the different directories, this is what I have now:

/web
/worker
/package.json
/Procfile

And my procfile is:

web: npm start --prefix /web
worker: npm start --prefix /worker

which seemed to fix the startup problem. There isn't any way of setting the #of dynos in the Procfile.


问:
How can I delete the Cappuccino Xcode Extension?
I installed an Xcode template for Cappuccino. I would like to delete it, but I am not sure how?</p>

答: You'll find the templates somewhere in /Library/Application Support/Developer/Shared/Xcode/..., I think. Once you find the files, just delete them, and everything should be fine.

ContentLicense: CC BY-SA 2.5


答:
Using Row number</p>

```<code>SELECT Customer
    ,sum(Discount) as Total_Discount
FROM (
    SELECT Customer
        ,[Transaction]
        ,Discount
        ,row_number() OVER (
            PARTITION BY Customer
            ,[Transaction] ORDER BY Discount
            ) AS rn
    FROM @table
    ) t
WHERE rn = 1
GROUP BY Customer
</code>```

Title: Sum of value per X grouped by Y

Body:
Using Row number

SELECT Customer
    ,sum(Discount) as Total_Discount
FROM (
    SELECT Customer
        ,[Transaction]
        ,Discount
        ,row_number() OVER (
            PARTITION BY Customer
            ,[Transaction] ORDER BY Discount
            ) AS rn
    FROM @table
    ) t
WHERE rn = 1
GROUP BY Customer


问:
Extract particular value from column
How to better extract following:

I have following values in column:

```<code>\\v8pip1\90PI-200009-10.PV
</code>```

I need to get just below, \\v8pip1\ is the same for all rows:

```<code> 90PI-200009-10.PV
</code>```

thanks,
S

答:
I think you can use (following is just an example):

```<code>SELECT replace('\\v8pip1\90PI-200009-10.PV','\\v8pip1\','') FROM DUAL;
</code>```

Output:

```<code>90PI-200009-10.PV
</code>```

Title: Extract particular value from column

Body:
How to better extract following:

I have following values in column:

\\v8pip1\90PI-200009-10.PV

I need to get just below, \\v8pip1\ is the same for all rows:

 90PI-200009-10.PV

thanks,
S

Body:
I think you can use (following is just an example):

SELECT replace('\\v8pip1\90PI-200009-10.PV','\\v8pip1\','') FROM DUAL;

Output:

90PI-200009-10.PV


问:
Delay response jumps
What is the best way to show a user multiple responses?

Currently I have a few nodes that jump to another node without a condition to tigger a new response to show a new line of content to the user. The issue is that it all comes in the same time.

Is there a way to delay a response??

答:
The Watson Conversation service uses REST API to communicate with client application and responds "at once". This works in a way that the client request is processed via the defined dialog nodes tree and when this is finished everything is sent back to the client.
If multiple nodes were hit then multiple responses can be returned to the client. If the client (implementing the chat console) wants to delay the answers this needs to be implemented on the client side.</p>

Title: Delay response jumps


问:
Using ! or @ in Summernote hint content
In my summernote hint option I have the following

```<code>hint: {
    match: /\B[@!](\w*)$/,
    search: function (keyword, callback) {
        callback($.grep(mentions, function (i) {
            user = mentionData[i];
            return user.name.indexOf(keyword) === 0;
        }));
    },
    template: function...
    content: function (i) {
        var user = mentionData[i];
        return $('<span>@' + user.username + '</span>')[0];
    }
}
</code>```

I want to be able to insert the @ or ! symbol (whichever one the user initiated the hint with) into the content option. Is there a way to pass the keyword to the content function? or is there a way specific to summernote to do this?

答:
You can use array hints, example:</p>

```<code>hint:[
      {
        words: ['apple', 'orange', 'watermelon', 'lemon'],
        match: /\b(\w{1,})$/,
        search: function (keyword, callback) {
        callback($.grep(this.words, function (item) {
         return item.indexOf(keyword) === 0;
        }));
      },
      {
        mentions: ['jayden', 'sam', 'alvin', 'david'],
        match: /\B@(\w*)$/,
        search: function (keyword, callback) {
         callback($.grep(this.mentions, function (item) {
          return item.indexOf(keyword) == 0;
         }));
        },
        content: function (item) {
         return '@' + item;
        }
      }
    ]
  }
},
</code>```

Title: Using ! or @ in Summernote hint content

Body:
In my summernote hint option I have the following

hint: {
    match: /\B[@!](\w*)$/,
    search: function (keyword, callback) {
        callback($.grep(mentions, function (i) {
            user = mentionData[i];
            return user.name.indexOf(keyword) === 0;
        }));
    },
    template: function...
    content: function (i) {
        var user = mentionData[i];
        return $('@' + user.username + '')[0];
    }
}

I want to be able to insert the @ or ! symbol (whichever one the user initiated the hint with) into the content option. Is there a way to pass the keyword to the content function? or is there a way specific to summernote to do this?

Body:
You can use array hints, example:

hint:[
      {
        words: ['apple', 'orange', 'watermelon', 'lemon'],
        match: /\b(\w{1,})$/,
        search: function (keyword, callback) {
        callback($.grep(this.words, function (item) {
         return item.indexOf(keyword) === 0;
        }));
      },
      {
        mentions: ['jayden', 'sam', 'alvin', 'david'],
        match: /\B@(\w*)$/,
        search: function (keyword, callback) {
         callback($.grep(this.mentions, function (item) {
          return item.indexOf(keyword) == 0;
         }));
        },
        content: function (item) {
         return '@' + item;
        }
      }
    ]
  }
},


问:
How to create a universal jquery validate and reset function call
I am using the jquery validate plugin to create a validation method for all forms in an application. Using the jquery each() function to cycle each form and applyt the method. I want to achieve the reset using the same each method. how can i accomplish this?

This is the code that works:

```<code> $("form").each(function () {
        $(this).validate();
    });
</code>```

This is the code that doesn't

```<code>   $("form").each(function () {
        validator = $(this).validate();
        validator.resetForm();
        $("#reset").click(function () {
            validator.resetForm();
        });
    });
</code>```

Please advise..

答:
try this maybe?</p>

```<code>$("form").each(function () {
var validator = $(this);
validator.validate();
validator.resetForm();
$("#reset").click(function () {
    validator.resetForm();
});
 });
</code>```

Body:
I am using the jquery validate plugin to create a validation method for all forms in an application. Using the jquery each() function to cycle each form and applyt the method. I want to achieve the reset using the same each method. how can i accomplish this?

This is the code that works:

 $("form").each(function () {
        $(this).validate();
    });

This is the code that doesn't

   $("form").each(function () {
        validator = $(this).validate();
        validator.resetForm();
        $("#reset").click(function () {
            validator.resetForm();
        });
    });

Please advise..

Body:
try this maybe?

$("form").each(function () {
var validator = $(this);
validator.validate();
validator.resetForm();
$("#reset").click(function () {
    validator.resetForm();
});
 });


问:
Remote form post Python and cookies headers
I have a script to post a form from a distant web page.
This webpage sends a cookie, and I like to get this and insert it in the header to post the form.

How could I do that ?

Thank you

答:
If you want to get cookies from GET request and use it in POST, you can try to use session() as below:

```<code>session = requests.session()
response = session.get(URL) # send GET to get cookies
cookies = response.cookies.get_dict() # Grab cookies
post = session.post(URL, cookies=cookies) # Send POST with grabbed cookies
</code>```

Body:
If you want to get cookies from GET request and use it in POST, you can try to use session() as below:

session = requests.session()
response = session.get(URL) # send GET to get cookies
cookies = response.cookies.get_dict() # Grab cookies
post = session.post(URL, cookies=cookies) # Send POST with grabbed cookies


问:
Ads disappear from the main page (UWP App)
I'm developing an uwp app, and I have an Ad on the main page. Also on the main page I have a button to remove this advertisement. I have it all done, and it works without any problem. However when I enter the app (on the main page) the advertisement is displayed and the button to remove it too, but if I navigate to another page (for example for the settings) and return to the main page the advertisement disappears without my having removed it.

Why this happen?
In my XAML of main page I have: Visibility="Visible" (for button and ad)

This is my code (it removes the ad and the button, when the button is clicked):

```<code>if (results.Status == ProductPurchaseStatus.Succeeded)
    {
      RemoveAds.Visibility = Visibility.Collapsed;
      Ad.Visibility = Visibility.Collapsed;
    }
</code>```

答:
It's quite likely a bug in AdControl which has bitten others too. To make sure, disable main page's NavigationCache:

```<code>NavigationCacheMode="Disabled"
</code>```

Now, when user navigates back to the main page, the page should be a "fresh" instance. Your ad should work.

To make the AdControl work between page navigations you can try recreating the AdControl everytime user navigates back to the page. There's maybe some useful info here: AdControl stops updating after navigating back in UWP.

Other option is to add the AdControl into your Frame, not into your page. This way your ad is always there, on every page.

Body:
I'm developing an uwp app, and I have an Ad on the main page. Also on the main page I have a button to remove this advertisement. I have it all done, and it works without any problem. However when I enter the app (on the main page) the advertisement is displayed and the button to remove it too, but if I navigate to another page (for example for the settings) and return to the main page the advertisement disappears without my having removed it.

Why this happen?
In my XAML of main page I have: Visibility="Visible" (for button and ad)

This is my code (it removes the ad and the button, when the button is clicked):

if (results.Status == ProductPurchaseStatus.Succeeded)
    {
      RemoveAds.Visibility = Visibility.Collapsed;
      Ad.Visibility = Visibility.Collapsed;
    }

Body:
It's quite likely a bug in AdControl which has bitten others too. To make sure, disable main page's NavigationCache:

NavigationCacheMode="Disabled"

Now, when user navigates back to the main page, the page should be a "fresh" instance. Your ad should work.

To make the AdControl work between page navigations you can try recreating the AdControl everytime user navigates back to the page. There's maybe some useful info here: AdControl stops updating after navigating back in UWP.

Other option is to add the AdControl into your Frame, not into your page. This way your ad is always there, on every page.


问:
Using number/text input field to set the data values in ChartJs stops the chart from being displayed
I'm still relatively new to HTML and Javascript code so this could just be a minor stupid error.

Basically I'm trying to use chartjs to create a line chart and for one of those lines I want the user to be able to enter their own data, so I've been testing out a few methods but can't figure out why they won't work.

I was hoping to use document.getElementById to take the value of the first number input and then use it as a data value for the line chart, for example:

```<code>data: [addData(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
</code>```

This is how the function to add the input value as data is called, then the function itself is:

```<code>function addData()  {

        var input = document.getElementById("testId").value;

     }
</code>```

I've also tried to use return input; but the whole chart just disappears when I use either of those, however if I use the function below for addData() the chart still works fine and accepts 2 as the first data value:

```<code>function addData()  {

        var input = 2;
        return input;

     }
</code>```

Here is the number input code:

```<code>Birth: <input  type="number" maxlength="4" id="testId" value="2"><br>
</code>```

Any ideas why the entire chart disappears when I attempt to use a number input field for the data value?

EDIT: I've just solved this now thanks to Shai Aharoni for pointing out any possible errors, I just needed to rearrange the order of the input field to be before the script, just a silly error.

答:
It is hard to evaluate my solution when I do not have a complete example. So I'm not sure, but I hope the following helps you: It could be that you have a simple type error as the code

```<code>var input = document.getElementById("testId").value;
</code>```

assigns a string value to the input variable. However, I think, you need an integer as input for your chart.

A solution could be:

```<code>var input = parseInt(document.getElementById("testId").value)
</code>```

Although you have defined your input field as "number", javascript does not use this type to convert the value automatically. So, you have to convert the value by yourself.

Body:
I'm still relatively new to HTML and Javascript code so this could just be a minor stupid error.

Basically I'm trying to use chartjs to create a line chart and for one of those lines I want the user to be able to enter their own data, so I've been testing out a few methods but can't figure out why they won't work.

I was hoping to use document.getElementById to take the value of the first number input and then use it as a data value for the line chart, for example:

data: [addData(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],

This is how the function to add the input value as data is called, then the function itself is:

function addData()  {

        var input = document.getElementById("testId").value;

     }

I've also tried to use return input; but the whole chart just disappears when I use either of those, however if I use the function below for addData() the chart still works fine and accepts 2 as the first data value:

function addData()  {

        var input = 2;
        return input;

     }

Here is the number input code:

Birth: <input  type="number" maxlength="4" id="testId" value="2">

Any ideas why the entire chart disappears when I attempt to use a number input field for the data value?

EDIT: I've just solved this now thanks to Shai Aharoni for pointing out any possible errors, I just needed to rearrange the order of the input field to be before the script, just a silly error.

Body:
It is hard to evaluate my solution when I do not have a complete example. So I'm not sure, but I hope the following helps you: It could be that you have a simple type error as the code

var input = document.getElementById("testId").value;

assigns a string value to the input variable. However, I think, you need an integer as input for your chart.

A solution could be:

var input = parseInt(document.getElementById("testId").value)

Although you have defined your input field as "number", javascript does not use this type to convert the value automatically. So, you have to convert the value by yourself.


问:
Increment html input number element
I have an input element

```<code><input type="number" min=0.083 step=0.5>
</code>```

I want to increment it with 0.5 when the up and down arrows are pressed in the input element and on the keyboard.

min needs to be at 0.083. But of course this can be checked in a input/changed event for the input field.

I want

0 + step = 0.5

0.5 + step = 1

1.3 + step = 1.8

2 + step = 2.5

0.5 - step = 0.083

But what I get is

0 + step = 0.083

0.083 + step = 0.583

1.3 + step = 1.583

2 + step = 2.083

0.5 - step = 0.083

With min = 0

0 + step = 0.5

0.5 + step = 1

1.3 + step = 1.5 //which is not what I want. I need it to be 1.8

https://jsfiddle.net/6eL64umx/1/

Any help is appreciated :)

答:
A little JavaScript to help with your problem.

You will need to set the min attribute to 0, and let JavaScript test whether it’s too far down.

Change your HTML to:

```<code><input id="test" type="number" step="0.5" min=0 data-min="0.083" value="0.083">
</code>```

and add the following JavaScript somewhere:

```<code>document.querySelector('input#test').onchange=function() {
    if(this.value<this.getAttribute('data-min')) this.value=this.getAttribute('data-min');
}
</code>```

I have set your real minimum id the data-min attribute so you can change it in HTML.

Title: Increment html input number element

Body:
I have an input element

<input type="number" min=0.083 step=0.5>

I want to increment it with 0.5 when the up and down arrows are pressed in the input element and on the keyboard.

min needs to be at 0.083. But of course this can be checked in a input/changed event for the input field.

I want

0 + step = 0.5

0.5 + step = 1

1.3 + step = 1.8

2 + step = 2.5

0.5 - step = 0.083

But what I get is

0 + step = 0.083

0.083 + step = 0.583

1.3 + step = 1.583

2 + step = 2.083

0.5 - step = 0.083

With min = 0

0 + step = 0.5

0.5 + step = 1

1.3 + step = 1.5 //which is not what I want. I need it to be 1.8

https://jsfiddle.net/6eL64umx/1/

Any help is appreciated :)

Body:
A little JavaScript to help with your problem.

You will need to set the min attribute to 0, and let JavaScript test whether it’s too far down.

Change your HTML to:

<input id="test" type="number" step="0.5" min=0 data-min="0.083" value="0.083">

and add the following JavaScript somewhere:

document.querySelector('input#test').onchange=function() {
    if(this.value<this.getAttribute('data-min')) this.value=this.getAttribute('data-min');
}

I have set your real minimum id the data-min attribute so you can change it in HTML.


问:
How to execute code before MSTest TestContext is set
For our data-driven tests we're using Excel files for datasource.
Now, because the Excel files are binary data, we had a lot of headaches with git (not being able to diff, files overwritten and implicitly a lot of false positives due to incorrect test data that was actually changed several time).

So, to overcome this I thought that we may use Google Drive to store the datasource and everytime download the Excel file that will be used.

The problem now is that TestContext is set in AssemblyInitialize before I get to download the datasource from Google Drive and therefore it's not able to find it.

Is there a possibility to determine the download of the datasource in the same assembly as the tests?
I know that I could create a new solution to set it as a build task before executing the test assembly, however I'm looking for something for neat, if possible.

EDIT:
I gave it a try using the option to create a new Console Application project that will be ran as a build task and download the Excel file before executing the tests.

However, it seems that since the Excel file was not added to the Solution it doesn't get picked up by the Datasource attribute.

答:
So the only way to make it work was to create a new console application project that was added as a pre-build task to the data-driven tests project.

At least this was the initial approach because it caused our solution to have an extra 1-2 mins (depending on the network traffic).

So I ended creating a new build task in the build system that will handle this.


问:
List passed by ref - help me explain this behaviour
Take a look at the following program:

```<code>class Test
{
    List<int> myList = new List<int>();

    public void TestMethod()
    {
        myList.Add(100);
        myList.Add(50);
        myList.Add(10);

        ChangeList(myList);

        foreach (int i in myList)
        {
            Console.WriteLine(i);
        }
    }

    private void ChangeList(List<int> myList)
    {
        myList.Sort();

        List<int> myList2 = new List<int>();
        myList2.Add(3);
        myList2.Add(4);

        myList = myList2;
    }
}
</code>```

I assumed myList would have passed by ref, and the output would

```<code>3
4
</code>```

The list is indeed "passed by ref", but only the sort function takes effect. The following statement myList = myList2; has no effect.

So the output is in fact:

```<code>10
50
100
</code>```

Can you help me explain this behavior? If indeed myList is not passed-by-ref (as it appears from myList = myList2 not taking effect), how does myList.Sort() take effect?

I was assuming even that statement to not take effect and the output to be:

```<code>100
50
10
</code>```

答:
Here is an easy way to understand it

Your List is an object created on heap. The variable myList is a
reference to that object.

In C# you never pass objects, you pass their references by value.

When you access the list object via the passed reference in
ChangeList (while sorting, for example) the original list is changed.

The assignment on the ChangeList method is made to the value of the reference, hence no changes are done to the original list (still on the heap but not referenced on the method variable anymore).

Body:
Take a look at the following program:

class Test
{
    List<int> myList = new List<int>();

    public void TestMethod()
    {
        myList.Add(100);
        myList.Add(50);
        myList.Add(10);

        ChangeList(myList);

        foreach (int i in myList)
        {
            Console.WriteLine(i);
        }
    }

    private void ChangeList(List<int> myList)
    {
        myList.Sort();

        List<int> myList2 = new List<int>();
        myList2.Add(3);
        myList2.Add(4);

        myList = myList2;
    }
}

I assumed myList would have passed by ref, and the output would

3
4

The list is indeed "passed by ref", but only the sort function takes effect. The following statement myList = myList2; has no effect.

So the output is in fact:

10
50
100

Can you help me explain this behavior? If indeed myList is not passed-by-ref (as it appears from myList = myList2 not taking effect), how does myList.Sort() take effect?

I was assuming even that statement to not take effect and the output to be:

100
50
10


问:
Magento error: Unable to create directory '/var/www/html/magento/media/tmp/catalog/product'
When adding images for new products to my magento store I get the error:

```<code>Unable to create directory '/var/www/html/magento/media/tmp/catalog/product'.
</code>```

Now, I have made sure file permissions are set to 777, so I am wondering why is this happening and how can I fix this ?

UPDATE
Tried everything suggested below to no avail. I get the error:
    Destination folder is not writable or does not exists.

well, this is a lie. As for a temporary basis I have set all folders and files within the magento folder to have world write permission (777). Are the directory locations stored in some configuration file ? or what else could be causing this ? Been pulling my hair out over last week trying to solve this!

答:
Was an issue with SELINUX:</p>

```<code>chcon -R -t httpd_sys_rw_content_t /var/www/html/magentofoldername/*

chmod -R a+w /var/www/html/magentofoldername/*
</code>```

Body:
When adding images for new products to my magento store I get the error:

Unable to create directory '/var/www/html/magento/media/tmp/catalog/product'.

Now, I have made sure file permissions are set to 777, so I am wondering why is this happening and how can I fix this ?

UPDATE
Tried everything suggested below to no avail. I get the error:
    Destination folder is not writable or does not exists.

well, this is a lie. As for a temporary basis I have set all folders and files within the magento folder to have world write permission (777). Are the directory locations stored in some configuration file ? or what else could be causing this ? Been pulling my hair out over last week trying to solve this!

Body:
Was an issue with SELINUX:

chcon -R -t httpd_sys_rw_content_t /var/www/html/magentofoldername/*

chmod -R a+w /var/www/html/magentofoldername/*


问:
row number based on unique column value in oralce?
I do need to implement a oracle sql to have row number defined as below:

```<code>row_num, column1, column2, cloumn3
1, ABC, 123, a1
1, ABC, 125, a2
2, ABD, 123, a3
2, ABD, 124, a4
2, ABD, 125, a5
3, ABE, 123, a1
</code>```

Here I defined row number based on unique value of column1.

Can any one help me to write oracle sql to define row number in this way?

Thanks
Venkat

答:
You can use this as well, but I forgot about dense rank. So Boneist's answer is better.

```<code>select rn.row_num , t.* from
(select column1,row_number() over (order by column1) as row_num from
(select distinct column1 column1 from tbl23) )rn
inner join tbl23 t
on rn.column1=t.column1
</code>```

Body:
I do need to implement a oracle sql to have row number defined as below:

row_num, column1, column2, cloumn3
1, ABC, 123, a1
1, ABC, 125, a2
2, ABD, 123, a3
2, ABD, 124, a4
2, ABD, 125, a5
3, ABE, 123, a1

Here I defined row number based on unique value of column1.

Can any one help me to write oracle sql to define row number in this way?

Thanks
Venkat

Body:
You can use this as well, but I forgot about dense rank. So Boneist's answer is better.

select rn.row_num , t.* from
(select column1,row_number() over (order by column1) as row_num from
(select distinct column1 column1 from tbl23) )rn
inner join tbl23 t
on rn.column1=t.column1


问:
make null value as X sql server
i have problem.., i want to display the null value as 'X'
i has been using the case statement but still failed,
i already using Isnull and failed too.

```<code>DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
DECLARE @X AS NVARCHAR(MAX)

SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(code)
FROM (SELECT DISTINCT code FROM edrsDB..tbl_users where area='west' ) AS status

SET @DynamicPivotQuery =
N'SELECT date, '+ @ColumnName +'
FROM (
SELECT DISTINCT userid, status , DATEPART(dd, [date]) as Date
FROM edrsDB..tbl_status
WHERE DatePart(MM, [Date]) = 3
 And DATEPART(YYYY, [Date]) = 2017
Union
SELECT DISTINCT userid, status , DATEPART(DD,[date]) as Date
FROM edrsDB..tbl_public_holiday
WHERE DatePart(MM, [Date]) = 3
And DATEPART(YYYY, [Date]) = 2017
Union
SELECT DISTINCT userid, status , DATEPART(DD,[Date]) as Date
FROM edrsDB..tbl_station_weekend
WHERE DatePart(MM, [Date]) = 3
And DATEPART(YYYY, [Date]) = 2017
And date IS NOT NULL
 ) AS x
 PIVOT
 (
max(status)
FOR userid IN (' + @ColumnName + ')
) AS PVTTable'
 EXEC sp_executesql @DynamicPivotQuery
</code>```

this is ouput.. , i want null to be display as 'X'

output

答:
Use ISNULL function in SQL Server :</p>

```<code>SELECT ISNULL(Your_column,'X')
</code>```

Title: make null value as X sql server

Body:
i have problem.., i want to display the null value as 'X'
i has been using the case statement but still failed,
i already using Isnull and failed too.

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
DECLARE @X AS NVARCHAR(MAX)

SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(code)
FROM (SELECT DISTINCT code FROM edrsDB..tbl_users where area='west' ) AS status

SET @DynamicPivotQuery =
N'SELECT date, '+ @ColumnName +'
FROM (
SELECT DISTINCT userid, status , DATEPART(dd, [date]) as Date
FROM edrsDB..tbl_status
WHERE DatePart(MM, [Date]) = 3
 And DATEPART(YYYY, [Date]) = 2017
Union
SELECT DISTINCT userid, status , DATEPART(DD,[date]) as Date
FROM edrsDB..tbl_public_holiday
WHERE DatePart(MM, [Date]) = 3
And DATEPART(YYYY, [Date]) = 2017
Union
SELECT DISTINCT userid, status , DATEPART(DD,[Date]) as Date
FROM edrsDB..tbl_station_weekend
WHERE DatePart(MM, [Date]) = 3
And DATEPART(YYYY, [Date]) = 2017
And date IS NOT NULL
 ) AS x
 PIVOT
 (
max(status)
FOR userid IN (' + @ColumnName + ')
) AS PVTTable'
 EXEC sp_executesql @DynamicPivotQuery

this is ouput.. , i want null to be display as 'X'

output

Body:
Use ISNULL function in SQL Server :

SELECT ISNULL(Your_column,'X')


问:
In C why can I pass function name (not a pointer) as parameter to funtion?
I have test the following code:

```<code>#include <stdio.h>
void f(void g()) {
    g();
}

void g(void) {
    printf("hello, world\n");
}

int main() {
    f(g);
    return 0;
}
</code>```

It works well. In the code above, why in c we can take the function name g as paramter and take the function prototype as parameter?

In book K&R, it says that we can use the pointer to function:
So I can define the function f like this:

```<code>void f(void (*g)()) {
    g();
}
void g(void) {
    printf("hello, world\n");
}

int main() {
    void (*pf)() = g;
    f(pf);
    f(g);   // Here f(g) also works.
    return 0;
}
</code>```

So in the first f definition form, the parameter prototype is void g(), in the second form the parameter prototype is void (*g)(). Why the two forms of definition of f are the same?

And in the second form, the parameter is a pointer to function, why f(g) also works?

答:
From the C Standard (6.3.2.1 Lvalues, arrays, and function designators)

4 A function designator is an expression that has function type.
  Except when it is the operand of the sizeof operator65) or the unary &
  operator, a function designator with type ‘‘function returning type’’
  is converted to an expression that has type ‘‘pointer to function
  returning type’’.

and (6.7.6.3 Function declarators (including prototypes))

8 A declaration of a parameter as ‘‘function returning type’’ shall be
  adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1.

Thus these function declarations

```<code>void f(void g());
</code>```

and

```<code>void f(void ( *g )());
</code>```

declare the same one function.

Body:
I have test the following code:

#include <stdio.h>
void f(void g()) {
    g();
}

void g(void) {
    printf("hello, world\n");
}

int main() {
    f(g);
    return 0;
}

It works well. In the code above, why in c we can take the function name g as paramter and take the function prototype as parameter?

In book K&R, it says that we can use the pointer to function:
So I can define the function f like this:

void f(void (*g)()) {
    g();
}
void g(void) {
    printf("hello, world\n");
}

int main() {
    void (*pf)() = g;
    f(pf);
    f(g);   // Here f(g) also works.
    return 0;
}

So in the first f definition form, the parameter prototype is void g(), in the second form the parameter prototype is void (*g)(). Why the two forms of definition of f are the same?

And in the second form, the parameter is a pointer to function, why f(g) also works?

Body:
From the C Standard (6.3.2.1 Lvalues, arrays, and function designators)

4 A function designator is an expression that has function type.
  Except when it is the operand of the sizeof operator65) or the unary &
  operator, a function designator with type ‘‘function returning type’’
  is converted to an expression that has type ‘‘pointer to function
  returning type’’.

and (6.7.6.3 Function declarators (including prototypes))

8 A declaration of a parameter as ‘‘function returning type’’ shall be
  adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1.

Thus these function declarations

void f(void g());

and

void f(void ( *g )());

declare the same one function.


问:
Python subprocess Popen parameter difference
What's the difference between

```<code>subprocess.Popen(['cat','/path/to/file'], stdout=subprocess.PIPE, shell=True)
</code>```

and

```<code>subprocess.Popen(['cat '+'/path/to/file'], stdout=subprocess.PIPE, shell=True)
</code>```

?
I'm doing this in ipython.
For the first one, ipython just hang. Maybe not hang, but it's significantly slower.
The second is just OK.

Just don't know why.

答:
i tested the samples and found that the first worked returning a Popen object in ipython but the second did the same but printed cat: /path/to/file: No such file or directory

i like to avoid using subprocess.Popen with shell=True when possible and use a list ['x', '--version'] as this avoids the need to quote path names with say ` graves in them or some such muck

in a patch to pymp.py i changed:

```<code>p = subprocess.Popen(['mplayer -slave -quiet \'' + target + '\' -include \'' + MPLAYERCONFFILE + '\' 2>/dev/null'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
</code>```

to:

```<code>devnull = open('/dev/null', 'w')
p = subprocess.Popen(['mplayer', '-slave', '-quiet', target, '-include', MPLAYERCONFFILE], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=devnull)
</code>```

Body:
What's the difference between

subprocess.Popen(['cat','/path/to/file'], stdout=subprocess.PIPE, shell=True)

and

subprocess.Popen(['cat '+'/path/to/file'], stdout=subprocess.PIPE, shell=True)

?
I'm doing this in ipython.
For the first one, ipython just hang. Maybe not hang, but it's significantly slower.
The second is just OK.

Just don't know why.

Body:
i tested the samples and found that the first worked returning a Popen object in ipython but the second did the same but printed cat: /path/to/file: No such file or directory

i like to avoid using subprocess.Popen with shell=True when possible and use a list ['x', '--version'] as this avoids the need to quote path names with say ` graves in them or some such muck

in a patch to pymp.py i changed:

p = subprocess.Popen(['mplayer -slave -quiet \'' + target + '\' -include \'' + MPLAYERCONFFILE + '\' 2>/dev/null'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)

to:

devnull = open('/dev/null', 'w')
p = subprocess.Popen(['mplayer', '-slave', '-quiet', target, '-include', MPLAYERCONFFILE], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=devnull)


问:
Any references how to load pictures in jquery on swift not lagging?
I don't have any problems such as an error but it's too lagging on the page. Here is my js:

```<code>$(document).ready( function() {
photosdone();

});

function photosdone() {
     setTimeout( function() {
     photosupdates();
     photosdone();
     }, 800);

}

function photosupdates() {
$.getJSON("check_photos.php", { id:  $("#id").val() },function(data) {
    $("#photos").empty();
    $.each(data.result, function(){
    $("#photos").append("<li class='col-lg-3 col-md-3 '><img class='img-responsive' src='data:"+this['MIME']+";base64,"+this['img']+"' width=150px height=150px></li>");

    });
});
}
</code>```

and here is my page:

```<code><ul id="photos" class="row bar">
</ul>
</code>```

While the page doesn't have picture, it's running as well. But when I upload some pictures more than 2, I think my page is stuck although it occurs in several times.

答:
In photosdone() you call photosdone() again, it is ok ?
Recursive photosdone calls makes your page laggy</p>

Body:
I don't have any problems such as an error but it's too lagging on the page. Here is my js:

$(document).ready( function() {
photosdone();

});

function photosdone() {
     setTimeout( function() {
     photosupdates();
     photosdone();
     }, 800);

}

function photosupdates() {
$.getJSON("check_photos.php", { id:  $("#id").val() },function(data) {
    $("#photos").empty();
    $.each(data.result, function(){
    $("#photos").append("

");

    });
});
}

and here is my page:

While the page doesn't have picture, it's running as well. But when I upload some pictures more than 2, I think my page is stuck although it occurs in several times.


问:
How to prevent saving child object with JPA?
I got OneToMany relationship between school and student entities. What I want to do is when I save a school object don't save or update students object.(and of course don't delete them)

When I try to save school object like below it also updates my student objects but I don't want them to be updated but only jointable. Is there any way?

I removed Cascade but its still not working.

```<code>School school = new School();
school.setStudents(studentList);
repository.save(school);
</code>```

My Entity;

```<code>@OneToMany(fetch = FetchType.EAGER)
@JoinTable(name = "school_student", joinColumns = {@JoinColumn(name = "school_id")},
        inverseJoinColumns = {@JoinColumn(name = "student_id")})
private List<Student> students;
</code>```

EDIT:

When I try to save/update/remove a School object DON'T save/update/remove Student object. Think that I don't have any insert/update/delete authority on Student table.

答:
Perhaps you can try @JoinColumn:</p>

```<code>@OneToMany
@JoinColumn(name = "school_id", updatable = false, insertable = false)
private List<Student> students;
</code>```

Body:
I got OneToMany relationship between school and student entities. What I want to do is when I save a school object don't save or update students object.(and of course don't delete them)

When I try to save school object like below it also updates my student objects but I don't want them to be updated but only jointable. Is there any way?

I removed Cascade but its still not working.

School school = new School();
school.setStudents(studentList);
repository.save(school);

My Entity;

@OneToMany(fetch = FetchType.EAGER)
@JoinTable(name = "school_student", joinColumns = {@JoinColumn(name = "school_id")},
        inverseJoinColumns = {@JoinColumn(name = "student_id")})
private List<Student> students;

EDIT:

When I try to save/update/remove a School object DON'T save/update/remove Student object. Think that I don't have any insert/update/delete authority on Student table.

Body:
Perhaps you can try @JoinColumn:

@OneToMany
@JoinColumn(name = "school_id", updatable = false, insertable = false)
private List<Student> students;


问:
How to remove an unwanted badge(object) from wordpress website?
Accidently I have added this CLEF badge on my wordpress website and now it appears at the bottom most of it. Here is how it looks:

This is the code on clicking "Inspect Element":

How can I remove this blue badge from my website?

答:
Add this to your css file:</p>

```<code>.clef-badge {
     display:none !important;
}
</code>```

Body:
Add this to your css file:

.clef-badge {
     display:none !important;
}


问:
HashMap not adding all keys
I am adding strings to a HashMap<String, ChartSeries> but it doesn't add all the strings. It does however change the size integer of the hashmap:

As you can see it says size:6 but when you look into the table it only holds 4 objects.

This is my code:

```<code>for (CaseTypeActivationAmount CTAM : caseTypeActivationAmounts) {
    ChartSeries cs;
    if (!caseTypes.containsKey(CTAM.getOmschrijving())) {
        if (CTAM.getOmschrijving() != null) {
            cs = new ChartSeries(CTAM.getOmschrijving());
        } else {
            cs = new ChartSeries(" ");
        }

        caseTypes.put(CTAM.getOmschrijving(), cs);
    } else {
        cs = caseTypes.get(CTAM.getOmschrijving());
    }
    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
    cs.set(dateFormat.format(CTAM.getDate()), CTAM.getAmount());
}
</code>```

Am I missing something?

答:
Yes, you are missing something. Each position of the backing array of the HashMap can hold a reference to a single HashMap.Node. However, that Node does not necessarily contain just a single Map.Entry. It can contain a linked-list or tree of Entries which were mapped to the same bucket (bit) of the HashMap.

Therefore the 4 Nodes you are seeing do not correspond with 4 Entries.

If you iterate over the entrySet of the map you'll see all 6 Entries.

Title: HashMap not adding all keys

Body:
I am adding strings to a HashMap<String, ChartSeries> but it doesn't add all the strings. It does however change the size integer of the hashmap:

As you can see it says size:6 but when you look into the table it only holds 4 objects.

This is my code:

for (CaseTypeActivationAmount CTAM : caseTypeActivationAmounts) {
    ChartSeries cs;
    if (!caseTypes.containsKey(CTAM.getOmschrijving())) {
        if (CTAM.getOmschrijving() != null) {
            cs = new ChartSeries(CTAM.getOmschrijving());
        } else {
            cs = new ChartSeries(" ");
        }

        caseTypes.put(CTAM.getOmschrijving(), cs);
    } else {
        cs = caseTypes.get(CTAM.getOmschrijving());
    }
    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
    cs.set(dateFormat.format(CTAM.getDate()), CTAM.getAmount());
}

Am I missing something?


问:
DataPower - Azure Service Bus Integration
I am trying to post messages to Azure service bus from DataPower using http protocol. How should I pass the credentials since I am getting an unauthorized error 401.

Please help since I got stuck here

Thanks

答:
I figured out the solution. Below is how I achieve SAS authentication token.

Generate SAS token in IIB using a Java module which requires 4 parameters:

a. Resource URI of Azure Service Bus

b. Key

c. Key Name

d. Expiry in seconds.

Set the SAS token in MQRFH2 header and send to DataPower

Extract SAS token and set as Authorization header for HTTP POST request in DataPower using the below xslt.

```<code><xsl:variable name="entries" select="dp:request-header('MQRFH2')" />
<xsl:variable name="header" select="dp:parse($entries)" />
<xsl:variable name="SAS">
<xsl:choose>
<xsl:when test="$header//usr//SAS">
<xsl:value-of select="$header//usr//SAS" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="false()" />
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<dp:set-http-request-header name="'Authorization'" value="$SAS"/>
</code>```

Body:
I figured out the solution. Below is how I achieve SAS authentication token.

Generate SAS token in IIB using a Java module which requires 4 parameters:

a. Resource URI of Azure Service Bus

b. Key

c. Key Name

d. Expiry in seconds.

Set the SAS token in MQRFH2 header and send to DataPower

Extract SAS token and set as Authorization header for HTTP POST request in DataPower using the below xslt.

<xsl:variable name="entries" select="dp:request-header('MQRFH2')" />
<xsl:variable name="header" select="dp:parse($entries)" />
<xsl:variable name="SAS">
<xsl:choose>
<xsl:when test="$header//usr//SAS">
<xsl:value-of select="$header//usr//SAS" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="false()" />
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<dp:set-http-request-header name="'Authorization'" value="$SAS"/>

ContentLicense: CC BY-SA 4.0


问:
Creating new table which contains unique rows with conditions ; MySQL
I have a table with the following columns:

SessionID - contains actions within a session (1-10 rows per SessionID let's say)

ActionName - is the name of the action

Time - time action occurred

I need to return a new table, whose columns are the same, and contains only 1 row per SessionID IF the action's name is either "a" or "b".

That is, my new table should have a 1 row per SessionID which had the action "a" or "b".

I tried:

```<code>CREATE TABLE U_SessionID (
SELECT DISTINCT(SessionID) AS SessionID FROM test1)
;
</code>```

I copy the unique sessions to a new table

```<code>SELECT U_SessionID.SessionID, test1.ActionName, test1.SessionID
FROM test1
INNER JOIN U_SessionID ON (SELECT SessionID
FROM test1
WHERE U_SessionID.SessionID = test1.SessionID AND (ActionName =
"a" OR ActionName = "b")
ORDER BY Time DESC
LIMIT 1);
</code>```

But this code causes MySQL workbench to crash (timeout performing query), and I have no idea if it even works.

Sample data:

Can you think of a lighter query to run this?

Maybe a better approach would be:

take all rows with action "a" or action "b":

SELECT * FROM test1 WHERE ActionName = "a" OR ActionName = "b";

drop duplicates based on the SessionID only (no matter the time order)

Ideas for that?

答:
You can change you query like below. Your subquery is unnecessary here.</p>

```<code>SELECT U_SessionID.SessionID, test1.ActionName, test1.SessionID
FROM test1
INNER JOIN U_SessionID ON U_SessionID.SessionID = test1.SessionID
WHERE ActionName  IN ("a" , "b")
ORDER BY `Time` DESC
LIMIT 1;
</code>```

Body:
I have a table with the following columns:

SessionID - contains actions within a session (1-10 rows per SessionID let's say)

ActionName - is the name of the action

Time - time action occurred

I need to return a new table, whose columns are the same, and contains only 1 row per SessionID IF the action's name is either "a" or "b".

That is, my new table should have a 1 row per SessionID which had the action "a" or "b".

I tried:

CREATE TABLE U_SessionID (
SELECT DISTINCT(SessionID) AS SessionID FROM test1)
;

I copy the unique sessions to a new table

SELECT U_SessionID.SessionID, test1.ActionName, test1.SessionID
FROM test1
INNER JOIN U_SessionID ON (SELECT SessionID
FROM test1
WHERE U_SessionID.SessionID = test1.SessionID AND (ActionName =
"a" OR ActionName = "b")
ORDER BY Time DESC
LIMIT 1);

But this code causes MySQL workbench to crash (timeout performing query), and I have no idea if it even works.

Sample data:

Can you think of a lighter query to run this?

Maybe a better approach would be:

take all rows with action "a" or action "b":

SELECT * FROM test1 WHERE ActionName = "a" OR ActionName = "b";

drop duplicates based on the SessionID only (no matter the time order)

Ideas for that?

Body:
You can change you query like below. Your subquery is unnecessary here.

SELECT U_SessionID.SessionID, test1.ActionName, test1.SessionID
FROM test1
INNER JOIN U_SessionID ON U_SessionID.SessionID = test1.SessionID
WHERE ActionName  IN ("a" , "b")
ORDER BY `Time` DESC
LIMIT 1;


问:
Hibernate criteria with referenced column returning infinite error
I have a model for a table

```<code>@Entity(name="gpl_bd_stage")
public class GplBdStage implements Serializable {

/** Primary key. */
protected static final String PK = "stageId";

/**
 * The optimistic lock. Available via standard bean get/set operations.
 */
@Column(name="created_on")
private Timestamp createdOn;
@Column(nullable=false, length=250)
private String stage;
@Column(name="updated_on")
private Timestamp updatedOn;
@Column(name="record_display_order", precision=2)
private BigDecimal recordDisplayOrder;
@Column(name="escalation_1_timeline", precision=131089)
private BigDecimal escalation1Timeline;
@Column(name="escalation_2_timeline", precision=131089)
private BigDecimal escalation2Timeline;
@Column(name="escalation_3_timeline", precision=131089)
private BigDecimal escalation3Timeline;
@Id @Column(name="stage_id", unique=true, nullable=false, precision=10)
private int stageId;
@Column(name="tat_days", precision=131089)
private BigDecimal tatDays;
@Column(name="is_active", length=1)
private boolean isActive;
@OneToMany(mappedBy="gplBdStage")
private Set<GplBdBusinessDeal> gplBdBusinessDeal;
@OneToMany(mappedBy="gplBdStage")
private Set<GplBdDealEscalation> gplBdDealEscalation;
@OneToMany(mappedBy="gplBdStage")
private Set<GplBdEscalationRule> gplBdEscalationRule;
@ManyToOne @JoinColumn(name="created_by")
private GplBdUser gplBdUser;

@OneToMany(mappedBy="gplBdStage3")

private Set<GplBdStage> gplBdStage4;

@ManyToOne @JoinColumn(name="parent_stage")
private GplBdStage gplBdStage3;
@ManyToOne @JoinColumn(name="updated_by")
private GplBdUser gplBdUser2;
@OneToMany(mappedBy="gplBdStage")
private Set<GplBdTag> gplBdTag;
</code>```

When I try to use the below query for fetching specific columns from a table :

```<code>Criteria cr = session.createCriteria(GplBdStage.class,"e")
        .setProjection(Projections.projectionList()
        .add(Projections.property("gplBdStage3"),"gplBdStage3")
        .add(Projections.property("stageId"),"stageId")
        .add(Projections.property("stage"),"stage"))
        .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<GplBdStage> result = cr.list();
</code>```

It gives infinite recursion with infinite result

Where I want something like this

```<code>[{"stage":"First Contract","gplBdStage3":{"stage":"First Contract","stageId":1},"stageId":1}]
</code>```

I use spring boot hibernate

答:
I think you are getting infinite json loop as you have @OneToMany and @ManyToOne associations.

Try to restrict it by using @JsonManagedReference and @JsonBackReference annotations

For Jackson to work well, one of the two sides of the relationship should not be serialized, in order to avoid the infite loop that causes your stackoverflow error.

```<code>    // This is pseudo code
    @OneToMany(mappedBy = "--" cascade = CascadeType.ALL)
    @JsonManagedReference
    private Set<?> -- = ;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "--", nullable = false)
    @JsonBackReference
    private -- --;
</code>```

Or

If not interested in getting some entity data just use @JsonIgnore in any one of the class

Body:
I have a model for a table

@Entity(name="gpl_bd_stage")
public class GplBdStage implements Serializable {

/** Primary key. */
protected static final String PK = "stageId";

/**
 * The optimistic lock. Available via standard bean get/set operations.
 */
@Column(name="created_on")
private Timestamp createdOn;
@Column(nullable=false, length=250)
private String stage;
@Column(name="updated_on")
private Timestamp updatedOn;
@Column(name="record_display_order", precision=2)
private BigDecimal recordDisplayOrder;
@Column(name="escalation_1_timeline", precision=131089)
private BigDecimal escalation1Timeline;
@Column(name="escalation_2_timeline", precision=131089)
private BigDecimal escalation2Timeline;
@Column(name="escalation_3_timeline", precision=131089)
private BigDecimal escalation3Timeline;
@Id @Column(name="stage_id", unique=true, nullable=false, precision=10)
private int stageId;
@Column(name="tat_days", precision=131089)
private BigDecimal tatDays;
@Column(name="is_active", length=1)
private boolean isActive;
@OneToMany(mappedBy="gplBdStage")
private Set<GplBdBusinessDeal> gplBdBusinessDeal;
@OneToMany(mappedBy="gplBdStage")
private Set<GplBdDealEscalation> gplBdDealEscalation;
@OneToMany(mappedBy="gplBdStage")
private Set<GplBdEscalationRule> gplBdEscalationRule;
@ManyToOne @JoinColumn(name="created_by")
private GplBdUser gplBdUser;

@OneToMany(mappedBy="gplBdStage3")

private Set<GplBdStage> gplBdStage4;

@ManyToOne @JoinColumn(name="parent_stage")
private GplBdStage gplBdStage3;
@ManyToOne @JoinColumn(name="updated_by")
private GplBdUser gplBdUser2;
@OneToMany(mappedBy="gplBdStage")
private Set<GplBdTag> gplBdTag;

When I try to use the below query for fetching specific columns from a table :

Criteria cr = session.createCriteria(GplBdStage.class,"e")
        .setProjection(Projections.projectionList()
        .add(Projections.property("gplBdStage3"),"gplBdStage3")
        .add(Projections.property("stageId"),"stageId")
        .add(Projections.property("stage"),"stage"))
        .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<GplBdStage> result = cr.list();

It gives infinite recursion with infinite result

Where I want something like this

[{"stage":"First Contract","gplBdStage3":{"stage":"First Contract","stageId":1},"stageId":1}]

I use spring boot hibernate

Body:
I think you are getting infinite json loop as you have @OneToMany and @ManyToOne associations.

Try to restrict it by using @JsonManagedReference and @JsonBackReference annotations

For Jackson to work well, one of the two sides of the relationship should not be serialized, in order to avoid the infite loop that causes your stackoverflow error.

    // This is pseudo code
    @OneToMany(mappedBy = "--" cascade = CascadeType.ALL)
    @JsonManagedReference
    private Set<?> -- = ;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "--", nullable = false)
    @JsonBackReference
    private -- --;

Or

If not interested in getting some entity data just use @JsonIgnore in any one of the class


答:
when you look into the table it only holds 4 objects.

The table does hold six objects. However, due to hash collisions, it holds them in only four separate chains.

You can see what's going on in the debugger: open the value of each node, and examine the next value. You will find that either (1) two of the six nodes have a second item, or (2) one of the six nodes has two additional items in its chain, for the overall count of six objects.

Title: HashMap not adding all keys


问:
use RxSwift, driver and bind to
I'm the first time to ask a question，I'm learning RxSwift, how to use bind to and driver, what's the difference between of driver and bind to.Anyone else learning RxSwift now.If you are learning RxSwift or Swift or OC,i hope we can be friends and learn from each other.</p>

答:
I suggest that you read the documentation for RxSwift Traits such as Driver.

Why use Traits?

Swift has a powerful type system that can be used to improve the correctness and stability of applications and make using Rx a more intuitive and straightforward experience.

By using units that follow constraints, we can rely on the compiler to show us errors if we're trying to do something we're not supposed to do (e.g. perform UI code on a Driver's drive method).

It is the same concept as to why we use data structures like Stacks and Queues depending on what is appropriate for the context or problem.

Driver

You can read more in detail what the Driver is all about from the documentation. In summary, it simply allows you to rely on these properties:

Can't error out

Observe on main scheduler

Sharing side effects

which is common when dealing with your user interface.

Why it's named Driver

Its intended use case was to model sequences that drive your application.

Community

Come join the RxSwift community in Slack if you are interested to meet like-minded and new and old RxSwift-ers. :)

Quotations are lifted from the documentation of RxSwift.

Title: use RxSwift, driver and bind to


问:
Copying data to another worksheet (using For Each) - but the last 2 columns offset by a certain number of columns
I'm using the code below to copy data entered into a table into another larger database in another sheet (original question and information on my worksheets here).

```<code>For Each cl In Sheet2.Range("A8:A23")
    If Not IsEmpty(cl.Value) Then
        With Worksheets("Database")
            .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).Resize(1, 18).Value = cl.Resize(1, 18).Value
        End With
    End If
Next
</code>```

This has been working great so far, however I've recently added another 2 columns of data into the data entry sheet (Row S & T). I need these new columns to also be pasted into the new sheet when the command button is pressed, but not into columns S & T - I want them to be pasted into columns AL & AM.

Any ideas how best to do this?

Any help much appreciated.

答:
I'd go as follows:

```<code>With Worksheets("Database")
    For Each cl In Sheet2.Range("A8:A23").SpecialCells(xlCellTypeConstants)
        With .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0)
            .Resize(1, 18).Value = cl.Resize(1, 18).Value
            .Offset(, 37).Resize(, 2).Value = cl.Offset(, 18).Resize(, 2)
        End With
    Next
End With
</code>```

where:

I took With Worksheets("Database") outside the loop since it's not affected by it

I used SpecialCells(xlCellTypeConstants) method to directly iterate through not-blank cells and avoid the If Not IsEmpty(cl.Value) Then check

Body:
I'm using the code below to copy data entered into a table into another larger database in another sheet (original question and information on my worksheets here).

For Each cl In Sheet2.Range("A8:A23")
    If Not IsEmpty(cl.Value) Then
        With Worksheets("Database")
            .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).Resize(1, 18).Value = cl.Resize(1, 18).Value
        End With
    End If
Next

This has been working great so far, however I've recently added another 2 columns of data into the data entry sheet (Row S & T). I need these new columns to also be pasted into the new sheet when the command button is pressed, but not into columns S & T - I want them to be pasted into columns AL & AM.

Any ideas how best to do this?

Any help much appreciated.

Body:
I'd go as follows:

With Worksheets("Database")
    For Each cl In Sheet2.Range("A8:A23").SpecialCells(xlCellTypeConstants)
        With .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0)
            .Resize(1, 18).Value = cl.Resize(1, 18).Value
            .Offset(, 37).Resize(, 2).Value = cl.Offset(, 18).Resize(, 2)
        End With
    Next
End With

where:

I took With Worksheets("Database") outside the loop since it's not affected by it

I used SpecialCells(xlCellTypeConstants) method to directly iterate through not-blank cells and avoid the If Not IsEmpty(cl.Value) Then check


问:
No. Pattern print
How to print this pattern

```<code>1 2 3
4 5 6
7 8 9
</code>```

I tried to do this way

```<code>for (int i = 1; i <= 3; i++) {
    for (int j = i; j <= i + 2; j++) {
        System.out.print(j);
        System.out.print(" ");
    }
    System.out.println();
}
</code>```

But, it gave me this output

```<code>1 2 3
2 3 4
3 4 5
</code>```

答:
A java-8 implementation of the problem:

```<code>IntStream.range(0, MAX)
         .forEach(i -> IntStream.rangeClosed(1, MAX)
                                .mapToObj(j -> j == MAX ?
                                               String.format("%3d", i * MAX + j) + "\n" :
                                               String.format("%3d", i * MAX + j) + "  ")
                                .forEach(System.out::print)
                 );
</code>```

The value for MAX in this case will be 3.

Output for MAX = 5 -

```<code>  1    2    3    4    5
  6    7    8    9   10
 11   12   13   14   15
 16   17   18   19   20
 21   22   23   24   25
</code>```

Title: No. Pattern print

Body:
How to print this pattern

1 2 3
4 5 6
7 8 9

I tried to do this way

for (int i = 1; i <= 3; i++) {
    for (int j = i; j <= i + 2; j++) {
        System.out.print(j);
        System.out.print(" ");
    }
    System.out.println();
}

But, it gave me this output

1 2 3
2 3 4
3 4 5

Body:
A java-8 implementation of the problem:

IntStream.range(0, MAX)
         .forEach(i -> IntStream.rangeClosed(1, MAX)
                                .mapToObj(j -> j == MAX ?
                                               String.format("%3d", i * MAX + j) + "\n" :
                                               String.format("%3d", i * MAX + j) + "  ")
                                .forEach(System.out::print)
                 );

The value for MAX in this case will be 3.

Output for MAX = 5 -

  1    2    3    4    5
  6    7    8    9   10
 11   12   13   14   15
 16   17   18   19   20
 21   22   23   24   25


答:
Instead of returning all images within the JSON response, every 800ms, you should just return their url instead. This will not only decrease network traffic a lot, it will also allow the browser to cache the images. Also, base64 encoded strings are much larger than binary image data (about 33%).</p>

```<code>$("#photos").append("<li class='col-lg-3 col-md-3 '><img class='img-responsive' src='"+this['url']+"' width=150px height=150px></li>");
</code>```

Title: Any references how to load pictures in jquery on swift not lagging?

Body:
Instead of returning all images within the JSON response, every 800ms, you should just return their url instead. This will not only decrease network traffic a lot, it will also allow the browser to cache the images. Also, base64 encoded strings are much larger than binary image data (about 33%).

$("#photos").append("<li class='col-lg-3 col-md-3 '><img class='img-responsive' src='"+this['url']+"' width=150px height=150px></li>");


问:
Javascript question: about variable definition
I have no idea why it didn't work if I specify a variable with 'var':
like this:

```<code>var mytool = function(){
      return {
         method: function(){}
     }
}();
</code>```

And later I use it in the same template: mytool.method. This will output mytool was not defined.

But if I define it like this:

```<code>     mytool = function(){
          return {
             method: function(){}
         }
    }();
</code>```

Then it works.

答:
I take it that you're using this inside of some function:

```<code>function setup_mytool() {
    var mytool = function(){
          return {
             method: function(){}
         }
    }();
}
</code>```

This creates the variable mytool in the function's scope; when the function setup_mytool exits, the variable is destroyed.

Saying window.mytool or window.my_global_collection.mytool will leave the variable mytool intact when the function exits.

Or:

```<code>var mytool;

function setup_mytool() {
    mytool = function(){
          return {
             method: function(){}
         }
    }();
}
</code>```

will also do what I think it is you're intending.

Body:
I have no idea why it didn't work if I specify a variable with 'var':
like this:

var mytool = function(){
      return {
         method: function(){}
     }
}();

And later I use it in the same template: mytool.method. This will output mytool was not defined.

But if I define it like this:

     mytool = function(){
          return {
             method: function(){}
         }
    }();

Then it works.

Body:
I take it that you're using this inside of some function:

function setup_mytool() {
    var mytool = function(){
          return {
             method: function(){}
         }
    }();
}

This creates the variable mytool in the function's scope; when the function setup_mytool exits, the variable is destroyed.

Saying window.mytool or window.my_global_collection.mytool will leave the variable mytool intact when the function exits.

Or:

var mytool;

function setup_mytool() {
    mytool = function(){
          return {
             method: function(){}
         }
    }();
}

will also do what I think it is you're intending.


问:
Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (http://repo1.maven.org/maven2)
I have created a new maven project in SpringSource Tool Suite. I am getting this error in my new maven project.

Failure to transfer
  org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from
  http://repo1.maven.org/maven2 was cached in the local repository,
  resolution will not be reattempted until the update interval of
  central has elapsed or updates are forced. Original error: Could not
  transfer artifact
  org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to
  central (http://repo1.maven.org/maven2): Connect times out

pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.test.app</groupId>
  <artifactId>TestApp</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>TestApp</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>
</code>```

Settings.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <pluginGroups>
  </pluginGroups>
 <proxies>
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>user</username>
      <password>pass</password>
      <host>ip</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
  </proxies>
  <servers>
  </servers>
    <mirrors>
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://repo1.maven.org/maven2/</url>
    </mirror>
  </mirrors>
<profiles>
 </profiles>
</settings>
</code>```

Please note that I am able to build it.Error is showing in pom.xml inside IDE .Any solutions?

答:
This problem was solved by following steps -

Go to the local m2 repository and find the directory
org/apache/maven/plugins/maven-surefire-plugin.

Delete the problematic version.

maven update the project, then download it again.

Body:
I have created a new maven project in SpringSource Tool Suite. I am getting this error in my new maven project.

Failure to transfer
  org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from
  http://repo1.maven.org/maven2 was cached in the local repository,
  resolution will not be reattempted until the update interval of
  central has elapsed or updates are forced. Original error: Could not
  transfer artifact
  org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to
  central (http://repo1.maven.org/maven2): Connect times out

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.test.app</groupId>
  <artifactId>TestApp</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>TestApp</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

Settings.xml

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <pluginGroups>
  </pluginGroups>
 <proxies>
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>user</username>
      <password>pass</password>
      <host>ip</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
  </proxies>
  <servers>
  </servers>
    <mirrors>
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://repo1.maven.org/maven2/</url>
    </mirror>
  </mirrors>
<profiles>
 </profiles>
</settings>

Please note that I am able to build it.Error is showing in pom.xml inside IDE .Any solutions?


问:
First available date previous day/month/year from a datetime range
I have a datetime instance with dates (dfDates):

```<code>2017-03-01 00:00
2017-03-02 00:00
2017-03-04 00:00
...
</code>```

For the last day (here: 2017-03-04) I calculate the previous day/month/year/etc. as follows:

```<code>def previous_day(dtToday):
    return dtToday - pd.DateOffset(days=1)
</code>```

This returns 2017-03-03. However, this business day is not available in my range of dates (dfDates).

I am therefore looking for a robust way to find the date that is the closest to the previous day/month/year/etc.. In this case for the previous day it should return 2017-03-02.

Note, I understand that you can do something like index -1 to get the previous day. It becomes however complicated when taking the previous month (there are not always 30 days in a month) and even the previous year (there are not always 252 working days in a year). Is there therefore a robust method to get the closest available date?

Update

I understand also that you can use timedelta as follows:

```<code>from datetime import datetime, timedelta

d = datetime.today() - timedelta(days=days_to_subtract)
</code>```

However, how does that relate to dtToday and how can I link it with dfDates? dtToday in my case is not always datetime.today(). Sometimes its a random date.

答:
I solved it like this:

dtToday = the reference date

dtDates = a datetime sequence of the
available dates

nbOffset = the number of days/months/years we want
to go back

Code:

```<code>def previous_day(dtToday, dtDates, nbOffset):
    prevx   = dtToday - pd.DateOffset(days=nbOffset)
    return test_day_in(prevx, dtDates)

def previous_month(dtToday, dtDates, nbOffset):
    prevx = dtToday - pd.DateOffset(months=nbOffset)
    return test_day_in(prevx, dtDates)

def previous_year(dtToday, dtDates, nbOffset):
    prevx = dtToday - pd.DateOffset(years=nbOffset)
    return test_day_in(prevx, dtDates)

def test_day_in(dtTest, dtDates):
    if dtTest in dtDates:
        return dtTest
    else:
        return tryNextDay(dtTest, dtDates)

def tryNextDay(dtTest, dtDates):

    # if not outside the bound
    if (dtTest < dtDates.min()):
        return dtDates.min()

    # check if next day exist
    if (dtTest + pd.DateOffset(days=1) <= dtDates.max()):
        return previous_day(dtTest + pd.DateOffset(days=2), dtDates, 1) # 2-1
    else:
        print('warning, tryNextDay triggered')
        # should not be triggered, it should take by default the dtDates.min() if far outside range
        return dtTest
</code>```

Body:
I have a datetime instance with dates (dfDates):

2017-03-01 00:00
2017-03-02 00:00
2017-03-04 00:00
...

For the last day (here: 2017-03-04) I calculate the previous day/month/year/etc. as follows:

def previous_day(dtToday):
    return dtToday - pd.DateOffset(days=1)

This returns 2017-03-03. However, this business day is not available in my range of dates (dfDates).

I am therefore looking for a robust way to find the date that is the closest to the previous day/month/year/etc.. In this case for the previous day it should return 2017-03-02.

Note, I understand that you can do something like index -1 to get the previous day. It becomes however complicated when taking the previous month (there are not always 30 days in a month) and even the previous year (there are not always 252 working days in a year). Is there therefore a robust method to get the closest available date?

Update

I understand also that you can use timedelta as follows:

from datetime import datetime, timedelta

d = datetime.today() - timedelta(days=days_to_subtract)

However, how does that relate to dtToday and how can I link it with dfDates? dtToday in my case is not always datetime.today(). Sometimes its a random date.

Body:
I solved it like this:

dtToday = the reference date

dtDates = a datetime sequence of the
available dates

nbOffset = the number of days/months/years we want
to go back

Code:

def previous_day(dtToday, dtDates, nbOffset):
    prevx   = dtToday - pd.DateOffset(days=nbOffset)
    return test_day_in(prevx, dtDates)

def previous_month(dtToday, dtDates, nbOffset):
    prevx = dtToday - pd.DateOffset(months=nbOffset)
    return test_day_in(prevx, dtDates)

def previous_year(dtToday, dtDates, nbOffset):
    prevx = dtToday - pd.DateOffset(years=nbOffset)
    return test_day_in(prevx, dtDates)

def test_day_in(dtTest, dtDates):
    if dtTest in dtDates:
        return dtTest
    else:
        return tryNextDay(dtTest, dtDates)

def tryNextDay(dtTest, dtDates):

    # if not outside the bound
    if (dtTest < dtDates.min()):
        return dtDates.min()

    # check if next day exist
    if (dtTest + pd.DateOffset(days=1) <= dtDates.max()):
        return previous_day(dtTest + pd.DateOffset(days=2), dtDates, 1) # 2-1
    else:
        print('warning, tryNextDay triggered')
        # should not be triggered, it should take by default the dtDates.min() if far outside range
        return dtTest


问:
How correctly bind data to radio buttons in Angular2?
I have a component with two radio buttons, HTML looks like :

```<code><div class="btn-group"  id="ProfitCodes">
<div class="radio">
    <label>
        <input type="radio"
           class="radio-inline"
           value="1"
           [checked]="model.ForeignCompany.ProfitCode === 1"
           [(ngModel)]="model.ForeignCompany.ProfitCode"
           id="point1"
           name="ProfitCode"><small>description</small>
    </label>
</div>
<div class="radio">
    <label>
        <input type="radio"
           class="radio-inline"
           [(ngModel)]="model.ForeignCompany.ProfitCode"
           [checked]="model.ForeignCompany.ProfitCode === 2"
           value="2"
           id="point2"
           name="ProfitCode"><small>description</small>
    </label>
</div>
</code>```

When I click save and send model to server I see valid selected value of radio button on server side. And this value stored in the database without errors. But radio button with appropriate value is not checked after binding data.
In devTools I see the first radio button:

```<code><input class="radio-inline ng-untouched ng-pristine ng-valid" id="point1" name="ProfitCode" title="asdasda" type="radio" value="1" ng-reflect-name="ProfitCode" ng-reflect-value="1" ng-reflect-model="2" ng-reflect-checked="false">
</code>```

Second radio button:

```<code><input class="radio-inline ng-untouched ng-pristine ng-valid" id="point2" name="ProfitCode" title="asd" type="radio" value="2" ng-reflect-name="ProfitCode" ng-reflect-value="2" ng-reflect-model="2" ng-reflect-checked="true">
</code>```

I see that angular changed attributes and waiting that second radio button will be checked. But this does not happen.
What am I doing wrong?

答:
This works in my case. I removed [(ngModel)]

```<code><div class="radio">
<label>
    <input type="radio"
           value="1"
           [checked]="model.ForeignCompany.ProfitCode === 1"
           id="point1"
           (change)="onProfitSelectionChange(1)"
           name="ProfitCode"><small>description</small>
</label>
</div>
<div class="radio">
    <label>
        <input type="radio"
               value="2"
               [checked]="model.ForeignCompany.ProfitCode === 2"
               id="point2"
               (change)="onProfitSelectionChange(2)"
               name="ProfitCode"><small>description</small>
    </label>
</div>
</code>```

and TS method looks like:

```<code>onProfitSelectionChange(entry): void {
    this.model.ForeignCompany.ProfitCode = entry;
}
</code>```

Body:
I have a component with two radio buttons, HTML looks like :

        <input type="radio"
           class="radio-inline"
           value="1"
           [checked]="model.ForeignCompany.ProfitCode === 1"
           [(ngModel)]="model.ForeignCompany.ProfitCode"
           id="point1"
           name="ProfitCode">description

        <input type="radio"
           class="radio-inline"
           [(ngModel)]="model.ForeignCompany.ProfitCode"
           [checked]="model.ForeignCompany.ProfitCode === 2"
           value="2"
           id="point2"
           name="ProfitCode">description

When I click save and send model to server I see valid selected value of radio button on server side. And this value stored in the database without errors. But radio button with appropriate value is not checked after binding data.
In devTools I see the first radio button:

<input class="radio-inline ng-untouched ng-pristine ng-valid" id="point1" name="ProfitCode" title="asdasda" type="radio" value="1" ng-reflect-name="ProfitCode" ng-reflect-value="1" ng-reflect-model="2" ng-reflect-checked="false">

Second radio button:

<input class="radio-inline ng-untouched ng-pristine ng-valid" id="point2" name="ProfitCode" title="asd" type="radio" value="2" ng-reflect-name="ProfitCode" ng-reflect-value="2" ng-reflect-model="2" ng-reflect-checked="true">

I see that angular changed attributes and waiting that second radio button will be checked. But this does not happen.
What am I doing wrong?

Body:
This works in my case. I removed [(ngModel)]

<div class="radio">
<label>
    <input type="radio"
           value="1"
           [checked]="model.ForeignCompany.ProfitCode === 1"
           id="point1"
           (change)="onProfitSelectionChange(1)"
           name="ProfitCode"><small>description</small>
</label>
</div>
<div class="radio">
    <label>
        <input type="radio"
               value="2"
               [checked]="model.ForeignCompany.ProfitCode === 2"
               id="point2"
               (change)="onProfitSelectionChange(2)"
               name="ProfitCode"><small>description</small>
    </label>
</div>

and TS method looks like:

onProfitSelectionChange(entry): void {
    this.model.ForeignCompany.ProfitCode = entry;
}


问:
How to count sub data of customer in SQL
I have Customer table as following

```<code>CustomerId     CustomerName   CustomerEmail
1              AAA            AAA@AAA.com
2              BBB            BBB@BBB.BBB
</code>```

This is example data I have shown. Like this I have 50000 customer in customer table now their invoices are also stored in invoice table

```<code>InvoiceId      InvoiceAmount   InvoiceCustomerID
1              22.00           1
2              58.00           2
3              21.00           2
4              45.00           2
</code>```

Now I want to count the invoice for each customer when I show the customer listing, for example:

```<code>CustomerId     CustomerName   CustomerEmail  TotalInvoice
1              AAA            AAA@AAA.com    1
2              BBB            BBB@BBB.BBB    3
</code>```

I have used the following query but didnt worked

```<code>SELECT customer.*,COUNT(invoice.InvoiceId) FROM `customer` as customer INNER JOIN invoice as invoice ON customer.CustomerId= invoice.InvoiceCustomerID
</code>```

Can suggest any method to solve this ?

Also there is more then 5 lacks invoice so it's taking to much time to load.

答:
```<code>select c.CustomerId "CustomerId",
c.CustomerName "CustomerName",
c.CustomerEmail "CustomerEmail",
count(i.InvoiceCustomerID) "TotalInvoice"
from customer as c
inner join invocie i
on(i.InvoiceCustomerID = c.CustomerId) group by
c.CustomerId, c.CustomerName, c.CustomerEmail order by CustomerId
</code>```

Body:
I have Customer table as following

CustomerId     CustomerName   CustomerEmail
1              AAA            AAA@AAA.com
2              BBB            BBB@BBB.BBB

This is example data I have shown. Like this I have 50000 customer in customer table now their invoices are also stored in invoice table

InvoiceId      InvoiceAmount   InvoiceCustomerID
1              22.00           1
2              58.00           2
3              21.00           2
4              45.00           2

Now I want to count the invoice for each customer when I show the customer listing, for example:

CustomerId     CustomerName   CustomerEmail  TotalInvoice
1              AAA            AAA@AAA.com    1
2              BBB            BBB@BBB.BBB    3

I have used the following query but didnt worked

SELECT customer.*,COUNT(invoice.InvoiceId) FROM `customer` as customer INNER JOIN invoice as invoice ON customer.CustomerId= invoice.InvoiceCustomerID

Can suggest any method to solve this ?

Also there is more then 5 lacks invoice so it's taking to much time to load.


答:
Those are Nodes, actually LinkedNodes. The hashcode of some of the keys are equal, and you get more then one entry in the same bucket.

One of the HashMap$Node that you see is actually :

```<code> HashMap$Node -> HashMap$Node(next)...
</code>```

Here is how it actually looks internally:

```<code>static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next; // NOTICE the next here
</code>```

When you go after a certain limit, those Nodes are going to become TreeNodes (holding an entire Tree of Entries) in a single bucket.

Title: HashMap not adding all keys

Body:
I am adding strings to a HashMap<String, ChartSeries> but it doesn't add all the strings. It does however change the size integer of the hashmap:

As you can see it says size:6 but when you look into the table it only holds 4 objects.

This is my code:

for (CaseTypeActivationAmount CTAM : caseTypeActivationAmounts) {
    ChartSeries cs;
    if (!caseTypes.containsKey(CTAM.getOmschrijving())) {
        if (CTAM.getOmschrijving() != null) {
            cs = new ChartSeries(CTAM.getOmschrijving());
        } else {
            cs = new ChartSeries(" ");
        }

        caseTypes.put(CTAM.getOmschrijving(), cs);
    } else {
        cs = caseTypes.get(CTAM.getOmschrijving());
    }
    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
    cs.set(dateFormat.format(CTAM.getDate()), CTAM.getAmount());
}

Am I missing something?

Body:
Those are Nodes, actually LinkedNodes. The hashcode of some of the keys are equal, and you get more then one entry in the same bucket.

One of the HashMap$Node that you see is actually :

 HashMap$Node -> HashMap$Node(next)...

Here is how it actually looks internally:

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next; // NOTICE the next here

When you go after a certain limit, those Nodes are going to become TreeNodes (holding an entire Tree of Entries) in a single bucket.


问:
angular-cli build prod "Runtime compiler is not loaded”
I did ng build -prod and met a weird error that is
_zone_symbol__error
:

```<code>Error: Uncaught (in promise): Error: Runtime compiler is not loaded Error: Runtime compiler is not loaded at d (http://localhost:4200/polyfills.cd321326a3dfc08ceb46.bund
</code>```

I am not using the compiler manually in my app. And the weirdest is that the error seems to come from the polyfills.
How can i solve this?

答:
In my case it works to disable Ahead-of-Time compilation for the build

```<code>ng build -prod --aot=false
</code>```

This way the source is still packed and uglyfied and Just-in-Time compiler is included.

main.bundle js file is smaller than when using aot compilation but vendor.bundle js increases by approx 1,5 MB.

Edit 2018-07-11

There seem to be two cases:

1) If your project intentionally creates true dynamic components, currently the only way to include the JIT compiler seems to disable AOT for the production build. See https://github.com/angular/angular/issues/11780 for a discussion

2) If your project does not need to create components dynamically and you don't know why the error happens, disabling AOT can be a workaround but beware of the drawbacks. Without AOT you have larger file sizes and it takes longer for the user to start with your application. In this case it may be more appropriate to investigate why the JIT compiler is referenced in the production build.

There are some SO Discussions (AngularCli & AOT: ERROR Error: Runtime compiler is not loaded, Trouble shoot "Runtime compiler is not loaded") around which suggest that lazy loading a third party module which uses 'COMPILER_PROVIDERS' can be the reason for the error. At the time of writing they have no accepted answer though.

For the description of another pitfall when using lazy loading modules see the answer of Alexei in this thread

Body:
I did ng build -prod and met a weird error that is
_zone_symbol__error
:

Error: Uncaught (in promise): Error: Runtime compiler is not loaded Error: Runtime compiler is not loaded at d (http://localhost:4200/polyfills.cd321326a3dfc08ceb46.bund

I am not using the compiler manually in my app. And the weirdest is that the error seems to come from the polyfills.
How can i solve this?

Body:
In my case it works to disable Ahead-of-Time compilation for the build

ng build -prod --aot=false

This way the source is still packed and uglyfied and Just-in-Time compiler is included.

main.bundle js file is smaller than when using aot compilation but vendor.bundle js increases by approx 1,5 MB.

Edit 2018-07-11

There seem to be two cases:

1) If your project intentionally creates true dynamic components, currently the only way to include the JIT compiler seems to disable AOT for the production build. See https://github.com/angular/angular/issues/11780 for a discussion

2) If your project does not need to create components dynamically and you don't know why the error happens, disabling AOT can be a workaround but beware of the drawbacks. Without AOT you have larger file sizes and it takes longer for the user to start with your application. In this case it may be more appropriate to investigate why the JIT compiler is referenced in the production build.

There are some SO Discussions (AngularCli & AOT: ERROR Error: Runtime compiler is not loaded, Trouble shoot "Runtime compiler is not loaded") around which suggest that lazy loading a third party module which uses 'COMPILER_PROVIDERS' can be the reason for the error. At the time of writing they have no accepted answer though.

For the description of another pitfall when using lazy loading modules see the answer of Alexei in this thread