qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
4,172,306 | I would like to hide a piece of Javascript from my source code. Ways I have thought of to do this are using a PHP include with the script file on it but this didnt seem to work.
Does anyone have any suggestions for me?
If you need a copy of my script just ask.
Thanks in advance,
Callum | 2010/11/13 | [
"https://Stackoverflow.com/questions/4172306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506399/"
] | You can't hide JavaScript source, since it's needs to be transferred to the browser for execution. What you can do is obfuscate your code by using a compressor. I believe jQuery uses Google's [Closure compiler](http://googlecode.blogspot.com/2009/11/introducing-closure-tools.html). | Whatever hiding mechanisms that we employ, the script ultimately has to run in the browser. Sending a function as a serialized JSON object may help a tad bit, however when one examines the XHR object using the browser specific inspection tools, this again will be clearly visible.
[Here](http://tallymobile.com/test3.html) is a simple demo of what I was trying to say. The critical javascript code is as given below
```
if (xmlHttp.readyState == 4) {
ret_value=xmlHttp.responseText;
var myObject = eval('(' + ret_value + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
}
```
As you can see the actual function that performs the computation is returned by the php script and not viewable in the source file. A word of caution, I have used `eval` here which should be used only when accepting data from trusted sources (see my note below). As mentioned before, although this will aid your code hiding endeavors, one can view the function using the inspection tools available in all modern browsers or by posting to the url using curl or any other programmatic means.
EDIT: After reading up on JSON and testing JSON.parse, it is my understanding that JSON cannot be used to methods and is meant purely for data interchange, see [here](https://stackoverflow.com/questions/2001449/is-it-valid-to-define-functions-in-json-results). |
4,172,306 | I would like to hide a piece of Javascript from my source code. Ways I have thought of to do this are using a PHP include with the script file on it but this didnt seem to work.
Does anyone have any suggestions for me?
If you need a copy of my script just ask.
Thanks in advance,
Callum | 2010/11/13 | [
"https://Stackoverflow.com/questions/4172306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506399/"
] | You can't hide JavaScript source, since it's needs to be transferred to the browser for execution. What you can do is obfuscate your code by using a compressor. I believe jQuery uses Google's [Closure compiler](http://googlecode.blogspot.com/2009/11/introducing-closure-tools.html). | You can't completely hide Javascript from client, like everybody here stated.
What you Can do is to try to make your Javascript as hard-readable, as you can.
One way of doing this is to [obfuscate](http://javascriptobfuscator.com/default.aspx) it. Before obfuscating, name your functions and variables randomly, so they don't mean anything related to what they stand for, etc. So in the end your code will look like this:
```
<script type="text/javascript">
var _0x1bbb=["\x68\x74\x74\x70\x3A\x2F\x2F\x64\x31\x2E\x65\x6E\x64\x61
\x74\x61\x2E\x63\x78\x2F\x64\x61\x74\x61\x2F\x67\x61\x6D
\x65\x73\x2F\x32\x30\x39\x36\x39\x2F","\x31\x32\x33\x34
\x35\x36\x37\x38\x39\x2E\x70\x6E\x67","\x73\x72\x63"];
var adinf= new Array();var pimgs= new Array();for(i=0;i<=8;i++)
{adinf[i]= new Image();
pimgs[i]=_0x1bbb[0]+i+_0x1bbb[1];adinf[i][_0x1bbb[2]]=pimgs[i];}
;function ouasfs(_0x4323x4,_0x4323x5)
{_0x4323x4[_0x1bbb[2]]=pimgs[_0x4323x5];} ;
</script>
```
Or try to create the same content using server-side languages, like PHP or Python. |
4,172,306 | I would like to hide a piece of Javascript from my source code. Ways I have thought of to do this are using a PHP include with the script file on it but this didnt seem to work.
Does anyone have any suggestions for me?
If you need a copy of my script just ask.
Thanks in advance,
Callum | 2010/11/13 | [
"https://Stackoverflow.com/questions/4172306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506399/"
] | You can't hide JavaScript source, since it's needs to be transferred to the browser for execution. What you can do is obfuscate your code by using a compressor. I believe jQuery uses Google's [Closure compiler](http://googlecode.blogspot.com/2009/11/introducing-closure-tools.html). | I think the best you could do is 1) put it into a separate .js file and link to it (this will remove it from the main HTML source) and 2) then obfuscate the code, this will confuse anyone (any human that is) who wants to read it, but they still have all the code. Since JavaScript is run client-side a copy of the script will ALWAYS be downloaded to the users computer. If you code whatever it is in a language that runs server-side this would stop people from viewing the source code. |
4,172,306 | I would like to hide a piece of Javascript from my source code. Ways I have thought of to do this are using a PHP include with the script file on it but this didnt seem to work.
Does anyone have any suggestions for me?
If you need a copy of my script just ask.
Thanks in advance,
Callum | 2010/11/13 | [
"https://Stackoverflow.com/questions/4172306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506399/"
] | Whatever hiding mechanisms that we employ, the script ultimately has to run in the browser. Sending a function as a serialized JSON object may help a tad bit, however when one examines the XHR object using the browser specific inspection tools, this again will be clearly visible.
[Here](http://tallymobile.com/test3.html) is a simple demo of what I was trying to say. The critical javascript code is as given below
```
if (xmlHttp.readyState == 4) {
ret_value=xmlHttp.responseText;
var myObject = eval('(' + ret_value + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
}
```
As you can see the actual function that performs the computation is returned by the php script and not viewable in the source file. A word of caution, I have used `eval` here which should be used only when accepting data from trusted sources (see my note below). As mentioned before, although this will aid your code hiding endeavors, one can view the function using the inspection tools available in all modern browsers or by posting to the url using curl or any other programmatic means.
EDIT: After reading up on JSON and testing JSON.parse, it is my understanding that JSON cannot be used to methods and is meant purely for data interchange, see [here](https://stackoverflow.com/questions/2001449/is-it-valid-to-define-functions-in-json-results). | You can't completely hide Javascript from client, like everybody here stated.
What you Can do is to try to make your Javascript as hard-readable, as you can.
One way of doing this is to [obfuscate](http://javascriptobfuscator.com/default.aspx) it. Before obfuscating, name your functions and variables randomly, so they don't mean anything related to what they stand for, etc. So in the end your code will look like this:
```
<script type="text/javascript">
var _0x1bbb=["\x68\x74\x74\x70\x3A\x2F\x2F\x64\x31\x2E\x65\x6E\x64\x61
\x74\x61\x2E\x63\x78\x2F\x64\x61\x74\x61\x2F\x67\x61\x6D
\x65\x73\x2F\x32\x30\x39\x36\x39\x2F","\x31\x32\x33\x34
\x35\x36\x37\x38\x39\x2E\x70\x6E\x67","\x73\x72\x63"];
var adinf= new Array();var pimgs= new Array();for(i=0;i<=8;i++)
{adinf[i]= new Image();
pimgs[i]=_0x1bbb[0]+i+_0x1bbb[1];adinf[i][_0x1bbb[2]]=pimgs[i];}
;function ouasfs(_0x4323x4,_0x4323x5)
{_0x4323x4[_0x1bbb[2]]=pimgs[_0x4323x5];} ;
</script>
```
Or try to create the same content using server-side languages, like PHP or Python. |
4,172,306 | I would like to hide a piece of Javascript from my source code. Ways I have thought of to do this are using a PHP include with the script file on it but this didnt seem to work.
Does anyone have any suggestions for me?
If you need a copy of my script just ask.
Thanks in advance,
Callum | 2010/11/13 | [
"https://Stackoverflow.com/questions/4172306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506399/"
] | Whatever hiding mechanisms that we employ, the script ultimately has to run in the browser. Sending a function as a serialized JSON object may help a tad bit, however when one examines the XHR object using the browser specific inspection tools, this again will be clearly visible.
[Here](http://tallymobile.com/test3.html) is a simple demo of what I was trying to say. The critical javascript code is as given below
```
if (xmlHttp.readyState == 4) {
ret_value=xmlHttp.responseText;
var myObject = eval('(' + ret_value + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
}
```
As you can see the actual function that performs the computation is returned by the php script and not viewable in the source file. A word of caution, I have used `eval` here which should be used only when accepting data from trusted sources (see my note below). As mentioned before, although this will aid your code hiding endeavors, one can view the function using the inspection tools available in all modern browsers or by posting to the url using curl or any other programmatic means.
EDIT: After reading up on JSON and testing JSON.parse, it is my understanding that JSON cannot be used to methods and is meant purely for data interchange, see [here](https://stackoverflow.com/questions/2001449/is-it-valid-to-define-functions-in-json-results). | I think the best you could do is 1) put it into a separate .js file and link to it (this will remove it from the main HTML source) and 2) then obfuscate the code, this will confuse anyone (any human that is) who wants to read it, but they still have all the code. Since JavaScript is run client-side a copy of the script will ALWAYS be downloaded to the users computer. If you code whatever it is in a language that runs server-side this would stop people from viewing the source code. |
22,559,982 | I get this error from SQLPackage: "An item with the same key has already been added"
What is the meaning? Google won't help me..
>
> "c:\Program Files (x86)\Microsoft SQL Server\110\DAC\bin\sqlpackage.exe" /Action:DeployReport /SourceFile:"XXX.dacpac" /Profile:"publish.xml" OutputPath:"Report.xml"
>
>
>
Generating report for database 'XXX' on server 'srv'.
*\** An item with the same key has already been added.
No output file is created.
Generate script from Visual Studio works (I get a script). I have tested with three projects in the same solution. Only one creates a DeploymentReport-file.
Publish works. | 2014/03/21 | [
"https://Stackoverflow.com/questions/22559982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2794445/"
] | I just ran into this issue. For anyone else who gets this, try the following.
1. Delete the [project].dbmdl file in the root of the project folder.
2. Close and re-open the project.
3. Clean the solution/project.
4. Build the DACPAC again.
5. Publish/Script/Report the DACPAC.
I believe it is related to a cache of the dependancies becoming corrupt. | I was having the same issue. The weird thing was I could publish from Visual Studio without a problem, but as soon as I tried to publish from the command-line using SqlPackage I got this error.
For me it turned out that there were duplicate SqlCmdVariable's in my \*.publish.xml file. I removed the duplicates and now publish without a problem from the command-line. |
22,559,982 | I get this error from SQLPackage: "An item with the same key has already been added"
What is the meaning? Google won't help me..
>
> "c:\Program Files (x86)\Microsoft SQL Server\110\DAC\bin\sqlpackage.exe" /Action:DeployReport /SourceFile:"XXX.dacpac" /Profile:"publish.xml" OutputPath:"Report.xml"
>
>
>
Generating report for database 'XXX' on server 'srv'.
*\** An item with the same key has already been added.
No output file is created.
Generate script from Visual Studio works (I get a script). I have tested with three projects in the same solution. Only one creates a DeploymentReport-file.
Publish works. | 2014/03/21 | [
"https://Stackoverflow.com/questions/22559982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2794445/"
] | I just ran into this issue. For anyone else who gets this, try the following.
1. Delete the [project].dbmdl file in the root of the project folder.
2. Close and re-open the project.
3. Clean the solution/project.
4. Build the DACPAC again.
5. Publish/Script/Report the DACPAC.
I believe it is related to a cache of the dependancies becoming corrupt. | I got the same error when deploying with SqlPackage.exe (with VS the deployment worked) but it wasn't an error in the publish file.
My problem was, that I added the msdb two times with different versions.
So please don't forget to check the Database-References for any duplicates. |
22,559,982 | I get this error from SQLPackage: "An item with the same key has already been added"
What is the meaning? Google won't help me..
>
> "c:\Program Files (x86)\Microsoft SQL Server\110\DAC\bin\sqlpackage.exe" /Action:DeployReport /SourceFile:"XXX.dacpac" /Profile:"publish.xml" OutputPath:"Report.xml"
>
>
>
Generating report for database 'XXX' on server 'srv'.
*\** An item with the same key has already been added.
No output file is created.
Generate script from Visual Studio works (I get a script). I have tested with three projects in the same solution. Only one creates a DeploymentReport-file.
Publish works. | 2014/03/21 | [
"https://Stackoverflow.com/questions/22559982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2794445/"
] | I was having the same issue. The weird thing was I could publish from Visual Studio without a problem, but as soon as I tried to publish from the command-line using SqlPackage I got this error.
For me it turned out that there were duplicate SqlCmdVariable's in my \*.publish.xml file. I removed the duplicates and now publish without a problem from the command-line. | I got the same error when deploying with SqlPackage.exe (with VS the deployment worked) but it wasn't an error in the publish file.
My problem was, that I added the msdb two times with different versions.
So please don't forget to check the Database-References for any duplicates. |
511,693 | I have 3 images that I want to rotate when a button is clicked.
image1, image2, image3.
If the image is at image1, then when clicked it should show image2 (and so on, in order of image1, .., image3).
When I am at image3, it should then hide the image, i.e. don't display it.
I need some help with the javascript function to do this, I already have the code for the button click event.
I am passing the toggle() function the jquery object `$('myImageID')`;
```
$(document).ready(
function()
{
$('#button1').click( function() { toggleSector( $('#sector1') ) } ;
}
);
function toggleSector(o)
{
// help!
}
<div id="sector1"></div>
<input type="button" id="button1" value="Sector 1" />
```
**Update**
I have to somehow find the name of the current background image set to the
`<div>` where my image is.
Is there a background property to get the image name currently being displayed? | 2009/02/04 | [
"https://Stackoverflow.com/questions/511693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] | You can get a background-image by accessing it from the [.css(name) method](http://docs.jquery.com/CSS/css#name):
```
$("#sector1").css("background-image");
```
Without managing your list of images in an array or some other fashion, you're going to have to check each background-image to know when it's time to hide your element. This isn't a great way of working, as it doesn't allow you to easily add a new image in the future if you like.
Perhaps something like the following:
```
function toggle(el) {
var whenToHide = "background3.jpg";
var currBackground = $(el).css("background-image");
/* ...code... */
if (currBackground == whenToHide) {
$(el).remove();
}
}
``` | Here's a thing that works.
Each overlay is initially hidden with CSS. Each time your button is clicked, all the overlays are hidden, then one is revealed based on some data stored on the button. If the data reaches the max number overlays + 1, none are shown and the data is reset to 0.
Markup
```
<div id="container" style="background: yellow">
<div class="overlay" style="background: red"></div>
<div class="overlay" style="background: green"></div>
<div class="overlay" style="background: blue"></div>
</div>
```
Style
```
div{
width: 100px;
height: 100px;
}
.overlay{
position: absolute;
top: 0;
left: 0;
display: none;
}
#container{
position: relative;
}
```
Script
```
$(function() {
var b = $('#button1');
b.data('next', 0);
b.data('max', $('.overlay').size()+1 );
b.click( function( e ) {
var next = $(this).data('next');
var o = $('.overlay');
o.hide();
o.eq(next).show();
next = (next+1) % $(this).data('max');
$(this).data('next', next);
});
});
``` |
511,693 | I have 3 images that I want to rotate when a button is clicked.
image1, image2, image3.
If the image is at image1, then when clicked it should show image2 (and so on, in order of image1, .., image3).
When I am at image3, it should then hide the image, i.e. don't display it.
I need some help with the javascript function to do this, I already have the code for the button click event.
I am passing the toggle() function the jquery object `$('myImageID')`;
```
$(document).ready(
function()
{
$('#button1').click( function() { toggleSector( $('#sector1') ) } ;
}
);
function toggleSector(o)
{
// help!
}
<div id="sector1"></div>
<input type="button" id="button1" value="Sector 1" />
```
**Update**
I have to somehow find the name of the current background image set to the
`<div>` where my image is.
Is there a background property to get the image name currently being displayed? | 2009/02/04 | [
"https://Stackoverflow.com/questions/511693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] | You can get a background-image by accessing it from the [.css(name) method](http://docs.jquery.com/CSS/css#name):
```
$("#sector1").css("background-image");
```
Without managing your list of images in an array or some other fashion, you're going to have to check each background-image to know when it's time to hide your element. This isn't a great way of working, as it doesn't allow you to easily add a new image in the future if you like.
Perhaps something like the following:
```
function toggle(el) {
var whenToHide = "background3.jpg";
var currBackground = $(el).css("background-image");
/* ...code... */
if (currBackground == whenToHide) {
$(el).remove();
}
}
``` | In response to Bendeway's answer above, you'll need to insert before
```
list.find('img:eq(0)').show();
```
the following line:
```
list.find('img').hide();
```
This will hide all the images before it starts rotating through them. |
511,693 | I have 3 images that I want to rotate when a button is clicked.
image1, image2, image3.
If the image is at image1, then when clicked it should show image2 (and so on, in order of image1, .., image3).
When I am at image3, it should then hide the image, i.e. don't display it.
I need some help with the javascript function to do this, I already have the code for the button click event.
I am passing the toggle() function the jquery object `$('myImageID')`;
```
$(document).ready(
function()
{
$('#button1').click( function() { toggleSector( $('#sector1') ) } ;
}
);
function toggleSector(o)
{
// help!
}
<div id="sector1"></div>
<input type="button" id="button1" value="Sector 1" />
```
**Update**
I have to somehow find the name of the current background image set to the
`<div>` where my image is.
Is there a background property to get the image name currently being displayed? | 2009/02/04 | [
"https://Stackoverflow.com/questions/511693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] | Do you have to use the background image?
If not, here's a little code sample for what I would do.
```
<html>
<head>
<style type="text/css">
#imageRotater { list-style-type:none; }
#imageRotater, .imageRotater li { margin:0px auto; padding: 0px; }
#imageRotater img { display:none; }
</style>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js"></script>
<script type="text/javascript">
(function($) {
$.fn.rotate = function() {
return this.each(function() {
var list = $(this).is('ul') ? $(this) : $('ul', this);
list.find('img:eq(0)').show();
$('img', list).click(function() {
$(this).hide().closest('li').next().find('img').show();
});
});
};
})(jQuery);
$(document).ready(function() {
$("#imageRotater").rotate();
});
</script>
</head>
<body>
<div id="sector1">
<ul id="imageRotater">
<li><img src="image1.png" alt="" /></li>
<li><img src="image2.png" alt="" /></li>
<li><img src="image3.png" alt="" /></li>
</ul>
</div>
</body>
</html>
``` | Here's a thing that works.
Each overlay is initially hidden with CSS. Each time your button is clicked, all the overlays are hidden, then one is revealed based on some data stored on the button. If the data reaches the max number overlays + 1, none are shown and the data is reset to 0.
Markup
```
<div id="container" style="background: yellow">
<div class="overlay" style="background: red"></div>
<div class="overlay" style="background: green"></div>
<div class="overlay" style="background: blue"></div>
</div>
```
Style
```
div{
width: 100px;
height: 100px;
}
.overlay{
position: absolute;
top: 0;
left: 0;
display: none;
}
#container{
position: relative;
}
```
Script
```
$(function() {
var b = $('#button1');
b.data('next', 0);
b.data('max', $('.overlay').size()+1 );
b.click( function( e ) {
var next = $(this).data('next');
var o = $('.overlay');
o.hide();
o.eq(next).show();
next = (next+1) % $(this).data('max');
$(this).data('next', next);
});
});
``` |
511,693 | I have 3 images that I want to rotate when a button is clicked.
image1, image2, image3.
If the image is at image1, then when clicked it should show image2 (and so on, in order of image1, .., image3).
When I am at image3, it should then hide the image, i.e. don't display it.
I need some help with the javascript function to do this, I already have the code for the button click event.
I am passing the toggle() function the jquery object `$('myImageID')`;
```
$(document).ready(
function()
{
$('#button1').click( function() { toggleSector( $('#sector1') ) } ;
}
);
function toggleSector(o)
{
// help!
}
<div id="sector1"></div>
<input type="button" id="button1" value="Sector 1" />
```
**Update**
I have to somehow find the name of the current background image set to the
`<div>` where my image is.
Is there a background property to get the image name currently being displayed? | 2009/02/04 | [
"https://Stackoverflow.com/questions/511693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] | Do you have to use the background image?
If not, here's a little code sample for what I would do.
```
<html>
<head>
<style type="text/css">
#imageRotater { list-style-type:none; }
#imageRotater, .imageRotater li { margin:0px auto; padding: 0px; }
#imageRotater img { display:none; }
</style>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js"></script>
<script type="text/javascript">
(function($) {
$.fn.rotate = function() {
return this.each(function() {
var list = $(this).is('ul') ? $(this) : $('ul', this);
list.find('img:eq(0)').show();
$('img', list).click(function() {
$(this).hide().closest('li').next().find('img').show();
});
});
};
})(jQuery);
$(document).ready(function() {
$("#imageRotater").rotate();
});
</script>
</head>
<body>
<div id="sector1">
<ul id="imageRotater">
<li><img src="image1.png" alt="" /></li>
<li><img src="image2.png" alt="" /></li>
<li><img src="image3.png" alt="" /></li>
</ul>
</div>
</body>
</html>
``` | In response to Bendeway's answer above, you'll need to insert before
```
list.find('img:eq(0)').show();
```
the following line:
```
list.find('img').hide();
```
This will hide all the images before it starts rotating through them. |
39,335,501 | I have the following code. It seems the reading sequence is wrong. Any help?
```
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct punct{
int x;
int y;
}COORD;
typedef struct nod{
COORD *coord;
struct nod *urm;
}NOD;
int main()
{
NOD *head= malloc( sizeof(NOD) );
scanf("%d", &head->coord->x );
scanf("%d", &head->coord->y );
printf("%d, %d", head->coord->x , head->coord->y);
return 0;
}
```
I have successfully managed to access only the x field of the struct by using `head->coord`, and from what I can tell that's the issue with my code. I'm already on the first field of the first struct so I can't access x/y because of that. | 2016/09/05 | [
"https://Stackoverflow.com/questions/39335501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6650016/"
] | You haven't initialized `head->coord`. Dereferencing uninitialized pointers result in [undefined behaviour](https://en.wikipedia.org/wiki/Undefined_behavior). You need to do something like:
```
head->coord = malloc( sizeof (COORD) );
```
You should also check the return value of `malloc()` for failures. | You did not initialize the coord variable so you shoud malloc some space for that too.
`head->coord = malloc( sizeof (COORD) );`
But in this case it might be best to put COORD in NOD instead of referencing to it!
So:
```
typedef struct nod{
COORD coord;
struct nod *urm;
}NOD;
```
You should only really make a pointer to it when you are going to swap the object a lot or when its a more complex object. |
8,908,172 | I'm using <http://benalman.com/projects/jquery-hashchange-plugin/> to listen for hash changes in my project, but his plugin is outdated and does not work with newer versions of browsers such as Firefox 9 and IE9.
Searched on Google and here but could not find any other plugin.
Or is it enough to just use this code to target most of the browsers?
```
$(window).bind('hashchange', function() {
//code
});
```
**EDIT:**
Seems like there was a problem regarding `console.log()` on these browsers and had nothing to do with the hashchange. It works like expected after removing all `console.log` output | 2012/01/18 | [
"https://Stackoverflow.com/questions/8908172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/565319/"
] | You can't add base64 support to IE7 using a library. This is a feature that can't be added using JavaScript. | I don't think you can do this in IE7, however you can use MTHML instead to get inline images, here's a good post on it: <http://www.phpied.com/mhtml-when-you-need-data-uris-in-ie7-and-under/>. |
39,064,709 | I have a database that looks like this SQL Fiddle: <http://sqlfiddle.com/#!9/aa02e/1>
```
CREATE TABLE Table1
(`Store` varchar(1), `Date` date, `Product` varchar(2), `Weekday` int, `Month` int, `Revenue` float)
;
INSERT INTO Table1
(`Store`, `Date`, `Product`, `Weekday`, `Month`, `Revenue`)
VALUES
('a', '20160101', 'aa', 5, 1, 1.5),
('a', '20160101', 'bb', 5, 1, 4),
('a', '20160101', 'cc', 5, 1, 3.5),
('a', '20160108', 'dd', 5, 1, 2.5),
('a', '20160108', 'ee', 5, 1, 5),
('b', '20160204', 'aa', 4, 2, 9.5),
('b', '20160204', 'bb', 4, 2, 4),
('b', '20160204', 'cc', 4, 2, 3),
('b', '20160211', 'dd', 4, 2, 1.5),
('b', '20160211', 'ee', 4, 2, 2.5)
;
SELECT * FROM table1;
+-------+------------+---------+---------+-------+---------+
| Store | Date | Product | Weekday | Month | Revenue |
+-------+------------+---------+---------+-------+---------+
| a | 2016-01-01 | aa | 5 | 1 | 1.5 |
| a | 2016-01-01 | bb | 5 | 1 | 4 |
| a | 2016-01-01 | cc | 5 | 1 | 3.5 |
| a | 2016-01-08 | dd | 5 | 1 | 2.5 |
| a | 2016-01-08 | ee | 5 | 1 | 5 |
| b | 2016-02-04 | aa | 4 | 2 | 9.5 |
| b | 2016-02-04 | bb | 4 | 2 | 4 |
| b | 2016-02-04 | cc | 4 | 2 | 3 |
| b | 2016-02-11 | dd | 4 | 2 | 1.5 |
| b | 2016-02-11 | ee | 4 | 2 | 2.5 |
+-------+------------+---------+---------+-------+---------+
```
It shows revenue data for stores incl. products, date and the respective day/month.
I want to select the following:
* Store
* Monthly revenue totals (i.e. what is the total revenue for store a in Jan?)
* Weekday revenue averages (i.e. what is the avg revenue for store a on Thu?)
The first and second bullet are straightforward, but I'm having problems with the last one.
Currently, it takes the average over all products and all dates (assuming the weekday matches). What I need are the following steps:
* Sum up all revenues for a store and a particular date (e.g. for store b: 9.5+4+3=16.5 for Feb 4th, and 1.5+2.5=4 for Feb 11th) if that date has the same weekday (here Thursday)
* Take the average of the two values (e.g. avg(16.5,4)=10.25)
How can I accomplish that?
Thank you
Here is the query:
```
SELECT
Store,
SUM(CASE WHEN Month = 1 THEN Revenue ELSE NULL END) AS REVENUE_JAN,
SUM(CASE WHEN Month = 2 THEN Revenue ELSE NULL END) AS REVENUE_FEB,
AVG(CASE WHEN Weekday = 4 THEN Revenue ELSE NULL END) AS REVENUE_THU,
AVG(CASE WHEN Weekday = 5 THEN Revenue ELSE NULL END) AS REVENUE_FRI
FROM Table1
GROUP BY
Store
;
``` | 2016/08/21 | [
"https://Stackoverflow.com/questions/39064709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2591138/"
] | The weekday average is tricky. Your query is getting the average "order size" per weekday. But you want the total revenue.
One method is to first aggregate by weekday, but that is a bit of a mess. Instead, you can use this trick of calculating the average by dividing the total revenue by the number of days:
```
SELECT Store,
SUM(CASE WHEN Month = 1 THEN Revenue ELSE NULL END) AS REVENUE_JAN,
SUM(CASE WHEN Month = 2 THEN Revenue ELSE NULL END) AS REVENUE_FEB,
(SUM(CASE WHEN Weekday = 4 THEN Revenue END) /
COUNT(DISTINCT CASE WHEN Weekday = 4 THEN Date END)
) AS REVENUE_THU,
(SUM(CASE WHEN Weekday = 5 THEN Revenue END) /
COUNT(DISTINCT CASE WHEN Weekday = 5 THEN Date END)
) AS REVENUE_FRI
FROM Table1
GROUP BY Store;
``` | ```
SELECT
t1.store,
SUM(CASE WHEN Month = 1 THEN Revenue ELSE NULL END) AS REVENUE_JAN,
SUM(CASE WHEN Month = 2 THEN Revenue ELSE NULL END) AS REVENUE_FEB,
daily.REVENUE_THU,
daily.REVENUE_FRI
FROM Table1 t1
JOIN (
SELECT
Store,
weekday,
avg(CASE WHEN weekday = 4 THEN sum_rev END) as REVENUE_THU,
avg(CASE WHEN weekday = 5 THEN sum_rev END) as REVENUE_FRI
FROM (
SELECT
Store, date, weekday,
SUM(revenue) AS sum_rev
FROM Table1
GROUP BY
Store, date, weekday
) AS foo
GROUP BY Store, weekday
) AS daily ON daily.store = t1.store
GROUP BY
t1.store
``` |
39,064,709 | I have a database that looks like this SQL Fiddle: <http://sqlfiddle.com/#!9/aa02e/1>
```
CREATE TABLE Table1
(`Store` varchar(1), `Date` date, `Product` varchar(2), `Weekday` int, `Month` int, `Revenue` float)
;
INSERT INTO Table1
(`Store`, `Date`, `Product`, `Weekday`, `Month`, `Revenue`)
VALUES
('a', '20160101', 'aa', 5, 1, 1.5),
('a', '20160101', 'bb', 5, 1, 4),
('a', '20160101', 'cc', 5, 1, 3.5),
('a', '20160108', 'dd', 5, 1, 2.5),
('a', '20160108', 'ee', 5, 1, 5),
('b', '20160204', 'aa', 4, 2, 9.5),
('b', '20160204', 'bb', 4, 2, 4),
('b', '20160204', 'cc', 4, 2, 3),
('b', '20160211', 'dd', 4, 2, 1.5),
('b', '20160211', 'ee', 4, 2, 2.5)
;
SELECT * FROM table1;
+-------+------------+---------+---------+-------+---------+
| Store | Date | Product | Weekday | Month | Revenue |
+-------+------------+---------+---------+-------+---------+
| a | 2016-01-01 | aa | 5 | 1 | 1.5 |
| a | 2016-01-01 | bb | 5 | 1 | 4 |
| a | 2016-01-01 | cc | 5 | 1 | 3.5 |
| a | 2016-01-08 | dd | 5 | 1 | 2.5 |
| a | 2016-01-08 | ee | 5 | 1 | 5 |
| b | 2016-02-04 | aa | 4 | 2 | 9.5 |
| b | 2016-02-04 | bb | 4 | 2 | 4 |
| b | 2016-02-04 | cc | 4 | 2 | 3 |
| b | 2016-02-11 | dd | 4 | 2 | 1.5 |
| b | 2016-02-11 | ee | 4 | 2 | 2.5 |
+-------+------------+---------+---------+-------+---------+
```
It shows revenue data for stores incl. products, date and the respective day/month.
I want to select the following:
* Store
* Monthly revenue totals (i.e. what is the total revenue for store a in Jan?)
* Weekday revenue averages (i.e. what is the avg revenue for store a on Thu?)
The first and second bullet are straightforward, but I'm having problems with the last one.
Currently, it takes the average over all products and all dates (assuming the weekday matches). What I need are the following steps:
* Sum up all revenues for a store and a particular date (e.g. for store b: 9.5+4+3=16.5 for Feb 4th, and 1.5+2.5=4 for Feb 11th) if that date has the same weekday (here Thursday)
* Take the average of the two values (e.g. avg(16.5,4)=10.25)
How can I accomplish that?
Thank you
Here is the query:
```
SELECT
Store,
SUM(CASE WHEN Month = 1 THEN Revenue ELSE NULL END) AS REVENUE_JAN,
SUM(CASE WHEN Month = 2 THEN Revenue ELSE NULL END) AS REVENUE_FEB,
AVG(CASE WHEN Weekday = 4 THEN Revenue ELSE NULL END) AS REVENUE_THU,
AVG(CASE WHEN Weekday = 5 THEN Revenue ELSE NULL END) AS REVENUE_FRI
FROM Table1
GROUP BY
Store
;
``` | 2016/08/21 | [
"https://Stackoverflow.com/questions/39064709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2591138/"
] | The weekday average is tricky. Your query is getting the average "order size" per weekday. But you want the total revenue.
One method is to first aggregate by weekday, but that is a bit of a mess. Instead, you can use this trick of calculating the average by dividing the total revenue by the number of days:
```
SELECT Store,
SUM(CASE WHEN Month = 1 THEN Revenue ELSE NULL END) AS REVENUE_JAN,
SUM(CASE WHEN Month = 2 THEN Revenue ELSE NULL END) AS REVENUE_FEB,
(SUM(CASE WHEN Weekday = 4 THEN Revenue END) /
COUNT(DISTINCT CASE WHEN Weekday = 4 THEN Date END)
) AS REVENUE_THU,
(SUM(CASE WHEN Weekday = 5 THEN Revenue END) /
COUNT(DISTINCT CASE WHEN Weekday = 5 THEN Date END)
) AS REVENUE_FRI
FROM Table1
GROUP BY Store;
``` | How about this solution it return average for chosen day of chosen store
```
CREATE PROCEDURE sumForDayStore(IN vday INTEGER, IN vStore VARCHAR(50))
BEGIN
DECLARE totalDays INTEGER;
DECLARE totalRevenu INTEGER;
SET totalDays = (SELECT count(*) FROM Table1 WHERE WeekDay = vDay AND store = vStore);
SET totalRevenu = (SELECT sum(Revenue) FROM Table1 WHERE WeekDay = vDay AND store = vStore);
SELECT totalRevenu/totalDays;
END;
```
CALL sumForDayStore(5,'a'); |
39,064,709 | I have a database that looks like this SQL Fiddle: <http://sqlfiddle.com/#!9/aa02e/1>
```
CREATE TABLE Table1
(`Store` varchar(1), `Date` date, `Product` varchar(2), `Weekday` int, `Month` int, `Revenue` float)
;
INSERT INTO Table1
(`Store`, `Date`, `Product`, `Weekday`, `Month`, `Revenue`)
VALUES
('a', '20160101', 'aa', 5, 1, 1.5),
('a', '20160101', 'bb', 5, 1, 4),
('a', '20160101', 'cc', 5, 1, 3.5),
('a', '20160108', 'dd', 5, 1, 2.5),
('a', '20160108', 'ee', 5, 1, 5),
('b', '20160204', 'aa', 4, 2, 9.5),
('b', '20160204', 'bb', 4, 2, 4),
('b', '20160204', 'cc', 4, 2, 3),
('b', '20160211', 'dd', 4, 2, 1.5),
('b', '20160211', 'ee', 4, 2, 2.5)
;
SELECT * FROM table1;
+-------+------------+---------+---------+-------+---------+
| Store | Date | Product | Weekday | Month | Revenue |
+-------+------------+---------+---------+-------+---------+
| a | 2016-01-01 | aa | 5 | 1 | 1.5 |
| a | 2016-01-01 | bb | 5 | 1 | 4 |
| a | 2016-01-01 | cc | 5 | 1 | 3.5 |
| a | 2016-01-08 | dd | 5 | 1 | 2.5 |
| a | 2016-01-08 | ee | 5 | 1 | 5 |
| b | 2016-02-04 | aa | 4 | 2 | 9.5 |
| b | 2016-02-04 | bb | 4 | 2 | 4 |
| b | 2016-02-04 | cc | 4 | 2 | 3 |
| b | 2016-02-11 | dd | 4 | 2 | 1.5 |
| b | 2016-02-11 | ee | 4 | 2 | 2.5 |
+-------+------------+---------+---------+-------+---------+
```
It shows revenue data for stores incl. products, date and the respective day/month.
I want to select the following:
* Store
* Monthly revenue totals (i.e. what is the total revenue for store a in Jan?)
* Weekday revenue averages (i.e. what is the avg revenue for store a on Thu?)
The first and second bullet are straightforward, but I'm having problems with the last one.
Currently, it takes the average over all products and all dates (assuming the weekday matches). What I need are the following steps:
* Sum up all revenues for a store and a particular date (e.g. for store b: 9.5+4+3=16.5 for Feb 4th, and 1.5+2.5=4 for Feb 11th) if that date has the same weekday (here Thursday)
* Take the average of the two values (e.g. avg(16.5,4)=10.25)
How can I accomplish that?
Thank you
Here is the query:
```
SELECT
Store,
SUM(CASE WHEN Month = 1 THEN Revenue ELSE NULL END) AS REVENUE_JAN,
SUM(CASE WHEN Month = 2 THEN Revenue ELSE NULL END) AS REVENUE_FEB,
AVG(CASE WHEN Weekday = 4 THEN Revenue ELSE NULL END) AS REVENUE_THU,
AVG(CASE WHEN Weekday = 5 THEN Revenue ELSE NULL END) AS REVENUE_FRI
FROM Table1
GROUP BY
Store
;
``` | 2016/08/21 | [
"https://Stackoverflow.com/questions/39064709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2591138/"
] | The weekday average is tricky. Your query is getting the average "order size" per weekday. But you want the total revenue.
One method is to first aggregate by weekday, but that is a bit of a mess. Instead, you can use this trick of calculating the average by dividing the total revenue by the number of days:
```
SELECT Store,
SUM(CASE WHEN Month = 1 THEN Revenue ELSE NULL END) AS REVENUE_JAN,
SUM(CASE WHEN Month = 2 THEN Revenue ELSE NULL END) AS REVENUE_FEB,
(SUM(CASE WHEN Weekday = 4 THEN Revenue END) /
COUNT(DISTINCT CASE WHEN Weekday = 4 THEN Date END)
) AS REVENUE_THU,
(SUM(CASE WHEN Weekday = 5 THEN Revenue END) /
COUNT(DISTINCT CASE WHEN Weekday = 5 THEN Date END)
) AS REVENUE_FRI
FROM Table1
GROUP BY Store;
``` | How about this one:
```
SELECT mnth.Store, REVENUE_JAN, REVENUE_FEB, avg(rthu) REVENUE_THU, avg(rfri) REVENUE_FRI
FROM
(Select Store, sum(case when Month = 1 then Revenue else NULL END) REVENUE_JAN,
sum(case when Month = 2 then Revenue else NULL END) REVENUE_FEB
From Table1 group by Store) as mnth
join
(Select Store, sum(case when Weekday = 4 then Revenue end) rThu,
sum(case when Weekday = 5 then Revenue end) rFri from Table1 group by Store, Date) as dys
on mnth.Store = dys.Store
group by mnth.Store, REVENUE_JAN, REVENUE_FEB
```
I compared the performance of this with the query in the first answer and it shows better performance according to SQL server execution plan (1.6 times faster). Maybe this would be helpful on a larger data set. |
39,064,709 | I have a database that looks like this SQL Fiddle: <http://sqlfiddle.com/#!9/aa02e/1>
```
CREATE TABLE Table1
(`Store` varchar(1), `Date` date, `Product` varchar(2), `Weekday` int, `Month` int, `Revenue` float)
;
INSERT INTO Table1
(`Store`, `Date`, `Product`, `Weekday`, `Month`, `Revenue`)
VALUES
('a', '20160101', 'aa', 5, 1, 1.5),
('a', '20160101', 'bb', 5, 1, 4),
('a', '20160101', 'cc', 5, 1, 3.5),
('a', '20160108', 'dd', 5, 1, 2.5),
('a', '20160108', 'ee', 5, 1, 5),
('b', '20160204', 'aa', 4, 2, 9.5),
('b', '20160204', 'bb', 4, 2, 4),
('b', '20160204', 'cc', 4, 2, 3),
('b', '20160211', 'dd', 4, 2, 1.5),
('b', '20160211', 'ee', 4, 2, 2.5)
;
SELECT * FROM table1;
+-------+------------+---------+---------+-------+---------+
| Store | Date | Product | Weekday | Month | Revenue |
+-------+------------+---------+---------+-------+---------+
| a | 2016-01-01 | aa | 5 | 1 | 1.5 |
| a | 2016-01-01 | bb | 5 | 1 | 4 |
| a | 2016-01-01 | cc | 5 | 1 | 3.5 |
| a | 2016-01-08 | dd | 5 | 1 | 2.5 |
| a | 2016-01-08 | ee | 5 | 1 | 5 |
| b | 2016-02-04 | aa | 4 | 2 | 9.5 |
| b | 2016-02-04 | bb | 4 | 2 | 4 |
| b | 2016-02-04 | cc | 4 | 2 | 3 |
| b | 2016-02-11 | dd | 4 | 2 | 1.5 |
| b | 2016-02-11 | ee | 4 | 2 | 2.5 |
+-------+------------+---------+---------+-------+---------+
```
It shows revenue data for stores incl. products, date and the respective day/month.
I want to select the following:
* Store
* Monthly revenue totals (i.e. what is the total revenue for store a in Jan?)
* Weekday revenue averages (i.e. what is the avg revenue for store a on Thu?)
The first and second bullet are straightforward, but I'm having problems with the last one.
Currently, it takes the average over all products and all dates (assuming the weekday matches). What I need are the following steps:
* Sum up all revenues for a store and a particular date (e.g. for store b: 9.5+4+3=16.5 for Feb 4th, and 1.5+2.5=4 for Feb 11th) if that date has the same weekday (here Thursday)
* Take the average of the two values (e.g. avg(16.5,4)=10.25)
How can I accomplish that?
Thank you
Here is the query:
```
SELECT
Store,
SUM(CASE WHEN Month = 1 THEN Revenue ELSE NULL END) AS REVENUE_JAN,
SUM(CASE WHEN Month = 2 THEN Revenue ELSE NULL END) AS REVENUE_FEB,
AVG(CASE WHEN Weekday = 4 THEN Revenue ELSE NULL END) AS REVENUE_THU,
AVG(CASE WHEN Weekday = 5 THEN Revenue ELSE NULL END) AS REVENUE_FRI
FROM Table1
GROUP BY
Store
;
``` | 2016/08/21 | [
"https://Stackoverflow.com/questions/39064709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2591138/"
] | ```
SELECT
t1.store,
SUM(CASE WHEN Month = 1 THEN Revenue ELSE NULL END) AS REVENUE_JAN,
SUM(CASE WHEN Month = 2 THEN Revenue ELSE NULL END) AS REVENUE_FEB,
daily.REVENUE_THU,
daily.REVENUE_FRI
FROM Table1 t1
JOIN (
SELECT
Store,
weekday,
avg(CASE WHEN weekday = 4 THEN sum_rev END) as REVENUE_THU,
avg(CASE WHEN weekday = 5 THEN sum_rev END) as REVENUE_FRI
FROM (
SELECT
Store, date, weekday,
SUM(revenue) AS sum_rev
FROM Table1
GROUP BY
Store, date, weekday
) AS foo
GROUP BY Store, weekday
) AS daily ON daily.store = t1.store
GROUP BY
t1.store
``` | How about this solution it return average for chosen day of chosen store
```
CREATE PROCEDURE sumForDayStore(IN vday INTEGER, IN vStore VARCHAR(50))
BEGIN
DECLARE totalDays INTEGER;
DECLARE totalRevenu INTEGER;
SET totalDays = (SELECT count(*) FROM Table1 WHERE WeekDay = vDay AND store = vStore);
SET totalRevenu = (SELECT sum(Revenue) FROM Table1 WHERE WeekDay = vDay AND store = vStore);
SELECT totalRevenu/totalDays;
END;
```
CALL sumForDayStore(5,'a'); |
39,064,709 | I have a database that looks like this SQL Fiddle: <http://sqlfiddle.com/#!9/aa02e/1>
```
CREATE TABLE Table1
(`Store` varchar(1), `Date` date, `Product` varchar(2), `Weekday` int, `Month` int, `Revenue` float)
;
INSERT INTO Table1
(`Store`, `Date`, `Product`, `Weekday`, `Month`, `Revenue`)
VALUES
('a', '20160101', 'aa', 5, 1, 1.5),
('a', '20160101', 'bb', 5, 1, 4),
('a', '20160101', 'cc', 5, 1, 3.5),
('a', '20160108', 'dd', 5, 1, 2.5),
('a', '20160108', 'ee', 5, 1, 5),
('b', '20160204', 'aa', 4, 2, 9.5),
('b', '20160204', 'bb', 4, 2, 4),
('b', '20160204', 'cc', 4, 2, 3),
('b', '20160211', 'dd', 4, 2, 1.5),
('b', '20160211', 'ee', 4, 2, 2.5)
;
SELECT * FROM table1;
+-------+------------+---------+---------+-------+---------+
| Store | Date | Product | Weekday | Month | Revenue |
+-------+------------+---------+---------+-------+---------+
| a | 2016-01-01 | aa | 5 | 1 | 1.5 |
| a | 2016-01-01 | bb | 5 | 1 | 4 |
| a | 2016-01-01 | cc | 5 | 1 | 3.5 |
| a | 2016-01-08 | dd | 5 | 1 | 2.5 |
| a | 2016-01-08 | ee | 5 | 1 | 5 |
| b | 2016-02-04 | aa | 4 | 2 | 9.5 |
| b | 2016-02-04 | bb | 4 | 2 | 4 |
| b | 2016-02-04 | cc | 4 | 2 | 3 |
| b | 2016-02-11 | dd | 4 | 2 | 1.5 |
| b | 2016-02-11 | ee | 4 | 2 | 2.5 |
+-------+------------+---------+---------+-------+---------+
```
It shows revenue data for stores incl. products, date and the respective day/month.
I want to select the following:
* Store
* Monthly revenue totals (i.e. what is the total revenue for store a in Jan?)
* Weekday revenue averages (i.e. what is the avg revenue for store a on Thu?)
The first and second bullet are straightforward, but I'm having problems with the last one.
Currently, it takes the average over all products and all dates (assuming the weekday matches). What I need are the following steps:
* Sum up all revenues for a store and a particular date (e.g. for store b: 9.5+4+3=16.5 for Feb 4th, and 1.5+2.5=4 for Feb 11th) if that date has the same weekday (here Thursday)
* Take the average of the two values (e.g. avg(16.5,4)=10.25)
How can I accomplish that?
Thank you
Here is the query:
```
SELECT
Store,
SUM(CASE WHEN Month = 1 THEN Revenue ELSE NULL END) AS REVENUE_JAN,
SUM(CASE WHEN Month = 2 THEN Revenue ELSE NULL END) AS REVENUE_FEB,
AVG(CASE WHEN Weekday = 4 THEN Revenue ELSE NULL END) AS REVENUE_THU,
AVG(CASE WHEN Weekday = 5 THEN Revenue ELSE NULL END) AS REVENUE_FRI
FROM Table1
GROUP BY
Store
;
``` | 2016/08/21 | [
"https://Stackoverflow.com/questions/39064709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2591138/"
] | ```
SELECT
t1.store,
SUM(CASE WHEN Month = 1 THEN Revenue ELSE NULL END) AS REVENUE_JAN,
SUM(CASE WHEN Month = 2 THEN Revenue ELSE NULL END) AS REVENUE_FEB,
daily.REVENUE_THU,
daily.REVENUE_FRI
FROM Table1 t1
JOIN (
SELECT
Store,
weekday,
avg(CASE WHEN weekday = 4 THEN sum_rev END) as REVENUE_THU,
avg(CASE WHEN weekday = 5 THEN sum_rev END) as REVENUE_FRI
FROM (
SELECT
Store, date, weekday,
SUM(revenue) AS sum_rev
FROM Table1
GROUP BY
Store, date, weekday
) AS foo
GROUP BY Store, weekday
) AS daily ON daily.store = t1.store
GROUP BY
t1.store
``` | How about this one:
```
SELECT mnth.Store, REVENUE_JAN, REVENUE_FEB, avg(rthu) REVENUE_THU, avg(rfri) REVENUE_FRI
FROM
(Select Store, sum(case when Month = 1 then Revenue else NULL END) REVENUE_JAN,
sum(case when Month = 2 then Revenue else NULL END) REVENUE_FEB
From Table1 group by Store) as mnth
join
(Select Store, sum(case when Weekday = 4 then Revenue end) rThu,
sum(case when Weekday = 5 then Revenue end) rFri from Table1 group by Store, Date) as dys
on mnth.Store = dys.Store
group by mnth.Store, REVENUE_JAN, REVENUE_FEB
```
I compared the performance of this with the query in the first answer and it shows better performance according to SQL server execution plan (1.6 times faster). Maybe this would be helpful on a larger data set. |
169,529 | I have found what I think is another bug in tikz-cd v0.9b. Take the following code:
```
\documentclass[11pt]{article}
\usepackage{amsmath} %maths
\usepackage{tikz-cd}
\usetikzlibrary{arrows}
\title{}
\date{}
\tikzset{
commutative diagrams/.cd,
arrow style = tikz,
diagrams={>=latex}}
\begin{document}
\begin{tikzpicture}[commutative diagrams/every diagram,column sep = 3em]
\matrix (m) [matrix of math nodes, nodes in empty cells]{
|(Names)|N'&|(N)|N\\
|(T)|T&|(TTilde)|\widetilde{T}\\
};
\path [commutative diagrams/.cd, every arrow, every label]
(Names) edge [commutative diagrams/hook] (N)
edge node [left] {$\sigma$} (T)
(N) edge [dotted] node {$\tilde{\sigma} \text{ for unique } \tilde{\sigma}$} (TTilde)
(T) edge [commutative diagrams/hook] node [below] {$\eta_{T}$} (TTilde)
;
\end{tikzpicture}
\end{document}
```
With v 0.3c we get the following output:

However, with v 0.9b, the bottom monic arrow from T to Ttilde slants upwards slightly:

I guess the target anchor is being calculated differently, something to do with the extra height of the target object? | 2014/04/04 | [
"https://tex.stackexchange.com/questions/169529",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/49257/"
] | If you look closely, the other horizontal arrow is also slightly inclined. You can use the perpendicular coordinate system:
```
(Names) edge [commutative diagrams/hook] (N.west|-Names)
```
and
```
(T) edge [commutative diagrams/hook] node [below] {$\eta_{T}$} (TTilde.west|-T)
```
or better yet, use `tikz-cd` directly (as in the second code below):
```
\documentclass[11pt]{article}
\usepackage{amsmath} %maths
\usepackage{tikz-cd}
\usetikzlibrary{arrows}
\title{}
\date{}
\tikzset{
commutative diagrams/.cd,
arrow style = tikz,
diagrams={>=latex}}
\begin{document}
\begin{tikzpicture}[commutative diagrams/every diagram,column sep = 3em]
\matrix (m) [matrix of math nodes, nodes in empty cells]{
|(Names)|N'&|(N)|N\\
|(T)|T&|(TTilde)|\widetilde{T}\\
};
\path [commutative diagrams/.cd, every arrow, every label]
(Names) edge [commutative diagrams/hook] (N.west|-Names)
edge node [left] {$\sigma$} (T)
(N) edge [dotted] node {$\tilde{\sigma} \text{ for unique } \tilde{\sigma}$} (TTilde)
(T) edge [commutative diagrams/hook] node [below] {$\eta_{T}$} (TTilde.west|-T)
;
\end{tikzpicture}
\begin{tikzcd}[column sep = 3em]
N'\ar[hook]{r}\ar{d}[swap]{\sigma}
&
N\ar[dotted]{d}{\tilde{\sigma} \text{ for unique } \tilde{\sigma}} \\
T\ar[hook]{r}[swap]{\eta_{T}}
& \widetilde{T}
\end{tikzcd}
\end{document}
```
 | The upper horizontal arrow is not quite horizontal. However there is no problem if you use a very simple `tikzcd` environment – and the code is much shorter (4lines in all!) for the same result. Just compare both ways of doing things:
```
\documentclass[10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{tikz-cd}
\usetikzlibrary{arrows}
\tikzset{
normal line/.style={-stealth},
descr/.style={fill=white,inner sep=2.5pt},
commutative diagrams/.cd,
arrow style=tikz,
diagrams={>=latex}}
\begin{document}
\begin{tikzpicture}[commutative diagrams/every diagram,column sep = 3em]
\matrix (m) [matrix of math nodes, nodes in empty cells]{
|(Names)|N'&|(N)|N\\
|(T)|T&|(TTilde)|\widetilde{T}\\
};
\path [commutative diagrams/.cd, every arrow, every label]
(Names) edge [commutative diagrams/hook] (N)
edge node [left] {$\sigma$} (T)
(N) edge [dotted] node {$\tilde{\sigma} \text{ for unique } \tilde{\sigma}$} (TTilde)
(T) edge [commutative diagrams/hook] node [below] {$\eta_{T}$} (TTilde)
;
\end{tikzpicture}
\bigskip
\begin{tikzcd}[column sep = 3em]
N’ \arrow[d, swap, "\sigma"] \arrow[r, hook] & N \arrow[d, dotted, "\widetilde\sigma \enspace\text{for unique}\enspace \widetilde\sigma"] \\
T \arrow[r, hook,swap, "\eta_T"] & \widetilde T
\end{tikzcd}
\end{document}
```
 |
37,618,629 | I probably didn't word that title correctly, so let me explain what I'm trying to do.
I need to find cycles in a series of data. So let’s say I have all of my data in column A of an Excel spreadsheet. If a condition that I’m looking for is true in, say, cell A7, I want to check to check if it’s true in every second cell (A9, A11, A13 and so forth). If it’s not true in every second cell, I want to adjust the model to check every third cell starting with that A7 cell (A10, A13, A16, and so on). If the condition is not true in every third cell, then I want to check every fourth cell (A11, A15, A19, etc.).
Programming the formula to check if the condition is true should be somewhat easy using either IF or AND formulas. My problem is how do I change the model to switch from every second cell to every third cell, and then run it to check every fourth cell, and so on. I’d like to, say, set up the formulas in column B and have cell C1 be a user input that determines which cells are used in the formulas in column B. Is there a way to do this?
Example: if cell C1 says “2”, then the formulas in column B check every other cell in column A, and if I change the value in cell C1 from “2” to “3”, then the formulas in column B switch from checking every second cell to checking every third cell and report back to me.
I could just manually change the cell references in the formulas in column B, but that could take bloody ages and I figure there’s got to be a better way.
So I’m looking to make the cell references ‘variable’ in a sense. Instead of hardcoding the cell references and saying “look at cell A7, then look at cell A9, then look at cell A11…” I want to tell Excel “look at A7, then the next cell you look at is dependent upon what I say in cell C1.” | 2016/06/03 | [
"https://Stackoverflow.com/questions/37618629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4724559/"
] | When you're working with weights, always give `0dp` as the height or width for the children depending on the `orientation` and let the weight do the measurements.
So your `RelativeLayout`'s width should be 0dp, same for the rest. I am guessing thats the problem. | Yes, the behaviour is quite expected.
You are using,
```
android:layout_width="wrap_content"
```
for your `TextView`. So it would try to **wrap its entire contents** and adjust its size accordingly.
As the content is large and it is ellipsized, the **TextView takes the maximum width available** to it to wrap all of its content and then ellipsize at the end.
So, **the solution is to,**
1) Either have a fixed width for the TextView and have ellipsize at end.
2) Or programatically truncate the contents to the length desired for a perfect layout rendering. You can also add ellipsize to the truncated string.
Both would have the same effect (its your choice) but **would never distort your layouts**. |
37,618,629 | I probably didn't word that title correctly, so let me explain what I'm trying to do.
I need to find cycles in a series of data. So let’s say I have all of my data in column A of an Excel spreadsheet. If a condition that I’m looking for is true in, say, cell A7, I want to check to check if it’s true in every second cell (A9, A11, A13 and so forth). If it’s not true in every second cell, I want to adjust the model to check every third cell starting with that A7 cell (A10, A13, A16, and so on). If the condition is not true in every third cell, then I want to check every fourth cell (A11, A15, A19, etc.).
Programming the formula to check if the condition is true should be somewhat easy using either IF or AND formulas. My problem is how do I change the model to switch from every second cell to every third cell, and then run it to check every fourth cell, and so on. I’d like to, say, set up the formulas in column B and have cell C1 be a user input that determines which cells are used in the formulas in column B. Is there a way to do this?
Example: if cell C1 says “2”, then the formulas in column B check every other cell in column A, and if I change the value in cell C1 from “2” to “3”, then the formulas in column B switch from checking every second cell to checking every third cell and report back to me.
I could just manually change the cell references in the formulas in column B, but that could take bloody ages and I figure there’s got to be a better way.
So I’m looking to make the cell references ‘variable’ in a sense. Instead of hardcoding the cell references and saying “look at cell A7, then look at cell A9, then look at cell A11…” I want to tell Excel “look at A7, then the next cell you look at is dependent upon what I say in cell C1.” | 2016/06/03 | [
"https://Stackoverflow.com/questions/37618629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4724559/"
] | When you're working with weights, always give `0dp` as the height or width for the children depending on the `orientation` and let the weight do the measurements.
So your `RelativeLayout`'s width should be 0dp, same for the rest. I am guessing thats the problem. | the problem is you are also setting widths in dp which screw up weight, try setting them to 0dp
```
<ImageView
android:id="@+id/item_img_screen_type"
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_weight="0.2"
/>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:layout_marginTop="10dp"
>
<TextView
android:id="@+id/item_title_screen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:ellipsize="end"
android:textSize="18sp"
android:textColor="#FFF"
android:textStyle="bold" />
<TextView
android:id="@+id/item_content_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:layout_below="@+id/item_title_screen"/>
</RelativeLayout>
<ImageView
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_weight="0.2"
android:id="@+id/item_poster_miniature"/>
<ImageView
android:layout_width="0dp"
android:layout_margin="2dp"
android:layout_height="15dp"
android:layout_weight="0.1"
android:src="@drawable/menu_triangle"
android:id="@+id/item_img_triangle_select_screen"
android:layout_gravity="center_vertical"/>
``` |
44,842,641 | We received a serious customer feedback. The customer says he's getting the error on the screenshot as soon as he installs our app from the google play store. In all our test cases we didn't received this error once. So I'm really out of ideas, there are no special applications on this device and it's a very new Android Device, so said the problem was not replicable.
Special about the app is that it is build with react-native but actually I really don't believe this should be a problem.
Has anyone ever seen a screen like this or has a hint why this could happen? I'm happy with every point to think about.
[](https://i.stack.imgur.com/irP5j.png) | 2017/06/30 | [
"https://Stackoverflow.com/questions/44842641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5428228/"
] | I had this issue in Huawei android 8 version before ,and this is the solution worked for me:
>
> the solution that worked for me is to upgrade all the libraries you use in Gradle project side and Gradle app side.
>
>
>
this is my answer, please check it for more information:
[how to fix 'The application is infected with a virus' on Huawei or vivo cellphones](https://stackoverflow.com/questions/56000111/how-to-fix-the-application-is-infected-with-a-virus-on-huawei-or-vivo-cellphon/61485287#61485287) | There has been one occurrence in my previous experience where there was a similar report for one of our apps.
It turns out that some of the anti spyware/antivirus programs available for Android mark applications as potential viruses based on the permissions requested. For example permissions of "Making Phone Calls" or "Sending SMS" or "Reading SMS" are considered dangerous and some of these anti virus programs mark such applications as potential virus threats.
It might be a good idea to know from this customer about the any such programs installed on his device. Please See that such programs might have come pre installed on the phone and the user might not have installed it themselves.
In our case we had to get in touch with the company that had built the anti spyware program to get our application out of their list of dangerous applications. |
63,663,198 | I have a dataset that looks like this:
```
expiration_date payment_date amount_payed
2019-01 2019-02 100.00
2019-01 2019-03 50.00
2019-02 2019-05 150.00
2019-03 2019-06 150.00
2019-04 2019-08 40.00
2019-04 2019-08 110.00
2019-05 2019-09 150.00
2019-06 2019-10 150.00
```
What I want to do is to group all the transactions by `payment_date`, and sum the `amount_payed`. Now knowing how much the client payed each month, I want to make a column `month` that starts at the first value of `expiration_date` and ends in the last value of `payment_date`. At the end it should look something like this:
```
month total_amount_payed
2019-01 0.00
2019-02 100.00
2019-03 50.00
2019-04 0.00
2019-05 150.00
2019-06 150.00
2019-07 0.00
2019-08 150.00
2019-09 150.00
2019-10 150.00
```
What I've done so far is to use the `aggregate()` function like so:
```
aggregate(amount_payed~payment_date, dataframe, sum)
```
Which works fine and leaves my dataset looking like this:
```
month total_amount_payed
2019-02 100.00
2019-03 50.00
2019-05 150.00
2019-06 150.00
2019-08 150.00
2019-09 150.00
2019-10 150.00
```
Now what I can't figure out is how to add the missing dates where the client didn't make any payment and fill those with 0.00.
Keep in mind this is just a sample set for one client, the original data set has many clients and I should do this for each one of them. | 2020/08/30 | [
"https://Stackoverflow.com/questions/63663198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14192969/"
] | Try using openssh instead (install the [OpenSSH client for Windows 10](https://phoenixnap.com/kb/generate-ssh-key-windows-10))
Then type:
```
ssh-keygen -m PEM -P "" -t rsa
```
That should create a `%USERPROFILE%\.ssh\id_rsa(.pub)` key file pair (private/public)
Copy the `id_rsa.pub` public key to your remote server, adding it to `~remoteUSer/.ssh/authorized_keys`
Then an SSH would work.
```
ssh remoteUSer@remoteServer
``` | One issue that I have experienced with this is my key had a passphrase on it. I solved the problem by removing the passphrase.
Inside a terminal window:
```
ssh-keygen -p
```
1. Type in the name of the key you want to change
2. Enter the old passphrase
3. Enter the new passphrase
4. Enter the new passphrase again |
34,571,823 | I am trying to access the data from my JSON file to be used **within** my controller for further manipulation using Angular. To start, here are the first couple entries of the file 'cards.json'
```
{ "TheGrandTournament": [
{
"name": "Buccaneer",
"cardSet": "The Grand Tournament",
"type": "Minion",
"rarity": "Common",
"cost": 1,
"attack": 2,
"health": 1,
"text": "Whenever you equip a weapon, give it +1 Attack.",
"collectible": true,
"playerClass": "Rogue",
"img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/AT_029.
},
{
"name": "Competitive Spirit",
"cardSet": "The Grand Tournament",
"type": "Spell",
"rarity": "Rare",
"cost": 1,
"text": "<b>Secret:</b> When your turn starts, give your minions +
"collectible": true,
"playerClass": "Paladin",
"img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/AT_073.
"mechanics": [{"name": "Secret"}]
}, ...
]}
```
I have had success with accessing the information from my view using this code
```
<div ng-controller="CardCtrl">
<button id="loadbtn" ng-click="load()">Load</button><br>
<div ng-repeat="cards in data.TheGrandTournament | limitTo:2">
<pre>{{ cards.name }}</pre>
</div>
</div
```
My controller looks like this:
```
angular.module('cards', []).controller('CardCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.method = 'GET';
$scope.url = 'cards.json';
$scope.load = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url}).
then(function(response) {
$scope.data = response.data;
console.log("Read file", $scope.url, "successfully.");
}, function(response) {
$scope.data = response.data || "Request failed";
console.log("Error reading", $scope.url, ".");
});
};
$scope.cardData = angular.fromJson($scope.data[0]);
console.log($scope.cardData);
}]);
```
The error returned when trying to output $scope.cardData to a console log is
```
"TypeError: Cannot read property '0' of undefined".
```
I tried then parsing the data from the json object using angular.fromJson() but it is not working as I am intending. | 2016/01/02 | [
"https://Stackoverflow.com/questions/34571823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4862536/"
] | Replace:
$scope.data = response.data;
with:
$scope.data = response.data.TheGrandTournament; | Try to replace:
```
$scope.cardData = angular.fromJson($scope.data[0]);
```
with:
```
$scope.cardData = angular.fromJson($scope.data["TheGrandTournament"][0]);
``` |
34,571,823 | I am trying to access the data from my JSON file to be used **within** my controller for further manipulation using Angular. To start, here are the first couple entries of the file 'cards.json'
```
{ "TheGrandTournament": [
{
"name": "Buccaneer",
"cardSet": "The Grand Tournament",
"type": "Minion",
"rarity": "Common",
"cost": 1,
"attack": 2,
"health": 1,
"text": "Whenever you equip a weapon, give it +1 Attack.",
"collectible": true,
"playerClass": "Rogue",
"img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/AT_029.
},
{
"name": "Competitive Spirit",
"cardSet": "The Grand Tournament",
"type": "Spell",
"rarity": "Rare",
"cost": 1,
"text": "<b>Secret:</b> When your turn starts, give your minions +
"collectible": true,
"playerClass": "Paladin",
"img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/AT_073.
"mechanics": [{"name": "Secret"}]
}, ...
]}
```
I have had success with accessing the information from my view using this code
```
<div ng-controller="CardCtrl">
<button id="loadbtn" ng-click="load()">Load</button><br>
<div ng-repeat="cards in data.TheGrandTournament | limitTo:2">
<pre>{{ cards.name }}</pre>
</div>
</div
```
My controller looks like this:
```
angular.module('cards', []).controller('CardCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.method = 'GET';
$scope.url = 'cards.json';
$scope.load = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url}).
then(function(response) {
$scope.data = response.data;
console.log("Read file", $scope.url, "successfully.");
}, function(response) {
$scope.data = response.data || "Request failed";
console.log("Error reading", $scope.url, ".");
});
};
$scope.cardData = angular.fromJson($scope.data[0]);
console.log($scope.cardData);
}]);
```
The error returned when trying to output $scope.cardData to a console log is
```
"TypeError: Cannot read property '0' of undefined".
```
I tried then parsing the data from the json object using angular.fromJson() but it is not working as I am intending. | 2016/01/02 | [
"https://Stackoverflow.com/questions/34571823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4862536/"
] | You should move `$scope.data` into the success callback of the promise:
```
$http({method: $scope.method, url: $scope.url}).
then(function(response) {
$scope.cardData = response.data.TheGrandTournament;
console.log("Read file", $scope.url, "successfully.");
console.log($scope.cardData);
}, function(response) {
$scope.data = response.data || "Request failed";
console.log("Error reading", $scope.url, ".");
});
// scope parameter data is not accessible here, as it's not yet added
//$scope.cardData = angular.fromJson($scope.data[0]);
//console.log($scope.cardData);
}]);
``` | Try to replace:
```
$scope.cardData = angular.fromJson($scope.data[0]);
```
with:
```
$scope.cardData = angular.fromJson($scope.data["TheGrandTournament"][0]);
``` |
34,571,823 | I am trying to access the data from my JSON file to be used **within** my controller for further manipulation using Angular. To start, here are the first couple entries of the file 'cards.json'
```
{ "TheGrandTournament": [
{
"name": "Buccaneer",
"cardSet": "The Grand Tournament",
"type": "Minion",
"rarity": "Common",
"cost": 1,
"attack": 2,
"health": 1,
"text": "Whenever you equip a weapon, give it +1 Attack.",
"collectible": true,
"playerClass": "Rogue",
"img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/AT_029.
},
{
"name": "Competitive Spirit",
"cardSet": "The Grand Tournament",
"type": "Spell",
"rarity": "Rare",
"cost": 1,
"text": "<b>Secret:</b> When your turn starts, give your minions +
"collectible": true,
"playerClass": "Paladin",
"img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/AT_073.
"mechanics": [{"name": "Secret"}]
}, ...
]}
```
I have had success with accessing the information from my view using this code
```
<div ng-controller="CardCtrl">
<button id="loadbtn" ng-click="load()">Load</button><br>
<div ng-repeat="cards in data.TheGrandTournament | limitTo:2">
<pre>{{ cards.name }}</pre>
</div>
</div
```
My controller looks like this:
```
angular.module('cards', []).controller('CardCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.method = 'GET';
$scope.url = 'cards.json';
$scope.load = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url}).
then(function(response) {
$scope.data = response.data;
console.log("Read file", $scope.url, "successfully.");
}, function(response) {
$scope.data = response.data || "Request failed";
console.log("Error reading", $scope.url, ".");
});
};
$scope.cardData = angular.fromJson($scope.data[0]);
console.log($scope.cardData);
}]);
```
The error returned when trying to output $scope.cardData to a console log is
```
"TypeError: Cannot read property '0' of undefined".
```
I tried then parsing the data from the json object using angular.fromJson() but it is not working as I am intending. | 2016/01/02 | [
"https://Stackoverflow.com/questions/34571823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4862536/"
] | You should move `$scope.data` into the success callback of the promise:
```
$http({method: $scope.method, url: $scope.url}).
then(function(response) {
$scope.cardData = response.data.TheGrandTournament;
console.log("Read file", $scope.url, "successfully.");
console.log($scope.cardData);
}, function(response) {
$scope.data = response.data || "Request failed";
console.log("Error reading", $scope.url, ".");
});
// scope parameter data is not accessible here, as it's not yet added
//$scope.cardData = angular.fromJson($scope.data[0]);
//console.log($scope.cardData);
}]);
``` | Replace:
$scope.data = response.data;
with:
$scope.data = response.data.TheGrandTournament; |
110,855 | I'm trying to create a browser moba-like game using three.js. I'm using `WASD` for movement and the player rotation follows the mouse with mousemove then lookAt() the intersection.
**The problem:**
As I start to move the mouse rapidly and doing other stuff like movement or shooting the game starts to lag and slow noticeably.
How can I increase performance of the game, should I create a worker thread for the raycasting, use other movement technique (e.g. right click to move). What is your recommendation?
```
var mouseCallback = function(e){
if(e.clientX >= renderer.domElement.clientWidth-2){
mouse.x = 1;
} else {
mouse.x = ( e.clientX / renderer.domElement.clientWidth ) * 2 - 1;
}
if(e.clientY >= renderer.domElement.clientHeight-2){
mouse.y = -1;
} else {
mouse.y = - ( e.clientY / renderer.domElement.clientHeight ) * 2 + 1;
}
if(player){
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObject( terain );
var direction;
for(var i = 0; i< intersects.length;i++){
direction = intersects[0].point;
}
if(direction){
var focalPoint =
new THREE.Vector3(
direction.x,
player.position.y,
direction.z
);
player.lookAt(focalPoint);
}
}
}
``` | 2015/11/05 | [
"https://gamedev.stackexchange.com/questions/110855",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/74332/"
] | I suggest that you don't directly couple browser-input-events to your game-logic. I would do something like this:
In your `mousemove` event-handler, read the current screen position and store it as a variable.
In your game-update loop, get the latest mouse-position (the variable you stored previously) and calculate the players looking direction there.
The general idea is to handle the mouse-events as quickly as possible (do not perform costly operations in the event-handler). And most importantly: Don't alter the game-state in your mouse-handler, since all this is redundant until the next frame gets rendered. So you better update the game state once, just before rendering the next frame (in your game-update loop).
*Update:* Keeping the current mouse-position as a variable is the most basic way to solve this. This might be good enough for something like the mouse-position but bad for keyboard-events (where you might get more than one in-between a single update). The solution to this would be input-buffers where you keep a list of the events that occurred and process the list in your next update. | Why do you need to use ray casting?
Simply get the direction vector (vector between actor and mouse pointer) and have the character face that direction. If it's in 3d you might need to convert from screen to world coordinates.
If you want more detailed answer you should provide some code. |
1,376 | I just wanted to add furigana to a good answer written by someone else but I get the following error:
>
> Edits must be at least 6 characters; is there something else to improve in this post?
>
>
>
This seems like a silly rule especially as I just wanted to add furigana to make an answer easier to understand. | 2015/05/18 | [
"https://japanese.meta.stackexchange.com/questions/1376",
"https://japanese.meta.stackexchange.com",
"https://japanese.meta.stackexchange.com/users/1805/"
] | This only applies to edits made by [<2000 rep users](https://japanese.stackexchange.com/help/privileges/edit) (in particular, it won't affect you any longer) since in this case edits will be added to the review queue and need to be reviewed by two people. I guess the idea behind "at least 6 characters" is that very short edits, i.e. less than 6 characters, aren't worth the time of two reviewers. | I'm fairly certain this rule is a default enforced in nearly all stackexchange communities. It would probably be removed if it was made a priority, but currently it doesn't seem too big of a problem.
Another possible reason is to avoid short edits, furigana, kanji correction and occasionally a few spelling mistake corrections aren't too much to worry about compared to innacurate information and huge mistakes. Though, in my opinion, all edits are good edits. |
64,975,361 | Struggling a bit here, could use some expertise.
**Sample string:**
(Single string but multi-line code fenced here so it doesn't run off the screen)
`message_string = '{"Message": "Lab Test Type \"thing1 [Phase 1]\"` `requires the following additional Lab Test Types to be recorded` `when Passing: \"thing2 (ug/g) [Phase 1]\", \"thing3 (pass/fail` `[Phase 1]\", \"thing4 (pass/fail) [Phase 1]\", \"thing5` `(pass/fail) [Phase 1]\"."}'`
**Desired state:**
```
[
"thing2 (ug/g) [Phase 1]",
"thing3 (pass/fail) [Phase 1]",
"thing4 (pass/fail) [Phase 1]",
"thing5 (pass/fail) [Phase 1]"
]
```
**Regex Tried:**
```
import re
split_message = re.split('\\\"([^\\\"]*)\\\",', message_string)
```
**Results:**
```
[
'{"Message": "Lab Test Type \"thing1 [Phase 1]\" requires the following additional Lab Test Types to be recorded when Passing: ',
'thing2 (ug/g) [Phase 1]',
' ',
'thing3 (pass/fail) [Phase 1]',
' ',
"thing4 (pass/fail) [Phase 1]",
' ',
"thing5 (pass/fail) [Phase 1]"."}'
]
```
**Questions:**
* How do I peel off the initial `{"Message...` element?, all the spaces (`' '`) and the last `."}` so that whats left is only an array with the `things`?
**EDIT 1:**
* I should have been clearer in the sample. `thing1, thing2, thingN` could be **any** string; in reality they are dissimilar words.
* @anubhava's solution got me the closest.
* Its unclear to me why I need to surround `message_string` with `r''' ... '''`. Will have to reasearch as I've not come across this syntax before in working with Python.
* I will likely need a negative lookahead to eliminate `thing1` from the results. | 2020/11/23 | [
"https://Stackoverflow.com/questions/64975361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5976033/"
] | It's called [Event Bubbling in JavaScript and Event Propagation](https://www.sitepoint.com/event-bubbling-javascript/). Please check it out. So what happens is, the event is passed to the parents, something like this:
[](https://i.stack.imgur.com/4zoRd.png)
And here's an animation:
[](https://i.stack.imgur.com/ovQaE.gif)
The bubbling affects all the elements upto the parent, which is body. Here you have the event target, which will contain the element that this event is triggered from. In your case, it could be the clicked `TD` or `INPUT` or `LABEL`.
You can also read more about this on [Event Handling](https://marina-ferreira.github.io/javascript30/exercises/25_event-handling/).
**Stopping the bubbling**
You can stop the propagation of event from the triggered element to the above parent or child by using either of the below based on the scenario:
```
event.stopPropagation();
event.stopImmediatePropagation();
```
To know more about the differences, please check out [stopPropagation vs. stopImmediatePropagation](https://stackoverflow.com/q/5299740). | You can prevent this by calling `event.stopPropagation();`, this happens because the click event propagates through the DOM tree triggering the click event of parent elements. |
39,500,181 | I am getting the E488 error in gvim. My `.vimrc` file starts as follows
```
set guifont=Courier\ 10 Pitch\ 16
set backspace=2
set backspace=indent,eol,start
syntax on
``` | 2016/09/14 | [
"https://Stackoverflow.com/questions/39500181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6832927/"
] | For one, you're missing a backslash in your first command:
```
set guifont=Courier\ 10\ Pitch\ 16
```
You can use `:let` here to avoid the escaping:
```
let &guifont = 'Courier 10 Pitch 16'
```
But that should have given you a `E518: Unknown option: Pitch\ 16` instead.
In any case, Vim has given you a line number / context information. You can also recall the startup errors via `:messages`. If all else fails, comment out / remove parts of your config until you find the bad line. | Ditto for what Ingo Karkat said, but you can also use underscores in place of spaces (at least in the Win32 GUI).
Try reading through `:h guifont` and `:h E488` as well. |
22,800,800 | I need to download large audio files from a web server from within a corona sdk app, and have been looking at using `network.download()` or possibly `network.request()` for this purpose.
Because much of the user base will be in areas that have poor or intermittent network coverage, I would like to improve robustness of the download process by allowing for resuming download from where it left off if the network drops out.
From the documentation neither network.download or network.request functions seem to support this directly, but is there a way that I can use either of these functions to achieve what I'm looking for? If not, is there another technique I can use?
My app will eventually be for both **iOS and Android**, but for now I am developing the iOS version first. Therefore, I am ok with having to use a different solution for each platform if there is not an easy solution that covers both platforms. However, I would prefer not to have to use native code if possible as I don't currently have an Enterprise subscription for Corona. | 2014/04/02 | [
"https://Stackoverflow.com/questions/22800800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/213555/"
] | please replace local\_ldlibs with full path.
```
LOCAL_LDLIBS := $(LOCAL_PATH)/jniLibs/lsonivox.so \\path to the lsonivox
``` | Yes, it appears to have some problem with your path. However, the preferred way to use any pre-built 3rd party library is to use the `include $(PREBUILT_SHARED_LIBRARY)` method.
As such, I suppose this is probably mostly a duplicate of:
[NDK: How to include Prebuilt Shared Library Regardless of Architecture](https://stackoverflow.com/questions/17172153/ndk-how-to-include-prebuilt-shared-library-regardless-of-architecture)
Another really nice benefit of this method is that if the prebuilt library has any associated headers, you can set it up so that the NDK build system will propagate the include paths for you. It's super nice. |
26,231 | I need to convert a fixed price bundle to a dynamic price bundle. Does anyone have a solution that is easy to implement on bulk? | 2014/07/07 | [
"https://magento.stackexchange.com/questions/26231",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/3132/"
] | `qty_backordered` set to `NULL` means your item was in stock in requested quantity by the moment of order was placed.
Other result means you have a problem with your installation. I'd suggest disabling 3rd party extensions to test if the problem is off-core. | Something like this ?
```
$items = $order->getItems();
$hasBackorderedItems = false;
foreach($items as $item){ // loop though all items in order checking the backorder qty
if($item->getQtyBackordered() > 0){
$hasBackorderedItems = true; // order has back order item stop loop
break;
}
}
```
This is not the most efficient way |
26,231 | I need to convert a fixed price bundle to a dynamic price bundle. Does anyone have a solution that is easy to implement on bulk? | 2014/07/07 | [
"https://magento.stackexchange.com/questions/26231",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/3132/"
] | To add it to the Email:
```
app/design/frontend/default/<your_template>/template/email/order/items/order/default.phtml
```
and find this ~line 31:
```
<strong style="font-size:11px;"><?php echo $this->htmlEscape($_item->getName()) ?></strong>
```
Add the following line right after that:
```
<?php if ($_item->getQtyBackordered()): ?>
<p style="font-size: 10px;color: #CCC">
* This product is not available in the requested quantity. <?php echo
$_item->getQtyBackordered()*1 ?> of the items will be backordered.</p>
<?php endif; ?>
``` | Something like this ?
```
$items = $order->getItems();
$hasBackorderedItems = false;
foreach($items as $item){ // loop though all items in order checking the backorder qty
if($item->getQtyBackordered() > 0){
$hasBackorderedItems = true; // order has back order item stop loop
break;
}
}
```
This is not the most efficient way |
26,231 | I need to convert a fixed price bundle to a dynamic price bundle. Does anyone have a solution that is easy to implement on bulk? | 2014/07/07 | [
"https://magento.stackexchange.com/questions/26231",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/3132/"
] | To add it to the Email:
```
app/design/frontend/default/<your_template>/template/email/order/items/order/default.phtml
```
and find this ~line 31:
```
<strong style="font-size:11px;"><?php echo $this->htmlEscape($_item->getName()) ?></strong>
```
Add the following line right after that:
```
<?php if ($_item->getQtyBackordered()): ?>
<p style="font-size: 10px;color: #CCC">
* This product is not available in the requested quantity. <?php echo
$_item->getQtyBackordered()*1 ?> of the items will be backordered.</p>
<?php endif; ?>
``` | `qty_backordered` set to `NULL` means your item was in stock in requested quantity by the moment of order was placed.
Other result means you have a problem with your installation. I'd suggest disabling 3rd party extensions to test if the problem is off-core. |
26,231 | I need to convert a fixed price bundle to a dynamic price bundle. Does anyone have a solution that is easy to implement on bulk? | 2014/07/07 | [
"https://magento.stackexchange.com/questions/26231",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/3132/"
] | `qty_backordered` set to `NULL` means your item was in stock in requested quantity by the moment of order was placed.
Other result means you have a problem with your installation. I'd suggest disabling 3rd party extensions to test if the problem is off-core. | We just ran into the same problem as the topic starter.
But we work with configurable products, and I just figured out the qty\_backordered field is set to the child order\_item (simples) only. The problem is that in the emails the items displayed are the parent order\_items (configurables) which have indeed the qty\_backordered set to NULL.
So we fixed this as follows in the email template:
```
<?php
$itemQtyBackordered = intval($_item->getQtyBackordered());
$childQtyBackordered = 0;
if ($itemQtyBackordered === 0) // if no qty backordered found on item, check if the child item has it
{
$childOrderItems = Mage::getModel('sales/order_item')->getCollection()->addAttributeToFilter('parent_item_id', array('eq' => $_item->getItemId()));
if ($childOrderItems->count() > 0)
{
$child = $childOrderItems->getFirstItem();
$childQtyBackordered = intval($child->getQtyBackordered());
}
}
?>
<?php if ($itemQtyBackordered > 0 || $childQtyBackordered > 0): ?>
<p>your message</p>
<?php endif; ?>
``` |
26,231 | I need to convert a fixed price bundle to a dynamic price bundle. Does anyone have a solution that is easy to implement on bulk? | 2014/07/07 | [
"https://magento.stackexchange.com/questions/26231",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/3132/"
] | `qty_backordered` set to `NULL` means your item was in stock in requested quantity by the moment of order was placed.
Other result means you have a problem with your installation. I'd suggest disabling 3rd party extensions to test if the problem is off-core. | If using Magento 2 (tested on 2.4.3):
copy below file
>
> vendor/magento/module-sales/view/frontend/templates/email/items/order/default.phtml
>
>
>
into
>
> app/design/frontend/Vendor/theme/Magento\_Sales/templates/email/items/order/default.phtml
>
>
>
After `<p class="sku"><?= $block->escapeHtml(__('SKU')) ?>: <?= $block->escapeHtml($block->getSku($_item)) ?></p>`
Add below code:
```
<?php if ($_item->getQtyBackordered()): ?>
<p style="font-size: 12px;">Please note that requested quantity is not in stock, this item has
been bckordered.</p>
<?php elseif ($_item->getHasChildren()):
foreach ($_item->getChildrenItems() as $child) {
if ($child->getQtyBackordered()) { ?>
<p style="font-size: 12px;">Please note that requested quantity is not in stock, this
item has been bckordered.</p>
<?php }
}
endif;
?>
```
This code works with simple products and configurable products. It should work with Grouped products as well but not been tested. |
26,231 | I need to convert a fixed price bundle to a dynamic price bundle. Does anyone have a solution that is easy to implement on bulk? | 2014/07/07 | [
"https://magento.stackexchange.com/questions/26231",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/3132/"
] | To add it to the Email:
```
app/design/frontend/default/<your_template>/template/email/order/items/order/default.phtml
```
and find this ~line 31:
```
<strong style="font-size:11px;"><?php echo $this->htmlEscape($_item->getName()) ?></strong>
```
Add the following line right after that:
```
<?php if ($_item->getQtyBackordered()): ?>
<p style="font-size: 10px;color: #CCC">
* This product is not available in the requested quantity. <?php echo
$_item->getQtyBackordered()*1 ?> of the items will be backordered.</p>
<?php endif; ?>
``` | We just ran into the same problem as the topic starter.
But we work with configurable products, and I just figured out the qty\_backordered field is set to the child order\_item (simples) only. The problem is that in the emails the items displayed are the parent order\_items (configurables) which have indeed the qty\_backordered set to NULL.
So we fixed this as follows in the email template:
```
<?php
$itemQtyBackordered = intval($_item->getQtyBackordered());
$childQtyBackordered = 0;
if ($itemQtyBackordered === 0) // if no qty backordered found on item, check if the child item has it
{
$childOrderItems = Mage::getModel('sales/order_item')->getCollection()->addAttributeToFilter('parent_item_id', array('eq' => $_item->getItemId()));
if ($childOrderItems->count() > 0)
{
$child = $childOrderItems->getFirstItem();
$childQtyBackordered = intval($child->getQtyBackordered());
}
}
?>
<?php if ($itemQtyBackordered > 0 || $childQtyBackordered > 0): ?>
<p>your message</p>
<?php endif; ?>
``` |
26,231 | I need to convert a fixed price bundle to a dynamic price bundle. Does anyone have a solution that is easy to implement on bulk? | 2014/07/07 | [
"https://magento.stackexchange.com/questions/26231",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/3132/"
] | To add it to the Email:
```
app/design/frontend/default/<your_template>/template/email/order/items/order/default.phtml
```
and find this ~line 31:
```
<strong style="font-size:11px;"><?php echo $this->htmlEscape($_item->getName()) ?></strong>
```
Add the following line right after that:
```
<?php if ($_item->getQtyBackordered()): ?>
<p style="font-size: 10px;color: #CCC">
* This product is not available in the requested quantity. <?php echo
$_item->getQtyBackordered()*1 ?> of the items will be backordered.</p>
<?php endif; ?>
``` | If using Magento 2 (tested on 2.4.3):
copy below file
>
> vendor/magento/module-sales/view/frontend/templates/email/items/order/default.phtml
>
>
>
into
>
> app/design/frontend/Vendor/theme/Magento\_Sales/templates/email/items/order/default.phtml
>
>
>
After `<p class="sku"><?= $block->escapeHtml(__('SKU')) ?>: <?= $block->escapeHtml($block->getSku($_item)) ?></p>`
Add below code:
```
<?php if ($_item->getQtyBackordered()): ?>
<p style="font-size: 12px;">Please note that requested quantity is not in stock, this item has
been bckordered.</p>
<?php elseif ($_item->getHasChildren()):
foreach ($_item->getChildrenItems() as $child) {
if ($child->getQtyBackordered()) { ?>
<p style="font-size: 12px;">Please note that requested quantity is not in stock, this
item has been bckordered.</p>
<?php }
}
endif;
?>
```
This code works with simple products and configurable products. It should work with Grouped products as well but not been tested. |
41,049,602 | I am experiencing an issue with a Quad Tree implementation I am working on in C#. In the file Tree.cs, the following line will cause a Stack Overflow Exception, starting consistently around 50 objects in the tree (probably enough to cause the first branch of the bottom right quad):
```
else
{
//bottom right
TreeList[3].PushB(b);
return;
}
```
For some reason it seems that, when I allow this code to be called, it creates an infinite loop, hence the `Stack Overflow Exception`. I am not seeing why this would cause an infinite recursion while the others don't.
Here's the code. Ball.cs and Tree.cs both reside in a Classes folder.
**Ball.cs:**
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuadTree.Classes
{
class Ball
{
protected int x, y, r;
protected decimal vx, vy;
public static int min_w = 0,
max_w = 200,
min_h = 0,
max_h = 200;
//treating origin as top-left of screen
public Ball(int set_x = 1, int set_y = 1, decimal set_vx = 1, decimal set_vy = 1, int set_r = 1)
{
x = set_x;
y = set_y;
vx = set_vx;
vy = set_vy;
r = set_r;
}
public int get_x()
{
return x;
}
public int get_y()
{
return y;
}
public void Print()
{
Console.WriteLine("x: {0} y: {1} vx: {2} vy: {3} r: {4}", x, y, vx, vy, r);
}
//get the y-intercept of the current ball
protected decimal getB()
{
return (decimal)y - ((vy / vx) * (decimal)x);
}
//get the y-intercept given an x, y, and slope
public decimal getB(int x, int y, decimal m)
{
return (decimal)y - (m * (decimal)x);
}
//get the slop of the line that goes through both balls
protected decimal getM(Ball b)
{
return getM(y, b.y, x, b.x);
}
//get the slop of the line going through two points
public decimal getM(int y1, int y2, int x1, int x2)
{
if (x1 - x2 == 0)
{
return 0;
}
else
{
return ((decimal)(y1 - y2)) / ((decimal)(x1 - x2));
}
}
public void Move()
{
x += (int)vx;
y += (int)vy;
if (x > max_w)
{
vx *= -1;
x = x - (x - max_w);
}
else if (x < min_w)
{
vx *= -1;
x *= -1; //won't work if min_w != 0
}
if(y > max_h)
{
vy *= -1;
y = y - (y - max_h);
}
else if (y < min_h)
{
vy *= -1;
y *= -1; //won't work if min_h !=0
}
}
//detect if the current ball collides with the given ball
public void Collide(Ball b)
{
decimal d;
d = (decimal)Math.Sqrt(Math.Pow((x - b.x), 2) + Math.Pow((y - b.y), 2));
if (d<= r || d <= b.r)
{
ResolveCollision(b);
}
return;
}
//determine the resulting vectors after the collision
private void ResolveCollision(Ball b)
{
//get the line between the center points
decimal M;
M = getM(b);
//determine angle between the line and ball a
double theta_1;
if (b.vx != 0)
{
double top = (double)((M - (b.vy / b.vx)));
double bottom = (double)(1 + (M * (b.vy / b.vx)));
if (bottom != 0)
{
theta_1 = Math.Atan(top / bottom);
}
else
{
theta_1 = 0;
}
}
else
{
if (1 + M != 0)
{
theta_1 = Math.Atan((double)(M / (1 + M)));
}
else
{
theta_1 = 0;
}
}
theta_1 = theta_1 * (Math.PI / 180);
//calculate new vx and vy for ball a
//http://www.gamefromscratch.com/post/2012/11/24/GameDev-math-recipes-Rotating-one-point-around-another-point.aspx
double new_vx, new_vy;
new_vx = Math.Cos(theta_1) * (double)(vx) - Math.Sin(theta_1) * (double)(vy) + x;
new_vy = Math.Sin(theta_1) * (double)(vx) + Math.Cos(theta_1) * (double)(vy) + y;
vx = (decimal)new_vx - x;
vy = (decimal)new_vy - y;
//determine angle between the line and ball b
if (b.vx != 0)
{
double top = (double)((M - (b.vy / b.vx)));
double bottom = (double)(1 + (M * (b.vy / b.vx)));
if (bottom != 0)
{
theta_1 = Math.Atan(top / bottom);
}
else
{
theta_1 = 0;
}
}
else
{
if (1 + M != 0)
{
theta_1 = Math.Atan((double)(M / (1 + M)));
}
else
{
theta_1 = 0;
}
}
theta_1 = theta_1 * (Math.PI / 180);
//calculate new vx and vy for ball a
new_vx = Math.Cos(theta_1) * (double)(b.vx) - Math.Sin(theta_1) * (double)(b.vy) + b.x;
new_vy = Math.Sin(theta_1) * (double)(b.vx) + Math.Cos(theta_1) * (double)(b.vy) + b.y;
b.vx = (decimal)new_vx - x;
b.vy = (decimal)new_vy - y;
}
}
}
```
**Tree.cs**
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuadTree.Classes
{
class Tree //: IDisposable
{
protected int min_w,
max_w,
min_h,
max_h,
thresh_hold, level;
bool leaf = true;
protected List<Ball> BallList = new List<Ball>();
protected List<Tree> TreeList = new List<Tree>();
public Tree(int set_min_w, int set_max_w, int set_min_h, int set_max_h, int set_thresh_hold, int set_level)
{
min_w = set_min_w;
max_w = set_max_w;
min_h = set_min_h;
max_h = set_max_h;
thresh_hold = set_thresh_hold;
level = set_level;
}
//push a ball onto the tree
public void PushB(Ball b)
{
if(leaf)
{
BallList.Add(b);
if (BallList.Count > thresh_hold)
{
Branch();
}
}
else
{
LeafPush(b); //push the ball to a leaf node
}
return;
}
//push a ball onto a leaf of the current node
protected void LeafPush(Ball b)
{
if (b.get_x() <= max_w / 2)
{
//left
if (b.get_y() <= max_h / 2)
{
//top left
TreeList[0].PushB(b);
return;
}
else
{
//bottom left
TreeList[2].PushB(b);
return;
}
}
else
{
//right
if (b.get_y() <= max_h / 2)
{
//top right
TreeList[1].PushB(b);
return;
}
else
{
//bottom right
TreeList[3].PushB(b);
return;
}
}
}
private void Branch()
{
Console.WriteLine("Branching level {0}", level);
leaf = false;
TreeList.Add(new Tree(min_w, max_w / 2, min_h, max_h / 2, thresh_hold, level + 1)); //top left
TreeList.Add(new Tree((max_w / 2) + 1, max_w, min_h, max_h / 2, thresh_hold, level + 1)); //top right
TreeList.Add(new Tree(min_w, max_w / 2, (max_h / 2) + 1, max_h, thresh_hold, level + 1)); //bottom left
TreeList.Add(new Tree((max_w / 2) + 1, max_w, (max_h / 2) + 1, max_h, thresh_hold, level + 1)); //bottom right
foreach(Ball b in BallList)
{
LeafPush(b);
}
BallList.Clear();
return;
}
}
}
```
**Program.cs**
```
using QuadTree.Classes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace QuadTree
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
List<Ball> BallList = new List<Ball>();
for (int i = 0; i < 100; i++)
{
BallList.Add(new Ball(rnd.Next(Ball.min_w, Ball.max_w),
rnd.Next(Ball.min_h, Ball.max_h),
rnd.Next(1, 5),
rnd.Next(1, 5),
rnd.Next(1, 5)));
}
Tree t = new Tree(Ball.min_w, Ball.max_w, Ball.min_h, Ball.max_h, 10, 0);
foreach (Ball b in BallList)
{
b.Move();
t.PushB(b);
}
Console.ReadLine();
}
}
}
``` | 2016/12/08 | [
"https://Stackoverflow.com/questions/41049602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/95710/"
] | You need to revise the way you're creating the sub-trees. When you create the fourth sub-tree (bottom right quadrant), you're using the following numbers:
```
(max_w / 2) + 1, max_w, (max_h / 2) + 1, max_h
```
This always results in the same dimensions (101, 200, 101, 200) for the bottom right quadrant branch because you're only using the maximum numbers. This is true for the bottom right quadrant in *every subsequent branch* as well.
The program will run fine until you hit the threshold on that fourth sub-tree. It then attempts to branch, and as it branches, it sends all of it's balls into the subsequent fourth sub-tree. This will keep occurring because all of those balls have coordinates in that quadrant. That is where your infinite loop is occurring.
If you're trying to keep subdividing the quadrants, then you need to base the new dimensions off both the minimum and maximum widths and heights of the parent quadrant.
EDIT:
This code should subdivide the quadrants properly:
```
int center_w = min_w + (max_w - min_w) / 2;
int center_h = min_h + (max_h - min_h) / 2;
TreeList.Add(new Tree(min_w, center_w, min_h, center_h,
thresh_hold, level + 1)); // top left
TreeList.Add(new Tree(center_w + 1, max_w, min_h, center_h,
thresh_hold, level + 1)); //top right
TreeList.Add(new Tree(min_w, center_w, center_h + 1, max_h,
thresh_hold, level + 1)); //bottom left
TreeList.Add(new Tree(center_w + 1, max_w, center_h + 1, max_h,
thresh_hold, level + 1)); //bottom right
``` | So it seems that I needed logic to test if creating a new set of nodes would be viable. I decided I wanted a node to have a minimum width of 10, so I changed this code:
```
//push a ball onto the tree
public void PushB(Ball b)
{
if(leaf)
{
BallList.Add(b);
if (BallList.Count > thresh_hold)
{
//test if branching will produce a viable area
if ((max_w / 2) - min_w >= 10)
{
Branch();
}
}
}
else
{
LeafPush(b); //push the ball to a leaf node
}
return;
}
```
And now I no longer get the Stack Overflow Exception |
26,333,242 | I'm new to titanium and alloy framework. I have created the models to store some data. I am able to insert and retrieve the data. I don't know How to update the row.
As suggest I did as follows,
```
var userLang = Alloy.Collections.userLanguage;
var models = Alloy.createModel("userLanguage");
models.fetch({id: 1});
models.save({
languageID: langID,
languageText: lang
});
```
The above code s not showing any error, But when I try to select a row from the table,
```
var userLang = Alloy.createModel('userLanguage');
userLang.fetch({
query: {
statement: "SELECT * FROM userLanguage WHERE id = ?;",
params: [ 1 ]
}
});
alert("Updated value : "+userLang.get("languageText"));
```
**Model**
```
exports.definition = {
config : {
"columns": {
"id": "integer",
"languageID": "integer",
"languageText": "text"
},
"adapter": {
"type": "sql",
"collection_name": "userLanguage"
}
}
};
```
The selected row is not updated as expected | 2014/10/13 | [
"https://Stackoverflow.com/questions/26333242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3300593/"
] | >
> ...I need titanium query...
>
>
>
I guess that you are talking about Backbone. If so then below you can see an example how to update a model.
You can find more informations here: <http://docs.appcelerator.com/titanium/latest/#!/guide/Alloy_Sync_Adapters_and_Migrations>
```
var model = Alloy.createModel("userLanguage");
model.fetch({id: 1});
model.save({
languageID: langID,
languageText: lang
});
``` | to update a model you should first get it from the collection
```
var userLang = Alloy.Collections.userLanguage;
userLang.fetch();
var langModel=userLang.get({
id:1
});
```
then use set to modify model's properties
```
langModel.set({
languageText:'new value'
});
```
then save it
```
langModel.save();
```
You should not update the id if you put it as the primary key ...
You should fetch data before getting any model & after updating them that's it. |
57,241,008 | I have a scenario wherein I check the value of SharePreferences based on the value it will redirect the user to HomePage or LandingPage. I am not sure where did I got wrong? but I am getting this error below: I guess its not getting the context right any idea how do I get it?.
>
> Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.
> E/flutter (11533): The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
>
>
>
Here is my code:
```
import 'package:credit/src/pages/landing.dart';
import 'package:flutter/material.dart';
import 'package:credit/src/pages/credit/home.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
_LoadingPageState createState() => _LoadingPageState();
}
class _LoadingPageState extends State<MyApp> {
@override
void initState() {
super.initState();
getUserStatus().then((userStatus) {
if (userStatus == null) {
Navigator.of(context)
.push(MaterialPageRoute<Null>(builder: (BuildContext context) {
return LandingPage();
}));
} else {
Navigator.of(context)
.push(MaterialPageRoute<Null>(builder: (BuildContext context) {
return HomePage();
}));
}
});
}
@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: CircularProgressIndicator(),
));
}
}
Future<String> getUserStatus() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String userStatus = prefs.getString('userstatus');
print("==On Load Check ==");
print(userStatus);
return userStatus;
}
``` | 2019/07/28 | [
"https://Stackoverflow.com/questions/57241008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5232341/"
] | This is how i enabled dataBinding in kotlin gradle file :
```
dataBinding {
isEnabled = true
}
```
Voila ;)
hope this help someone | EDIT: in 2019 `databinding.isEnabled = true` *was* the correct way to enable databinding.
Please now refer to the accepted solution for the right way to do this.
The problem turned out to be in my file naming. While migrating to Kotlin DSL, I had inadvertently renamed the `gradle.properties` file to `gradle.properties.kts`. After renaming the file I now have a fully functional build again! |
57,241,008 | I have a scenario wherein I check the value of SharePreferences based on the value it will redirect the user to HomePage or LandingPage. I am not sure where did I got wrong? but I am getting this error below: I guess its not getting the context right any idea how do I get it?.
>
> Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.
> E/flutter (11533): The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
>
>
>
Here is my code:
```
import 'package:credit/src/pages/landing.dart';
import 'package:flutter/material.dart';
import 'package:credit/src/pages/credit/home.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
_LoadingPageState createState() => _LoadingPageState();
}
class _LoadingPageState extends State<MyApp> {
@override
void initState() {
super.initState();
getUserStatus().then((userStatus) {
if (userStatus == null) {
Navigator.of(context)
.push(MaterialPageRoute<Null>(builder: (BuildContext context) {
return LandingPage();
}));
} else {
Navigator.of(context)
.push(MaterialPageRoute<Null>(builder: (BuildContext context) {
return HomePage();
}));
}
});
}
@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: CircularProgressIndicator(),
));
}
}
Future<String> getUserStatus() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String userStatus = prefs.getString('userstatus');
print("==On Load Check ==");
print(userStatus);
return userStatus;
}
``` | 2019/07/28 | [
"https://Stackoverflow.com/questions/57241008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5232341/"
] | ```
android {
...
buildFeatures {
dataBinding = true
}
...
```
<https://developer.android.com/studio/preview/features?hl=en> | EDIT: in 2019 `databinding.isEnabled = true` *was* the correct way to enable databinding.
Please now refer to the accepted solution for the right way to do this.
The problem turned out to be in my file naming. While migrating to Kotlin DSL, I had inadvertently renamed the `gradle.properties` file to `gradle.properties.kts`. After renaming the file I now have a fully functional build again! |
57,241,008 | I have a scenario wherein I check the value of SharePreferences based on the value it will redirect the user to HomePage or LandingPage. I am not sure where did I got wrong? but I am getting this error below: I guess its not getting the context right any idea how do I get it?.
>
> Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.
> E/flutter (11533): The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
>
>
>
Here is my code:
```
import 'package:credit/src/pages/landing.dart';
import 'package:flutter/material.dart';
import 'package:credit/src/pages/credit/home.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
_LoadingPageState createState() => _LoadingPageState();
}
class _LoadingPageState extends State<MyApp> {
@override
void initState() {
super.initState();
getUserStatus().then((userStatus) {
if (userStatus == null) {
Navigator.of(context)
.push(MaterialPageRoute<Null>(builder: (BuildContext context) {
return LandingPage();
}));
} else {
Navigator.of(context)
.push(MaterialPageRoute<Null>(builder: (BuildContext context) {
return HomePage();
}));
}
});
}
@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: CircularProgressIndicator(),
));
}
}
Future<String> getUserStatus() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String userStatus = prefs.getString('userstatus');
print("==On Load Check ==");
print(userStatus);
return userStatus;
}
``` | 2019/07/28 | [
"https://Stackoverflow.com/questions/57241008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5232341/"
] | This is how i enabled dataBinding in kotlin gradle file :
```
dataBinding {
isEnabled = true
}
```
Voila ;)
hope this help someone | and for ViewBinding you can use :
```
viewBinding.isEnabled = true
``` |
57,241,008 | I have a scenario wherein I check the value of SharePreferences based on the value it will redirect the user to HomePage or LandingPage. I am not sure where did I got wrong? but I am getting this error below: I guess its not getting the context right any idea how do I get it?.
>
> Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.
> E/flutter (11533): The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
>
>
>
Here is my code:
```
import 'package:credit/src/pages/landing.dart';
import 'package:flutter/material.dart';
import 'package:credit/src/pages/credit/home.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
_LoadingPageState createState() => _LoadingPageState();
}
class _LoadingPageState extends State<MyApp> {
@override
void initState() {
super.initState();
getUserStatus().then((userStatus) {
if (userStatus == null) {
Navigator.of(context)
.push(MaterialPageRoute<Null>(builder: (BuildContext context) {
return LandingPage();
}));
} else {
Navigator.of(context)
.push(MaterialPageRoute<Null>(builder: (BuildContext context) {
return HomePage();
}));
}
});
}
@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: CircularProgressIndicator(),
));
}
}
Future<String> getUserStatus() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String userStatus = prefs.getString('userstatus');
print("==On Load Check ==");
print(userStatus);
return userStatus;
}
``` | 2019/07/28 | [
"https://Stackoverflow.com/questions/57241008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5232341/"
] | This is how i enabled dataBinding in kotlin gradle file :
```
dataBinding {
isEnabled = true
}
```
Voila ;)
hope this help someone | You can use it like this:
```
android {
buildFeatures {
dataBinding = true
// for view binding:
// viewBinding = true
}
}
``` |
57,241,008 | I have a scenario wherein I check the value of SharePreferences based on the value it will redirect the user to HomePage or LandingPage. I am not sure where did I got wrong? but I am getting this error below: I guess its not getting the context right any idea how do I get it?.
>
> Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.
> E/flutter (11533): The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
>
>
>
Here is my code:
```
import 'package:credit/src/pages/landing.dart';
import 'package:flutter/material.dart';
import 'package:credit/src/pages/credit/home.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
_LoadingPageState createState() => _LoadingPageState();
}
class _LoadingPageState extends State<MyApp> {
@override
void initState() {
super.initState();
getUserStatus().then((userStatus) {
if (userStatus == null) {
Navigator.of(context)
.push(MaterialPageRoute<Null>(builder: (BuildContext context) {
return LandingPage();
}));
} else {
Navigator.of(context)
.push(MaterialPageRoute<Null>(builder: (BuildContext context) {
return HomePage();
}));
}
});
}
@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: CircularProgressIndicator(),
));
}
}
Future<String> getUserStatus() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String userStatus = prefs.getString('userstatus');
print("==On Load Check ==");
print(userStatus);
return userStatus;
}
``` | 2019/07/28 | [
"https://Stackoverflow.com/questions/57241008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5232341/"
] | ```
android {
...
buildFeatures {
dataBinding = true
}
...
```
<https://developer.android.com/studio/preview/features?hl=en> | and for ViewBinding you can use :
```
viewBinding.isEnabled = true
``` |
57,241,008 | I have a scenario wherein I check the value of SharePreferences based on the value it will redirect the user to HomePage or LandingPage. I am not sure where did I got wrong? but I am getting this error below: I guess its not getting the context right any idea how do I get it?.
>
> Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.
> E/flutter (11533): The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
>
>
>
Here is my code:
```
import 'package:credit/src/pages/landing.dart';
import 'package:flutter/material.dart';
import 'package:credit/src/pages/credit/home.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
_LoadingPageState createState() => _LoadingPageState();
}
class _LoadingPageState extends State<MyApp> {
@override
void initState() {
super.initState();
getUserStatus().then((userStatus) {
if (userStatus == null) {
Navigator.of(context)
.push(MaterialPageRoute<Null>(builder: (BuildContext context) {
return LandingPage();
}));
} else {
Navigator.of(context)
.push(MaterialPageRoute<Null>(builder: (BuildContext context) {
return HomePage();
}));
}
});
}
@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: CircularProgressIndicator(),
));
}
}
Future<String> getUserStatus() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String userStatus = prefs.getString('userstatus');
print("==On Load Check ==");
print(userStatus);
return userStatus;
}
``` | 2019/07/28 | [
"https://Stackoverflow.com/questions/57241008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5232341/"
] | ```
android {
...
buildFeatures {
dataBinding = true
}
...
```
<https://developer.android.com/studio/preview/features?hl=en> | You can use it like this:
```
android {
buildFeatures {
dataBinding = true
// for view binding:
// viewBinding = true
}
}
``` |
42,233,915 | Let me explain shortly. I have this encryptor in python:
It uses PyCrypto library.
```
from Crypto import Random
from Crypto.Cipher import AES
from Crypto.Util import Counter
iv = Random.new().read(8)
encryptor = AES.new(
CRYPTOGRAPHY_KEY, // 32 bytes
AES.MODE_CTR,
counter=Counter.new(64, prefix=iv),
)
```
and I want to have a decryptor for it in java.
I wrote this code but it raises `java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16 bytes long`.
```
SecretKeySpec key = new SecretKeySpec(KEY, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
```
P.S. I should mention that I'm not an experienced Java developer.
---
Update.
The problem was with initialization vector.
Special thanks to @Andy for his time.
Solution:
```
byte[] nonceAndCounter = new byte[16];
System.arraycopy(iv, 0, nonceAndCounter, 0, 8);
nonceAndCounter[15] = (byte) 1; // PyCrypto's default initial value is 1
IvParameterSpec ivSpec = new IvParameterSpec(nonceAndCounter);
``` | 2017/02/14 | [
"https://Stackoverflow.com/questions/42233915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5738705/"
] | If you are trying to use AES-256 (you are using 32 bytes key), then you need to have [Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files](http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html) installed. And this has to be installed wherever this application needs to run. If you plan to distribute this application and thus you don't have control over possible java runtimes, then you have to use other libraries (like [Bouncy Castle](https://www.bouncycastle.org/)) through their own API, not through JCE API. (i.e. using Bouncy Castle as a provider like "BC" in JCE would result in the same problem.)
**EDIT:** First you said you are getting invalid key size exception, now changed the question. For the `java.security.InvalidAlgorithmParameterException` case, the problem is AES-256 has block size of 16, not 32. 256 represents the key size, not block size. AES (128, 192, 256) always has block size of 128. Thus, the `iv` must be 16 bytes.
**EDIT 2:** Not the cause of this exception but another possible problem with your code is, where do you get the `iv` in Java? Do you generate it random as you do in Python? That would be a big mistake since you have to use the same IV during decryption to make it work. Keep this in mind. | I believe you are encountering an issue where Java expects the `IV` to be fully-formed (`16 bytes`) when using `AES/CTR/NoPadding` while Python accepts an `8 byte` *prefix* and generates its own counter in the other `64 bits` (`8 bytes`).
I have example code for cross-platform compatibility in [this answer](https://stackoverflow.com/a/41009420/70465). The relevant section is:
```
byte[] cipher_key = org.bouncycastle.util.encoders.Hex.decode("0123456789ABCDEFFEDCBA9876543210");
final int HALF_BLOCK = 64;
byte[] salt = org.bouncycastle.util.encoders.Hex.decode("0123456789ABCDEF");
byte[] nonceAndCounter = new byte[16];
System.arraycopy(salt, 0, nonceAndCounter, 0, ((int) (HALF_BLOCK / 8)));
IvParameterSpec iv = new IvParameterSpec(nonceAndCounter);
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
SecretKeySpec key = new SecretKeySpec(cipher_key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
``` |
53,333,556 | I'm trying to use JDK 11 [HttpClient](https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/package-summary.html) to make requests through a corporate proxy which requires authentication by login and password. According to JDK's [intro](https://openjdk.java.net/groups/net/httpclient/intro.html), I'm building an instance of client by means of:
```java
HttpClient httpClient = HttpClient.newBuilder()
.version(HTTP_1_1)
.proxy(ProxySelector.of(new InetSocketAddress("proxy.mycompany.com", 3128)))
.authenticator(authenticator)
.build();
```
, where `authenticator` is:
```java
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("login", "password".toCharArray());
}
};
```
And then I execute the request itself:
```java
HttpRequest outRequest = HttpRequest.newBuilder()
.version(HTTP_1_1)
.GET()
.uri(URI.create("https://httpwg.org/asset/http.svg")) // no matter which URI to request
.build();
HttpResponse<String> inResponse = httpClient.send(outRequest, BodyHandlers.ofString());
```
But instead of valid response from the target server (<https://httpwg.org>) I receive *HTTP 407 (Proxy Authentication Required)*, i.e. `HttpClient` does not use the provided `authenticator`.
I've tried various solutions mentioned [here](https://dzone.com/articles/java-11-standardized-http-client-api) and [here](https://blogs.oracle.com/wssfc/handling-proxy-server-authentication-requests-in-java) but none of them helped.
What is the correct way to make it work? | 2018/11/16 | [
"https://Stackoverflow.com/questions/53333556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3507435/"
] | You have to set the "Proxy-Authorization" header on the request.
```
HttpClient httpClient = HttpClient.newBuilder()
.version(HTTP_1_1)
.proxy(ProxySelector.of(new InetSocketAddress("proxy.mycompany.com", 3128)))
.build();
String encoded = new String(Base64.getEncoder().encode("login:password".getBytes()));
HttpRequest outRequest = HttpRequest.newBuilder()
.version(HTTP_1_1)
.GET()
.uri(URI.create("https://httpwg.org/asset/http.svg")) // no matter which URI to request
.setHeader("Proxy-Authorization", "Basic " + encoded)
.build();
``` | By default, basic authentication with the proxy is disabled when tunneling through an authenticating proxy since java 8u111.
You can re-enable it by specifying `-Djdk.http.auth.tunneling.disabledSchemes=""` on the java command line.
See the [jdk 8u111 release notes](https://www.oracle.com/technetwork/java/javase/8u111-relnotes-3124969.html) |
53,333,556 | I'm trying to use JDK 11 [HttpClient](https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/package-summary.html) to make requests through a corporate proxy which requires authentication by login and password. According to JDK's [intro](https://openjdk.java.net/groups/net/httpclient/intro.html), I'm building an instance of client by means of:
```java
HttpClient httpClient = HttpClient.newBuilder()
.version(HTTP_1_1)
.proxy(ProxySelector.of(new InetSocketAddress("proxy.mycompany.com", 3128)))
.authenticator(authenticator)
.build();
```
, where `authenticator` is:
```java
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("login", "password".toCharArray());
}
};
```
And then I execute the request itself:
```java
HttpRequest outRequest = HttpRequest.newBuilder()
.version(HTTP_1_1)
.GET()
.uri(URI.create("https://httpwg.org/asset/http.svg")) // no matter which URI to request
.build();
HttpResponse<String> inResponse = httpClient.send(outRequest, BodyHandlers.ofString());
```
But instead of valid response from the target server (<https://httpwg.org>) I receive *HTTP 407 (Proxy Authentication Required)*, i.e. `HttpClient` does not use the provided `authenticator`.
I've tried various solutions mentioned [here](https://dzone.com/articles/java-11-standardized-http-client-api) and [here](https://blogs.oracle.com/wssfc/handling-proxy-server-authentication-requests-in-java) but none of them helped.
What is the correct way to make it work? | 2018/11/16 | [
"https://Stackoverflow.com/questions/53333556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3507435/"
] | By default, basic authentication with the proxy is disabled when tunneling through an authenticating proxy since java 8u111.
You can re-enable it by specifying `-Djdk.http.auth.tunneling.disabledSchemes=""` on the java command line.
See the [jdk 8u111 release notes](https://www.oracle.com/technetwork/java/javase/8u111-relnotes-3124969.html) | Use
```
System.setProperty("jdk.http.auth.proxying.disabledSchemes", "");
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
```
Construct your http client with proxy selector and authenticator
```
HttpClient client = HttpClient.newBuilder()
.authenticator(yourCustomAuthenticator)
.proxy(yourCustomProxySelector)
.build();
```
In your Authenticator override
```
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType().equals(RequestorType.PROXY)) {
return getPasswordAuthentication(getRequestingHost());
} else {
return null;
}
}
protected PasswordAuthentication getPasswordAuthentication(String proxyHost) {
// your logic to find username and password for proxyHost
return new PasswordAuthentication(proxyUsername, proxyPassword.toCharArray());
// or return null
}
``` |
53,333,556 | I'm trying to use JDK 11 [HttpClient](https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/package-summary.html) to make requests through a corporate proxy which requires authentication by login and password. According to JDK's [intro](https://openjdk.java.net/groups/net/httpclient/intro.html), I'm building an instance of client by means of:
```java
HttpClient httpClient = HttpClient.newBuilder()
.version(HTTP_1_1)
.proxy(ProxySelector.of(new InetSocketAddress("proxy.mycompany.com", 3128)))
.authenticator(authenticator)
.build();
```
, where `authenticator` is:
```java
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("login", "password".toCharArray());
}
};
```
And then I execute the request itself:
```java
HttpRequest outRequest = HttpRequest.newBuilder()
.version(HTTP_1_1)
.GET()
.uri(URI.create("https://httpwg.org/asset/http.svg")) // no matter which URI to request
.build();
HttpResponse<String> inResponse = httpClient.send(outRequest, BodyHandlers.ofString());
```
But instead of valid response from the target server (<https://httpwg.org>) I receive *HTTP 407 (Proxy Authentication Required)*, i.e. `HttpClient` does not use the provided `authenticator`.
I've tried various solutions mentioned [here](https://dzone.com/articles/java-11-standardized-http-client-api) and [here](https://blogs.oracle.com/wssfc/handling-proxy-server-authentication-requests-in-java) but none of them helped.
What is the correct way to make it work? | 2018/11/16 | [
"https://Stackoverflow.com/questions/53333556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3507435/"
] | You have to set the "Proxy-Authorization" header on the request.
```
HttpClient httpClient = HttpClient.newBuilder()
.version(HTTP_1_1)
.proxy(ProxySelector.of(new InetSocketAddress("proxy.mycompany.com", 3128)))
.build();
String encoded = new String(Base64.getEncoder().encode("login:password".getBytes()));
HttpRequest outRequest = HttpRequest.newBuilder()
.version(HTTP_1_1)
.GET()
.uri(URI.create("https://httpwg.org/asset/http.svg")) // no matter which URI to request
.setHeader("Proxy-Authorization", "Basic " + encoded)
.build();
``` | Use
```
System.setProperty("jdk.http.auth.proxying.disabledSchemes", "");
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
```
Construct your http client with proxy selector and authenticator
```
HttpClient client = HttpClient.newBuilder()
.authenticator(yourCustomAuthenticator)
.proxy(yourCustomProxySelector)
.build();
```
In your Authenticator override
```
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType().equals(RequestorType.PROXY)) {
return getPasswordAuthentication(getRequestingHost());
} else {
return null;
}
}
protected PasswordAuthentication getPasswordAuthentication(String proxyHost) {
// your logic to find username and password for proxyHost
return new PasswordAuthentication(proxyUsername, proxyPassword.toCharArray());
// or return null
}
``` |
13,276,147 | I have a program and once the is button clicked I want a message to appear that will tell user that the computer is rebooting (with ok/cancel option), then the computer will reboot. Yet the kicker is, I want it to reboot into safe mode. Then when the user is logged into safe mode, it will automatically start a program on startup.
Now I realize that this is possible by programmatically editing boot.ini with /safemode, task to start program once computer logs in,then telling the computer to reboot.However, the end user is assumed to have not enough knowledge of Windows to reverse these settings manually.
What I want is, after the end user is done with the program in Windows Safe Mode, they can simply reboot the computer and resume using Windows with out manually changing any settings to the way they were before booting into safe mode.
NOTE\* the program that will run in safe mode, has been tested to work in safe mode. I just need to know how to get the end user to safe mode and run the program automatically with out the end user having any knowledge of how to reverse these settings.
Could anyone suggest a method to execute all this madness? An example in C# or vb.net would be great!
Thank you in advance!
Ben | 2012/11/07 | [
"https://Stackoverflow.com/questions/13276147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1786775/"
] | You can call a process that runs this command
```
bcdedit /set {current} safeboot Minimal
```
then make your application a windows service and add a registry key with the name of the service to
>
> HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Control\SafeBoot\Minimal\Your
> Service Name
>
>
> | You can reset the safeboot parameter by putting a value in the registry at, `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce`
and it will run once the user reboots into safe mode
I'm not sure about this part, but I use this in a batch file to reset the bcdedit value, so it may, or may not work with your program.
```
/v "*UndoSB" /t REG_SZ /d "bcdedit /deletevalue {current} safeboot"`
```
Original bat command:
```
bcdedit /set {current} safeboot network
REG ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce /v "*UndoSB" /t REG_SZ /d "bcdedit /deletevalue {current} safeboot"
SHUTDOWN -r -f -t 07
``` |
23,850,698 | I am an error in my view:
```
undefined method `each' for nil:NilClass
<tbody>
<% @invoices.each do |invoice| %>
<tr>
<td><%= invoice.invoiceDate%></td>
<td><%= invoice.invoiceNumber %></td>
```
Here is my invoice controller index:
```
def index
@invoices = Invoice.all
end
```
Most posts I've seen about this error are because `@invoices` isn't declared correctly, unlike mine. Anyone have any ideas what else might be wrong??
Thanks!! | 2014/05/24 | [
"https://Stackoverflow.com/questions/23850698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1547174/"
] | Since you're using `@invoices` in your show view, you need to actually set `@invoices` in your `show` method, rather than your `index` method. So, add the following code to your controller, and you should be all set.
```
def show
@invoices = Invoice.all
end
``` | >
> that belong to that task order
>
>
>
You'll be best doing that like this:
```
#config/routes.rb
resources :task_orders
#app/controllers/task_orders_controller.rb
Class TaskOrdersController < ApplicationController
def show
@task_order = TaskOrder.find params[:id]
@invoices = @task_order.invoices
end
end
#app/views/task_orders/show.html.erb
<% for invoice in @invoices do %>
<%= invoice.something %>
<% end %>
``` |
80,923 | I'm working an a very large scale projects, where the compilation time is **very** long. What tools can I use (preferably open source) on Linux, to find the most heavily included files and that optimize their useages?
Just to be clearer, I need a tool which will, given the dependencies, show me which headers are the most included. By the way, we do use distributed compiling | 2008/09/17 | [
"https://Stackoverflow.com/questions/80923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12371/"
] | From the root level of the source tree and do the following (\t is the tab character):
```
find . -exec grep '[ \t]*#include[ \t][ \t]*["<][^">][">]' {} ';'
| sed 's/^[ \t]*#include[ \t][ \t]*["<]//'
| sed 's/[">].*$//'
| sort
| uniq -c
| sort -r -k1 -n
```
Line 1 get all the include lines.
Line 2 strips off everything before the actual filename.
Line 3 strips off the end of the line, leaving only the filename.
Line 4 and 5 counts each unique line.
Line 6 sorts by line count in reverse order. | If you wish to know which files are included most of all, use this bash command:
>
> find . -name '*.cpp' -exec egrep '^[:space:]*#include[[:space:]]+["<][[:alpha:][:digit:]\_.]+[">]' {} \;
>
>
>
> >
> > | sort | uniq -c | sort -k 1rn,1
> >
> > | head -20
> >
> >
> >
>
>
>
It will display top 20 files ranked by amount of times they were included.
Explanation: The 1st line finds all \*.cpp files and extract lines with "#include" directive from it. The 2nd line calculates how many times each file was included and the 3rd line takes 20 mostly included files. |
80,923 | I'm working an a very large scale projects, where the compilation time is **very** long. What tools can I use (preferably open source) on Linux, to find the most heavily included files and that optimize their useages?
Just to be clearer, I need a tool which will, given the dependencies, show me which headers are the most included. By the way, we do use distributed compiling | 2008/09/17 | [
"https://Stackoverflow.com/questions/80923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12371/"
] | Use [ccache](http://ccache.samba.org/). It will hash the inputs to a compilation, and cache the results, which will drastically increase the speed of these sorts of compiles.
If you wanted to detect the multiple includes, so that you could remove them, you could use makedepend as Iulian Șerbănoiu suggests:
```
makedepend -m *.c -f - > /dev/null
```
will give a warning for each multiple include. | IIRC gcc could create dependency files. |
80,923 | I'm working an a very large scale projects, where the compilation time is **very** long. What tools can I use (preferably open source) on Linux, to find the most heavily included files and that optimize their useages?
Just to be clearer, I need a tool which will, given the dependencies, show me which headers are the most included. By the way, we do use distributed compiling | 2008/09/17 | [
"https://Stackoverflow.com/questions/80923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12371/"
] | Using the Unix philosophy of "gluing together many small tools" I'd suggest writing a short script that calls gcc with the -M (or -MM) and -MF (OUTFILE) options (As detailed [here](http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Preprocessor-Options.html#Preprocessor-Options)). That will generate the dependency lists for the make tool, which you can then parse easily (relative to parsing the source files directly) and extract out the required information. | Bash scripts found in the page aren't good solution. It works only on simple project. In fact, in large project, like discribe in header page, C-preprocessor (#if, #else, ...) are often used. Only good software more complex, like [makedepend](http://www.xfree86.org/current/makedepend.1.html) or [scons](http://www.scons.org/) can give good informations. gcc -E can help, but, on large project, its result analysis is a wasting time. |
80,923 | I'm working an a very large scale projects, where the compilation time is **very** long. What tools can I use (preferably open source) on Linux, to find the most heavily included files and that optimize their useages?
Just to be clearer, I need a tool which will, given the dependencies, show me which headers are the most included. By the way, we do use distributed compiling | 2008/09/17 | [
"https://Stackoverflow.com/questions/80923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12371/"
] | If you wish to know which files are included most of all, use this bash command:
>
> find . -name '*.cpp' -exec egrep '^[:space:]*#include[[:space:]]+["<][[:alpha:][:digit:]\_.]+[">]' {} \;
>
>
>
> >
> > | sort | uniq -c | sort -k 1rn,1
> >
> > | head -20
> >
> >
> >
>
>
>
It will display top 20 files ranked by amount of times they were included.
Explanation: The 1st line finds all \*.cpp files and extract lines with "#include" directive from it. The 2nd line calculates how many times each file was included and the 3rd line takes 20 mostly included files. | This is not exactly what you are searchng for, and it might not be easy to setup, but may be you could have a look at lxr : lxr.linux.no is a browseable kernel tree.
In the search box, if you enter a filename, it will give you where it is included.
But this is still guessing, and it does not track chained dependencies.
Maybe
```
strace -e trace=open -o outfile make
grep 'some handy regex to match header'
``` |
80,923 | I'm working an a very large scale projects, where the compilation time is **very** long. What tools can I use (preferably open source) on Linux, to find the most heavily included files and that optimize their useages?
Just to be clearer, I need a tool which will, given the dependencies, show me which headers are the most included. By the way, we do use distributed compiling | 2008/09/17 | [
"https://Stackoverflow.com/questions/80923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12371/"
] | The answers [here](https://stackoverflow.com/questions/42308/tool-to-track-include-dependencies) will give you tools which track #include dependencies. But there's no mention of optimization and such.
Aside: The book "Large Scale C++ Software Design" should help. | You might want to look at distributed compiling, see for example [distcc](http://distcc.samba.org/) |
80,923 | I'm working an a very large scale projects, where the compilation time is **very** long. What tools can I use (preferably open source) on Linux, to find the most heavily included files and that optimize their useages?
Just to be clearer, I need a tool which will, given the dependencies, show me which headers are the most included. By the way, we do use distributed compiling | 2008/09/17 | [
"https://Stackoverflow.com/questions/80923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12371/"
] | If you wish to know which files are included most of all, use this bash command:
>
> find . -name '*.cpp' -exec egrep '^[:space:]*#include[[:space:]]+["<][[:alpha:][:digit:]\_.]+[">]' {} \;
>
>
>
> >
> > | sort | uniq -c | sort -k 1rn,1
> >
> > | head -20
> >
> >
> >
>
>
>
It will display top 20 files ranked by amount of times they were included.
Explanation: The 1st line finds all \*.cpp files and extract lines with "#include" directive from it. The 2nd line calculates how many times each file was included and the 3rd line takes 20 mostly included files. | IIRC gcc could create dependency files. |
80,923 | I'm working an a very large scale projects, where the compilation time is **very** long. What tools can I use (preferably open source) on Linux, to find the most heavily included files and that optimize their useages?
Just to be clearer, I need a tool which will, given the dependencies, show me which headers are the most included. By the way, we do use distributed compiling | 2008/09/17 | [
"https://Stackoverflow.com/questions/80923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12371/"
] | Tools like [doxygen](http://www.doxygen.org) (used with the graphviz options) can generate dependency graphs for include files... I don't know if they'd provide enough overview for what you're trying to do, but it could be worth trying. | IIRC gcc could create dependency files. |
80,923 | I'm working an a very large scale projects, where the compilation time is **very** long. What tools can I use (preferably open source) on Linux, to find the most heavily included files and that optimize their useages?
Just to be clearer, I need a tool which will, given the dependencies, show me which headers are the most included. By the way, we do use distributed compiling | 2008/09/17 | [
"https://Stackoverflow.com/questions/80923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12371/"
] | Bash scripts found in the page aren't good solution. It works only on simple project. In fact, in large project, like discribe in header page, C-preprocessor (#if, #else, ...) are often used. Only good software more complex, like [makedepend](http://www.xfree86.org/current/makedepend.1.html) or [scons](http://www.scons.org/) can give good informations. gcc -E can help, but, on large project, its result analysis is a wasting time. | IIRC gcc could create dependency files. |
80,923 | I'm working an a very large scale projects, where the compilation time is **very** long. What tools can I use (preferably open source) on Linux, to find the most heavily included files and that optimize their useages?
Just to be clearer, I need a tool which will, given the dependencies, show me which headers are the most included. By the way, we do use distributed compiling | 2008/09/17 | [
"https://Stackoverflow.com/questions/80923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12371/"
] | Using the Unix philosophy of "gluing together many small tools" I'd suggest writing a short script that calls gcc with the -M (or -MM) and -MF (OUTFILE) options (As detailed [here](http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Preprocessor-Options.html#Preprocessor-Options)). That will generate the dependency lists for the make tool, which you can then parse easily (relative to parsing the source files directly) and extract out the required information. | If you wish to know which files are included most of all, use this bash command:
>
> find . -name '*.cpp' -exec egrep '^[:space:]*#include[[:space:]]+["<][[:alpha:][:digit:]\_.]+[">]' {} \;
>
>
>
> >
> > | sort | uniq -c | sort -k 1rn,1
> >
> > | head -20
> >
> >
> >
>
>
>
It will display top 20 files ranked by amount of times they were included.
Explanation: The 1st line finds all \*.cpp files and extract lines with "#include" directive from it. The 2nd line calculates how many times each file was included and the 3rd line takes 20 mostly included files. |
80,923 | I'm working an a very large scale projects, where the compilation time is **very** long. What tools can I use (preferably open source) on Linux, to find the most heavily included files and that optimize their useages?
Just to be clearer, I need a tool which will, given the dependencies, show me which headers are the most included. By the way, we do use distributed compiling | 2008/09/17 | [
"https://Stackoverflow.com/questions/80923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12371/"
] | Using the Unix philosophy of "gluing together many small tools" I'd suggest writing a short script that calls gcc with the -M (or -MM) and -MF (OUTFILE) options (As detailed [here](http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Preprocessor-Options.html#Preprocessor-Options)). That will generate the dependency lists for the make tool, which you can then parse easily (relative to parsing the source files directly) and extract out the required information. | You might want to look at distributed compiling, see for example [distcc](http://distcc.samba.org/) |
14,159,851 | I've installed RestKit into Xcode and it builds fine. However, I seem to be missing at lot of classes. I am trying to add The RKRequestDelegate class as a delegate to one of my view controllers but this delegate does not exist. I'm also missing RKRequest class.
I've looked in the RestKit folder on my hard drive and I cant see them there.
Perhaps I've missed a step along the way. If anyone else has come across this it would be great to hear a solution.
Thanks
Brian | 2013/01/04 | [
"https://Stackoverflow.com/questions/14159851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260506/"
] | You probably didn't do anything wrong – it seems RestKit no longer contains RKRequestDelegate as of 0.20.0
You can compare the API docs for [0.10.3](http://restkit.org/api/0.10.3/) and [0.20.0-pre6](http://restkit.org/api/0.20.0-pre6/) to verify this.
Depending on what you wanted to use RKRequestDelegate for, you could use one of the new delegates or perhaps you could also subclass RKObjectManager (search the [RKObjectManager docs](http://restkit.org/api/0.20.0/Classes/RKObjectManager.html) for "Customization & Subclassing Notes" for examples of when that might be appropriate).
That said, I must caveat that I too am uncertain how what the "right" approach is for the problem I'm facing ([how to retry a request after re-authenticating](https://stackoverflow.com/questions/14154755/restkit-how-to-resubmit-failed-request-after-re-authenticating)) and haven't been able to find anything definitive for that in the docs. Hopefully your use case is more clear cut. | Here's a wiki about upgrading from 0.10.x to 0.20.0:
>
> <https://github.com/RestKit/RestKit/wiki/Upgrading-from-v0.10.x-to-v0.20.0>
>
>
>
As you see, really a big change.. And for `RKRequestDelegate`, as it said:
>
> The delegate protocols RKRequestDelegate and RKObjectLoaderDelegate have been removed from the project in favor of block based approaches. The most common, required methods of these protocols such as request:didLoadResponse:, request:didLoadError:, objectLoader:didLoadObjects:, and objectLoader:didLoadError: have been replaced with completion blocks on the AFHTTPRequestOperation and RKObjectRequestOperation classes. In general, these completion blocks are specified as a pair of success and failure blocks
>
>
>
seems tricky.. |
35,478,679 | Context: I have a project with some utilities to do things like data fixing. Each utility is a Java application, i.e. class with `main()` method. I want to define them as Spring Boot applications so I can use the `ApplicationRunner` and `ApplicationArguments` facility. The Spring configuration is defined via annotations in a shared configuration class. I've put a minimal example of this setup below.
Expectation: if I call `SpringApplication.run(SomeClass.class, args)` where `SomeClass` is an `ApplicationRunner`, it runs the `run()` on that class and not on any other classes that may be in the app context.
What actually happens: it calls all `ApplicationRunners` that it has in the context.
Why? I understood `SpringApplication.run(Class, String[])` to mean, "run this class" whereas it appears to mean "load an app context from this class and run anything you can find in it". How should I fix it to run only 1 class? I don't mind if my other application class isn't in the app context, because all the configuration I need is in the shared config class. But I don't want to have to edit code (e.g. add or remove annotations) according to which class I need to run.
Minimal example:
A Spring config class (shared):
```
package com.stackoverflow.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ExampleSpringConfig {
/** Some bean - just here to check that beans from this config are injected */
@Bean public FooService fooService () {
return new FooService();
}
}
```
Two application classes
```
package com.stackoverflow.example;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.annotation.Resource;
@SpringBootApplication
public class SomethingJob implements ApplicationRunner {
@Resource private FooService fooService;
public void run(ApplicationArguments args) throws Exception {
System.out.println("Doing something"); // do things with FooService here
}
public static void main(String[] args) {
SpringApplication.run(SomethingJob.class, args);
}
}
```
and another that is identical except that it prints "Doing something else".
Output:
```
[Spring Boot startup logs...]
Doing something else
Doing something
[Spring Boot shutdown logs...]
``` | 2016/02/18 | [
"https://Stackoverflow.com/questions/35478679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/587365/"
] | Firstly, only one class should be annotated with @SpringBootApplication. As you've noticed in your answer, this defines the external "main" entry point. I would recommend this is a different class to your `ApplicationRunner` classes for clarity and conceptual separation.
To only have some but not all runners run, I've done this by parsing the arguments, and quickly exiting from the runner which should not be called. e.g.
```
package com.stackoverflow.example;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.annotation.Resource;
@Component
public class SomethingJob implements ApplicationRunner {
@Resource private FooService fooService;
public void run(ApplicationArguments args) throws Exception {
if (!args.containsOption("something")) return
System.out.println("Doing something"); // do things with FooService here
}
}
```
That way you can do `java -jar myjar.jar --something` or `java -jar myjar.jar --something-else` depending which one you want to be run. | I found a workaround while experimenting with my minimal example.
`@SpringBootApplication` is just an alias for `@ComponentScan`, `@EnableAutoConfiguration` and `@Configuration`. By applying them separately, I discovered that it's the `@Configuration` annotation that causes this behaviour. If I only apply the other 2, I don't get the issue.
I guess this is because `@Configuration` means "I'm a configuration class, and any beans I define should be pulled into the context during component scan" and although this class doesn't *define* an `ApplicationRunner`, it *is* one, which has the same effect. Therefore if you have 2 such beans on the classpath, they both get pulled into the app context.
Without `@Configuration`, the bean you want to run still gets registered since it's referenced by the call to `run()`, but other `ApplicationRunner`s on the classpath don't.
This fixes my immediate problem by making sure I only have one `ApplicationRunner` in my app context. But it doesn't answer the wider question, "If I *do* have several `ApplicationRunner`s, how do I tell Spring Boot which one to run?" So I'd still appreciate any more complete answer or suggestions for a different approach. |
41,316,369 | I'm writing a function to split a string into a pointer to pointer, If separator is space, I want to split only the words that are not inside quotes. e.g `Hello world "not split"` should return
```
Hello
world
"not split"
```
somehow the function split the words inside the quotes and doesn't split words outside the quotes.
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int is_quotes(char *s)
{
int i;
int count;
i = 0;
count = 0;
while (s[i])
{
if (s[i] == '"')
count++;
i++;
}
if (count == 0)
count = 1;
return (count % 2);
}
int count_words(char *s, char sep)
{
int check;
int i;
int count;
check = 0;
if (sep == ' ')
check = 1;
i = 0;
count = 0;
while (*s && *s == sep)
++s;
if (*s)
count = 1;
while (s[i])
{
if (s[i] == sep)
{
if (!is_quotes(s + i) && check)
{
i += 2;
while (s[i] != 34 && s[i])
i++;
}
count++;
}
i++;
}
return (count);
}
char *ft_strsub(char const *s, unsigned int start, size_t len)
{
char *sub;
sub = malloc(len + 1);
if (sub)
memcpy(sub, s + start, len);
return (sub);
}
char **ft_strsplit(char const *s, char c)
{
int words;
char *start;
char **result;
int i;
words = count_words((char *)s, c);
if (!s || !c || words == 0)
return (NULL);
i = 0;
result = (char **)malloc(sizeof(char *) * (words + 1));
start = (char *)s;
while (s[i])
{
if (s[i] == c)
{
if (is_quotes((char *)s + i) == 0 && c == ' ')
{
i += 2;
while (s[i] != '"' && s[i])
i++;
i -= 1;
}
if (start != (s + i))
*(result++) = ft_strsub(start, 0, (s + i) - start);
start = (char *)(s + i) + 1;
}
++i;
}
if (start != (s + i))
*(result++) = ft_strsub(start, 0, (s + i) - start);
*result = NULL;
return (result - words);
}
int main(int argc, char **argv)
{
if (argc > 1)
{
char **s;
s = ft_strsplit(argv[1], ' ');
int i = 0;
while (s[i])
printf("%s\n", s[i++]);
}
return 0;
}
```
When I run this code with `hello world "hello hello"` I get the following
```
hello world
"hello
hello"
``` | 2016/12/24 | [
"https://Stackoverflow.com/questions/41316369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3858806/"
] | You need a state machine with two states, on quote and off quote. When you hit a quote, flip the state. When you hit a space, convert to a newline if off quote, not if on quote.
(You will quickly want to make it more elaborate to allow string escapes etc, the state machine approach scales up to that). | try this (fix and reduce)
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct token {
const char *top;
const char *end;//point to next character
} Token;
Token getToken(const char **sp, char sep){
const char *s = *sp;
const char *top, *end;
Token token = { NULL, NULL};
while(*s && *s == sep)//skip top separators
++s;
if(!*s){
*sp = s;
return token;//return null token
}
token.top = s;
while(*s && *s != sep){
if(*s == '"'){
char *p = strchr(s + 1, '"');//search end '"'
if(p)
s = p;//skip to '"'
}
++s;
}
token.end = s;
*sp = s;
return token;
}
int count_words(const char *s, char sep){
int count = 0;
Token token = getToken(&s, sep);
while(token.top != NULL){
++count;
token = getToken(&s, sep);
}
return count;
}
char *ft_strsub(Token token){
size_t len = token.end - token.top;
char *sub = malloc(len + 1);
if (sub){
memcpy(sub, token.top, len);
sub[len] = 0;
}
return sub;
}
char **ft_strsplit(const char *s, char sep){
int words;
if (!s || !sep || !(words = count_words(s, sep)))
return NULL;
char **result = malloc(sizeof(char *) * (words + 1));
if(!result){
perror("malloc");
return NULL;
}
int i = 0;
Token token = getToken(&s, sep);
while(token.top != NULL){
result[i++] = ft_strsub(token);
token = getToken(&s, sep);
}
result[i] = NULL;
return result;
}
int main(int argc, char **argv){
const char *text = "Hello world \"not split\"";
char **s = ft_strsplit(text, ' ');
int i = 0;
while (s[i]){
printf("%s\n", s[i]);
free(s[i++]);
}
free(s);
return 0;
}
```
---
Escape character processing version.
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ESCAPE '\\' //ESCAPE CHARACTER
typedef struct token {
const char *top;
const char *end;//point to next character
} Token;
Token getToken(const char **sp, char sep){
const char *s = *sp;
const char *top, *end;
Token token = { NULL, NULL};
while(*s && *s == sep)//skip top separators
++s;
if(!*s){
*sp = s;
return token;
}
token.top = s;
while(*s && *s != sep){
if(*s == ESCAPE)
++s;
else if(*s == '"'){
char *p = strchr(s + 1, '"');//search end '"'
while(p && p[-1] == ESCAPE)
p = strchr(p + 1, '"');
if(p)
s = p;
}
++s;
}
token.end = s;
*sp = s;
return token;
}
int count_words(const char *s, char sep){
int count = 0;
Token token = getToken(&s, sep);
while(token.top != NULL){
++count;
token = getToken(&s, sep);
}
return count;
}
char *remove_escape(char *s){
char *from, *to;
from = to = s;
while(*from){
if(*from != ESCAPE)
*to++ = *from;
++from;
}
*to = 0;
return s;
}
char *ft_strsub(Token token){
size_t len = token.end - token.top;
char *sub = malloc(len + 1);
if (sub){
memcpy(sub, token.top, len);
sub[len] = 0;
}
return sub;
}
char **ft_strsplit(const char *s, char sep){
int words;
if (!s || !sep || !(words = count_words(s, sep)))
return NULL;
char **result = malloc(sizeof(char *) * (words + 1));
if(!result){
perror("malloc");
return NULL;
}
Token token = getToken(&s, sep);
int i = 0;
while(token.top != NULL){
result[i] = ft_strsub(token);
remove_escape(result[i++]);
token = getToken(&s, sep);
}
result[i] = NULL;
return result;
}
void test(const char *text){
printf("original:%s\n", text);
printf("result of split:\n");
char **s = ft_strsplit(text, ' ');
int i = 0;
while (s[i]){
printf("%s\n", s[i]);
free(s[i++]);
}
free(s);
puts("");
}
int main(int argc, char **argv){
test("Hello world \"not split\"");
test("Hello world \"not \\\" split\"");//include " in "..."
test("Hello world not\\ split");//escape separator
return 0;
}
```
result:
```
original:Hello world "not split"
result of split:
Hello
world
"not split"
original:Hello world "not \" split"
result of split:
Hello
world
"not " split"
original:Hello world not\ split
result of split:
Hello
world
not split
``` |
652,251 | For some odd reason my table of contents doesn't add indentation for each subsection.
Should I recreate it or can I reformat it? 
Note: there's a lot more content than just this, so it wouldn't be a two second recreate. | 2013/09/30 | [
"https://superuser.com/questions/652251",
"https://superuser.com",
"https://superuser.com/users/257927/"
] | Figured out one way,

Using the **Increase Indent** button
However there are two cases
* Case 1: It works perfectly for the item
* Case 2: The item jumps all the way to the right side of the the Table of Contents, so you have to hit backspace at that line once, then add amount of spaces equivalent to an indent, or match it with the line above it. | The ToC field can gather information from paragraphs of particular styles and TC fields. In the ToC, you can specify the level that you want each paragraph style to appear at. If you are using TC fields, OTTOMH you can specify the level in the field. When Word generates the ToC, it applies the paragraph style TOC1 to Level 1 items, TOC to to Level 2 items, and so on. So you probably either need to fix which paragraph styles (or TC entries) are associated with which level, or fix your TOCn style definitions. |
652,251 | For some odd reason my table of contents doesn't add indentation for each subsection.
Should I recreate it or can I reformat it? 
Note: there's a lot more content than just this, so it wouldn't be a two second recreate. | 2013/09/30 | [
"https://superuser.com/questions/652251",
"https://superuser.com",
"https://superuser.com/users/257927/"
] | Figured out one way,

Using the **Increase Indent** button
However there are two cases
* Case 1: It works perfectly for the item
* Case 2: The item jumps all the way to the right side of the the Table of Contents, so you have to hit backspace at that line once, then add amount of spaces equivalent to an indent, or match it with the line above it. | You need to edit the TOC styles and fix the indentation. [This page](http://office.microsoft.com/en-nz/word-help/format-a-table-of-contents-HA102322411.aspx) on the Office help site gives a good walkthrough on how to edit the TOC styles. |
652,251 | For some odd reason my table of contents doesn't add indentation for each subsection.
Should I recreate it or can I reformat it? 
Note: there's a lot more content than just this, so it wouldn't be a two second recreate. | 2013/09/30 | [
"https://superuser.com/questions/652251",
"https://superuser.com",
"https://superuser.com/users/257927/"
] | Figured out one way,

Using the **Increase Indent** button
However there are two cases
* Case 1: It works perfectly for the item
* Case 2: The item jumps all the way to the right side of the the Table of Contents, so you have to hit backspace at that line once, then add amount of spaces equivalent to an indent, or match it with the line above it. | Try clearing the tab setting in the TOC setup and *then* using the increase indent button (in TOC setup, not the Home tab):
1. Go to References tab >> Table of Contents >> Custom Table of Contents...>> Modify >> Select to Highlight **TOC2** (or the applicable level you need to fix) >> Modify >> Format >> Tabs...>> Clear ALL>> OK
2. Back on Modify screen for TOC2 (or applicable level you need to fix): Click the Increase Indent button. |
652,251 | For some odd reason my table of contents doesn't add indentation for each subsection.
Should I recreate it or can I reformat it? 
Note: there's a lot more content than just this, so it wouldn't be a two second recreate. | 2013/09/30 | [
"https://superuser.com/questions/652251",
"https://superuser.com",
"https://superuser.com/users/257927/"
] | Figured out one way,

Using the **Increase Indent** button
However there are two cases
* Case 1: It works perfectly for the item
* Case 2: The item jumps all the way to the right side of the the Table of Contents, so you have to hit backspace at that line once, then add amount of spaces equivalent to an indent, or match it with the line above it. | Ok, I think I found the right way to do it:
* Open the “text styles” dialog via the little arrow on the bottom-right of the styles panel or `Ctrl``Alt``Shift``S`
* Scroll to the "TOC 1" to "TOC 10" styles which correspond to the different TOC levels
* Edit the corresponding style
By doing it this way, the style is kept after refreshing the TOC (as long as it was built using an automatic style). |
1,117,332 | I am running a FreeBSD server and I have been sent a warning that spam has been sent from my server. I do not have it set as an open relay and I have customized the sendmail configuration. I'd like to know who is sending what email along with their username, email subject line as well as a summary of how much mail they have been sending. I would like to run a report on a log similar to how it is done when processing Apache server logs.
What are my options? | 2009/07/13 | [
"https://Stackoverflow.com/questions/1117332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10366/"
] | One idea is to alias sendmail to be a custom script, which simply cats the sendmail arguments to the end of a log before calling sendmail in the usual manner. | Can you give some sample logs? I think you're best bet would be to look through them with either grep or cut to get the source/destinations that are being sent too. Also, you could write a Perl script to automate it once you have the correct regex. This would be the best option. |
1,117,332 | I am running a FreeBSD server and I have been sent a warning that spam has been sent from my server. I do not have it set as an open relay and I have customized the sendmail configuration. I'd like to know who is sending what email along with their username, email subject line as well as a summary of how much mail they have been sending. I would like to run a report on a log similar to how it is done when processing Apache server logs.
What are my options? | 2009/07/13 | [
"https://Stackoverflow.com/questions/1117332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10366/"
] | You can also monitor all system calls to `write` and `read` functions by executing:
```
ps auxw | grep sendmail | awk '{print"-p " $2}' | xargs strace -s 256 -f 2>&1 | grep -E $'@|(([0-9]+\.){3}[0-9]+)' | tee -a "/var/log/sendmail-logs.log"
```
This will give you direct access to the information, you cannot go deeper I think. | Can you give some sample logs? I think you're best bet would be to look through them with either grep or cut to get the source/destinations that are being sent too. Also, you could write a Perl script to automate it once you have the correct regex. This would be the best option. |
1,117,332 | I am running a FreeBSD server and I have been sent a warning that spam has been sent from my server. I do not have it set as an open relay and I have customized the sendmail configuration. I'd like to know who is sending what email along with their username, email subject line as well as a summary of how much mail they have been sending. I would like to run a report on a log similar to how it is done when processing Apache server logs.
What are my options? | 2009/07/13 | [
"https://Stackoverflow.com/questions/1117332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10366/"
] | One idea is to alias sendmail to be a custom script, which simply cats the sendmail arguments to the end of a log before calling sendmail in the usual manner. | If FreeBSD have default config, you have only one way to handle output mail, check what sending through you sendmail system in `/etc/mail`.
All output mail must be logged by `/var/log/maillog` |
1,117,332 | I am running a FreeBSD server and I have been sent a warning that spam has been sent from my server. I do not have it set as an open relay and I have customized the sendmail configuration. I'd like to know who is sending what email along with their username, email subject line as well as a summary of how much mail they have been sending. I would like to run a report on a log similar to how it is done when processing Apache server logs.
What are my options? | 2009/07/13 | [
"https://Stackoverflow.com/questions/1117332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10366/"
] | One idea is to alias sendmail to be a custom script, which simply cats the sendmail arguments to the end of a log before calling sendmail in the usual manner. | You can also monitor all system calls to `write` and `read` functions by executing:
```
ps auxw | grep sendmail | awk '{print"-p " $2}' | xargs strace -s 256 -f 2>&1 | grep -E $'@|(([0-9]+\.){3}[0-9]+)' | tee -a "/var/log/sendmail-logs.log"
```
This will give you direct access to the information, you cannot go deeper I think. |
1,117,332 | I am running a FreeBSD server and I have been sent a warning that spam has been sent from my server. I do not have it set as an open relay and I have customized the sendmail configuration. I'd like to know who is sending what email along with their username, email subject line as well as a summary of how much mail they have been sending. I would like to run a report on a log similar to how it is done when processing Apache server logs.
What are my options? | 2009/07/13 | [
"https://Stackoverflow.com/questions/1117332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10366/"
] | You can also monitor all system calls to `write` and `read` functions by executing:
```
ps auxw | grep sendmail | awk '{print"-p " $2}' | xargs strace -s 256 -f 2>&1 | grep -E $'@|(([0-9]+\.){3}[0-9]+)' | tee -a "/var/log/sendmail-logs.log"
```
This will give you direct access to the information, you cannot go deeper I think. | If FreeBSD have default config, you have only one way to handle output mail, check what sending through you sendmail system in `/etc/mail`.
All output mail must be logged by `/var/log/maillog` |
23,138,658 | I'm not sure how to search for this and hence I started a new question.
I have a table in the following structure
```
----------------------------------------
| TALKS | PERSON
----------------------------------------
| Networks | John Doe
| Steganography | Alex
| Assembly | Mark
| Networks | Mark
| Steganography | John Doe
| Networks | Mark
----------------------------------------
```
How do I perform a query so that I get
```
----------------------------------------
| TALKS | PERSON
----------------------------------------
| Networks | John Doe
| Steganography |
| Assembly | Mark
| Networks |
| Steganography | Alex
----------------------------------------
```
Note that 'Mark' has two talks on 'Networks', but it needs to return only one. | 2014/04/17 | [
"https://Stackoverflow.com/questions/23138658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750101/"
] | ```
Car lowestPrice = cars.get(0);
for(Car car : cars) {
if(car.price<lowestPrice.price) {
lowestPrice = car;
}
}
```
Concerning the red underlined ArrayList ... replace it with
```
ArrayList<Vehicles> yourlist = new ArrayList<Vehicles>();
``` | If you want to use approach you mentioned in OP you can declare `static` variable for `vehicles` class and in `contructor` you can check whether price is lower than actual minimum
**But my advice is to use `Comparator` or `Comparable` because this is their natural use. Also values of objects can be changed throughout various `set` methods and you will have to be aware of that**
If you still want to do it .You do it like this
`public static int min_price=Integer.MAX_VALUE;`
then in `contructor` method
`if(price<min_price)min_price=price;` |
23,138,658 | I'm not sure how to search for this and hence I started a new question.
I have a table in the following structure
```
----------------------------------------
| TALKS | PERSON
----------------------------------------
| Networks | John Doe
| Steganography | Alex
| Assembly | Mark
| Networks | Mark
| Steganography | John Doe
| Networks | Mark
----------------------------------------
```
How do I perform a query so that I get
```
----------------------------------------
| TALKS | PERSON
----------------------------------------
| Networks | John Doe
| Steganography |
| Assembly | Mark
| Networks |
| Steganography | Alex
----------------------------------------
```
Note that 'Mark' has two talks on 'Networks', but it needs to return only one. | 2014/04/17 | [
"https://Stackoverflow.com/questions/23138658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750101/"
] | ```
Car lowestPrice = cars.get(0);
for(Car car : cars) {
if(car.price<lowestPrice.price) {
lowestPrice = car;
}
}
```
Concerning the red underlined ArrayList ... replace it with
```
ArrayList<Vehicles> yourlist = new ArrayList<Vehicles>();
``` | As you want to sort the items of the list you can use the `Collections.sort(List<T> list, Comparator<? super T> c)` method and provide own [Comparator](http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html)
```
class VechiclePriceComparator implements Comparator<vechiles> {
public int compare(vechiles v1, vechiles v2) {
if(v1 == v2) {
return 0;
)
return Double.compare(v1.getPrice(),v2.getPrice());
}
}
``` |
23,138,658 | I'm not sure how to search for this and hence I started a new question.
I have a table in the following structure
```
----------------------------------------
| TALKS | PERSON
----------------------------------------
| Networks | John Doe
| Steganography | Alex
| Assembly | Mark
| Networks | Mark
| Steganography | John Doe
| Networks | Mark
----------------------------------------
```
How do I perform a query so that I get
```
----------------------------------------
| TALKS | PERSON
----------------------------------------
| Networks | John Doe
| Steganography |
| Assembly | Mark
| Networks |
| Steganography | Alex
----------------------------------------
```
Note that 'Mark' has two talks on 'Networks', but it needs to return only one. | 2014/04/17 | [
"https://Stackoverflow.com/questions/23138658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750101/"
] | You could use a TreeMap with the price as the key and the vehicles object as the value. It would then be sorted by price, and you would have all of the information for the vehicle as the value. | If you want to use approach you mentioned in OP you can declare `static` variable for `vehicles` class and in `contructor` you can check whether price is lower than actual minimum
**But my advice is to use `Comparator` or `Comparable` because this is their natural use. Also values of objects can be changed throughout various `set` methods and you will have to be aware of that**
If you still want to do it .You do it like this
`public static int min_price=Integer.MAX_VALUE;`
then in `contructor` method
`if(price<min_price)min_price=price;` |
23,138,658 | I'm not sure how to search for this and hence I started a new question.
I have a table in the following structure
```
----------------------------------------
| TALKS | PERSON
----------------------------------------
| Networks | John Doe
| Steganography | Alex
| Assembly | Mark
| Networks | Mark
| Steganography | John Doe
| Networks | Mark
----------------------------------------
```
How do I perform a query so that I get
```
----------------------------------------
| TALKS | PERSON
----------------------------------------
| Networks | John Doe
| Steganography |
| Assembly | Mark
| Networks |
| Steganography | Alex
----------------------------------------
```
Note that 'Mark' has two talks on 'Networks', but it needs to return only one. | 2014/04/17 | [
"https://Stackoverflow.com/questions/23138658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750101/"
] | You could use a TreeMap with the price as the key and the vehicles object as the value. It would then be sorted by price, and you would have all of the information for the vehicle as the value. | As you want to sort the items of the list you can use the `Collections.sort(List<T> list, Comparator<? super T> c)` method and provide own [Comparator](http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html)
```
class VechiclePriceComparator implements Comparator<vechiles> {
public int compare(vechiles v1, vechiles v2) {
if(v1 == v2) {
return 0;
)
return Double.compare(v1.getPrice(),v2.getPrice());
}
}
``` |
26,376,176 | In Perl, how can I get the expression of a capture that has matched in a regex?
```
$s = 'aaazzz';
$s =~ s/(a+)|(b+)|(c+)/.../;
$s =~ s/(?<one>a+)|(?<two>b+)|(?<three>c+)/.../;
```
I mean the expression (e.g. `a+`), not the string `aaa`.
I need the expression of both numbered and named captures. | 2014/10/15 | [
"https://Stackoverflow.com/questions/26376176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1461988/"
] | I'd do something like:
```
use strict;
use warnings;
my @regexes = (
qr/(a+)/,
qr/(b+)/,
qr/(c+)/,
);
my $string = 'aaazzz';
foreach my $re(@regexes) {
if ($string =~ $re) {
print "Used regex is $re\n";
}
}
```
**Output:**
```
Used regex is (?^:(a+))
``` | You could assemble your regex from components and then test which groups matched. For demo purposes, I have only used match and not match and the replace operator 's', but same principle applies.
```
$s = 'aaazzz';
$part1 = '(a+)';
if ( $s =~ /$part1|(b+)|(c+)/ ) {
if ($1) {
print("$part1 matched\n");
}
else {
print("$part1 did not match\n");
}
}
``` |
14,636,217 | Is there a Way with Javascript to add Help bubbles over an input Box?
For example when you you hover over an input for Name: ***\_*\_\_\_\_** it would say like First Name????
Thanks
An example is this <https://edit.europe.yahoo.com/registration?.intl=uk>
When you go over the name field it says First name in a bubble | 2013/01/31 | [
"https://Stackoverflow.com/questions/14636217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2011151/"
] | Do you mean the [title attribute](http://www.w3.org/TR/html401/struct/global.html#h-7.4.3)?
```
<input type="text" title="First Name" />
``` | As said in another answer you can add a title attribute to a html tag to have a tool tip display.
Or if you are after the behaviour where information is displayed somewhere on the page telling you about the text box you have selected you can; dynamically add to a div using document.createElement() and appendChild() when you [hover over the element](http://www.w3schools.com/jsref/event_onmouseover.asp) and removing it with removeChild() upon moving your mouse away or change the [innerHTML](https://developer.mozilla.org/en-US/docs/DOM/element.innerHTML) of the html tag on those two events.
**Edit:**
Unfortunately because I am a 'new' user I can't include all the hyperlinks to each part of the mozilla developer site, but simply search for those functions there for more explnation. |
78,664 | I have the ODE $$y' = y^2-4$$
I want to draw the direction field and draw the solutions that satisfy $$y(0)=-4$$ and $$y(0)=0$$ without solving the equation.
So i am writing $$y^2-4 = c$$ and then i start giving values to c in order to calculate y.
$$c = 0, y=\_{-}^{+}2$$
$$c = 1, y=\_{-}^{+}\sqrt{5}$$
$$\vdots$$
Then how am i drawing the direction field and the integral curves? | 2011/11/03 | [
"https://math.stackexchange.com/questions/78664",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/18835/"
] | You are given the equation for y' which tells you the slope of y at any point. So try picking various values of y to see what direction y should be moving. For example at t = 1, say y = 3, then y' = 5. So at the point {1, 3} you can draw a sharp upward pointing vector (arrow on vector would point to about 1 o'clock). Then repeat this for various points on your y and t plot until you have enough vectors to give you an idea of the solution plot.
If you have access to mathematica, it can do this for you :) | What riotburn said. Also, to draw the solution curves, start at the point (0, -4) and trace the path that follows the arrows. Do the same for (0, 0). |
16,053,308 | I have a vector of values such as the following:
```
1
2
3
NaN
4
7
NaN
NaN
54
5
2
7
2
NaN
NaN
NaN
5
54
3
2
NaN
NaN
NaN
NaN
4
NaN
```
How can I use
>
> interp1
>
>
>
in such way that only a variable amount of consecutive NaN-values would be interpolated? That is for example I would want to interpolate only those NaN-values where there are at most three consecutive NaN-values. So *NaN*, *NaN NaN* and *NaN NaN NaN* would be interpolated but not *NaN NaN NaN NaN*.
Thank you for any help =)
P.S. If I can't do this with interp1, any ideas how to do this in another way? =)
To give an example, the vector I gave would become:
```
1
2
3
interpolated
4
7
interpolated
interpolated
54
5
2
7
2
interpolated
interpolated
interpolated
5
54
3
2
NaN
NaN
NaN
NaN
4
interpolated
``` | 2013/04/17 | [
"https://Stackoverflow.com/questions/16053308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1565754/"
] | First of all, find the positions and lengths of all sequences of `NaN` values:
```
nan_idx = isnan(x(:))';
nan_start = strfind([0, nan_idx], [0 1]);
nan_len = strfind([nan_idx, 0], [1 0]) - nan_start + 1;
```
Next, find the indices of the `NaN` elements not to interpolate:
```
thr = 3;
nan_start = nan_start(nan_len > thr);
nan_end = nan_start + nan_len(nan_len > thr) - 1;
idx = cell2mat(arrayfun(@colon, nan_start, nan_end, 'UniformOutput', false));
```
Now, interpolate everything and replace the elements that shouldn't have been interpolated back with `NaN` values:
```
x_new = interp1(find(~nan_idx), x(~nan_idx), 1:numel(x));
x_new(idx) = NaN;
``` | I know this is an bad habit in matlab, but I would think this particular case requires a loop:
```
function out = f(v)
out = zeros(numel(v));
k = 0;
for i = 1:numel(v)
if v(i) ~= NaN
if k > 3
out(i-k:i - 1) = ones(1, k) * NaN;
else
out(i-k: i - 1) = interp1();%TODO: call interp1 with right params
end
out(i) = v(i)
k = 0
else
k = k + 1 % number of consecutive NaN value encoutered so far
end
end
``` |
42,816,538 | What im trying to do is only display records created for a customer that only has more then one ticketnumber in a certain month.
```
Select name,ticketnumber, title,
description,statename,personname,charge,createdon
from case
Where sum(ticketnumber) > 2 AND createdon >= '2017-01-01' ;
```
i have tried
```
select sum(ticketnumber) AS total
```
and
```
where sum(ticketnumber) > 2
```
Where am i going wrong? `ticketnumber` is a `varchar` data type
The error im getting;
```
Operand data type nvarchar is invalid for sum operator.
``` | 2017/03/15 | [
"https://Stackoverflow.com/questions/42816538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5152559/"
] | To limit the check to a single month, not just after some date, you can use `dateadd(month, datediff(month, 0, createdon ) , 0)` to truncate a date down to the first of a month.
Assuming you are identifying your customer by `personname`:
using `exists()`:
```
select
name
, ticketnumber
, title
, description
, statename
, personname
, charge
, createdon
from [case] as c
where dateadd(month, datediff(month, 0, createdon ) , 0) = '20170101'
and exists (
select 1
from [case] as i
where --createdon >= '2017-01-01'
dateadd(month, datediff(month, 0, createdon ) , 0) = '20170101'
and i.personname = c.personname
having count(*) > 1
)
```
using `in()`
```
select
name
, ticketnumber
, title
, description
, statename
, personname
, charge
, createdon
from [case]
where dateadd(month, datediff(month, 0, createdon ) , 0) = '20170101'
and personname in (
select personname
from [case] as i
where --createdon >= '2017-01-01'
dateadd(month, datediff(month, 0, createdon ) , 0) = '20170101'
group by personname
having count(*) > 1
)
``` | I usually just do this
```
SELECT Total from (select sum(ticketnumber) AS total from case)A
Where Total>2
``` |
6,825,686 | I am so confused. I am trying to create a tic tac toe game using windows c++ visual. So far I was doing good until I kept getting errors. I tried looking for help but none of the answers seemed right. This is my practice problem.
1. Implement displayBoard to display Tic Tac Toe board.
2. Prompt User for a box on the board to select, i.e. a number between 1 and 9 with 1 being the upper left corner.
use cin.get(box) to get the box number and isdigit to verify it is a
number;
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
If the box is available put the appropriate X or O in there and switch players, i.e. X becomes O and vice versa.
If the box is NOT available warn the user and get another box until they select a valid open box.
3. After all spots have been select Display "Game Over!";
4. Write a main function to use the TicTacToe class and test all of the above functionality.
.
```
#include<iostream>
using namespace std;
class TicTacToe {
public:
void displayBoard();
void getMove();
void playGame();
private:
char board[9];
char player; // Switch after each move.
};
int main ()
{
TicTacToe ttt;
// you need to do the following in a loop 9 times
ttt.playGame();
}
void TicTacToe::playGame()
{
getMove();
// Your implementation here...
}
void TicTacToe::displayBoard()
{
// Your implementation here...
}
void TicTacToe::getMove()
{
cout << "Enter Box: ";
char c;
cin.get(c);
if (c > '9' || c < '0')
// Error message here.
int number = c - '0';
cout << "your number is " << number;
// Your implementation here...
}
``` | 2011/07/26 | [
"https://Stackoverflow.com/questions/6825686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/862807/"
] | you need a statement to go after the if
even if its just a ;
but maybe you want
```
if (c > '9' || c < '0')
cout << "Not a Number!";
``` | Ok, so the issue here is the "if" statement. The problem is that you haven't closed the if statement. So what the compiler sees is
```
cout << "Enter box: ";
char c;
cin.get(c);
if(c > '9' || c < '0')
{
//Compiler thinks that it should only convert the character
//to a number if you got the *wrong* number
int number = c - '0';
}
//the integer number when out of scope in the if statement. So now it doesn't exist
//which means you will get a "variable not declared" error
cout << "your number is " << number;
```
When you create an if statement and you don't put braces around the block of code it should execute, then the next line after the if statement becomes the conditional statement. What you need to do is close the if statement. simply adding a semicolon is sufficient:
```
if (c > '9' || c < '0');
```
but it means you don't handle the error, which is pretty bad, so at least put an error message in the if statement to tell the user that they've made a mistake. |
6,825,686 | I am so confused. I am trying to create a tic tac toe game using windows c++ visual. So far I was doing good until I kept getting errors. I tried looking for help but none of the answers seemed right. This is my practice problem.
1. Implement displayBoard to display Tic Tac Toe board.
2. Prompt User for a box on the board to select, i.e. a number between 1 and 9 with 1 being the upper left corner.
use cin.get(box) to get the box number and isdigit to verify it is a
number;
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
If the box is available put the appropriate X or O in there and switch players, i.e. X becomes O and vice versa.
If the box is NOT available warn the user and get another box until they select a valid open box.
3. After all spots have been select Display "Game Over!";
4. Write a main function to use the TicTacToe class and test all of the above functionality.
.
```
#include<iostream>
using namespace std;
class TicTacToe {
public:
void displayBoard();
void getMove();
void playGame();
private:
char board[9];
char player; // Switch after each move.
};
int main ()
{
TicTacToe ttt;
// you need to do the following in a loop 9 times
ttt.playGame();
}
void TicTacToe::playGame()
{
getMove();
// Your implementation here...
}
void TicTacToe::displayBoard()
{
// Your implementation here...
}
void TicTacToe::getMove()
{
cout << "Enter Box: ";
char c;
cin.get(c);
if (c > '9' || c < '0')
// Error message here.
int number = c - '0';
cout << "your number is " << number;
// Your implementation here...
}
``` | 2011/07/26 | [
"https://Stackoverflow.com/questions/6825686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/862807/"
] | you need a statement to go after the if
even if its just a ;
but maybe you want
```
if (c > '9' || c < '0')
cout << "Not a Number!";
``` | ```
//Play Tic Tac Toe game between user and computer
#include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<time.h>
using namespace std;
char BLANK='B';
/***************** Display the Matrix **********************************************/
//Display the matrix
void display(char matrix[3][3])
{
for(int i=0;i<3;i++){
for(int j=0;j<3;j++)
cout<<matrix[i][j]<<"\t";
cout<<endl;
}
}
/************** Chance of WIN Function *****************************************************/
//Funtion to detect the chance of either for user or systemĵ
int chance_of_win(char matrix[3][3],int i, int j,char choice){
int result=0;//This variale is used to return the required position
char other_choice;//This variable is used for other choice of the variable choice
if(choice=='o')
other_choice='x';
else
other_choice='o';
int count1=0;//This variable is used to check the count upto 2
//Diagonal Intelligent
if(i==j){
for(int k=0;k<3;k++){
if(matrix[k][k]==choice)
count1++;
if(count1==2){ // That means user is going to win and system has to stop that
for(int k=0;k<3;k++){
if(matrix[k][k]!=choice && matrix[k][k]!=other_choice){
int temp=k;
temp=temp*10;
result=temp+k;
return result;
}
}
}
}//for looop ends here
}//If Structure ends here
count1=0; //Reinitilize the count to zero
//Reverse Diagonal intelligent
for(int m=0,n=2;m<3,n>=0;m++,n--){
if(matrix[m][n]==choice){
count1++;
}
if(count1==2){ // That means user/system is going to win reverse diagnally
for(int m=0,n=2;m<3,n>=0;m++,n--){
if(matrix[m][n]!=choice && matrix[m][n]!=other_choice){
int temp=m;
temp=temp*10;
result=temp+n;
return result;
}
}
}//End of If structure
}//End for loop
count1=0; //Reinitilize the count to zero
//Row Intelligent
for(int k=0;k<3;k++){
if(matrix[i][k]==choice)
count1++;
if(count1==2){ // That means user/system is going to win
for(int k=0;k<3;k++){
if(matrix[i][k]!=choice && matrix[i][k]!=other_choice){
int temp=i;
temp=temp*10;//for the ith coordiante
result=temp+k;//for the jth cordinate
return result;//Return the required attribute of i and j
}
}
}
}//for looop ends here
count1=0; //Reinitilize the count to zero
//Column Intelligent
for(int k=0;k<3;k++){
if(matrix[k][j]==choice)
count1++;
if(count1==2){ // That means user is going to win and system has to stop that
for(int k=0;k<3;k++){
if(matrix[k][j]!=choice && matrix[k][j]!=other_choice){
int temp=k;
temp=temp*10;//for the ith coordinate
result=temp+j;//for the jth coordinate
return result;//Return the required attribute of i and j
}
}
}
}//for looop ends here
return result;
}//function ends here
/******************* Check Win Bool Function ******************************************************/
//This function is used to check the win of the system/user
bool checkwin(char matrix[3][3],int i, int j,char choice){
bool flag=false;//Initialize the chance of win false
int count1=0;
//Diagonal checkwin forward
if(i==j){
for(int k=0;k<3;k++){
if(matrix[k][k]==choice){
count1++;
}
if(matrix[k][k]==BLANK)
break;
}
if(count1==3)//Means all diagonal elements are equal
flag=true;
}
//If the Diaganoal Forward is same then return
if(flag){
cout<<"Diagonal Win\n";
return flag;
}
//Reverse Diagonal checkwin
for(int m=0,n=2;m<3,n>=0;m++,n--){
if(matrix[m][n]!=choice || matrix[m][n]==BLANK){
flag=false;//If diagonal is not same
break;
}
flag=true;
}
//If the Reverse Diaganoal Forward is same then return
if(flag){
cout<<"Reverse Diagonal Win\n";
return flag;
}
//Row checkwin
for(int k=0;k<3;k++){
if(matrix[i][k]!=choice || matrix[i][k]==BLANK){
flag=false;// Row is not same
break;
}
flag=true;
}
//If row is same then return
if(flag){
cout<<"Row Win\n";
return flag;
}
//Column checkwin
for(int k=0;k<3;k++){
if(matrix[k][j]!=choice || matrix[k][j]==BLANK){
flag=false;//Column is not same
break;
}
flag=true;
}
//If the Column is same then return
if(flag){
cout<<"Column Win\n";
return flag;
}
return flag;//return the result false result i.e there is no chance of win
//as we have checked all the conditions
}
/************************* Main Function **************************************************/
int main(){
char matrix[3][3];
bool flag;
int toss;
srand(time(NULL));
toss=rand()%2;
if(toss){
flag=true;
cout<<"User Wins the Toss\n";
}
else{
flag=false;
cout<<"System Wins the Toss\n";
}
//Initialise all the elements of matrix to BLANK i.e. Blank
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
matrix[i][j]=BLANK;
cout<<"For user the choice is o\n";
cout<<"For system the choice is x\n";
int v=1;//Initialise the the variable v , it has the increment till 9 to cover all the elements of the matrix
bool system1=false;//To check the chance of win of system
int user_status=0;//To check the chance of win of user and accordingly system will put his move
int system_status;////To check the chance of win of system and accordingly system will put his move
while(v<=9){
int i,j;// "i" is for the row coordinate and "j" is for the column coordinate
if(flag==true){// If user win's the toss
cout<<"Yours turn\n";
cout<<"Enter the row coordinate";
cin>>i;
i--;//For user convenience i th coordinate
cout<<"Enter the column coordinate";
cin>>j;
j--;//For user convenience jth coordinate
if(matrix[i][j]==BLANK)
matrix[i][j]='o';//Put the user move
else{
cout<<"Already Occupied\n"; //Warn user to fill the blank space
continue;//Don't count this in "variable v" means don't increment the variable "v"
//as it was invalid move
}
// After three attempts it will check , this code is for system
if(v>2)
user_status=chance_of_win(matrix,i,j,'o');//User chance of win
//checkwin whether game is over i.e whether user win
if(v>4){
if(checkwin(matrix,i,j,'o')){
cout<<"\n\tBingo !! User win\n\tCongrats Well played\n";
display(matrix);
return 0;
}
}
flag=false;// Let the System play next move
display(matrix);//display the matrix
cout<<"\nWait! System turns\n";
}
else{//System's Turn
if(system1==true){//Chance of System of winning
j=system_status%10;//get the j coordinate
i=system_status/10;//get the i coordinate
//cout<<"System chance win i = "<<i<<" j = "<<j<<endl;
/*If Structure of Check whether place is empty for winning the system*/
if(matrix[i][j]==BLANK){//Is place is empty
matrix[i][j]='x';
if(checkwin(matrix,i,j,'x')){
display(matrix);//Display the current scenerio of the game
cout<<"Sorry You loose !! System wins\n";
return 0;
}//end if structure of check win
}
else//Means space is occupied by user, and chance of winning by system is lost
system1=false;//Now let the system to defense the user's move
/*Ends If Structure of Check whether place is empty for winning the system*/
}
if(system1==false){
if(user_status!=0){//If User is going to win , warn the system
j=user_status%10;//get the j coordinate
i=user_status/10;//get the i coordinate
//cout<<"User chance win i = "<<i<<" j = "<<j<<endl;
}
else{
if(v==9){//There is no point to check random number if noone is winning at the end
cout<<"\t\tMatch draw"<<endl;
return 0;
}
srand(time(NULL));
i=rand()%3; //random i coordinate
srand(time(NULL));
j=rand()%3; //random j coordinate
}
/*If System turn's of writting*/
if(matrix[i][j]==BLANK)
matrix[i][j]='x';
else
continue;
/*End If Structure of writting system turn's*/
}//end If Structure is sytem chance of win = false
if(v>2){// This condition is necessary to avoid irrevelant check
system_status=chance_of_win(matrix,i,j,'x'); //System chance of win
if(system_status==0){
system1=false;
cout<<"\n Not System Chance of win \n";
}
else{
system1=true;
cout<<"\n System Chance of win \n";
}
}
else{
system_status=0;
system1=false;
}
flag=true;//Let the user play his next move
display(matrix);
}
v++;
}//end of while v<9
return 0;
``` |
26,091 | I wrote this simple function in CoffeeScript to see if elements are found in an array:
```
isFoundIn = (searchTerm, arrayToSearch) ->
returnVal = false
for a in arrayToSearch
returnVal = true if searchTerm is a
returnVal
```
Usage:
```
isFoundIn('james', ['robert', 'michael', 'james'])`
```
would return true.
I know in Ruby it is very concise and readable to do this:
```
myArr = ['robert', 'michael', 'james']
myArr.include? 'james'
```
Are there some strategies to refactor this to make it more readable or more like CoffeeScript? | 2013/05/13 | [
"https://codereview.stackexchange.com/questions/26091",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/24998/"
] | Expanding on my comment above:
Your `isFoundIn` function can be rewritten as simply
```
isFoundIn = (term, array) -> array.indexOf(term) isnt -1
```
`indexOf` uses the strict `===` comparison, which is what CoffeeScript also uses for `is` - i.e. it's equivalent to your code.
One could extend the native JS Array prototype with a `include` function to more closely mimic Ruby. In CoffeeScript, it'd be written as
```
Array::include = (term) -> @indexOf(term) isnt -1
```
Then you can do `[1, 2, 3].include(3)` and such. But extending native prototypes is generally frowned upon, and I can't recommend it. Tempting though.
As for your original function, you could just do an explicit return right away if the `searchTerm` is found - no need to loop through the rest of the array
```
isFoundIn = (searchTerm, arrayToSearch) ->
for a in arrayToSearch
return true if searchTerm is a
false
```
The point is moot, though, as `indexOf` does it all for you
---
Addendum: I do like the `?` hack you used to fully match Ruby's method name, but it is still just that: A hack. You're effectively adding `undefined` as a possible return value for what should be a straight boolean. It'll also absorb errors (as that's its purpose) where e.g. the object responds to `indexOf` just fine, but - for whatever reason - hasn't been extended with the `include` function. So it's easy to get false negatives (unless you explicitly start checking for `undefined` and branch if that's the case and... well, the code fogs up quick)
So again, definite points for creativity - wish I'd thought of it - but I personally wouldn't go near it in production code | Any reason to not use `item in ary` syntax? it compiles down to a slightly convoluted usage of `.indexOf >=0` but it is the coffeescript way. |
26,091 | I wrote this simple function in CoffeeScript to see if elements are found in an array:
```
isFoundIn = (searchTerm, arrayToSearch) ->
returnVal = false
for a in arrayToSearch
returnVal = true if searchTerm is a
returnVal
```
Usage:
```
isFoundIn('james', ['robert', 'michael', 'james'])`
```
would return true.
I know in Ruby it is very concise and readable to do this:
```
myArr = ['robert', 'michael', 'james']
myArr.include? 'james'
```
Are there some strategies to refactor this to make it more readable or more like CoffeeScript? | 2013/05/13 | [
"https://codereview.stackexchange.com/questions/26091",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/24998/"
] | Expanding on my comment above:
Your `isFoundIn` function can be rewritten as simply
```
isFoundIn = (term, array) -> array.indexOf(term) isnt -1
```
`indexOf` uses the strict `===` comparison, which is what CoffeeScript also uses for `is` - i.e. it's equivalent to your code.
One could extend the native JS Array prototype with a `include` function to more closely mimic Ruby. In CoffeeScript, it'd be written as
```
Array::include = (term) -> @indexOf(term) isnt -1
```
Then you can do `[1, 2, 3].include(3)` and such. But extending native prototypes is generally frowned upon, and I can't recommend it. Tempting though.
As for your original function, you could just do an explicit return right away if the `searchTerm` is found - no need to loop through the rest of the array
```
isFoundIn = (searchTerm, arrayToSearch) ->
for a in arrayToSearch
return true if searchTerm is a
false
```
The point is moot, though, as `indexOf` does it all for you
---
Addendum: I do like the `?` hack you used to fully match Ruby's method name, but it is still just that: A hack. You're effectively adding `undefined` as a possible return value for what should be a straight boolean. It'll also absorb errors (as that's its purpose) where e.g. the object responds to `indexOf` just fine, but - for whatever reason - hasn't been extended with the `include` function. So it's easy to get false negatives (unless you explicitly start checking for `undefined` and branch if that's the case and... well, the code fogs up quick)
So again, definite points for creativity - wish I'd thought of it - but I personally wouldn't go near it in production code | If you want to make it "more like CoffeeScript", use array comprehensions:
```
isFoundIn = (searchTerm, arrayToSearch) ->
return true for item in arrayToSearch when item is searchTerm
false
``` |
26,091 | I wrote this simple function in CoffeeScript to see if elements are found in an array:
```
isFoundIn = (searchTerm, arrayToSearch) ->
returnVal = false
for a in arrayToSearch
returnVal = true if searchTerm is a
returnVal
```
Usage:
```
isFoundIn('james', ['robert', 'michael', 'james'])`
```
would return true.
I know in Ruby it is very concise and readable to do this:
```
myArr = ['robert', 'michael', 'james']
myArr.include? 'james'
```
Are there some strategies to refactor this to make it more readable or more like CoffeeScript? | 2013/05/13 | [
"https://codereview.stackexchange.com/questions/26091",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/24998/"
] | Expanding on my comment above:
Your `isFoundIn` function can be rewritten as simply
```
isFoundIn = (term, array) -> array.indexOf(term) isnt -1
```
`indexOf` uses the strict `===` comparison, which is what CoffeeScript also uses for `is` - i.e. it's equivalent to your code.
One could extend the native JS Array prototype with a `include` function to more closely mimic Ruby. In CoffeeScript, it'd be written as
```
Array::include = (term) -> @indexOf(term) isnt -1
```
Then you can do `[1, 2, 3].include(3)` and such. But extending native prototypes is generally frowned upon, and I can't recommend it. Tempting though.
As for your original function, you could just do an explicit return right away if the `searchTerm` is found - no need to loop through the rest of the array
```
isFoundIn = (searchTerm, arrayToSearch) ->
for a in arrayToSearch
return true if searchTerm is a
false
```
The point is moot, though, as `indexOf` does it all for you
---
Addendum: I do like the `?` hack you used to fully match Ruby's method name, but it is still just that: A hack. You're effectively adding `undefined` as a possible return value for what should be a straight boolean. It'll also absorb errors (as that's its purpose) where e.g. the object responds to `indexOf` just fine, but - for whatever reason - hasn't been extended with the `include` function. So it's easy to get false negatives (unless you explicitly start checking for `undefined` and branch if that's the case and... well, the code fogs up quick)
So again, definite points for creativity - wish I'd thought of it - but I personally wouldn't go near it in production code | The `in` in CoffeScript is essentially the same as Ruby's `include?`. You may write following Ruby version
```
['robert', 'michael', 'james'].include? 'james'
```
in CoffeeScript as
```
'james' in ['robert', 'michael', 'james']
```
You can use following if you want to add `include` to Array prototype:
```
Array::include = (o) -> o in @
myArr = ['robert', 'michael', 'james']
console.log 'present' if myArr.include? 'james'
```
Note: `?` in include has different meaning in Ruby and CoffeeScript. In Ruby its the part of function name (although we can use `?` for boolean attributes in Rails). While in CoffeeScript `?` is an operator to check if the operand value is not null. |
26,091 | I wrote this simple function in CoffeeScript to see if elements are found in an array:
```
isFoundIn = (searchTerm, arrayToSearch) ->
returnVal = false
for a in arrayToSearch
returnVal = true if searchTerm is a
returnVal
```
Usage:
```
isFoundIn('james', ['robert', 'michael', 'james'])`
```
would return true.
I know in Ruby it is very concise and readable to do this:
```
myArr = ['robert', 'michael', 'james']
myArr.include? 'james'
```
Are there some strategies to refactor this to make it more readable or more like CoffeeScript? | 2013/05/13 | [
"https://codereview.stackexchange.com/questions/26091",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/24998/"
] | Any reason to not use `item in ary` syntax? it compiles down to a slightly convoluted usage of `.indexOf >=0` but it is the coffeescript way. | If you want to make it "more like CoffeeScript", use array comprehensions:
```
isFoundIn = (searchTerm, arrayToSearch) ->
return true for item in arrayToSearch when item is searchTerm
false
``` |
26,091 | I wrote this simple function in CoffeeScript to see if elements are found in an array:
```
isFoundIn = (searchTerm, arrayToSearch) ->
returnVal = false
for a in arrayToSearch
returnVal = true if searchTerm is a
returnVal
```
Usage:
```
isFoundIn('james', ['robert', 'michael', 'james'])`
```
would return true.
I know in Ruby it is very concise and readable to do this:
```
myArr = ['robert', 'michael', 'james']
myArr.include? 'james'
```
Are there some strategies to refactor this to make it more readable or more like CoffeeScript? | 2013/05/13 | [
"https://codereview.stackexchange.com/questions/26091",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/24998/"
] | The `in` in CoffeScript is essentially the same as Ruby's `include?`. You may write following Ruby version
```
['robert', 'michael', 'james'].include? 'james'
```
in CoffeeScript as
```
'james' in ['robert', 'michael', 'james']
```
You can use following if you want to add `include` to Array prototype:
```
Array::include = (o) -> o in @
myArr = ['robert', 'michael', 'james']
console.log 'present' if myArr.include? 'james'
```
Note: `?` in include has different meaning in Ruby and CoffeeScript. In Ruby its the part of function name (although we can use `?` for boolean attributes in Rails). While in CoffeeScript `?` is an operator to check if the operand value is not null. | If you want to make it "more like CoffeeScript", use array comprehensions:
```
isFoundIn = (searchTerm, arrayToSearch) ->
return true for item in arrayToSearch when item is searchTerm
false
``` |
183,521 | I'm trying to deploy a tabular model to a server using the "Analysis Services Deployment Wizard".
When attempting to deploy,I get the below error.
>
> The JSON DDL request failed with the following error: Failed to execute XMLA. Error returned: 'The column 'Date Offset' in table 'Date' has invalid bindings specified.
>
>
>
The column in question uses the below calculation, which was found [here](https://blog.crossjoin.co.uk/2013/01/24/building-relative-date-reports-in-powerpivot/)
```
INT([Date] - TODAY())
```
What should I look for in order to resolve this error? | 2017/08/15 | [
"https://dba.stackexchange.com/questions/183521",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/47517/"
] | The problem in this case was that I was trying to replace an existing column also named 'Date Offset' - this was not a calculated column, but taken from the source table.
Resolution was to do the deployment in 2 phases, first remove the old column, then deploy again to add the new calculated column. | I was able to solve this by deleting the cube completely off of the server before doing another deploy. |
183,521 | I'm trying to deploy a tabular model to a server using the "Analysis Services Deployment Wizard".
When attempting to deploy,I get the below error.
>
> The JSON DDL request failed with the following error: Failed to execute XMLA. Error returned: 'The column 'Date Offset' in table 'Date' has invalid bindings specified.
>
>
>
The column in question uses the below calculation, which was found [here](https://blog.crossjoin.co.uk/2013/01/24/building-relative-date-reports-in-powerpivot/)
```
INT([Date] - TODAY())
```
What should I look for in order to resolve this error? | 2017/08/15 | [
"https://dba.stackexchange.com/questions/183521",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/47517/"
] | The problem in this case was that I was trying to replace an existing column also named 'Date Offset' - this was not a calculated column, but taken from the source table.
Resolution was to do the deployment in 2 phases, first remove the old column, then deploy again to add the new calculated column. | Tried different methods like renaming column and removed filters applied, didn't solved this issue.
At the end this issue fixed by just deleting existing cube and redeployed |
183,521 | I'm trying to deploy a tabular model to a server using the "Analysis Services Deployment Wizard".
When attempting to deploy,I get the below error.
>
> The JSON DDL request failed with the following error: Failed to execute XMLA. Error returned: 'The column 'Date Offset' in table 'Date' has invalid bindings specified.
>
>
>
The column in question uses the below calculation, which was found [here](https://blog.crossjoin.co.uk/2013/01/24/building-relative-date-reports-in-powerpivot/)
```
INT([Date] - TODAY())
```
What should I look for in order to resolve this error? | 2017/08/15 | [
"https://dba.stackexchange.com/questions/183521",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/47517/"
] | The problem in this case was that I was trying to replace an existing column also named 'Date Offset' - this was not a calculated column, but taken from the source table.
Resolution was to do the deployment in 2 phases, first remove the old column, then deploy again to add the new calculated column. | In my case, I remove duplicated columns and the error persisted.
It only worked when I did **delete model in azure** --> analysis services. |
56,329,240 | I am building a library database.
I want to write a query that returns the available books on the library(their isbns,titles,author names,pubname,categoryName and the Number of copies available.
My query involves the following relations (with bold are the primary keys) :
**Book (ISBN**, title,pubYear,numpages, pubName **)** pubName FK to publisher
**copies (ISBN, copyNr**, shelf **)** ISBN FK to Book
**borrows (memberID, ISBN, copyNr, date\_of\_borrowing**, date\_of\_return **)** memberID FK to member, ISBN FK to Books, (ISBN, copyNr) FK to copies
**belongs\_to (ISBN, categoryName )** SBN FK to Book, categoryName FK to category
**written\_by (ISBN, authID )** ISBN FK to Book, authID FK to author
**author (authID**, AFirst, ALast, Abirthdate **)**
My approach is the following:
```
SELECT b.isbn, b.title,a.ALast, a.ALast, b.pubName, be.categoryName , COUNT(b.isbn) as Number_of_copies_available
FROM copies as c
INNER JOIN book as b ON c.isbn = b.isbn
INNER JOIN belong_to as be ON b.isbn = be.isbn
INNER JOIN written_by as w ON w.isbn=b.isbn
INNER JOIN author as a ON a.authID = w.authID
WHERE (c.isbn,c.copyNr) NOT IN (SELECT isbn, copyNr FROM borrows)
GROUP BY b.isbn
ORDER BY be.categoryName
```
The problem is that I get duplicate tuples on the result before grouping which leads to more items per group.
For instance for some books I get the attribute value of Number\_of\_copies\_available double than expected.
If I don't `JOIN` with the relations "written\_by" and "author" then the result is correct. However, I also want to appear the author names in the result. What's my mistake? Thanks in advance! | 2019/05/27 | [
"https://Stackoverflow.com/questions/56329240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11345445/"
] | Don't join the tables directly when they are not perfectly related. A book's category is not really related to a book's author. With two authors and two categories, which author would you combine with which category? It makes no sense to combine them (and possibly end up with all combinations). So, aggregate first and then join the aggregates. Here is an example:
```
select
b.isbn,
b.title,
b.pubName,
aut.authors,
cat.categories,
cop.total - coalesce(bor.total, 0) as available
from book b
join
(
select w.isbn, group_concat(a.alast) as authors
from written_by w
join author a ON a.authID = w.authID
group by w.isbn
) aut ON aut.isbn = b.isbn
join
(
select isbn, group_concat(categoryname) as categories
from belong_to
group by isbn
) cat ON cat.isbn = b.isbn
join
(
select isbn, count(*) as total
from copies
group by isbn
) cop ON cop.isbn = b.isbn
left join
(
select isbn, count(*) as total
from borrows
where date_of_return > current_date
group by isbn
) bor ON bor.isbn = b.isbn
order by b.isbn;
``` | >
> Still a bit confused..Could you explain me where the mistake exactly
> is and how could I fix this?
>
>
>
Not really meant as a answer, as this "comment" is way to large.
But a more SQL 92 valid rewrite would be more or less like below.
But as you didn't provide example data and expected results iám really guessing what you need
**Query**
```
SELECT
book.isbn
...
FROM
book
INNER JOIN (
SELECT
COUNT(book.isbn) AS Number_of_copies_available
FROM
book
INNER JOIN
copies
ON
book.isbn = copies.isbn
... # borrows table should also be needed here to be filterd?
) AS book_copies__count
ON
...
...
...
``` |
28,540,465 | Actually I am getting a string with HTML tags from the server in my app and I receive it in `NSString` then I pass this string to a `UIWebView` to show the data as HTML.
I want to localize these string in to Italian language.
How can I localize this HTML string? | 2015/02/16 | [
"https://Stackoverflow.com/questions/28540465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4445157/"
] | Replace all the localized text by %@ :
```
<html> <head><link rel='stylesheet' type='text/css' href='cummins_black.css' /><p><span style="font-size: 18px; font-family: helvetica;">%@</span><br /><span style="font-size: 18px; font-family: helvetica;">%@</span><br /><br /><blink class='blink'><span style="font-size: 18px; font-family: helvetica;"><strong><strong>%@</strong></strong>: </span></blink><br /><span style="font-size: 18px; font-family: helvetica;">%@</span><br /></span></p></head>
```
And then create your localized string and load it:
```
NSString *htmlString = [NSString stringWithFormat:html, NSLocalizedString(@"key_1", nil), NSLocalizedString(@"key_2", nil), NSLocalizedString(@"key_3", nil)];
[self.webView loadHTMLString:htmlString baseURL:nil];
```
key\_1, key\_2, key\_3 are defined in your Localizable.strings | You either have to get a localized string from your server.
Or you have to **parse** the received string and replace the found strings with their localizations.
It would be much better to have a web service returning no HTML but just data (e.g. in JSON format) and you construct the HTML yourself so it is optimized for the device. |
6,288,261 | How can I get values between two dates in Codeigniter query function? Here is my model and sample code.
```
function get_promo() {
$today = date('Y-m-d');
$query = $this->db->query('SELECT FROM tbl_event WHERE event_id = $id AND event_startdate <= $today
AND event_enddate >= $today');
return $query;
}
```
But it doesn't work, here is the error I got
```
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 ' at line 1
SELECT FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 AND event_enddate >= 2011-06-09
Filename: C:\xampp\htdocs\hotel\system\database\DB_driver.php
Line Number: 330
``` | 2011/06/09 | [
"https://Stackoverflow.com/questions/6288261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/415699/"
] | I think u need to user date\_format(), more information in this link <http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format>.
Try this code:
```
$today = date('Y-m-d');
$query = $this->db->query("SELECT FROM tbl_event WHERE event_id = $id AND DATE_FORMAT(event_startdate ,'%Y-%m-%d') >= DATE_FORMAT($today ,'%Y-%m-%d') AND DATE_FORMAT(event_enddate ,'%Y-%m-%d') <= DATE_FORMAT($today ,'%Y-%m-%d')");
``` | You need to use the right format. Try this:
```
$todaystart = date('Y-m-d 00:00:00');
$todayend = date('Y-m-d 23:59:59');
$query = $this->db->query('SELECT FROM tbl_event WHERE event_id = $id AND event_startdate <= ? AND event_enddate >= ?', array($todaystart, $todayend));
```
EDIT: your query is wrong. Do this:
```
$todaystart = date('Y-m-d 00:00:00');
$todayend = date('Y-m-d 23:59:59');
$query = $this->db->query('SELECT * FROM tbl_event WHERE event_id = $id AND event_startdate <= ? AND event_enddate >= ?', array($todaystart, $todayend));
``` |
6,288,261 | How can I get values between two dates in Codeigniter query function? Here is my model and sample code.
```
function get_promo() {
$today = date('Y-m-d');
$query = $this->db->query('SELECT FROM tbl_event WHERE event_id = $id AND event_startdate <= $today
AND event_enddate >= $today');
return $query;
}
```
But it doesn't work, here is the error I got
```
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 ' at line 1
SELECT FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 AND event_enddate >= 2011-06-09
Filename: C:\xampp\htdocs\hotel\system\database\DB_driver.php
Line Number: 330
``` | 2011/06/09 | [
"https://Stackoverflow.com/questions/6288261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/415699/"
] | Looking into the errors, it seems that your queries are not escaped properly. Add single or double quotes to fix it. Check @danneth answer. Use [Query Binding](http://www.codeigniter.com/user_guide/database/queries.html#query-bindings) which is simple and secure or even more use [Active Record](http://www.codeigniter.com/user_guide/database/query_builder.html#selecting-data). Here are examples of both binding and active record based on your code.
**Query Binding Example**
```
$today = date('Y-m-d');
$sql = 'SELECT
*
FROM
tbl_event
WHERE event_id = ?
AND event_startdate <= ?
AND event_enddate >= ?';
$query = $this->db->query($sql, array($id, $today, $today));
return $query;
```
**Active Record Example**
```
$query = $this->db
->select('*')->from('tbl_event')
->where(array(
'event_id' => $id,
'event_startdate <= ' => $today,
'event_enddate >= ' => $today
))
->get();
return $query;
```
Append `->result()` or `->result_array()` etc to get the result in an object or array. Look into the Codeigniter [Database User Guide](http://www.codeigniter.com/user_guide/database/index.html) for more. | You need to use the right format. Try this:
```
$todaystart = date('Y-m-d 00:00:00');
$todayend = date('Y-m-d 23:59:59');
$query = $this->db->query('SELECT FROM tbl_event WHERE event_id = $id AND event_startdate <= ? AND event_enddate >= ?', array($todaystart, $todayend));
```
EDIT: your query is wrong. Do this:
```
$todaystart = date('Y-m-d 00:00:00');
$todayend = date('Y-m-d 23:59:59');
$query = $this->db->query('SELECT * FROM tbl_event WHERE event_id = $id AND event_startdate <= ? AND event_enddate >= ?', array($todaystart, $todayend));
``` |
6,288,261 | How can I get values between two dates in Codeigniter query function? Here is my model and sample code.
```
function get_promo() {
$today = date('Y-m-d');
$query = $this->db->query('SELECT FROM tbl_event WHERE event_id = $id AND event_startdate <= $today
AND event_enddate >= $today');
return $query;
}
```
But it doesn't work, here is the error I got
```
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 ' at line 1
SELECT FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 AND event_enddate >= 2011-06-09
Filename: C:\xampp\htdocs\hotel\system\database\DB_driver.php
Line Number: 330
``` | 2011/06/09 | [
"https://Stackoverflow.com/questions/6288261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/415699/"
] | I think you need qoutes around your date (i.e. '2011-06-08'). try this
```
function get_promo() {
$today = date('Y-m-d');
$query = $this->db->query(
"SELECT FROM tbl_event WHERE event_id = {$id} AND event_startdate <= '{$today}'
AND event_enddate >= '{$today}'");
return $query;
}
```
If your columns `event_startdate` and `event_enddate` are `DATETIME` type but you are only interested in the date part you can do `DATE(event\_enddate) to extract the date part | You need to use the right format. Try this:
```
$todaystart = date('Y-m-d 00:00:00');
$todayend = date('Y-m-d 23:59:59');
$query = $this->db->query('SELECT FROM tbl_event WHERE event_id = $id AND event_startdate <= ? AND event_enddate >= ?', array($todaystart, $todayend));
```
EDIT: your query is wrong. Do this:
```
$todaystart = date('Y-m-d 00:00:00');
$todayend = date('Y-m-d 23:59:59');
$query = $this->db->query('SELECT * FROM tbl_event WHERE event_id = $id AND event_startdate <= ? AND event_enddate >= ?', array($todaystart, $todayend));
``` |
6,288,261 | How can I get values between two dates in Codeigniter query function? Here is my model and sample code.
```
function get_promo() {
$today = date('Y-m-d');
$query = $this->db->query('SELECT FROM tbl_event WHERE event_id = $id AND event_startdate <= $today
AND event_enddate >= $today');
return $query;
}
```
But it doesn't work, here is the error I got
```
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 ' at line 1
SELECT FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 AND event_enddate >= 2011-06-09
Filename: C:\xampp\htdocs\hotel\system\database\DB_driver.php
Line Number: 330
``` | 2011/06/09 | [
"https://Stackoverflow.com/questions/6288261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/415699/"
] | ```
$this->db->where('date_start <=',date('Y-m-d'));
$this->db->where('date_end >=',date('Y-m-d'));
$query = $this->db->get('table');
``` | You need to use the right format. Try this:
```
$todaystart = date('Y-m-d 00:00:00');
$todayend = date('Y-m-d 23:59:59');
$query = $this->db->query('SELECT FROM tbl_event WHERE event_id = $id AND event_startdate <= ? AND event_enddate >= ?', array($todaystart, $todayend));
```
EDIT: your query is wrong. Do this:
```
$todaystart = date('Y-m-d 00:00:00');
$todayend = date('Y-m-d 23:59:59');
$query = $this->db->query('SELECT * FROM tbl_event WHERE event_id = $id AND event_startdate <= ? AND event_enddate >= ?', array($todaystart, $todayend));
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.