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
17,720,594
I've tried searching for about an hour through all the Foreign Key / Collation Questions but I can't find something even remotely close to my question. I have 2 tables from two different software vendors sitting in the same database. One vendor hard codes their collations to Latin1\_General\_BIN while the other uses the Database Default (in this case Latin1\_General\_CI\_AS). Is it possible, without altering any of the columns, to create Foreign Keys between these two Collation Types? Typically you would simply change one but in this case the Tables are very sensitive and I'm not allowed to make such a change but I have to create a Foreign Key due to a piece of logic in a Trigger that reads data between these two tables only if it finds a Foreign Key: ``` SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE WHERE CONSTRAINT_NAME = ( SELECT name FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID( 'Table1' ) AND referenced_object_id = OBJECT_ID( 'Table2' ) ) ``` Any help would really be appreciate P.S. I just can't seem to figure out how this code thing works if anyone would help me out, I put in the 4 required spaces but it's still just displaying my code as text :(
2013/07/18
[ "https://Stackoverflow.com/questions/17720594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538480/" ]
Yes you must use js to do it dynamically on the spot You have a jQuery tag so I will show an example in jQuery This is not the best example but it works and it's a starting point **JS:** ``` $(function(){ $('#master').on('change', function() { var count = $(this).val(); $('#otherInputs').html('') for( var i = 0; i < count; i++) { $('#otherInputs').append( $('<input>', {type: 'text'}) ); } }); }); ``` **HTML:** ``` <input type="number" id="master" value="1"> <div id="otherInputs"></div> ``` [Demo](http://jsfiddle.net/3pdw9/) ================================== In English this is saying... When you `change` `#master` I will empty `#master` (`html('')`) loop through and append a new input depending on `#master`'s value
Here's the **[FIDDLE](http://jsfiddle.net/vonDy2791/h5RTG/)**. Hope it helps. :) html ``` <input type="text" size="3" maxlength="3" id="count" name="count" value="1"> <div id="container"></div> ``` script ``` $('#count').on('keyup', function () { var $this = $(this); var count = $this.val(); $('#container').empty(); for (var x = 1; x <= count; x++) { var newInput = '<input type="text" size="30" maxlength="30" id="input_' + x + '" name="input_' + x + '">'; $('#container').append(newInput); } }); ```
17,720,594
I've tried searching for about an hour through all the Foreign Key / Collation Questions but I can't find something even remotely close to my question. I have 2 tables from two different software vendors sitting in the same database. One vendor hard codes their collations to Latin1\_General\_BIN while the other uses the Database Default (in this case Latin1\_General\_CI\_AS). Is it possible, without altering any of the columns, to create Foreign Keys between these two Collation Types? Typically you would simply change one but in this case the Tables are very sensitive and I'm not allowed to make such a change but I have to create a Foreign Key due to a piece of logic in a Trigger that reads data between these two tables only if it finds a Foreign Key: ``` SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE WHERE CONSTRAINT_NAME = ( SELECT name FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID( 'Table1' ) AND referenced_object_id = OBJECT_ID( 'Table2' ) ) ``` Any help would really be appreciate P.S. I just can't seem to figure out how this code thing works if anyone would help me out, I put in the 4 required spaces but it's still just displaying my code as text :(
2013/07/18
[ "https://Stackoverflow.com/questions/17720594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538480/" ]
Here's a simple javascript snippet that doesn't make use of any frameworks: ``` function addInputs() { var count = parseInt(document.getElementById("count").value); for (var i = 2; i <= count; i++) { document.getElementById('moreinputs').innerHTML += '<input type="text" name="input_' + i + '" id="input_' + i + '" />'; } } ``` In this example you have to add a container (div) with id 'moreinputs'. However, when calling this function more than once, it will not work properly (e.g. it can only increase the number of input but not decrease)
Yes you must use js to do it dynamically on the spot You have a jQuery tag so I will show an example in jQuery This is not the best example but it works and it's a starting point **JS:** ``` $(function(){ $('#master').on('change', function() { var count = $(this).val(); $('#otherInputs').html('') for( var i = 0; i < count; i++) { $('#otherInputs').append( $('<input>', {type: 'text'}) ); } }); }); ``` **HTML:** ``` <input type="number" id="master" value="1"> <div id="otherInputs"></div> ``` [Demo](http://jsfiddle.net/3pdw9/) ================================== In English this is saying... When you `change` `#master` I will empty `#master` (`html('')`) loop through and append a new input depending on `#master`'s value
17,720,594
I've tried searching for about an hour through all the Foreign Key / Collation Questions but I can't find something even remotely close to my question. I have 2 tables from two different software vendors sitting in the same database. One vendor hard codes their collations to Latin1\_General\_BIN while the other uses the Database Default (in this case Latin1\_General\_CI\_AS). Is it possible, without altering any of the columns, to create Foreign Keys between these two Collation Types? Typically you would simply change one but in this case the Tables are very sensitive and I'm not allowed to make such a change but I have to create a Foreign Key due to a piece of logic in a Trigger that reads data between these two tables only if it finds a Foreign Key: ``` SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE WHERE CONSTRAINT_NAME = ( SELECT name FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID( 'Table1' ) AND referenced_object_id = OBJECT_ID( 'Table2' ) ) ``` Any help would really be appreciate P.S. I just can't seem to figure out how this code thing works if anyone would help me out, I put in the 4 required spaces but it's still just displaying my code as text :(
2013/07/18
[ "https://Stackoverflow.com/questions/17720594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538480/" ]
Yes you must use js to do it dynamically on the spot You have a jQuery tag so I will show an example in jQuery This is not the best example but it works and it's a starting point **JS:** ``` $(function(){ $('#master').on('change', function() { var count = $(this).val(); $('#otherInputs').html('') for( var i = 0; i < count; i++) { $('#otherInputs').append( $('<input>', {type: 'text'}) ); } }); }); ``` **HTML:** ``` <input type="number" id="master" value="1"> <div id="otherInputs"></div> ``` [Demo](http://jsfiddle.net/3pdw9/) ================================== In English this is saying... When you `change` `#master` I will empty `#master` (`html('')`) loop through and append a new input depending on `#master`'s value
This worked for me ``` function AddField() { var count = $("#countetfield").val(); var i = 1; var id = $("#container .testClass:last").attr('name'); var test = id.split("_"); id_name = test[1]; while (i <= count) { id_name++; var a = '<input type="text" class="testClass" size="30" maxlength="30" id="input_' + id_name + '" name="input_' + id_name + '"/>'; $("#container").append(a); i++; } } <input type="text" id="countetfield" value="1" /> <input type="button" value="Go" onclick="AddField();" /> <div id="container"> <input type="text" class="testClass" size="30" maxlength="30" id="input_1" name="input_1" /> </div> ```
17,720,594
I've tried searching for about an hour through all the Foreign Key / Collation Questions but I can't find something even remotely close to my question. I have 2 tables from two different software vendors sitting in the same database. One vendor hard codes their collations to Latin1\_General\_BIN while the other uses the Database Default (in this case Latin1\_General\_CI\_AS). Is it possible, without altering any of the columns, to create Foreign Keys between these two Collation Types? Typically you would simply change one but in this case the Tables are very sensitive and I'm not allowed to make such a change but I have to create a Foreign Key due to a piece of logic in a Trigger that reads data between these two tables only if it finds a Foreign Key: ``` SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE WHERE CONSTRAINT_NAME = ( SELECT name FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID( 'Table1' ) AND referenced_object_id = OBJECT_ID( 'Table2' ) ) ``` Any help would really be appreciate P.S. I just can't seem to figure out how this code thing works if anyone would help me out, I put in the 4 required spaces but it's still just displaying my code as text :(
2013/07/18
[ "https://Stackoverflow.com/questions/17720594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538480/" ]
Here's a simple javascript snippet that doesn't make use of any frameworks: ``` function addInputs() { var count = parseInt(document.getElementById("count").value); for (var i = 2; i <= count; i++) { document.getElementById('moreinputs').innerHTML += '<input type="text" name="input_' + i + '" id="input_' + i + '" />'; } } ``` In this example you have to add a container (div) with id 'moreinputs'. However, when calling this function more than once, it will not work properly (e.g. it can only increase the number of input but not decrease)
Here's the **[FIDDLE](http://jsfiddle.net/vonDy2791/h5RTG/)**. Hope it helps. :) html ``` <input type="text" size="3" maxlength="3" id="count" name="count" value="1"> <div id="container"></div> ``` script ``` $('#count').on('keyup', function () { var $this = $(this); var count = $this.val(); $('#container').empty(); for (var x = 1; x <= count; x++) { var newInput = '<input type="text" size="30" maxlength="30" id="input_' + x + '" name="input_' + x + '">'; $('#container').append(newInput); } }); ```
17,720,594
I've tried searching for about an hour through all the Foreign Key / Collation Questions but I can't find something even remotely close to my question. I have 2 tables from two different software vendors sitting in the same database. One vendor hard codes their collations to Latin1\_General\_BIN while the other uses the Database Default (in this case Latin1\_General\_CI\_AS). Is it possible, without altering any of the columns, to create Foreign Keys between these two Collation Types? Typically you would simply change one but in this case the Tables are very sensitive and I'm not allowed to make such a change but I have to create a Foreign Key due to a piece of logic in a Trigger that reads data between these two tables only if it finds a Foreign Key: ``` SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE WHERE CONSTRAINT_NAME = ( SELECT name FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID( 'Table1' ) AND referenced_object_id = OBJECT_ID( 'Table2' ) ) ``` Any help would really be appreciate P.S. I just can't seem to figure out how this code thing works if anyone would help me out, I put in the 4 required spaces but it's still just displaying my code as text :(
2013/07/18
[ "https://Stackoverflow.com/questions/17720594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538480/" ]
Here's a simple javascript snippet that doesn't make use of any frameworks: ``` function addInputs() { var count = parseInt(document.getElementById("count").value); for (var i = 2; i <= count; i++) { document.getElementById('moreinputs').innerHTML += '<input type="text" name="input_' + i + '" id="input_' + i + '" />'; } } ``` In this example you have to add a container (div) with id 'moreinputs'. However, when calling this function more than once, it will not work properly (e.g. it can only increase the number of input but not decrease)
This worked for me ``` function AddField() { var count = $("#countetfield").val(); var i = 1; var id = $("#container .testClass:last").attr('name'); var test = id.split("_"); id_name = test[1]; while (i <= count) { id_name++; var a = '<input type="text" class="testClass" size="30" maxlength="30" id="input_' + id_name + '" name="input_' + id_name + '"/>'; $("#container").append(a); i++; } } <input type="text" id="countetfield" value="1" /> <input type="button" value="Go" onclick="AddField();" /> <div id="container"> <input type="text" class="testClass" size="30" maxlength="30" id="input_1" name="input_1" /> </div> ```
723,869
Every once in a while I'm editing some long pair of if-then-else statements (or worse, *nested* if-then-else statements) , like, say, this: ``` if A < B then begin DoSomething; DoSomethingElse; {...and more statements going on and on and on...} FinallyWrapUpThisBit; end else begin DoThis; DoThat; {...and more statements going on and on and on...} FinallyWrapUpThisBit; end; ``` ...and I find myself wanting to "collapse" the first begin-end pair, to bring up the lower "else" part (usually because I'm referring to something above the if-then statemnent. Maybe so it would just say "begin..." and have [+} sign to the left of it to expand it out again. I've explored the "fold" functions in the IDE, but none of the commands seem to do this. It seems like my CodeRush for my old D6 did this, but I could be imagining things. (I have a very active imagination...). Do any of the IDE plug-ins like Castalia (or some other one) do this?
2009/04/07
[ "https://Stackoverflow.com/questions/723869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32303/" ]
With plain Delphi out of the box, you would have to surround your begin...end with ``` {$region 'begin...end'} .... {$endregion} ``` which can be done through a code template... I remember Castalia for the nice colored visualization of code blocks (begin..end) but I don't remember if it was foldable.
Use the refactoring tools to move the conditional branches' code into separate functions. Then you won't need to fold anything. You might also find that you can merge code that's common to the two branches, such as that call to `FinallyWrapUpThisBit`.
723,869
Every once in a while I'm editing some long pair of if-then-else statements (or worse, *nested* if-then-else statements) , like, say, this: ``` if A < B then begin DoSomething; DoSomethingElse; {...and more statements going on and on and on...} FinallyWrapUpThisBit; end else begin DoThis; DoThat; {...and more statements going on and on and on...} FinallyWrapUpThisBit; end; ``` ...and I find myself wanting to "collapse" the first begin-end pair, to bring up the lower "else" part (usually because I'm referring to something above the if-then statemnent. Maybe so it would just say "begin..." and have [+} sign to the left of it to expand it out again. I've explored the "fold" functions in the IDE, but none of the commands seem to do this. It seems like my CodeRush for my old D6 did this, but I could be imagining things. (I have a very active imagination...). Do any of the IDE plug-ins like Castalia (or some other one) do this?
2009/04/07
[ "https://Stackoverflow.com/questions/723869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32303/" ]
With plain Delphi out of the box, you would have to surround your begin...end with ``` {$region 'begin...end'} .... {$endregion} ``` which can be done through a code template... I remember Castalia for the nice colored visualization of code blocks (begin..end) but I don't remember if it was foldable.
Another big helper here would be [CNPack](http://www.cnpack.org/index.php?lang=en). It is a wizard which installs into Delphi and will colorize your begin/end pairs, making it MUCH easier to follow the code. It doesn't exactly do code folding, for that you need to use the {$REGION} {$ENDREGION} tags.
723,869
Every once in a while I'm editing some long pair of if-then-else statements (or worse, *nested* if-then-else statements) , like, say, this: ``` if A < B then begin DoSomething; DoSomethingElse; {...and more statements going on and on and on...} FinallyWrapUpThisBit; end else begin DoThis; DoThat; {...and more statements going on and on and on...} FinallyWrapUpThisBit; end; ``` ...and I find myself wanting to "collapse" the first begin-end pair, to bring up the lower "else" part (usually because I'm referring to something above the if-then statemnent. Maybe so it would just say "begin..." and have [+} sign to the left of it to expand it out again. I've explored the "fold" functions in the IDE, but none of the commands seem to do this. It seems like my CodeRush for my old D6 did this, but I could be imagining things. (I have a very active imagination...). Do any of the IDE plug-ins like Castalia (or some other one) do this?
2009/04/07
[ "https://Stackoverflow.com/questions/723869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32303/" ]
Use the refactoring tools to move the conditional branches' code into separate functions. Then you won't need to fold anything. You might also find that you can merge code that's common to the two branches, such as that call to `FinallyWrapUpThisBit`.
Another big helper here would be [CNPack](http://www.cnpack.org/index.php?lang=en). It is a wizard which installs into Delphi and will colorize your begin/end pairs, making it MUCH easier to follow the code. It doesn't exactly do code folding, for that you need to use the {$REGION} {$ENDREGION} tags.
67,013,686
I am getting an error in CPLEX about profiler error.This is being shown in the Profiler tab at the bottom window. Overflow occurred, please use oplrun -profile I have my outputs written back to excel using the sheetwrite command ( like for example solXbimt to SheetWrite(sheet,"Result!B3:E1000000"); ). The engine log shows there are several solutions that have been generated but they do not get written back to excel. I am doubting the overflow is causing this. Can you please help how to overcome this.
2021/04/09
[ "https://Stackoverflow.com/questions/67013686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10572464/" ]
You may use **"getOwnPropertyName"** to get all keys of object and assign them to a list or array. Let me know if my answer is helpful! ``` var text = { "28fca3e7-7b5a-95b1-205c-03ff199dc2b4": 6, "426fb283-6fa9-a58c-e896-f795a5d42c50": 8, "629fe212-0d74-f5ce-d476-baa527252ffb": 12}; var keys = Object.getOwnPropertyNames(this.text); keys.forEach(x => { let newKeyObject = new keyObject(); newKeyObject.key = x; newKeyObject.count = this.text[x]; this.keyObjectList.push(newKeyObject); }); console.log(JSON.stringify(this.keyObjectList)); ```
Like this: ``` const obj = { "28fca3e7-7b5a-95b1-205c-03ff199dc2b4": 6, "426fb283-6fa9-a58c-e896-f795a5d42c50": 8, "629fe212-0d74-f5ce-d476-baa527252ffb": 12, }; const arr = Object.keys(obj).map(k => ({ id: k, count: obj[k], })); ```
67,013,686
I am getting an error in CPLEX about profiler error.This is being shown in the Profiler tab at the bottom window. Overflow occurred, please use oplrun -profile I have my outputs written back to excel using the sheetwrite command ( like for example solXbimt to SheetWrite(sheet,"Result!B3:E1000000"); ). The engine log shows there are several solutions that have been generated but they do not get written back to excel. I am doubting the overflow is causing this. Can you please help how to overcome this.
2021/04/09
[ "https://Stackoverflow.com/questions/67013686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10572464/" ]
You may use **"getOwnPropertyName"** to get all keys of object and assign them to a list or array. Let me know if my answer is helpful! ``` var text = { "28fca3e7-7b5a-95b1-205c-03ff199dc2b4": 6, "426fb283-6fa9-a58c-e896-f795a5d42c50": 8, "629fe212-0d74-f5ce-d476-baa527252ffb": 12}; var keys = Object.getOwnPropertyNames(this.text); keys.forEach(x => { let newKeyObject = new keyObject(); newKeyObject.key = x; newKeyObject.count = this.text[x]; this.keyObjectList.push(newKeyObject); }); console.log(JSON.stringify(this.keyObjectList)); ```
just add the keys you want and put those values on there. try this. ``` Object.keys(arr).map(key => ({"id":key, "count": arr[key]})) ```
67,013,686
I am getting an error in CPLEX about profiler error.This is being shown in the Profiler tab at the bottom window. Overflow occurred, please use oplrun -profile I have my outputs written back to excel using the sheetwrite command ( like for example solXbimt to SheetWrite(sheet,"Result!B3:E1000000"); ). The engine log shows there are several solutions that have been generated but they do not get written back to excel. I am doubting the overflow is causing this. Can you please help how to overcome this.
2021/04/09
[ "https://Stackoverflow.com/questions/67013686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10572464/" ]
You may use **"getOwnPropertyName"** to get all keys of object and assign them to a list or array. Let me know if my answer is helpful! ``` var text = { "28fca3e7-7b5a-95b1-205c-03ff199dc2b4": 6, "426fb283-6fa9-a58c-e896-f795a5d42c50": 8, "629fe212-0d74-f5ce-d476-baa527252ffb": 12}; var keys = Object.getOwnPropertyNames(this.text); keys.forEach(x => { let newKeyObject = new keyObject(); newKeyObject.key = x; newKeyObject.count = this.text[x]; this.keyObjectList.push(newKeyObject); }); console.log(JSON.stringify(this.keyObjectList)); ```
You'll use the `Object.keys()` iterator to get an array of keys, and then transform that array into an array of objects. ``` const obj = { a: 1, b: 2, c: 3, }; console.log(Object.keys(obj).map(key => ({id: key, count: obj[key]}))); ```
67,013,686
I am getting an error in CPLEX about profiler error.This is being shown in the Profiler tab at the bottom window. Overflow occurred, please use oplrun -profile I have my outputs written back to excel using the sheetwrite command ( like for example solXbimt to SheetWrite(sheet,"Result!B3:E1000000"); ). The engine log shows there are several solutions that have been generated but they do not get written back to excel. I am doubting the overflow is causing this. Can you please help how to overcome this.
2021/04/09
[ "https://Stackoverflow.com/questions/67013686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10572464/" ]
You may use **"getOwnPropertyName"** to get all keys of object and assign them to a list or array. Let me know if my answer is helpful! ``` var text = { "28fca3e7-7b5a-95b1-205c-03ff199dc2b4": 6, "426fb283-6fa9-a58c-e896-f795a5d42c50": 8, "629fe212-0d74-f5ce-d476-baa527252ffb": 12}; var keys = Object.getOwnPropertyNames(this.text); keys.forEach(x => { let newKeyObject = new keyObject(); newKeyObject.key = x; newKeyObject.count = this.text[x]; this.keyObjectList.push(newKeyObject); }); console.log(JSON.stringify(this.keyObjectList)); ```
Simpler than mapping from the keys is map Object.entries() ```js const data = { "28fca3e7-7b5a-95b1-205c-03ff199dc2b4": 6, "426fb283-6fa9-a58c-e896-f795a5d42c50": 8, "629fe212-0d74-f5ce-d476-baa527252ffb": 12, }, res = Object.entries(data).map(([id, count]) => ({id, count})) console.log(res) ```
67,013,686
I am getting an error in CPLEX about profiler error.This is being shown in the Profiler tab at the bottom window. Overflow occurred, please use oplrun -profile I have my outputs written back to excel using the sheetwrite command ( like for example solXbimt to SheetWrite(sheet,"Result!B3:E1000000"); ). The engine log shows there are several solutions that have been generated but they do not get written back to excel. I am doubting the overflow is causing this. Can you please help how to overcome this.
2021/04/09
[ "https://Stackoverflow.com/questions/67013686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10572464/" ]
You may use **"getOwnPropertyName"** to get all keys of object and assign them to a list or array. Let me know if my answer is helpful! ``` var text = { "28fca3e7-7b5a-95b1-205c-03ff199dc2b4": 6, "426fb283-6fa9-a58c-e896-f795a5d42c50": 8, "629fe212-0d74-f5ce-d476-baa527252ffb": 12}; var keys = Object.getOwnPropertyNames(this.text); keys.forEach(x => { let newKeyObject = new keyObject(); newKeyObject.key = x; newKeyObject.count = this.text[x]; this.keyObjectList.push(newKeyObject); }); console.log(JSON.stringify(this.keyObjectList)); ```
You can simplify use [`Object.entries`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) combined with `Array#map` like this ```js const object = {"28fca3e7-7b5a-95b1-205c-03ff199dc2b4":6,"426fb283-6fa9-a58c-e896-f795a5d42c50":8,"629fe212-0d74-f5ce-d476-baa527252ffb":12,}; const result = Object.entries(object).map(([key, value]) => ({Id: key, count: value})); console.log(result); ``` > > The `Object.entries()` method returns an array of a given object's own > enumerable string-keyed property `[key, value] pairs` > > >
36,863,154
I'm developing Google Cast custom receiver app using WebTorrent (<https://webtorrent.io>, <https://github.com/feross/webtorrent>) and Google Cast sender app using JavaScript (Chrome) SDK. The idea of my app is sending torrent id (magnet URI like `magnet:?xt=urn:btih:6a9759bffd5c0af65319979fb7832189f4f3c35d` or HTTP/HTTPS URL to a \*.torrent file like `https://webtorrent.io/torrents/sintel.torrent`) from Google Cast sender to Google Cast receiver, and using WebTorrent in Google Cast receiver to display the media (video or audio) from the torrent. Note that torrent id is not a direct URL to the media file. Now I'm using Google Cast namespace and messageBus to send and receive the torrent id. WebTorrent API provides 2 ways to display the media: * append it to the DOM using `file.appendTo`: <https://webtorrent.io/docs#-file-appendto-rootelem-function-callback-err-elem-> * render directly into given element (or CSS selector) using `file.renderTo`: <https://webtorrent.io/docs#-file-renderto-elem-function-callback-err-elem-> Here is the code of my receiver: ``` <html> <head> <script src="https://www.gstatic.com/cast/sdk/libs/receiver/2.0.0/cast_receiver.js"></script> <script src="https://cdn.jsdelivr.net/webtorrent/latest/webtorrent.min.js"></script> </head> <body> <video autoplay id='media' /> <script> window.mediaElement = document.getElementById('media'); window.mediaManager = new cast.receiver.MediaManager(window.mediaElement); window.castReceiverManager = cast.receiver.CastReceiverManager.getInstance(); window.messageBus = window.castReceiverManager.getCastMessageBus('urn:x-cast:com.google.cast.sample.helloworld'); window.messageBus.onMessage = function(event) { displayVideo(event.data); // Inform all senders on the CastMessageBus of the incoming message event // sender message listener will be invoked window.messageBus.send(event.senderId, event.data); }; function displayVideo(torrentId) { var client = new WebTorrent(); client.add(torrentId, function (torrent) { var file = torrent.files[0]; file.renderTo('video'); }); } window.castReceiverManager.start(); </script> </body> </html> ``` Here is the code of my sender: ``` <!-- Copyright (C) 2014 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <html> <head> <style type="text/css"> html, body, #wrapper { height:100%; width: 100%; margin: 0; padding: 0; border: 0; } #wrapper td { vertical-align: middle; text-align: center; } input { font-family: "Arial", Arial, sans-serif; font-size: 40px; font-weight: bold; } .border { border: 2px solid #cccccc; border-radius: 5px; } .border:focus { outline: none; border-color: #8ecaed; box-shadow: 0 0 5px #8ecaed; } </style> <script type="text/javascript" src="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js"></script> <script type="text/javascript"> var applicationID = 'F5304A3D'; var namespace = 'urn:x-cast:com.google.cast.sample.helloworld'; var session = null; /** * Call initialization for Cast */ if (!chrome.cast || !chrome.cast.isAvailable) { setTimeout(initializeCastApi, 1000); } /** * initialization */ function initializeCastApi() { var sessionRequest = new chrome.cast.SessionRequest(applicationID); var apiConfig = new chrome.cast.ApiConfig(sessionRequest, sessionListener, receiverListener); chrome.cast.initialize(apiConfig, onInitSuccess, onError); }; /** * initialization success callback */ function onInitSuccess() { appendMessage("onInitSuccess"); } /** * initialization error callback */ function onError(message) { appendMessage("onError: "+JSON.stringify(message)); } /** * generic success callback */ function onSuccess(message) { appendMessage("onSuccess: "+message); } /** * callback on success for stopping app */ function onStopAppSuccess() { appendMessage('onStopAppSuccess'); } /** * session listener during initialization */ function sessionListener(e) { appendMessage('New session ID:' + e.sessionId); session = e; session.addUpdateListener(sessionUpdateListener); session.addMessageListener(namespace, receiverMessage); } /** * listener for session updates */ function sessionUpdateListener(isAlive) { var message = isAlive ? 'Session Updated' : 'Session Removed'; message += ': ' + session.sessionId; appendMessage(message); if (!isAlive) { session = null; } }; /** * utility function to log messages from the receiver * @param {string} namespace The namespace of the message * @param {string} message A message string */ function receiverMessage(namespace, message) { appendMessage("receiverMessage: "+namespace+", "+message); }; /** * receiver listener during initialization */ function receiverListener(e) { if( e === 'available' ) { appendMessage("receiver found"); } else { appendMessage("receiver list empty"); } } /** * stop app/session */ function stopApp() { session.stop(onStopAppSuccess, onError); } /** * send a message to the receiver using the custom namespace * receiver CastMessageBus message handler will be invoked * @param {string} message A message string */ function sendMessage(message) { if (session!=null) { session.sendMessage(namespace, message, onSuccess.bind(this, "Message sent: " + message), onError); } else { chrome.cast.requestSession(function(e) { session = e; session.sendMessage(namespace, message, onSuccess.bind(this, "Message sent: " + message), onError); }, onError); } } /** * append message to debug message window * @param {string} message A message string */ function appendMessage(message) { console.log(message); var dw = document.getElementById("debugmessage"); dw.innerHTML += '\n' + JSON.stringify(message); }; /** * utility function to handle text typed in by user in the input field */ function update() { sendMessage(document.getElementById("input").value); } /** * handler for the transcribed text from the speech input * @param {string} words A transcibed speech string */ function transcribe(words) { sendMessage(words); } </script> </head> <body> <table id="wrapper"> <tr> <td> <form method="get" action="JavaScript:update();"> <input id="input" class="border" type="text" size="30" onwebkitspeechchange="transcribe(this.value)" x-webkit-speech/> </form> </td> </tr> </table> <!-- Debbugging output --> <div style="margin:10px; visibility:hidden;"> <textarea rows="20" cols="70" id="debugmessage"> </textarea> </div> <script type="text/javascript"> document.getElementById("input").focus(); </script> </body> </html> ``` The problem: The receiver handles torrent id from sender and video plays as expected. But official Google Cast app or official Google Cast extension for Chrome doesn't show standard media controls for playing video to pause, stop, seek, etc. This is what I have (this is a screenshot of standard built-in modal dialog for Google Cast in the latest version of Google Chrome): [![Screenshot of standard built-in modal dialog for Google Cast in the latest version of Google Chrome](https://i.stack.imgur.com/FiBRg.png)](https://i.stack.imgur.com/FiBRg.png) This is what I want to achieve (this is a screenshot of standard built-in modal dialog for Google Cast in the latest version of Google Chrome): [![Screenshot of standard built-in modal dialog for Google Cast in the latest version of Google Chrome](https://i.stack.imgur.com/SsjfU.png)](https://i.stack.imgur.com/SsjfU.png) Adding ``` window.mediaElement = document.getElementById('media'); window.mediaManager = new cast.receiver.MediaManager(window.mediaElement); ``` for `<video autoplay id='media' />` element don't help. Should I add something to sender and/or receiver to add standard media controls for `<video autoplay id='media' />` on all senders? Maybe there is another way to send and receive torrent id without using Google Cast namespace and messageBus? **UPD** Looks like I've found the root of my problem... How to enable default media controls for existing playing video in receiver? For example, the receiver app already have playing video: ``` <video autoplay id='media' src='https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4' /> ``` How to enable default media controls - working buttons "Play/Pause", working progress bar (on all senders like official Google Cast extension for Chrome) for this playing video? Looks like adding the following code not help: ``` window.mediaElement = document.getElementById('media'); window.mediaManager = new cast.receiver.MediaManager(window.mediaElement); window.castReceiverManager = cast.receiver.CastReceiverManager.getInstance(); window.castReceiverManager.start(); ``` Here is the full source code of receiver: ``` <html> <head> <script src="https://www.gstatic.com/cast/sdk/libs/receiver/2.0.0/cast_receiver.js"></script> </head> <body> <video autoplay id='media' src='https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4' /> <script> window.mediaElement = document.getElementById('media'); window.mediaManager = new cast.receiver.MediaManager(window.mediaElement); window.castReceiverManager = cast.receiver.CastReceiverManager.getInstance(); window.castReceiverManager.start(); </script> </body> </html> ``` **UPD2:** Looks like it is possible to use any text string (the torrent id in my case) instead of media URL in `chrome.cast.media.MediaInfo` and use the media namespace instead of using custom namespace and custom message bus (i.e. without using <https://developers.google.com/cast/docs/reference/receiver/cast.receiver.CastReceiverManager#getCastMessageBus> and <https://developers.google.com/cast/docs/reference/receiver/cast.receiver.CastMessageBus> and <https://developers.google.com/cast/docs/reference/chrome/chrome.cast.Session#sendMessage>): ``` function cast() { url = 'magnet:?xt=urn:btih:6a9759bffd5c0af65319979fb7832189f4f3c35d'; chrome.cast.requestSession(function(session) { var mediaInfo = new chrome.cast.media.MediaInfo(url); //mediaInfo.contentType = 'video/mp4'; //mediaInfo.contentType = 'audio/mpeg'; //mediaInfo.contentType = 'image/jpeg'; var request = new chrome.cast.media.LoadRequest(mediaInfo); request.autoplay = true; session.loadMedia(request, function() {}, onError); }, onError); } ``` But how to handle it on the receiver in this case?
2016/04/26
[ "https://Stackoverflow.com/questions/36863154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4050470/" ]
There is actually an existing Google Cast UX Guidelines which states that the sender application must provide a top-level Cast button. There are three ways to support a Cast button which were fully discussed in [Android Sender App Development](https://developers.google.com/cast/docs/android_sender#top_of_page) * Using the MediaRouter ActionBar provider: android.support.v7.app.MediaRouteActionProvider * Using the MediaRouter Cast button: android.support.v7.app.MediaRouteButton * Developing a custom UI with the MediaRouter API’s and MediaRouter.Callback To show standard media controls once the media is playing, the sender application can control the media playback using the RemoteMediaPlayer instance. Steps and examples can be found in the documentation. For a comprehensive listing of all classes, methods and events in the Google Cast Android SDK, see the [Google Cast Android API Reference](https://developers.google.com/android/reference/com/google/android/gms/cast/package-summary#interfaces).
I realize it's been 3 years, but what jumps out at me is that you are missing the "controls" attribute on your video tag! Without the attribute, a player will render the video but provide no ui for controlling playback.... Syntax is the same as it is for autoplay: the controls attribute is standalone and takes no value. It is all or nothing - a standard set of controls with default styling, or none at all... if you were building for the browser, you might choose to omit the attribute and make your own controls to match the look and feel of the page. But based on the screenshots you shared, there's no need (and it might not work in a chromecast receiver environment) The correct html is below, and that should be all you need :) https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4' /> Please let us know if and how you ended up fixing your problem (and send me a DM... I recently started integrating webtorrent into a streaming video platform I'm creating and so far, so good, but the documentation is pretty bad and I have a few questions. Thanks!)
55,485,603
I have setup SMS on Twilio and can receive an SMS via webhooks. I can manipulate the form data to do what I want however every inbound SMS message throws an error on Twilio's dashboard. It's looking for some response. Right now I'm just dumping the form to a text file while testing. ``` <!doctype html> <?xml version="1.0" encoding="UTF-8"?> <html> <head> <Response> </Response> <cfdump var="#form#" label="HTTP Body" output="C:/webhook-sms.txt" /> </head> </html> ``` The error is: MESSAGE The markup in the document preceding the root element must be well-formed. Warning - 12200 Schema validation warning The provided XML does not conform to the Twilio Markup XML schema. Please refer to the specific error and correct the problem. What do I need to respond to Twilio with? Thanks in advance for any help! Gary
2019/04/03
[ "https://Stackoverflow.com/questions/55485603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10475625/" ]
Twilio expects a content type of `text/xml` and also expects the first line of the response to be `<?xml version="1.0" encoding="UTF-8"?>`. If your response has one or more empty lines before `<?xml version="1.0" encoding="UTF-8"?>` you're still going to get an error. What I ended up doing, was with an Application.cfm something like this: ``` <cfsetting enablecfoutputonly="true" showdebugoutput="false" requesttimeout="30" /> <cfheader name="content-type" value="text/xml" /> <!--- // more code ---> ``` and endpoint files which start with the first line like this: ``` <cfoutput><?xml version="1.0" encoding="UTF-8"?></cfoutput> <!--- // more code ---> ``` And make sure you send back valid TwiML (Twilio's XML) (no HTML).
Thanks everybody. My final test code looked like this: ``` <cfsetting enablecfoutputonly="true" showdebugoutput="false" requesttimeout="30" /> <cfheader name="content-type" value="text/xml" /> <cfoutput><?xml version="1.0" encoding="UTF-8"?> <Response> <Message>Thanks for getting in touch, I'll call you later</Message> </Response></cfoutput> ```
7,122,782
I want to compress the image with same quality using PHP.What is my situation is I want to display the user images when they loged in.Currently I am showing the original image whatever they uplaod in mysite.So if they uplaod 4MB file I am downloading the 4MB file and showing to them.Instead of that I want to compress the image with same quality. I want to do it with same height and width also.Like smush it trying to do.But for 4mb files its not working with smush it. Is there any way to do.How can I achieve it.
2011/08/19
[ "https://Stackoverflow.com/questions/7122782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197894/" ]
You can't compress an image maintaining the same quality and resolution. You can scale it down however (a 4MB JPEG file is pretty huge - if it's meant for screen use only, 1600 pixels or less image would do fine most of the times), using `GD`, `Imagick`, etc.
Try to convert them to different formats. gif is the best for small images. There are a lot of converting classes so just look around google
7,122,782
I want to compress the image with same quality using PHP.What is my situation is I want to display the user images when they loged in.Currently I am showing the original image whatever they uplaod in mysite.So if they uplaod 4MB file I am downloading the 4MB file and showing to them.Instead of that I want to compress the image with same quality. I want to do it with same height and width also.Like smush it trying to do.But for 4mb files its not working with smush it. Is there any way to do.How can I achieve it.
2011/08/19
[ "https://Stackoverflow.com/questions/7122782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197894/" ]
You can't compress an image maintaining the same quality and resolution. You can scale it down however (a 4MB JPEG file is pretty huge - if it's meant for screen use only, 1600 pixels or less image would do fine most of the times), using `GD`, `Imagick`, etc.
You should resize the images when they have been uploaded to your FTP server. Of course you will have to deal with a loss of quality and resolution. Have a look at <http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/>
74,427,883
I have a column that contains either letters or numbers. I want to add a column identifying whether each cell contains a letter or a number. The problem is that there are thousands of records in this particular database. I tried the following syntax: `= Table.AddColumn(Source, "Column2", each if [Column1] is number then "Number" else "Letters")` My problem is that when I enter this, it returns everything as "Letter" because it looks at the column type instead of the actual value in the cell. This remains the case even when I change the column type from Text to General. Either way, it still produces "Letter" as it automatically assigns text as the data type since the column contains both text and numbers.
2022/11/14
[ "https://Stackoverflow.com/questions/74427883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20172589/" ]
Use this expression: ``` = Table.AddColumn(Source, "Column2", each if List.Contains({"0".."9"}, Text.Start([Column1], 1)) then "Numbers" else "Letters") ``` [![enter image description here](https://i.stack.imgur.com/baEGV.png)](https://i.stack.imgur.com/baEGV.png) Note: It would have been smart to add sample data to your question so I wouldn't have to guess what your data actually looks like!
Add column, custom column with ``` = try if Value.Is(Number.From([Column1]), type number) then "number" else "not" otherwise "not" ``` Peter's method works if the choice is AAA/111 but this one tests for A11 and 1BC as well
9,919,909
I want to be able to limit Perl's `File::Find` to a directory depth (below the specified search) to the specified directory **and** 1 & 2 subdirectories beneath it. I want to be able to enumerate the files at the same time, if this is possible. It must work with absolute paths.
2012/03/29
[ "https://Stackoverflow.com/questions/9919909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/504239/" ]
This [perlmonks node](http://www.perlmonks.org/?node_id=217166) explains how to implement mindepth and maxdepth from GNU's find. Basically, they count the number of slashes in a directory, and use that to determine the depth. The [preprocess](http://perldoc.perl.org/File/Find.html#preprocess) function will then only return the values where the depth is smaller than the max\_depth. ``` my ($min_depth, $max_depth) = (2,3); find( { preprocess => \&preprocess, wanted => \&wanted, }, @dirs); sub preprocess { my $depth = $File::Find::dir =~ tr[/][]; return @_ if $depth < $max_depth; return grep { not -d } @_ if $depth == $max_depth; return; } sub wanted { my $depth = $File::Find::dir =~ tr[/][]; return if $depth < $min_depth; print; } ``` Tailored to your case: ``` use File::Find; my $max_depth = 2; find( { preprocess => \&preprocess, wanted => \&wanted, }, '.'); sub preprocess { my $depth = $File::Find::dir =~ tr[/][]; return @_ if $depth < $max_depth; return grep { not -d } @_ if $depth == $max_depth; return; } sub wanted { print $_ . "\n" if -f; #Only files } ```
Here is another solution that determines the current depth within `File::Find::find` by counting the number of directories returned by `File::Spec->splitdir`, which should be more portable than counting slashes: ``` use strict; use warnings; use File::Find; # maximum depth to continue search my $maxDepth = 2; # start with the absolute path my $findRoot = Cwd::realpath($ARGV[0] || "."); # determine the depth of our beginning directory my $begDepth = 1 + grep { length } File::Spec->splitdir($findRoot); find ( { preprocess => sub { @_ if (scalar File::Spec->splitdir($File::Find::dir) - $begDepth) <= $maxDepth }, wanted => sub { printf "%s$/", File::Spec->catfile($File::Find::dir, $_) if -f }, }, $findRoot ); ```
49,808,350
I'm new to android and I can't seemed to figure out what causes this error. Im trying to experiment a text view or edit view where if you click the button, it will save the inputted text and display it on the text view once you return to the app. The error prompt `error: cannot find symbol variable textView` and sometimes even `error: cannot find symbol variable Connect`. **Question:** why is it that `textView` got error even if I imported `import android.widget.TextView;` Also, why is the `import android.widget.TextView;` is colored light gray? below are the screenshots: [Import color to gray](https://i.stack.imgur.com/Ar0gS.jpg) and [Compiler error](https://i.stack.imgur.com/bQ5Y7.jpg) Here is my code ``` import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.EditText; public class MainActivity extends AppCompatActivity { EditText textView; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (EditText) findViewById(R.id.textView); button = (Button) findViewById(R.id.button); final SharedPreferences sharedPref = getPreferences(Connect.MODE_PRIVATE); String oldItem = sharedPref.getString("oldItem", "Nothing created yet..."); textView.setText(oldItem); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences.Editor editor = sharedPref.edit(); editor.putString("oldItem", textView.getText().toString()); editor.commit(); } }); } } ``` **Update:** I din't add any ID on my EditText XML code thats why the machine cannot find it. ``` android:id="@+id/textView" ``` Also, I updated from this ``` final SharedPreferences sharedPref = getPreferences(Connect.MODE_PRIVATE); ``` to this ``` final SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); ``` I'm not really sure what's the difference between Connect and Context. Thanks to @Kapil G
2018/04/13
[ "https://Stackoverflow.com/questions/49808350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9639128/" ]
Problem is: You are not using TextView. ``` textView = (EditText) findViewById(R.id.textView); ``` => ``` textView = (TextView) findViewById(R.id.textView); ``` Yes, EditText is a kind of TextView, but it seems that in your xml, it will be TextView. So, how about cast to TextView ?
It is simply nothing but unused. If you think you need it keep it or else you can remove it. Also most of the time imports are brought automatically so you dont have to worry. If you want to bring imports simply just do: ``` Alt + Enter ```
49,808,350
I'm new to android and I can't seemed to figure out what causes this error. Im trying to experiment a text view or edit view where if you click the button, it will save the inputted text and display it on the text view once you return to the app. The error prompt `error: cannot find symbol variable textView` and sometimes even `error: cannot find symbol variable Connect`. **Question:** why is it that `textView` got error even if I imported `import android.widget.TextView;` Also, why is the `import android.widget.TextView;` is colored light gray? below are the screenshots: [Import color to gray](https://i.stack.imgur.com/Ar0gS.jpg) and [Compiler error](https://i.stack.imgur.com/bQ5Y7.jpg) Here is my code ``` import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.EditText; public class MainActivity extends AppCompatActivity { EditText textView; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (EditText) findViewById(R.id.textView); button = (Button) findViewById(R.id.button); final SharedPreferences sharedPref = getPreferences(Connect.MODE_PRIVATE); String oldItem = sharedPref.getString("oldItem", "Nothing created yet..."); textView.setText(oldItem); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences.Editor editor = sharedPref.edit(); editor.putString("oldItem", textView.getText().toString()); editor.commit(); } }); } } ``` **Update:** I din't add any ID on my EditText XML code thats why the machine cannot find it. ``` android:id="@+id/textView" ``` Also, I updated from this ``` final SharedPreferences sharedPref = getPreferences(Connect.MODE_PRIVATE); ``` to this ``` final SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); ``` I'm not really sure what's the difference between Connect and Context. Thanks to @Kapil G
2018/04/13
[ "https://Stackoverflow.com/questions/49808350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9639128/" ]
Check you XML file to see if you have declared `R.id.textView` as TextView or Edittext. Both are different. Your input field is your EditText and your output field where you want to show the data is TextView. also not sure what you have declared as Connect. but `SharedPreference` need the mode from a Context so your line should be like this - ``` final SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); ``` Plus your import is coming as gray because you have not used TextView component anywhere in the activity.
It is simply nothing but unused. If you think you need it keep it or else you can remove it. Also most of the time imports are brought automatically so you dont have to worry. If you want to bring imports simply just do: ``` Alt + Enter ```
45,456,179
I have a chunk of code that does something like this: ``` if (sqlStatement.WillUpdateDatabase) DoThing1(); else DoThing2(); ``` Currently `WillUpdateDatabase`is implemented as ``` public bool WillUpdateDatabase { get { return statementText.StartsWith("SELECT"); } } ``` This catches the majority of cases, but it gets more complicated with `SELECT ... INTO ...`. And there are possibly a few other cases that I might need to take into account. **Just to be clear:** this is not to implement any type of security. There are other systems that check for SQL injection attacks, this bit of code just needs to make a choice whether to do thing1 or thing2. This seems like it should be a solved problem. Is there an industry standard way to do this reliably? **Update/clarification:** Something like `UPDATE Table1 SET Column1 = 'a' WHERE 1 = 2` should be treated as an update.
2017/08/02
[ "https://Stackoverflow.com/questions/45456179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2053848/" ]
As many others have commented, this really is a nasty problem and inspecting the SQL isn't really ever going to cut it for you because you'll practically end up writing an entire SQL parser (and that really would be reinventing the wheel). You'll probably have to make a database user that only has read permissions for all tables, then actually execute the query you want to test using that read-only user and catch the situations where it fails because of permission violations, (rather than SQL syntax etc)
Since your statement text will change values only with the SQL queries beginning with `UPDATE` or `INSERT`, one way to test if you query will try to update could be the following : ``` public bool WillUpdateDatabase { get { return (statementText.StartsWith("UPDATE") || statementText.StartsWith("INSERT") ) } } ``` But you cannot know if the query will effectively update some fields in the table. As an example, if your query is like `UPDATE persons SET age = 25 WHERE name = "John"` and there is no entry with name *John*, your query will try to update, but will obviously not be able to because there is nothing to update. **EDIT** Thanks to @NikBo and @Gusman, I replaced *Contains* with *StartsWith* to avoid any issue like Nik Bo explained in the comments bellow.
193,805
I need a plant that acts as a very relatively effective, portable source of stored chemical energy. I figure the best way to do this is to have a plant/plant-like organism that stores its unused energy as primarily adipose tissue instead of starch. I’ve currently settled on a tuber / potato-type thing that originates from a cold place with little sunlight (prone to long winters but short, warm summers). The plant has evolved to combat its own scarcity and a limited reproduction window by “hibernating” for most of the year and sprouting rapidly when the proper conditions are met. Its ability to hibernate allows it to go dormant for long periods of time - almost like a seed - and spring back up when re-planted and re-hydrated. The tuber itself is thick and fist-sized at the base, with a branched root system that resembles something like a mutated carrot. The roots have three layers: a thick skin, a carrot-like outer shell, and a core of unique adipose tissue. The two outer layers carry out normal root functions. The fatty core is composed of Cells with large, specialized leucoplasts that store fatty oil instead of starch. When it sprouts, its leaves are broad to absorb as much sunlight as possible. It’s thorny to deter opportunistic predators from getting to its roots. The flowers look very similar to your standard potato’s. The world is modern Earth-adjacent in every other way, so I’d like to know if my approach is Probable or at least reasonable, and if there’s anything else here I haven’t considered. I’m also curious if there’s any specific way this plant would have to look that conflicts with what I’ve imagined. This is also my first time posting here, so let me know if I’ve made any mistakes or need to be clearer!
2021/01/12
[ "https://worldbuilding.stackexchange.com/questions/193805", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/81873/" ]
**Probably Not** ---------------- @Cadence is entirely right in their assessment: there have been numerous cases throughout history where the expansion if an organized, agrarian society has been opposed by tight-knit groups of predators armed with human intelligence: indigenous peoples. **This isn’t just applicable to industrialized cultures practicing colonization** across the world in places like Australia, Latin America, Africa, and northeast Asia (Russia and Siberia). **It's also applicable to pre-Industrial Revolution civilizations like the medieval one in your OP.** The Romans rather infamously crushed numerous Stone and Iron Age agriculturalists and hunter-gatherers in France, England, Germany, and other places in northern Europe. China spread north and south from their initial birthplace along the Yellow River and crushed and incorporated less organized peoples along the way. The only reason they weren’t able to crush Outer Mongolia is they had trouble dealing with the logistics of the steppe nomads. The Japanese destroyed the Ainu. The Inca crushed and incorporated a lot of less organized peoples to form their empire. There are a lot of defeated, less organized cultures that show up in almost every culture's histories as footnotes. The list goes on and on and on. It's a recurring theme in human history. **The closest thing you're looking for to your setting in historical terms is the settlement of the American West and the displacement of the many, many Native American nations that lived there.** Many Native American nations at the time have traits that resemble your species: they didn't have permanent settlements or build cities, they lived as semi-migratory hunter-gatherers, and they didn't have heavy industry (this varied, of course, for example many nations did build large forts, but the broader point is they weren't organized in the types of agrarian societies common in Africa, Mesoamerica, Europe, or Asia, especially in the Great Plains region). There's been a lot of debate as to how the Europeans managed to displace the Native Americans but in terms of micro-scale interaction what really won the West for European settlers was that there were a lot more of them and they just. Wouldn't. Stop. Coming. The Native Americans and settlers butchered and back-stabbed each other with alarming frequency but the problem was even after entire towns were burned to the ground and their inhabitants killed or enslaved more European settlers would simply come from the east to replace them, whereas the Native tribes couldn't sustain the heavy losses. Just read the diaries of some of these settlers, even though they *knew* settlers in the area had been killed by the natives less than a winter before they were still rosy-eyed and optimistic about trying to settle in such an area. Many believed they were protected by God, or that the danger of Native Americans was overblown, or that European-style civiliztion would inevitably triumph, and were completely oblivious to the danger. **The only thing historically that could have preserved the Native American tribes would be them giving the Europeans enough of a bloody nose that they decided moving west wasn't worth it and force them to respect some arbitrarily set border.** This almost happened when Roanoke Island went bust and Jamestown was in the toilet, England almost gave up on colonizing the New World until John Smith managed to turn the colony around. However, even this might not be enough. One of the grievances behind the American Revolution was that King George III [banned settlement west of the Appalachians](https://en.wikipedia.org/wiki/Royal_Proclamation_of_1763#Proclamation_line) because they were afraid of the colonists aggravating the natives and starting a major war, especially since one of their neighbors was the very organized Iroquois (i.e., Haudenosaunee) Confederacy. The colonists ignored it and started going west anyway. Indeed, it's even been suggested that one of the reasons agriculturalists won out over hunter-gatherers despite hunting and gathering being a much healthier lifestyle that offered more leisure time and less overall stress than primitive agriculture is that agriculture allowed a plot of land to support more humans in a smaller amount of space, and these miserable, disease-ridden humans were too organized and too numerous for any hunter-gatherer band to stop. It should be noted this isn't too different from what humans did as hunter-gatherers, spreading out into the wilderness and killing off threatening megafauna in opportunistic encounters as they went. In some places like Africa or Siberia the megafauna were too hard to get at, but all that meant was they started to go extinct when humanity started to get better weapons. This is what you're looking at with your story. Wave after wave of colonists setting out again and again to try to settle the wilderness, only for most of them to get butchered by the local wildlife. Then another batch try again, believing that unlike previous efforts theirs are blessed by God, or in search of wealth and riches, or out of desperation due to being forced out of their former cities by political disputes, famine, poverty, or lack of opportunities. Most die. But a few of them survive. And with that, they slowly chip away at the wilderness, bit by bit, until they've swallowed it into their domain, and the human empire expands across the continent. **On top of this, your premise has basically thrown out diplomacy as a possible alternative.** It's not clear if the megafauna can even communicate with humans, and even if they could it's no guarantee the humans would recognize them as sapient. Heck, even today humans recognizing the sapience of great apes, cetaceans, parrots, corvids, and elephants and whether our treatment of them is ethical is controversial. Not to mention a common theme throughout human history is that the more organized invading force often saw the native population as subhuman anyway and treated them as such (and again, this isn't just a colonization thing, the Romans saw the Germanic peoples as little better than talking animals or savages. Part of the reason people like the Goths winning against Rome took the Romans by surprise is the Romans had been so brainwashed by propaganda that the "barbarians" were uncivilized idiots they ignored the fact that the barbarians had become organized and were politically savvy). Even if they can communicate, it's almost a guarantee that the people actually interacting with them won't want to. In cases of colonial warfare with natives, it's almost invariably people on the frontier who have lost loved ones to the conflict that least want peace. For example in many New World countries the central government tried to preserve peace with the natives but the settlers were the ones least sympathetic to the poor treatment of native groups and most likely to start violence with them. **The only, and I mean only, things that have ever stopped humans from colonizing an area are either environmental conditions that are too hostile for permanent settlement ([and even then](https://en.wikipedia.org/wiki/Greenland#Norse_settlement), [that won't stop](https://en.wikipedia.org/wiki/History_of_Antarctica) humans from trying anyway), or enough of a military response that forces humans to back off via threat of force.** And the only way you could do that against a medieval human power is either a standing army or organisms that are simply so overpowered that humans can't survive against them. Of course, that raises the question of why your animals haven't wiped out humans yet. If a group of dragons is powerful enough to wipe out a human army, then why doesn't a displaced flock of dragons simply wipe out a town to make a new nesting ground. When humans kill humans in the long term there are still humans left at the end of the day. If megafauna wipe out humans too much humans go extinct. **Even in a situation where the whole ecosystem turns against humanity Pandora-style, what humans will just end up doing is burning the entire ecosystem to the ground and importing their own plants and livestock to replace it.** This is basically what happened in New Zealand. New Zealand (and to a lesser degree Australia) was utterly unsuitable for European-style agriculture because it lacked a lot of the commensal organisms that made European-style agriculture thrive, such as dung beetles to break down and recycle ungulate poop and earthworms to break down and aerate the soil. What did settlers do? They ripped out the New Zealand ecosystem wholesale and replaced it with a mishmash of Eurasian species, creating a fake Eurasian ecosystem in New Zealand.
To stop medieval humans settling in an area, all you need to do is make their crops die. There are so many ways to do this if the animals are out to get us: * Birds that see humans planting crops and go in and eat the seeds (or fly away with them for their own crops). Also they eat anything naturally occurring near the attempted human settlement. * Animals can scoop up salt from a dry lake bed and scatter it over farmland. Birds may do this from the air if humans start guarding their farmlands in response to the first attempt. * Worms eat the roots of the plants under the ground. * An underground animal excavated under the crops, so water drains away from the roots. * Birds refuse to poo on the fields, depriving them of fertilisation. * A smart animal can call in locusts or other animals to strip the fields. * Rats can poison themselves and then intentionally die in the human fields, introducing poison into the food chain. * Animals can pretend to be easy to hunt, but skillfully dodge arrows at the last second, leading the humans on pointless hunts that take up the bulk of their time, leaving them no time for farming. * Animals can poison themselves and then let humans hunt them, killing the humans who eat them. * Animals can bring infected plants into the human fields, intentionally spreading wheat blight or other such things.
193,805
I need a plant that acts as a very relatively effective, portable source of stored chemical energy. I figure the best way to do this is to have a plant/plant-like organism that stores its unused energy as primarily adipose tissue instead of starch. I’ve currently settled on a tuber / potato-type thing that originates from a cold place with little sunlight (prone to long winters but short, warm summers). The plant has evolved to combat its own scarcity and a limited reproduction window by “hibernating” for most of the year and sprouting rapidly when the proper conditions are met. Its ability to hibernate allows it to go dormant for long periods of time - almost like a seed - and spring back up when re-planted and re-hydrated. The tuber itself is thick and fist-sized at the base, with a branched root system that resembles something like a mutated carrot. The roots have three layers: a thick skin, a carrot-like outer shell, and a core of unique adipose tissue. The two outer layers carry out normal root functions. The fatty core is composed of Cells with large, specialized leucoplasts that store fatty oil instead of starch. When it sprouts, its leaves are broad to absorb as much sunlight as possible. It’s thorny to deter opportunistic predators from getting to its roots. The flowers look very similar to your standard potato’s. The world is modern Earth-adjacent in every other way, so I’d like to know if my approach is Probable or at least reasonable, and if there’s anything else here I haven’t considered. I’m also curious if there’s any specific way this plant would have to look that conflicts with what I’ve imagined. This is also my first time posting here, so let me know if I’ve made any mistakes or need to be clearer!
2021/01/12
[ "https://worldbuilding.stackexchange.com/questions/193805", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/81873/" ]
A better natural barrier to human settlement in an area would be endemic diseases. There are plenty of pathogens in the real world that have reservoirs in various wild species, so they're almost impossible to properly eliminate. Sicknesses like malaria constrained European colonization for centuries until effective medications for them were discovered. The local peoples had a few genetic mutations and cultural practices that meant they didn't suffer from said diseases as much as the would-be colonizers. If anyone who tries to live in, say, a certain area of marshland starts coughing up blood and dies within a few weeks, settling there is going to look like a much less attractive prospect. In a pre-modern setting, people may even assume that the land is cursed, or the water is poisonous.
To stop medieval humans settling in an area, all you need to do is make their crops die. There are so many ways to do this if the animals are out to get us: * Birds that see humans planting crops and go in and eat the seeds (or fly away with them for their own crops). Also they eat anything naturally occurring near the attempted human settlement. * Animals can scoop up salt from a dry lake bed and scatter it over farmland. Birds may do this from the air if humans start guarding their farmlands in response to the first attempt. * Worms eat the roots of the plants under the ground. * An underground animal excavated under the crops, so water drains away from the roots. * Birds refuse to poo on the fields, depriving them of fertilisation. * A smart animal can call in locusts or other animals to strip the fields. * Rats can poison themselves and then intentionally die in the human fields, introducing poison into the food chain. * Animals can pretend to be easy to hunt, but skillfully dodge arrows at the last second, leading the humans on pointless hunts that take up the bulk of their time, leaving them no time for farming. * Animals can poison themselves and then let humans hunt them, killing the humans who eat them. * Animals can bring infected plants into the human fields, intentionally spreading wheat blight or other such things.
193,805
I need a plant that acts as a very relatively effective, portable source of stored chemical energy. I figure the best way to do this is to have a plant/plant-like organism that stores its unused energy as primarily adipose tissue instead of starch. I’ve currently settled on a tuber / potato-type thing that originates from a cold place with little sunlight (prone to long winters but short, warm summers). The plant has evolved to combat its own scarcity and a limited reproduction window by “hibernating” for most of the year and sprouting rapidly when the proper conditions are met. Its ability to hibernate allows it to go dormant for long periods of time - almost like a seed - and spring back up when re-planted and re-hydrated. The tuber itself is thick and fist-sized at the base, with a branched root system that resembles something like a mutated carrot. The roots have three layers: a thick skin, a carrot-like outer shell, and a core of unique adipose tissue. The two outer layers carry out normal root functions. The fatty core is composed of Cells with large, specialized leucoplasts that store fatty oil instead of starch. When it sprouts, its leaves are broad to absorb as much sunlight as possible. It’s thorny to deter opportunistic predators from getting to its roots. The flowers look very similar to your standard potato’s. The world is modern Earth-adjacent in every other way, so I’d like to know if my approach is Probable or at least reasonable, and if there’s anything else here I haven’t considered. I’m also curious if there’s any specific way this plant would have to look that conflicts with what I’ve imagined. This is also my first time posting here, so let me know if I’ve made any mistakes or need to be clearer!
2021/01/12
[ "https://worldbuilding.stackexchange.com/questions/193805", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/81873/" ]
**Probably Not** ---------------- @Cadence is entirely right in their assessment: there have been numerous cases throughout history where the expansion if an organized, agrarian society has been opposed by tight-knit groups of predators armed with human intelligence: indigenous peoples. **This isn’t just applicable to industrialized cultures practicing colonization** across the world in places like Australia, Latin America, Africa, and northeast Asia (Russia and Siberia). **It's also applicable to pre-Industrial Revolution civilizations like the medieval one in your OP.** The Romans rather infamously crushed numerous Stone and Iron Age agriculturalists and hunter-gatherers in France, England, Germany, and other places in northern Europe. China spread north and south from their initial birthplace along the Yellow River and crushed and incorporated less organized peoples along the way. The only reason they weren’t able to crush Outer Mongolia is they had trouble dealing with the logistics of the steppe nomads. The Japanese destroyed the Ainu. The Inca crushed and incorporated a lot of less organized peoples to form their empire. There are a lot of defeated, less organized cultures that show up in almost every culture's histories as footnotes. The list goes on and on and on. It's a recurring theme in human history. **The closest thing you're looking for to your setting in historical terms is the settlement of the American West and the displacement of the many, many Native American nations that lived there.** Many Native American nations at the time have traits that resemble your species: they didn't have permanent settlements or build cities, they lived as semi-migratory hunter-gatherers, and they didn't have heavy industry (this varied, of course, for example many nations did build large forts, but the broader point is they weren't organized in the types of agrarian societies common in Africa, Mesoamerica, Europe, or Asia, especially in the Great Plains region). There's been a lot of debate as to how the Europeans managed to displace the Native Americans but in terms of micro-scale interaction what really won the West for European settlers was that there were a lot more of them and they just. Wouldn't. Stop. Coming. The Native Americans and settlers butchered and back-stabbed each other with alarming frequency but the problem was even after entire towns were burned to the ground and their inhabitants killed or enslaved more European settlers would simply come from the east to replace them, whereas the Native tribes couldn't sustain the heavy losses. Just read the diaries of some of these settlers, even though they *knew* settlers in the area had been killed by the natives less than a winter before they were still rosy-eyed and optimistic about trying to settle in such an area. Many believed they were protected by God, or that the danger of Native Americans was overblown, or that European-style civiliztion would inevitably triumph, and were completely oblivious to the danger. **The only thing historically that could have preserved the Native American tribes would be them giving the Europeans enough of a bloody nose that they decided moving west wasn't worth it and force them to respect some arbitrarily set border.** This almost happened when Roanoke Island went bust and Jamestown was in the toilet, England almost gave up on colonizing the New World until John Smith managed to turn the colony around. However, even this might not be enough. One of the grievances behind the American Revolution was that King George III [banned settlement west of the Appalachians](https://en.wikipedia.org/wiki/Royal_Proclamation_of_1763#Proclamation_line) because they were afraid of the colonists aggravating the natives and starting a major war, especially since one of their neighbors was the very organized Iroquois (i.e., Haudenosaunee) Confederacy. The colonists ignored it and started going west anyway. Indeed, it's even been suggested that one of the reasons agriculturalists won out over hunter-gatherers despite hunting and gathering being a much healthier lifestyle that offered more leisure time and less overall stress than primitive agriculture is that agriculture allowed a plot of land to support more humans in a smaller amount of space, and these miserable, disease-ridden humans were too organized and too numerous for any hunter-gatherer band to stop. It should be noted this isn't too different from what humans did as hunter-gatherers, spreading out into the wilderness and killing off threatening megafauna in opportunistic encounters as they went. In some places like Africa or Siberia the megafauna were too hard to get at, but all that meant was they started to go extinct when humanity started to get better weapons. This is what you're looking at with your story. Wave after wave of colonists setting out again and again to try to settle the wilderness, only for most of them to get butchered by the local wildlife. Then another batch try again, believing that unlike previous efforts theirs are blessed by God, or in search of wealth and riches, or out of desperation due to being forced out of their former cities by political disputes, famine, poverty, or lack of opportunities. Most die. But a few of them survive. And with that, they slowly chip away at the wilderness, bit by bit, until they've swallowed it into their domain, and the human empire expands across the continent. **On top of this, your premise has basically thrown out diplomacy as a possible alternative.** It's not clear if the megafauna can even communicate with humans, and even if they could it's no guarantee the humans would recognize them as sapient. Heck, even today humans recognizing the sapience of great apes, cetaceans, parrots, corvids, and elephants and whether our treatment of them is ethical is controversial. Not to mention a common theme throughout human history is that the more organized invading force often saw the native population as subhuman anyway and treated them as such (and again, this isn't just a colonization thing, the Romans saw the Germanic peoples as little better than talking animals or savages. Part of the reason people like the Goths winning against Rome took the Romans by surprise is the Romans had been so brainwashed by propaganda that the "barbarians" were uncivilized idiots they ignored the fact that the barbarians had become organized and were politically savvy). Even if they can communicate, it's almost a guarantee that the people actually interacting with them won't want to. In cases of colonial warfare with natives, it's almost invariably people on the frontier who have lost loved ones to the conflict that least want peace. For example in many New World countries the central government tried to preserve peace with the natives but the settlers were the ones least sympathetic to the poor treatment of native groups and most likely to start violence with them. **The only, and I mean only, things that have ever stopped humans from colonizing an area are either environmental conditions that are too hostile for permanent settlement ([and even then](https://en.wikipedia.org/wiki/Greenland#Norse_settlement), [that won't stop](https://en.wikipedia.org/wiki/History_of_Antarctica) humans from trying anyway), or enough of a military response that forces humans to back off via threat of force.** And the only way you could do that against a medieval human power is either a standing army or organisms that are simply so overpowered that humans can't survive against them. Of course, that raises the question of why your animals haven't wiped out humans yet. If a group of dragons is powerful enough to wipe out a human army, then why doesn't a displaced flock of dragons simply wipe out a town to make a new nesting ground. When humans kill humans in the long term there are still humans left at the end of the day. If megafauna wipe out humans too much humans go extinct. **Even in a situation where the whole ecosystem turns against humanity Pandora-style, what humans will just end up doing is burning the entire ecosystem to the ground and importing their own plants and livestock to replace it.** This is basically what happened in New Zealand. New Zealand (and to a lesser degree Australia) was utterly unsuitable for European-style agriculture because it lacked a lot of the commensal organisms that made European-style agriculture thrive, such as dung beetles to break down and recycle ungulate poop and earthworms to break down and aerate the soil. What did settlers do? They ripped out the New Zealand ecosystem wholesale and replaced it with a mishmash of Eurasian species, creating a fake Eurasian ecosystem in New Zealand.
A better natural barrier to human settlement in an area would be endemic diseases. There are plenty of pathogens in the real world that have reservoirs in various wild species, so they're almost impossible to properly eliminate. Sicknesses like malaria constrained European colonization for centuries until effective medications for them were discovered. The local peoples had a few genetic mutations and cultural practices that meant they didn't suffer from said diseases as much as the would-be colonizers. If anyone who tries to live in, say, a certain area of marshland starts coughing up blood and dies within a few weeks, settling there is going to look like a much less attractive prospect. In a pre-modern setting, people may even assume that the land is cursed, or the water is poisonous.
13,975,595
I am working on an application which is compatible only with IE7 and IE8. I didn't know why but some suggested to use CSS over XPath while identifying the elements in IE. When I visited the official Selenium site. I read the message > > WebDriver uses a browser’s native XPath capabilities wherever possible. On those browsers that don’t have native XPath support, we have provided our own implementation. This can lead to some unexpected behaviour unless you are aware of the differences in the various xpath engines. > > > I would like to know where I can find the differences in the various xpath engines and in which situations I should use CSS and and in which XPath specifically if I'm using IE. Thanks.
2012/12/20
[ "https://Stackoverflow.com/questions/13975595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1918282/" ]
According to Ashley Wilson's [report from sauce labs](http://sauceio.com/index.php/2011/05/why-css-locators-are-the-way-to-go-vs-xpath/): **Pros**: 1. They’re faster 2. They’re more readable 3. CSS is jQuery’s locating strategy 4. No one else uses XPATH anyways! It's a bit outdated, however here are the numbers: ![image from cause lab's web site](https://i.stack.imgur.com/JNCmx.jpg) Personally, I would argue about (2)-nd statement, I must agree with the rest. **Cons**: 1. No "bottom up" navigation. XPath has `elem\..\another_elem` 2. Is Sizzle injected? Or Browser's CSS locator parser is used? Depends on the browser, and there are inconsistencies.
The biggest reason for suggesting CSS selectors over XPath in IE is performance. IE does not provide a native XPath-over-HTML option as does Firefox and Chrome. It does, however, provide a native CSS selector engine, which will **always** be faster than the JavaScript-only XPath engine implementation used in the IE driver. And the performance comparison isn't even close. I've seen it measured as much as an order of magnitude slower for XPath locators than CSS selectors (though I can't find the citation at the moment). This is particularly true in versions of IE before 9, where the IE JavaScript engine was vastly slower than the Chakra JavaScript engine introduced in 32-bit IE9.
13,975,595
I am working on an application which is compatible only with IE7 and IE8. I didn't know why but some suggested to use CSS over XPath while identifying the elements in IE. When I visited the official Selenium site. I read the message > > WebDriver uses a browser’s native XPath capabilities wherever possible. On those browsers that don’t have native XPath support, we have provided our own implementation. This can lead to some unexpected behaviour unless you are aware of the differences in the various xpath engines. > > > I would like to know where I can find the differences in the various xpath engines and in which situations I should use CSS and and in which XPath specifically if I'm using IE. Thanks.
2012/12/20
[ "https://Stackoverflow.com/questions/13975595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1918282/" ]
The biggest reason for suggesting CSS selectors over XPath in IE is performance. IE does not provide a native XPath-over-HTML option as does Firefox and Chrome. It does, however, provide a native CSS selector engine, which will **always** be faster than the JavaScript-only XPath engine implementation used in the IE driver. And the performance comparison isn't even close. I've seen it measured as much as an order of magnitude slower for XPath locators than CSS selectors (though I can't find the citation at the moment). This is particularly true in versions of IE before 9, where the IE JavaScript engine was vastly slower than the Chakra JavaScript engine introduced in 32-bit IE9.
Using CSS locator is the best option, not only on IE, also on FF and Chrome. Also, xpath is always the worst choice, because it needs to parse the whole page to find a simple element, so if you want performance in your tests and you can avoid it, just do it. Also, if you are using pageObjects I strongly recommend you to use cacheLookup, so the element will be located just once: ``` @CacheLookup @FindBy(id="doLogin") private WebElement loginButton; ``` Personally, I do the following: * If element has css class, use this locator * If element has name or id, use this locator * If none of the above is present, and you can not use linkText or another locator, go for xpath.
13,975,595
I am working on an application which is compatible only with IE7 and IE8. I didn't know why but some suggested to use CSS over XPath while identifying the elements in IE. When I visited the official Selenium site. I read the message > > WebDriver uses a browser’s native XPath capabilities wherever possible. On those browsers that don’t have native XPath support, we have provided our own implementation. This can lead to some unexpected behaviour unless you are aware of the differences in the various xpath engines. > > > I would like to know where I can find the differences in the various xpath engines and in which situations I should use CSS and and in which XPath specifically if I'm using IE. Thanks.
2012/12/20
[ "https://Stackoverflow.com/questions/13975595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1918282/" ]
The biggest reason for suggesting CSS selectors over XPath in IE is performance. IE does not provide a native XPath-over-HTML option as does Firefox and Chrome. It does, however, provide a native CSS selector engine, which will **always** be faster than the JavaScript-only XPath engine implementation used in the IE driver. And the performance comparison isn't even close. I've seen it measured as much as an order of magnitude slower for XPath locators than CSS selectors (though I can't find the citation at the moment). This is particularly true in versions of IE before 9, where the IE JavaScript engine was vastly slower than the Chakra JavaScript engine introduced in 32-bit IE9.
Brevity and Clarity are other reasons, in addition to speed. ------------------------------------------------------------ In addition to speed, I find that css is usually shorter and cleaner and easier to read. For example: xpath: ``` //ol[@class='choice-group'//li//label//input ``` vs css: ``` css=ol.choices-group li label input ```
13,975,595
I am working on an application which is compatible only with IE7 and IE8. I didn't know why but some suggested to use CSS over XPath while identifying the elements in IE. When I visited the official Selenium site. I read the message > > WebDriver uses a browser’s native XPath capabilities wherever possible. On those browsers that don’t have native XPath support, we have provided our own implementation. This can lead to some unexpected behaviour unless you are aware of the differences in the various xpath engines. > > > I would like to know where I can find the differences in the various xpath engines and in which situations I should use CSS and and in which XPath specifically if I'm using IE. Thanks.
2012/12/20
[ "https://Stackoverflow.com/questions/13975595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1918282/" ]
According to Ashley Wilson's [report from sauce labs](http://sauceio.com/index.php/2011/05/why-css-locators-are-the-way-to-go-vs-xpath/): **Pros**: 1. They’re faster 2. They’re more readable 3. CSS is jQuery’s locating strategy 4. No one else uses XPATH anyways! It's a bit outdated, however here are the numbers: ![image from cause lab's web site](https://i.stack.imgur.com/JNCmx.jpg) Personally, I would argue about (2)-nd statement, I must agree with the rest. **Cons**: 1. No "bottom up" navigation. XPath has `elem\..\another_elem` 2. Is Sizzle injected? Or Browser's CSS locator parser is used? Depends on the browser, and there are inconsistencies.
Using CSS locator is the best option, not only on IE, also on FF and Chrome. Also, xpath is always the worst choice, because it needs to parse the whole page to find a simple element, so if you want performance in your tests and you can avoid it, just do it. Also, if you are using pageObjects I strongly recommend you to use cacheLookup, so the element will be located just once: ``` @CacheLookup @FindBy(id="doLogin") private WebElement loginButton; ``` Personally, I do the following: * If element has css class, use this locator * If element has name or id, use this locator * If none of the above is present, and you can not use linkText or another locator, go for xpath.
13,975,595
I am working on an application which is compatible only with IE7 and IE8. I didn't know why but some suggested to use CSS over XPath while identifying the elements in IE. When I visited the official Selenium site. I read the message > > WebDriver uses a browser’s native XPath capabilities wherever possible. On those browsers that don’t have native XPath support, we have provided our own implementation. This can lead to some unexpected behaviour unless you are aware of the differences in the various xpath engines. > > > I would like to know where I can find the differences in the various xpath engines and in which situations I should use CSS and and in which XPath specifically if I'm using IE. Thanks.
2012/12/20
[ "https://Stackoverflow.com/questions/13975595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1918282/" ]
According to Ashley Wilson's [report from sauce labs](http://sauceio.com/index.php/2011/05/why-css-locators-are-the-way-to-go-vs-xpath/): **Pros**: 1. They’re faster 2. They’re more readable 3. CSS is jQuery’s locating strategy 4. No one else uses XPATH anyways! It's a bit outdated, however here are the numbers: ![image from cause lab's web site](https://i.stack.imgur.com/JNCmx.jpg) Personally, I would argue about (2)-nd statement, I must agree with the rest. **Cons**: 1. No "bottom up" navigation. XPath has `elem\..\another_elem` 2. Is Sizzle injected? Or Browser's CSS locator parser is used? Depends on the browser, and there are inconsistencies.
Brevity and Clarity are other reasons, in addition to speed. ------------------------------------------------------------ In addition to speed, I find that css is usually shorter and cleaner and easier to read. For example: xpath: ``` //ol[@class='choice-group'//li//label//input ``` vs css: ``` css=ol.choices-group li label input ```
13,975,595
I am working on an application which is compatible only with IE7 and IE8. I didn't know why but some suggested to use CSS over XPath while identifying the elements in IE. When I visited the official Selenium site. I read the message > > WebDriver uses a browser’s native XPath capabilities wherever possible. On those browsers that don’t have native XPath support, we have provided our own implementation. This can lead to some unexpected behaviour unless you are aware of the differences in the various xpath engines. > > > I would like to know where I can find the differences in the various xpath engines and in which situations I should use CSS and and in which XPath specifically if I'm using IE. Thanks.
2012/12/20
[ "https://Stackoverflow.com/questions/13975595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1918282/" ]
Brevity and Clarity are other reasons, in addition to speed. ------------------------------------------------------------ In addition to speed, I find that css is usually shorter and cleaner and easier to read. For example: xpath: ``` //ol[@class='choice-group'//li//label//input ``` vs css: ``` css=ol.choices-group li label input ```
Using CSS locator is the best option, not only on IE, also on FF and Chrome. Also, xpath is always the worst choice, because it needs to parse the whole page to find a simple element, so if you want performance in your tests and you can avoid it, just do it. Also, if you are using pageObjects I strongly recommend you to use cacheLookup, so the element will be located just once: ``` @CacheLookup @FindBy(id="doLogin") private WebElement loginButton; ``` Personally, I do the following: * If element has css class, use this locator * If element has name or id, use this locator * If none of the above is present, and you can not use linkText or another locator, go for xpath.
280,797
I need to choose and install a server-client platform for a ~150 user base. They should be able to upload files (after logging in) through a web form and browse folders, download whatever the other users have uploaded, etc. All files would be private, no public links are generated. Some basic admin tasks would be needed too (add users, delete files). It should run over PHP + MySQL since it's gonna be deployed in a basic, third-party hosting service. I know that FTP would be the straightforward solution but something fancier is required. The team wouldn't mind paying for a license as long as we're getting a popular, solid product. What's your recommendation?
2011/06/15
[ "https://serverfault.com/questions/280797", "https://serverfault.com", "https://serverfault.com/users/84658/" ]
Take a look at [filesender](http://www.filesender.org/) it is a new development for the academic (R&D) world, but it might suit your needs. There is a feature list on its website which I will not repeat here. Take a look and decide if it is for you or not.
[nephthys](http://oss.netshadow.at/wiki/nephthys) seems also apropriate, it has nice features as well.
165,756
Simple question: discounting Dumbledore (who knew Snape's loyalty was with him) and, eventually, Harry, **did the other members of the Order of the Phoenix like Sirius, Remus, Hagrid and others know that Snape was on their side?**
2017/07/26
[ "https://scifi.stackexchange.com/questions/165756", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/70135/" ]
Before the Battle of Hogwarts: No. I have no hard source for this, but there is some evidence: * Snape was treated like a traitor, for example, they secured Grimauld Place 12 against him * The Order forced Snape out of Hogwarts shortly before the final battle, that's not something you would do to an ally in such a desperate situation * After the battle at the Astronomy Tower, everyone seemed surprised by Snapes actions, so they were not aware of Dumbledore's plan to get killed by Snape, and thus had no reason to still expect him to be on the Orders side.
Snape was always known to be a double-agent, but everyone trusted his loyalty being with Dumbledore. At least, until the Battle of the Astronomy Tower. --- > > [...] Sirius and Snape were eyeing each other with the utmost loathing. > > > "I will settle, in the short term,' said Dumbledore, with a bite of impatience in his voice, "for a lack of open hostility. You will shake hands. You are on the same side now. Time is short, and unless the few of us who know the truth do not stand united, there is no hope for any us." > > > Very slowly — but still glaring at each other as though each wished the other nothing but ill — Sirius and Snape moved toward each other and shook hands. They let go extremely quickly. > > > "That will do to be going on with," said Dumbledore, stepping between them once more. [...] > > > *Harry Potter and the Goblet of Fire*, chapter 36, "The Parting of the Ways" > > > Here Dumbledore made absolutely clear to Sirius, a prominent member of the Order of the Phoenix, that he trusts Snape. > > "It isn't our business to know," said Lupin unexpectedly. He had turned his back on the fire now and faced Harry across Mr. Weasley. "It's Dumbledore's business. Dumbledore trusts Severus, and that ought to be good enough for all of us." > > > "But," said Harry, "just say — just say Dumbledore's wrong about Snape —" > > > "People have said it, many times. It comes down to whether or not you trust Dumbledore's judgement. I do; therefore, I trust Severus." > > > *Harry Potter and the Half-Blood Prince*, chapter 16, "A Very Frosty Christmas" > > > Here Lupin makes clear that he trusts Snape because he trusts Dumbledore. A bit further in the same chapter, he makes clear that Snape helped him when he was teaching Defense Against the Dark Arts at Hogwarts. --- The Battle of the Astronomy Tower changes this. > > "Snape," repeated McGonagall faintly, falling into the chair. "We all wondered... but he trusted... always... Snape... I can't believe it. ..." > > > "Snape was a highly accomplished Occlumens," said Lupin, his voice uncharacteristically harsh. "We always knew that." > > > "But Dumbledore swore he was on our side!" whispered Tonks. "I always thought Dumbledore must know something about Snape that we didn't. ..." > > > *Harry Potter and the Half-Blood Prince*, chapter 29, "The Phoenix Lament" > > > Of course, after Snape killing Dumbledore, how could anyone still believe him not to be on Voldemort's side? Only through what Harry learns of the deal between Snape and Dumbledore, is Snape redeemed again at the end of the saga.
50,088,730
I have a numpy array with shape likes ``` a1.shape # 1000 a1[0].shape # (100, 100, 3) ``` I want to change the shape in the way that ``` a1.shape # (1000, 100, 100, 3) ``` How can I achieve this?
2018/04/29
[ "https://Stackoverflow.com/questions/50088730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3866981/" ]
Make a list of arrays with differing shapes (but same number of elements): ``` In [72]: alist = [np.ones((2,3),int),np.zeros(6,int),np.arange(6)] In [73]: alist Out[73]: [array([[1, 1, 1], [1, 1, 1]]), array([0, 0, 0, 0, 0, 0]), array([0, 1, 2, 3, 4, 5])] In [74]: np.array(alist) Out[74]: array([array([[1, 1, 1], [1, 1, 1]]), array([0, 0, 0, 0, 0, 0]), array([0, 1, 2, 3, 4, 5])], dtype=object) ``` The result is an object dtype array. But if we reshape all elements of the list to the same shape, we get a 3d array: ``` In [75]: np.array([x.reshape(2,3) for x in alist]) Out[75]: array([[[1, 1, 1], [1, 1, 1]], [[0, 0, 0], [0, 0, 0]], [[0, 1, 2], [3, 4, 5]]]) ``` Now lets try reshaping elements after making the array: ``` In [76]: arr = np.array(alist) In [77]: arr.shape Out[77]: (3,) In [78]: for i in range(3): ...: arr[i] = arr[i].reshape(2,3) ...: In [79]: arr Out[79]: array([array([[1, 1, 1], [1, 1, 1]]), array([[0, 0, 0], [0, 0, 0]]), array([[0, 1, 2], [3, 4, 5]])], dtype=object) In [80]: np.array(arr) Out[80]: array([array([[1, 1, 1], [1, 1, 1]]), array([[0, 0, 0], [0, 0, 0]]), array([[0, 1, 2], [3, 4, 5]])], dtype=object) ``` Calling `array` on that array doesn't change anything. But `stack` does work (`stack` is just a convenient version of `concatenate`): ``` In [82]: np.stack(arr) Out[82]: array([[[1, 1, 1], [1, 1, 1]], [[0, 0, 0], [0, 0, 0]], [[0, 1, 2], [3, 4, 5]]]) ``` `stack` takes a list of arrays, or it is an array, iterates on the 1st dimension: ``` In [83]: np.stack([x for x in arr]) Out[83]: array([[[1, 1, 1], [1, 1, 1]], [[0, 0, 0], [0, 0, 0]], [[0, 1, 2], [3, 4, 5]]]) ```
Just post a solution in case anyone needs ``` x = [] for fname in fl1: x.append( np.array(Image.open(fname))) for i in range(0, len(x)): x[i] = imresize(x[i], [100,100], interp='bilinear') y = np.array(x) y.shape ```
6,447,898
I'm learning Javascript right now. Can anybody tell me why the second code block traces a empty path for -launch(this)- but using the first code block it gives me the right path? ``` "<form action='"+launchwebsite+"/subsite/' method='post' target='_blank' onsubmit='launch(this)'>" ``` and this not: ``` "<a onclick='launch(this)' title='launch' class='iblack' /></a></div>" ``` Best Uli
2011/06/22
[ "https://Stackoverflow.com/questions/6447898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/811334/" ]
The `this` refers to the the element it is attached to. In the first snippet it is the `<form>`- and in the second the `<a>`-element. Also the `<a>` lacks a `href`-attribute.
I'm not shure but if the code you put is exactly what you are testing you are missing a ; ``` <a onclick='launch(this)' title='launch' class='iblack' /></a></div> <-- You're Version <a onclick='launch(this);' title='launch' class='iblack' /></a></div> ``` Else I never really did an onclick on a html control I usually do href="" to call another page php per exemple and in that page to the treatment I want. Another point I`ve looked at is to catch this command in javascript you would need you to call and "blank" page as of `<a href="#" onClick='launch(this);' title='launch' class='iblack' /></a></div>` This last code acutally worked for me! Keep me in touch, wanna see if this works out for you!! Patrick
247,127
I'm trying to upload documents to SharePoint using web services attaching custom metadata to the files. I've searched but have not found a good tutorial covering all these topics. Can anybody point me in the right direction? Here's why I think I need to use web services: I'm developing on XP and the Sharepoint object model is not remotable. This means any code which has "using Microsoft.Sharepoint" is out :-( I'm looked into the CopyIntoItems web service but am having trouble implementing it myself. I was hoping for a clear tutorial. I've tried using the sample code from <http://msdn.microsoft.com/en-us/library/copy.copy.copyintoitems.aspx> , but I'm not sure what my sourceURL should be. Also, since I can't use "Microsoft.Sharepoint" references, I'm wondering what my Fields will look like? (Is this my metadata?) Also, I'm curious as to why only Website projects allow me to add a web service. Once the file is "in" Sharepoint using that web service, I'll have to use another one to update custom columns, or metadata. Some of these are freeform text, but other must match entries in lists or lookups. I haven't found any information on this yet. Thank you for your help!
2008/10/29
[ "https://Stackoverflow.com/questions/247127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17234/" ]
Here is some code <http://geek.hubkey.com/2007/10/upload-file-to-sharepoint-document.html> As for why it is that is the way because Microsoft wrote it that way :). Some people have written custom web services that combine them, <http://www.sharepointblogs.com/ssa/archive/2006/11/30/wsuploadservice-web-service-for-uploading-documents-into-sharepoint.aspx> Using the built in web services you have to upload the file and upload CAML which contains the columns. Another option if you are using a MS-Office document is to make sure the author fills in the properties in the document then you can have those fields displayed in sharepoint.
Here is some stuff on the Sharepoint Designer - <http://office.microsoft.com/en-us/sharepointdesigner/FX100487631033.aspx> Hope that helps a little. You can link to the Sharepoint 2007 training from here: <http://office.microsoft.com/en-us/training/HA102358581033.aspx> The designer I believe has a WS example in it.
54,597,334
i want to make a program reads integers from the user one by one, multiply them and shows the product of the read integers. The loop for reading the integers stops when the user presses 0. If the user enters a 0 as the first number, then user would not be able to provide any other numbers (Not adding the last 0 in the product). In this case, the program should display “No numbers entered!” Heres my code right now ProductNumbers.java ``` package L04b; import java.lang.reflect.Array; import java.util.Scanner; public class ProductNumbers { public static void main(String[] args) { int num = -1; boolean isValid = true; int numbersEntered = 0; int product = -1; Scanner scnr = new Scanner(System.in); System.out.println( "This program reads a list of integers from the user\r\n" + "and shows the product of the read integers"); while (num != 0) { System.out.print("Enter number = "); int curNum = scnr.nextInt(); if (curNum == 0) break; numbersEntered++; product *= num; } if (numbersEntered == 0) { System.out.println("No numbers entered!"); } else { System.out.println(product); } } } ``` I know this is completely wrong, i usually setup a template, try to figure out what needs to be changed, and go by that way, i also need to start thinking outside the box and learn the different functions, because i dont know how i would make it end if the first number entered is 0, and if the last number is 0, the program stops without multiplying that last 0 (so that the product doesnt end up being 0)... i need someone to guide me on how i could do this. Heres a sample output of how i want it to work ``` This program reads a list of integers from the user and shows the product of the read integers Enter the number: 0 No numbers entered! ``` and ``` This program reads a list of integers from the user and shows the product of the read integers Enter the number: 2 Enter the number: -5 Enter the number: 8 Enter the number: 0 The product of the numbers is: -80 ```
2019/02/08
[ "https://Stackoverflow.com/questions/54597334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10909546/" ]
You have a nested for loop, why? You only need the outer `while` loop that gets the user's input until the input is `0`. Also this line: ``` product *= i; ``` multiplies `i`, the `for` loop's counter to `product` and not the user's input! Later, at this line: ``` if (isValid = true) ``` you should replace `=` with `==`, if you want to make a comparison, although this is simpler: ``` if (isValid) ``` Your code can be simplified to this: ``` int num = -1; int product = 1; int counter = 0; Scanner scnr = new Scanner(System.in); System.out.println( "This program reads a list of integers from the user\r\n" + "and shows the product of the read integers"); while (num != 0) { System.out.print("Enter a number: "); num = scnr.nextInt(); scnr.nextLine(); if (num != 0) { counter++; product *= num; System.out.println(product); } } if (counter == 0) System.out.println("No numbers entered"); else System.out.println("Entered " + counter + " numbers with product: " + product); ```
One way to solve this is to utilize the `break;` keyword to escape from a loop, and then you can process the final result after the loop. Something like this: ``` int numbersEntered = 0; while (num != 0) { int curNum = // read input if (curNum == 0) break; numbersEntered++; // do existing processing to compute the running total } if (numbersEntered == 0) // print "No numbers entered! else // print the result ``` I think the key is to not try and do everything inside of the while loop. Think of it naturally "while the user is entering more numbers, ask for more numbers, then print the final result"
73,465,299
I´m starting to study PHP and I have a doubt in one lesson about array\_search. The teachers example shows "A peeple who got a 10" and as only one of the people got a 10 everything works fine, showing the person's name. But I've been trying to use it to fetch more than one result. In this case I created this array, with 3 people taking 10: ``` $notas2=array( "Ana"=>4, "Misca"=>10, "Chatuba"=>6, "Jurandir"=>7, "Musca"=>10, "Mickey Mouse"=>10, ); echo array_search(10,$notas2); ``` This code just returns "Misca". I tried a foreach, but it returned only "MiscaMiscaMiscaMiscaMiscaMisca". lol ``` foreach(array_search(10,$notas2)as $tirou10){ echo $tirou10; } ``` Anyone can help-me? Tanks.
2022/08/23
[ "https://Stackoverflow.com/questions/73465299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18271081/" ]
I found my mistake after trying a lot: Fastify did not like how the JWT Token Sign-Process was async, it seemed to return twice. It was as simple as changing the JWT Process to not use a callback, but rather just return as a let. Please visit [this](https://stackoverflow.com/a/73473685/19832591) answer. It explains it way better and more detailed
Hey your code was looking a bit messy so i've been so free to clear everything up a bit and hope that might work. Please tell me if the issue still persists ``` const login: FastifyPluginAsync = async (fastify, opts): Promise<void> => { fastify.post("/", async function (request: any, reply) { console.log("Request"); if (!request.body.username || !request.body.password) { return reply.code(400).send({ message: "Missing user or password" }); } const user = await prisma.user.findFirst({ where: { name: request.body.username }}) console.log("prisma"); if(!user?.id) { console.log("User not found"); return reply.code(404).send({ message: "User not found" }); } if (!bcrypt.compareSync(request.body.password, user!.hash)) { console.log("Password incorrect"); return reply.code(500).send({ message: "Password incorrect" }); } console.log("Password correct"); await jwt.sign({ user: user }, process.env.SECRET || "", { expiresIn: "365d" }, (err: any, token: any) => { if (err) { console.log("Error"); return reply.code(500).send({ message: "Error" }); } console.log("JWT"); return reply.code(200).send({ jwt: token }); } }); ``` }
73,465,299
I´m starting to study PHP and I have a doubt in one lesson about array\_search. The teachers example shows "A peeple who got a 10" and as only one of the people got a 10 everything works fine, showing the person's name. But I've been trying to use it to fetch more than one result. In this case I created this array, with 3 people taking 10: ``` $notas2=array( "Ana"=>4, "Misca"=>10, "Chatuba"=>6, "Jurandir"=>7, "Musca"=>10, "Mickey Mouse"=>10, ); echo array_search(10,$notas2); ``` This code just returns "Misca". I tried a foreach, but it returned only "MiscaMiscaMiscaMiscaMiscaMisca". lol ``` foreach(array_search(10,$notas2)as $tirou10){ echo $tirou10; } ``` Anyone can help-me? Tanks.
2022/08/23
[ "https://Stackoverflow.com/questions/73465299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18271081/" ]
As you already found, the issue is the mix of async / await + `than` and callbacks. It results in a code hard to read and with many edge cases because you don't know when and which code will be executed first (the callback or the statements after the await). Note that there is the same pattern on the `prisma` query, not only on JWT code. Let me show you the code in a full async / await style: ```js async function login(fastify, opts) { fastify.post("/", async function (request, reply) { console.log("Request"); // first thing first: we are avoiding to naste the code in if/else statements if (!request.body.username || !request.body.password) { console.log("Missing username or password"); return reply.code(400).send({ message: "Missing user or password" }); } const user = await prisma.user.findFirst({ where: { name: request.body.username }, }) console.log("prisma"); if (!user?.id) { console.log("User not found"); return reply.code(404).send({ message: "User not found" }); } if (!bcrypt.compareSync(request.body.password, user.hash)) { console.log("Password incorrect"); return reply.code(500).send({ message: "Password incorrect" }); } console.log("Password correct"); const token = await jwt.sign( { user: user }, process.env.SECRET || "", { expiresIn: "365d" }, ) console.log("JWT"); // using async handlers, you can return a json instead of calling reply.send return { jwt: token } }); } ```
Hey your code was looking a bit messy so i've been so free to clear everything up a bit and hope that might work. Please tell me if the issue still persists ``` const login: FastifyPluginAsync = async (fastify, opts): Promise<void> => { fastify.post("/", async function (request: any, reply) { console.log("Request"); if (!request.body.username || !request.body.password) { return reply.code(400).send({ message: "Missing user or password" }); } const user = await prisma.user.findFirst({ where: { name: request.body.username }}) console.log("prisma"); if(!user?.id) { console.log("User not found"); return reply.code(404).send({ message: "User not found" }); } if (!bcrypt.compareSync(request.body.password, user!.hash)) { console.log("Password incorrect"); return reply.code(500).send({ message: "Password incorrect" }); } console.log("Password correct"); await jwt.sign({ user: user }, process.env.SECRET || "", { expiresIn: "365d" }, (err: any, token: any) => { if (err) { console.log("Error"); return reply.code(500).send({ message: "Error" }); } console.log("JWT"); return reply.code(200).send({ jwt: token }); } }); ``` }
73,465,299
I´m starting to study PHP and I have a doubt in one lesson about array\_search. The teachers example shows "A peeple who got a 10" and as only one of the people got a 10 everything works fine, showing the person's name. But I've been trying to use it to fetch more than one result. In this case I created this array, with 3 people taking 10: ``` $notas2=array( "Ana"=>4, "Misca"=>10, "Chatuba"=>6, "Jurandir"=>7, "Musca"=>10, "Mickey Mouse"=>10, ); echo array_search(10,$notas2); ``` This code just returns "Misca". I tried a foreach, but it returned only "MiscaMiscaMiscaMiscaMiscaMisca". lol ``` foreach(array_search(10,$notas2)as $tirou10){ echo $tirou10; } ``` Anyone can help-me? Tanks.
2022/08/23
[ "https://Stackoverflow.com/questions/73465299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18271081/" ]
As you already found, the issue is the mix of async / await + `than` and callbacks. It results in a code hard to read and with many edge cases because you don't know when and which code will be executed first (the callback or the statements after the await). Note that there is the same pattern on the `prisma` query, not only on JWT code. Let me show you the code in a full async / await style: ```js async function login(fastify, opts) { fastify.post("/", async function (request, reply) { console.log("Request"); // first thing first: we are avoiding to naste the code in if/else statements if (!request.body.username || !request.body.password) { console.log("Missing username or password"); return reply.code(400).send({ message: "Missing user or password" }); } const user = await prisma.user.findFirst({ where: { name: request.body.username }, }) console.log("prisma"); if (!user?.id) { console.log("User not found"); return reply.code(404).send({ message: "User not found" }); } if (!bcrypt.compareSync(request.body.password, user.hash)) { console.log("Password incorrect"); return reply.code(500).send({ message: "Password incorrect" }); } console.log("Password correct"); const token = await jwt.sign( { user: user }, process.env.SECRET || "", { expiresIn: "365d" }, ) console.log("JWT"); // using async handlers, you can return a json instead of calling reply.send return { jwt: token } }); } ```
I found my mistake after trying a lot: Fastify did not like how the JWT Token Sign-Process was async, it seemed to return twice. It was as simple as changing the JWT Process to not use a callback, but rather just return as a let. Please visit [this](https://stackoverflow.com/a/73473685/19832591) answer. It explains it way better and more detailed
6,778,681
``` MyModel _model = new MyModel() { PriceDate = new DateTime(2000, 1, 1)}; var helper = new System.Web.Mvc.HtmlHelper<MyModel>(new ViewContext(), new ViewPage()); var result = helper.DisplayFor(m => _model.PriceDate); Assert.That(result, Is.EqualTo(expected)); ``` I want to test that the output produced by calling `DisplayFor` is in the format specified by... ``` [DisplayFormat(DataFormatString = "{0:dd/MM/yy}")] public DateTime? PriceDate { get; set; } ``` The code compiles but fails with a `NullReferenceException` at `DisplayFor`. Can anyone help me make this work? (Note: This is a trivial example of a larger problem)
2011/07/21
[ "https://Stackoverflow.com/questions/6778681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/231999/" ]
The steps are quite long so I couldn't write here. I wrote about it at my blog :D <http://thoai-nguyen.blogspot.com/2011/07/unit-test-displayformat-attribute.html> Cheers
I use the following code to test and validate html helpers. Validation is a another example. Try the following: ``` var sb = new StringBuilder(); var context = new ViewContext(); context.ViewData = new ViewDataDictionary(_testModel); context.Writer = new StringWriter(sb); var page = new ViewPage<TestModel>(); var helper = new HtmlHelper<TestModel>(context, page); //Do your stuff here to exercise your helper //Following example contains two helpers that are being tested //A MyCustomBeginForm Helper and a OtherCoolHelperIMade Helper using(helper.MyCustomBeginForm("secretSauce")) { helper.ViewContext.Writer.WriteLine(helper.OtherCoolHelperIMade("bigMacSauce")); } //End Example //Get the results of all helpers var result = sb.ToString(); //Asserts and string tests here for emitted HTML Assert.IsNotNullOrEmpty(result); ```
18,660,572
I have an large array, but with similar structure to: ``` [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] ``` What would be the best , most efficient way of taking the rolling average of 5 elements **without** flattening the array. i.e. value one would be (0+1+2+3+4)/5=2 value two would be (1+2+3+4+5)/5=3 value three would be (2+3+4+5+6)/5=4 Thanks
2013/09/06
[ "https://Stackoverflow.com/questions/18660572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1943587/" ]
Probably the "best" way to do this is to submit a view of the array to `uniform_filter`. Im not sure if this defeats your "cannot flatten the array", but without reshaping the array in some way all of these methods will be vastly slower then the following: ``` import numpy as np import scipy.ndimage.filters as filt arr=np.array([[0,1,2,3,4], [5,6,7,8,9], [10,11,12,13,14], [15,16,17,18,19]]) avg = filt.uniform_filter(arr.ravel(), size=5)[2:-2] print avg [ 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17] print arr.shape #Original array is not changed. (4, 5) ```
Pseudocode (though it does probably look a bit like Python): ``` for i = 0 to 15: sum = 0 for j from 0 to 4: // yourLists[m][n] is the nth element of your mth list (zero-indexed) sum = sum + yourLists [ (i + j) / 5 ] [ (i + j) % 5 ] next j print i, sum/5 next i ``` You can probably do a bit better not adding all five numbers each time.
18,660,572
I have an large array, but with similar structure to: ``` [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] ``` What would be the best , most efficient way of taking the rolling average of 5 elements **without** flattening the array. i.e. value one would be (0+1+2+3+4)/5=2 value two would be (1+2+3+4+5)/5=3 value three would be (2+3+4+5+6)/5=4 Thanks
2013/09/06
[ "https://Stackoverflow.com/questions/18660572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1943587/" ]
Probably the "best" way to do this is to submit a view of the array to `uniform_filter`. Im not sure if this defeats your "cannot flatten the array", but without reshaping the array in some way all of these methods will be vastly slower then the following: ``` import numpy as np import scipy.ndimage.filters as filt arr=np.array([[0,1,2,3,4], [5,6,7,8,9], [10,11,12,13,14], [15,16,17,18,19]]) avg = filt.uniform_filter(arr.ravel(), size=5)[2:-2] print avg [ 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17] print arr.shape #Original array is not changed. (4, 5) ```
**note:** This answer is *not* `numpy` specific. This would be simpler if the list of list could be flattened. ``` from itertools import tee def moving_average(list_of_list, window_size): nums = (n for l in list_of_list for n in l) it1, it2 = tee(nums) window_sum = 0 for _ in range(window_size): window_sum += next(it1) yield window_sum / window_size for n in it1: window_sum += n window_sum -= next(it2) yield window_sum / window_size ```
18,660,572
I have an large array, but with similar structure to: ``` [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] ``` What would be the best , most efficient way of taking the rolling average of 5 elements **without** flattening the array. i.e. value one would be (0+1+2+3+4)/5=2 value two would be (1+2+3+4+5)/5=3 value three would be (2+3+4+5+6)/5=4 Thanks
2013/09/06
[ "https://Stackoverflow.com/questions/18660572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1943587/" ]
Probably the "best" way to do this is to submit a view of the array to `uniform_filter`. Im not sure if this defeats your "cannot flatten the array", but without reshaping the array in some way all of these methods will be vastly slower then the following: ``` import numpy as np import scipy.ndimage.filters as filt arr=np.array([[0,1,2,3,4], [5,6,7,8,9], [10,11,12,13,14], [15,16,17,18,19]]) avg = filt.uniform_filter(arr.ravel(), size=5)[2:-2] print avg [ 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17] print arr.shape #Original array is not changed. (4, 5) ```
The "best" solution will depend on the reason *why* you don't want to flatten the array in the first place. If the data are contiguous in memory, using stride tricks is an efficient way to compute a rolling average without explicitly flattening the array: ``` In [1]: a = np.arange(20).reshape((4, 5)) In [2]: a Out[2]: array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]) In [3]: from numpy.lib.stride_tricks import as_strided In [4]: s = a.dtype.itemsize In [5]: aa = as_strided(a, shape=(16,5), strides=(s, s)) In [6]: np.average(aa, axis=1) Out[6]: array([ 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17.]) ```
9,516,164
I'm well versed in ASP.NET WebForms, and was considering switching my code to MVC 3. I am learning MVC, and have some understanding in it, but, there's one issue I haven't come to understand yet. It goes like this: With WebForms code, I was able to have a DropDownList, that when selected, would've triggered a Button press through Javascript, and that button would've triggered a Method that would've populated another DropDown, but both DropDown's were part of the same form, and the actual Button that is visible to the user (and is to be manually pressed by the user) triggers a Method that gets values from both those DropDowns as well as other fields. The thing is, I don't know how to do this with MVC. From my current understanding, if I wanted to send form data to the app, it has to follow a Model. That is what makes it so confusing to me (from my current understanding), how do I get the first DropDown to send ***only*** the data from inside the first DropDown? Also populating the other dropdown is a little bit of a foggy idea with MVC as well, but especially the point I made about the first DropDown is what makes me confused the most. If anyone can help me in any way on this it would be greatly appreciated.
2012/03/01
[ "https://Stackoverflow.com/questions/9516164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/822011/" ]
The big difference to get your head around here is that there are non of the old style postbacks in ASP.NET MVC. In this case, you get to be in control of how you obtain the new data for your dropdown box. When the form is complete and we're ready to send the data to the server, we'll be sending it back as a spcific type to our controller method but until that point, we can access the data we need from any other controller method. Personally I'd use jQuery to do this using an ajax request to a controller method that returns a `JsonResult` type. Something like: ``` $.getJSON("/MyController/GetSecondDropdownValues", function(result) { $.each(result, function() { $('#mySecondDropdown').append($("<option />").val(this.Name)); }); ``` C# ``` public JsonResult GetSecondDropdownValues(string initialDropdownValue) { /* Do the work to obtain the values here */ return Json(returnedValues); } ```
Asp.net clasic follows a different mindset than asp.net mvc. The first tries to mimic a desktop forms application and abstracs (hides) the web platform details. Asp.net mvc while is a MVC based framework, it is actually a 'real' web framework because it doesn't try to hide anything web related from you. That being said, the data the browser submits is actually 'data to update the Model' and not the Model itself. In most of the tutorials you'll see the View Model (or part of it) which is sent back, but it's just data submitted by the browser. There is a LOT of confusion of what the models is in an asp.net mvc application. > > how do I get the first DropDown to send only the data from inside the first DropDown > > > You make that dropdown the only element of a form. In asp.net mvc you can have in a page as many forms as you need (as long as you don't mix them), asp.net mvc doesn't follow the form mindset of the webforms. Alternately you can submit the value of the field via ajax (with jQuery) to a controller which returns a json that will be processed on the client side. And probably that's how you popoulate the second dropdown, when the first is selected, an ajax request is sent to an action of the controller which returns the content of the second dropdown as json, which is then inserted via javascript. A simple hint to make you transition easier to asp.net mvc: anything view related (html - including forms, javascript etc) is independent from the controller. The View only cares about its (view) model, the controller cares about the data it receives. The controller returns a result which usually is a view , but could be anything. THe controller doesn't know anything about the view details (html, js), it knows only about the view data (the view model).
9,516,164
I'm well versed in ASP.NET WebForms, and was considering switching my code to MVC 3. I am learning MVC, and have some understanding in it, but, there's one issue I haven't come to understand yet. It goes like this: With WebForms code, I was able to have a DropDownList, that when selected, would've triggered a Button press through Javascript, and that button would've triggered a Method that would've populated another DropDown, but both DropDown's were part of the same form, and the actual Button that is visible to the user (and is to be manually pressed by the user) triggers a Method that gets values from both those DropDowns as well as other fields. The thing is, I don't know how to do this with MVC. From my current understanding, if I wanted to send form data to the app, it has to follow a Model. That is what makes it so confusing to me (from my current understanding), how do I get the first DropDown to send ***only*** the data from inside the first DropDown? Also populating the other dropdown is a little bit of a foggy idea with MVC as well, but especially the point I made about the first DropDown is what makes me confused the most. If anyone can help me in any way on this it would be greatly appreciated.
2012/03/01
[ "https://Stackoverflow.com/questions/9516164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/822011/" ]
The big difference to get your head around here is that there are non of the old style postbacks in ASP.NET MVC. In this case, you get to be in control of how you obtain the new data for your dropdown box. When the form is complete and we're ready to send the data to the server, we'll be sending it back as a spcific type to our controller method but until that point, we can access the data we need from any other controller method. Personally I'd use jQuery to do this using an ajax request to a controller method that returns a `JsonResult` type. Something like: ``` $.getJSON("/MyController/GetSecondDropdownValues", function(result) { $.each(result, function() { $('#mySecondDropdown').append($("<option />").val(this.Name)); }); ``` C# ``` public JsonResult GetSecondDropdownValues(string initialDropdownValue) { /* Do the work to obtain the values here */ return Json(returnedValues); } ```
I just remembered this question I asked a couple years ago. Another way would be to use $.get(...) with jQuery (which is well-documented nowadays...)
71,427,827
I am trying to do fuzzy match and grouping using Python on multiple fields. I want to do the comparison on each column on a different fuzzy threshold. I tried to search on google but could not find any solution which can do deduplication and then create groups on different columns. **Input:** | Name | Address | | --- | --- | | Robert | 9185 Pumpkin Hill St. | | Rob | 9185 Pumpkin Hill Street | | Mike | 1296 Tunnel St. | | Mike | Tunnel Street 1296 | | John | 6200 Beechwood Drive | **Output:** | Group ID | Name | Address | | --- | --- | --- | | 1 | Robert | 9185 Pumpkin Hill St. | | 1 | Rob | 9185 Pumpkin Hill Street | | 2 | Mike | 1296 Tunnel St. | | 2 | Mike | Tunnel Street 1296 | | 3 | John | 6200 Beechwood Drive |
2022/03/10
[ "https://Stackoverflow.com/questions/71427827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014867/" ]
I'd recommend reviewing Levenstein distance as this is a common algorithm to identify similar strings. Library FuzzWuzzy(goofy name I know) implements it with 3 different approaches. See this [article](https://www.datacamp.com/community/tutorials/fuzzy-string-python) for more info Here's a starting place that compares each string against every other string. You mention having different thresholds, so all would need to do is loop through `l_match` and group them depending on your desired thresholds ``` #Run this to install the required libraries #pip install python-levenshtein fuzzywuzzy from fuzzywuzzy import fuzz l_data =[ ['Robert','9185 Pumpkin Hill St.'] ,['Rob','9185 Pumpkin Hill Street'] ,['Mike','1296 Tunnel St.'] ,['Mike','Tunnel Street 1296'] ,['John','6200 Beechwood Drive'] ] l_match = [] #loop through data for idx1,row1 in enumerate(l_data): #compare each person with every person that comes after later in the list (so compares only 1 way instead of comparing A vs B and B vs A) for idx2,row2 in enumerate(l_data[idx1+1:]): #Calculates index in original array for row2 origIdx=idx1+idx2+1 l_match.append([idx1,origIdx,fuzz.ratio(row1[0],row2[0]),fuzz.ratio(row1[1],row2[1])]) #Print raw data with index for idx,val in enumerate(l_data): print(f'{idx}-{val}') print ("*" * 100) #Print results of comparison for row in l_match: id1 = row[0] id2 = row[1] formattedName1 = f'{id1}-{l_data[id1][0]}' formattedName2 = f'{id2}-{l_data[id2][0]}' print (f'{formattedName1} and {formattedName2} have {row[2]}% name similarity ratio and {row[3]}% address similarity ratio') ``` Results: -------- ``` 0-['Robert', '9185 Pumpkin Hill St.'] 1-['Rob', '9185 Pumpkin Hill Street'] 2-['Mike', '1296 Tunnel St.'] 3-['Mike', 'Tunnel Street 1296'] 4-['John', '6200 Beechwood Drive'] **************************************************************************************************** 0-Robert and 1-Rob have 67% name similarity ratio and 89% address similarity ratio 0-Robert and 2-Mike have 20% name similarity ratio and 50% address similarity ratio 0-Robert and 3-Mike have 20% name similarity ratio and 31% address similarity ratio 0-Robert and 4-John have 20% name similarity ratio and 15% address similarity ratio 1-Rob and 2-Mike have 0% name similarity ratio and 41% address similarity ratio 1-Rob and 3-Mike have 0% name similarity ratio and 48% address similarity ratio 1-Rob and 4-John have 29% name similarity ratio and 18% address similarity ratio 2-Mike and 3-Mike have 100% name similarity ratio and 55% address similarity ratio 2-Mike and 4-John have 0% name similarity ratio and 23% address similarity ratio 3-Mike and 4-John have 0% name similarity ratio and 21% address similarity ratio ```
Stephan explained the code pretty well. I don't need to explain again. You can try using the fuzz.partial\_ratio as well. It might provide some interesting results. ``` from thefuzz import fuzz print(fuzz.ratio("Turkey is the best country", "Turkey is the best country!")) #98 print(fuzz.partial_ratio("Turkey is the best country", "Turkey is the best country!")) #100 ```
44,508,952
I have a page with dynamically generated content. In this page there is a form for users to submit questions. How can I include in this form, a reference that is unique to each one of these pages? ``` <div class="detalle-form-wrap"> <div> <h1> Contact us if you are interested! </h1> <h2> REF. VC0171 </h2> </div> ``` So the reference is dynamically generated inside the `h2` tag. I would like that when a user submits a form, we get that reference as well along with it. Can use jQuery if necessary.
2017/06/12
[ "https://Stackoverflow.com/questions/44508952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6738021/" ]
If that code you posted is inside an HTML form, you can use a hidden input field that contains a variable with your reference as a value: ``` <h2> REF. VC0171 <input type="hidden" name="reference_1" value="<?php echo $reference; ?>"> </h2> ``` That value will be sent with your form on submission, you can get it by its name, like `$reference = $_POST['reference_1'];` (or `$_GET['reference_1'];`, if the form method is `get`)
You can add an additional `input`-field with `type="hidden"` and set it's `value` to the reference: ``` <input type="hidden" name="reference", value="REF. VC0171" /> ``` You can access it just like any other form variable with `$_GET["reference"] or`$\_POST["reference"]`. But keep in mind that the user can change the value of it using the developer tools in any browser.
29,833
How do I say “stairs” in French? Is it *escalier* or *escaliers*? <https://www.collinsdictionary.com/dictionary/english-french/stair>
2018/04/17
[ "https://french.stackexchange.com/questions/29833", "https://french.stackexchange.com", "https://french.stackexchange.com/users/16701/" ]
That depends on the number of *escaliers* this is about... In standard French, an escalier is a single suite of steps, just like a ladder is a suite of rungs. However, there used te be regional usages in France and Belgium1 where even a single escalier might be used at the plural, so you'll find, *il est tombé dans les escaliers*, *redescendant les escaliers quatre à quatre* (Marcel Proust). Both the singular and the plural can be heard nowadays but the singular is more frequent, as shows [Google Ngram viewer](https://books.google.com/ngrams/graph?content=%28tomb%C3%A9%20dans%20l%27escalier*10%29%2C%28tomb%C3%A9%20dans%20les%20escaliers*10%29%2Cdans%20les%20escaliers%2Cdans%20l%27escalier&year_start=1800&year_end=2008&corpus=19&smoothing=3&share=&direct_url=t1%3B%2C%28tomb%C3%A9%20dans%20l%27%20escalier%20%2A%2010%29%3B%2Cc0%3B.t1%3B%2C%28tomb%C3%A9%20dans%20les%20escaliers%20%2A%2010%29%3B%2Cc0%3B.t1%3B%2Cdans%20les%20escaliers%3B%2Cc0%3B.t1%3B%2Cdans%20l%27%20escalier%3B%2Cc0): [![enter image description here](https://i.stack.imgur.com/mZ4JQ.png)](https://i.stack.imgur.com/mZ4JQ.png) Note also that there is a fixed expression that almost never uses the plural: *la concierge est dans l'escalier*. 1Ref. *Le Littré* and *Le français correct : Guide pratique des difficultés* Maurice Grevisse, Michèle Lenoble-Pinson
Moi j'aurais dis une "marche d'escalier" pour stair
29,833
How do I say “stairs” in French? Is it *escalier* or *escaliers*? <https://www.collinsdictionary.com/dictionary/english-french/stair>
2018/04/17
[ "https://french.stackexchange.com/questions/29833", "https://french.stackexchange.com", "https://french.stackexchange.com/users/16701/" ]
Basically the distinction is that *un escalier* is a **single flight of steps**. *Les escaliers*, however, usually refers to several flights of stairs (or in practice, what an English speakers might refer to as a *stairwell*, in French *la cage d'escalier*).
That depends on the number of *escaliers* this is about... In standard French, an escalier is a single suite of steps, just like a ladder is a suite of rungs. However, there used te be regional usages in France and Belgium1 where even a single escalier might be used at the plural, so you'll find, *il est tombé dans les escaliers*, *redescendant les escaliers quatre à quatre* (Marcel Proust). Both the singular and the plural can be heard nowadays but the singular is more frequent, as shows [Google Ngram viewer](https://books.google.com/ngrams/graph?content=%28tomb%C3%A9%20dans%20l%27escalier*10%29%2C%28tomb%C3%A9%20dans%20les%20escaliers*10%29%2Cdans%20les%20escaliers%2Cdans%20l%27escalier&year_start=1800&year_end=2008&corpus=19&smoothing=3&share=&direct_url=t1%3B%2C%28tomb%C3%A9%20dans%20l%27%20escalier%20%2A%2010%29%3B%2Cc0%3B.t1%3B%2C%28tomb%C3%A9%20dans%20les%20escaliers%20%2A%2010%29%3B%2Cc0%3B.t1%3B%2Cdans%20les%20escaliers%3B%2Cc0%3B.t1%3B%2Cdans%20l%27%20escalier%3B%2Cc0): [![enter image description here](https://i.stack.imgur.com/mZ4JQ.png)](https://i.stack.imgur.com/mZ4JQ.png) Note also that there is a fixed expression that almost never uses the plural: *la concierge est dans l'escalier*. 1Ref. *Le Littré* and *Le français correct : Guide pratique des difficultés* Maurice Grevisse, Michèle Lenoble-Pinson
29,833
How do I say “stairs” in French? Is it *escalier* or *escaliers*? <https://www.collinsdictionary.com/dictionary/english-french/stair>
2018/04/17
[ "https://french.stackexchange.com/questions/29833", "https://french.stackexchange.com", "https://french.stackexchange.com/users/16701/" ]
One stair as in a single step is *une marche (d'escalier)*. (Or *un degré*, but this word is very uncommon in this sense in modern French.) One stair as in one flight of steps (a series of step from a landing to the next one) is *un escalier*. The singular *escalier* can also refer to a series of flights spanning multiple floors. Whether one uses the singular or the plural in this case depends on the context. We tend to use the singular when we think of the set of steps connecting one floor to another, even when there are intermediate floors, and to use the plural when thinking of the stairs as a room (the stairwell: *la cage d'escalier*). > > J'ai pris l'escalier pour monter au cinquième étage.   *ou*   J'ai pris les escaliers pour monter au cinquième étage. > > Je suis tombé dans l'escalier.   *ou*   Je suis tombé dans les escaliers. > > Je l'ai croisée dans l'escalier.   *ou*   Je l'ai croisée dans les escaliers. > > \* J'ai renversé du café sur la troisième marche de l'escalier.   *(Here the plural is impossible since this refers to a specific flight of stairs.)* > > > The distinction between *escalier* and *escaliers* is rather fuzzy and depends on the speaker. I'd use the singular in all the sentences above. The \*[Trésor de la langue française](http://www.cnrtl.fr/definition/escalier) describes the usage of *escaliers* to mean *cage d'escalier* as “*populaire ou familier*”. The 19th century conservative and prescriptive dictionary *[Littré](https://www.littre.org/definition/escalier)* describes the use of *escaliers* in the sense of a flight of steps as “erroneous”, but allows its use to mean a series of flights spanning multiple floors. It's perfectly idiomatic to keep it simple and always use the singular except when referring to multiple staircases.
That depends on the number of *escaliers* this is about... In standard French, an escalier is a single suite of steps, just like a ladder is a suite of rungs. However, there used te be regional usages in France and Belgium1 where even a single escalier might be used at the plural, so you'll find, *il est tombé dans les escaliers*, *redescendant les escaliers quatre à quatre* (Marcel Proust). Both the singular and the plural can be heard nowadays but the singular is more frequent, as shows [Google Ngram viewer](https://books.google.com/ngrams/graph?content=%28tomb%C3%A9%20dans%20l%27escalier*10%29%2C%28tomb%C3%A9%20dans%20les%20escaliers*10%29%2Cdans%20les%20escaliers%2Cdans%20l%27escalier&year_start=1800&year_end=2008&corpus=19&smoothing=3&share=&direct_url=t1%3B%2C%28tomb%C3%A9%20dans%20l%27%20escalier%20%2A%2010%29%3B%2Cc0%3B.t1%3B%2C%28tomb%C3%A9%20dans%20les%20escaliers%20%2A%2010%29%3B%2Cc0%3B.t1%3B%2Cdans%20les%20escaliers%3B%2Cc0%3B.t1%3B%2Cdans%20l%27%20escalier%3B%2Cc0): [![enter image description here](https://i.stack.imgur.com/mZ4JQ.png)](https://i.stack.imgur.com/mZ4JQ.png) Note also that there is a fixed expression that almost never uses the plural: *la concierge est dans l'escalier*. 1Ref. *Le Littré* and *Le français correct : Guide pratique des difficultés* Maurice Grevisse, Michèle Lenoble-Pinson
29,833
How do I say “stairs” in French? Is it *escalier* or *escaliers*? <https://www.collinsdictionary.com/dictionary/english-french/stair>
2018/04/17
[ "https://french.stackexchange.com/questions/29833", "https://french.stackexchange.com", "https://french.stackexchange.com/users/16701/" ]
Basically the distinction is that *un escalier* is a **single flight of steps**. *Les escaliers*, however, usually refers to several flights of stairs (or in practice, what an English speakers might refer to as a *stairwell*, in French *la cage d'escalier*).
Moi j'aurais dis une "marche d'escalier" pour stair
29,833
How do I say “stairs” in French? Is it *escalier* or *escaliers*? <https://www.collinsdictionary.com/dictionary/english-french/stair>
2018/04/17
[ "https://french.stackexchange.com/questions/29833", "https://french.stackexchange.com", "https://french.stackexchange.com/users/16701/" ]
One stair as in a single step is *une marche (d'escalier)*. (Or *un degré*, but this word is very uncommon in this sense in modern French.) One stair as in one flight of steps (a series of step from a landing to the next one) is *un escalier*. The singular *escalier* can also refer to a series of flights spanning multiple floors. Whether one uses the singular or the plural in this case depends on the context. We tend to use the singular when we think of the set of steps connecting one floor to another, even when there are intermediate floors, and to use the plural when thinking of the stairs as a room (the stairwell: *la cage d'escalier*). > > J'ai pris l'escalier pour monter au cinquième étage.   *ou*   J'ai pris les escaliers pour monter au cinquième étage. > > Je suis tombé dans l'escalier.   *ou*   Je suis tombé dans les escaliers. > > Je l'ai croisée dans l'escalier.   *ou*   Je l'ai croisée dans les escaliers. > > \* J'ai renversé du café sur la troisième marche de l'escalier.   *(Here the plural is impossible since this refers to a specific flight of stairs.)* > > > The distinction between *escalier* and *escaliers* is rather fuzzy and depends on the speaker. I'd use the singular in all the sentences above. The \*[Trésor de la langue française](http://www.cnrtl.fr/definition/escalier) describes the usage of *escaliers* to mean *cage d'escalier* as “*populaire ou familier*”. The 19th century conservative and prescriptive dictionary *[Littré](https://www.littre.org/definition/escalier)* describes the use of *escaliers* in the sense of a flight of steps as “erroneous”, but allows its use to mean a series of flights spanning multiple floors. It's perfectly idiomatic to keep it simple and always use the singular except when referring to multiple staircases.
Moi j'aurais dis une "marche d'escalier" pour stair
29,833
How do I say “stairs” in French? Is it *escalier* or *escaliers*? <https://www.collinsdictionary.com/dictionary/english-french/stair>
2018/04/17
[ "https://french.stackexchange.com/questions/29833", "https://french.stackexchange.com", "https://french.stackexchange.com/users/16701/" ]
One stair as in a single step is *une marche (d'escalier)*. (Or *un degré*, but this word is very uncommon in this sense in modern French.) One stair as in one flight of steps (a series of step from a landing to the next one) is *un escalier*. The singular *escalier* can also refer to a series of flights spanning multiple floors. Whether one uses the singular or the plural in this case depends on the context. We tend to use the singular when we think of the set of steps connecting one floor to another, even when there are intermediate floors, and to use the plural when thinking of the stairs as a room (the stairwell: *la cage d'escalier*). > > J'ai pris l'escalier pour monter au cinquième étage.   *ou*   J'ai pris les escaliers pour monter au cinquième étage. > > Je suis tombé dans l'escalier.   *ou*   Je suis tombé dans les escaliers. > > Je l'ai croisée dans l'escalier.   *ou*   Je l'ai croisée dans les escaliers. > > \* J'ai renversé du café sur la troisième marche de l'escalier.   *(Here the plural is impossible since this refers to a specific flight of stairs.)* > > > The distinction between *escalier* and *escaliers* is rather fuzzy and depends on the speaker. I'd use the singular in all the sentences above. The \*[Trésor de la langue française](http://www.cnrtl.fr/definition/escalier) describes the usage of *escaliers* to mean *cage d'escalier* as “*populaire ou familier*”. The 19th century conservative and prescriptive dictionary *[Littré](https://www.littre.org/definition/escalier)* describes the use of *escaliers* in the sense of a flight of steps as “erroneous”, but allows its use to mean a series of flights spanning multiple floors. It's perfectly idiomatic to keep it simple and always use the singular except when referring to multiple staircases.
Basically the distinction is that *un escalier* is a **single flight of steps**. *Les escaliers*, however, usually refers to several flights of stairs (or in practice, what an English speakers might refer to as a *stairwell*, in French *la cage d'escalier*).
52,528,695
I have 3 divs that fades sequentially on page load just like on this link: <http://jsfiddle.net/x4qjscgv/6/> However, I want the fade function to happen once the user clicked a button. I tried to use the function: document.getElementById but it does not appear to be working. See full code below: ``` <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> $(document).ready(function() { $('.word1, .word2, .word3').each(function(fadeIn) { $(this).delay(fadeIn * 500).fadeIn(1000); }); }); document.getElementById('btn').onclick = function(e) </script> <style> #chat { display: none; } </style> </head> <body> <button id="btn"> fade divs </button> <div id="chat" class="word1">Word 1</div> <div id="chat" class="word2">Word 2</div> <div id="chat" class="word3">Word 3</div> <div id="" class="">Word 4</div> </body> </html> ```
2018/09/27
[ "https://Stackoverflow.com/questions/52528695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10227293/" ]
This indeed seems to be an issue when Eclipse is run with Java 11. I have created [Bug 539545](https://bugs.eclipse.org/bugs/show_bug.cgi?id=539545) to report this. In the meantime, you can work around this issue by disabling news feed polling. To do so, go to *Preferences... -> General -> News*, and untick the *Enable automatic news polling* option: [![Preferences news feed disabling](https://i.stack.imgur.com/2QHur.png)](https://i.stack.imgur.com/2QHur.png) The error window will no longer appear.
This is caused by the <http://openjdk.java.net/jeps/320> - which is removal of Java EE and CORBA Modules from the standard Java 11 version. As mentioned by @Pyves, the simple way would be unchecking "Enable automatic news polling" from the Preferences-> General -> News But if you still need this, you can install "javax.\*" bundles from the eclipse orbit repository. Here is the latest stable repo url: <http://download.eclipse.org/tools/orbit/downloads/drops/R20180905201904/repository> [![enter image description here](https://i.stack.imgur.com/4Plnt.png)](https://i.stack.imgur.com/4Plnt.png)
52,528,695
I have 3 divs that fades sequentially on page load just like on this link: <http://jsfiddle.net/x4qjscgv/6/> However, I want the fade function to happen once the user clicked a button. I tried to use the function: document.getElementById but it does not appear to be working. See full code below: ``` <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> $(document).ready(function() { $('.word1, .word2, .word3').each(function(fadeIn) { $(this).delay(fadeIn * 500).fadeIn(1000); }); }); document.getElementById('btn').onclick = function(e) </script> <style> #chat { display: none; } </style> </head> <body> <button id="btn"> fade divs </button> <div id="chat" class="word1">Word 1</div> <div id="chat" class="word2">Word 2</div> <div id="chat" class="word3">Word 3</div> <div id="" class="">Word 4</div> </body> </html> ```
2018/09/27
[ "https://Stackoverflow.com/questions/52528695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10227293/" ]
This indeed seems to be an issue when Eclipse is run with Java 11. I have created [Bug 539545](https://bugs.eclipse.org/bugs/show_bug.cgi?id=539545) to report this. In the meantime, you can work around this issue by disabling news feed polling. To do so, go to *Preferences... -> General -> News*, and untick the *Enable automatic news polling* option: [![Preferences news feed disabling](https://i.stack.imgur.com/2QHur.png)](https://i.stack.imgur.com/2QHur.png) The error window will no longer appear.
Turning off the news feed does solve this problem (Per @Pyves, unchecking "Enable automatic news polling" from Preferences-> General -> News), **but** be aware that you may get other issues because of the too-new JDK. Noga Rotman just spent several hours working out for me that Eclipse not being able to find JUnit, even though it was installed and correctly on the classpath, was because of using the new JDK (the one that is causing these same issues). You can solve the underlying issue by uninstalling your current version of the JDK and installing an old version, then reinstalling Eclipse. If you have the Oracle JDK you can find uninstall instructions [here](https://docs.oracle.com/javase/10/install/installation-jdk-and-jre-macos.htm#JSJIG-GUID-F575EB4A-70D3-4AB4-A20E-DBE95171AB5F) and and Java SE Development Kit 8u191 (which fixed my issues) is [here](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html).
52,528,695
I have 3 divs that fades sequentially on page load just like on this link: <http://jsfiddle.net/x4qjscgv/6/> However, I want the fade function to happen once the user clicked a button. I tried to use the function: document.getElementById but it does not appear to be working. See full code below: ``` <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> $(document).ready(function() { $('.word1, .word2, .word3').each(function(fadeIn) { $(this).delay(fadeIn * 500).fadeIn(1000); }); }); document.getElementById('btn').onclick = function(e) </script> <style> #chat { display: none; } </style> </head> <body> <button id="btn"> fade divs </button> <div id="chat" class="word1">Word 1</div> <div id="chat" class="word2">Word 2</div> <div id="chat" class="word3">Word 3</div> <div id="" class="">Word 4</div> </body> </html> ```
2018/09/27
[ "https://Stackoverflow.com/questions/52528695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10227293/" ]
This indeed seems to be an issue when Eclipse is run with Java 11. I have created [Bug 539545](https://bugs.eclipse.org/bugs/show_bug.cgi?id=539545) to report this. In the meantime, you can work around this issue by disabling news feed polling. To do so, go to *Preferences... -> General -> News*, and untick the *Enable automatic news polling* option: [![Preferences news feed disabling](https://i.stack.imgur.com/2QHur.png)](https://i.stack.imgur.com/2QHur.png) The error window will no longer appear.
For windows version Eclipse, 1. Enter search key string "news" 2. Check off "Enable automatic news polling" 3. Click [Apply and Close] button. That's it. [![enter image description here](https://i.stack.imgur.com/3IgiV.png)](https://i.stack.imgur.com/3IgiV.png)
52,528,695
I have 3 divs that fades sequentially on page load just like on this link: <http://jsfiddle.net/x4qjscgv/6/> However, I want the fade function to happen once the user clicked a button. I tried to use the function: document.getElementById but it does not appear to be working. See full code below: ``` <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> $(document).ready(function() { $('.word1, .word2, .word3').each(function(fadeIn) { $(this).delay(fadeIn * 500).fadeIn(1000); }); }); document.getElementById('btn').onclick = function(e) </script> <style> #chat { display: none; } </style> </head> <body> <button id="btn"> fade divs </button> <div id="chat" class="word1">Word 1</div> <div id="chat" class="word2">Word 2</div> <div id="chat" class="word3">Word 3</div> <div id="" class="">Word 4</div> </body> </html> ```
2018/09/27
[ "https://Stackoverflow.com/questions/52528695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10227293/" ]
This is caused by the <http://openjdk.java.net/jeps/320> - which is removal of Java EE and CORBA Modules from the standard Java 11 version. As mentioned by @Pyves, the simple way would be unchecking "Enable automatic news polling" from the Preferences-> General -> News But if you still need this, you can install "javax.\*" bundles from the eclipse orbit repository. Here is the latest stable repo url: <http://download.eclipse.org/tools/orbit/downloads/drops/R20180905201904/repository> [![enter image description here](https://i.stack.imgur.com/4Plnt.png)](https://i.stack.imgur.com/4Plnt.png)
Turning off the news feed does solve this problem (Per @Pyves, unchecking "Enable automatic news polling" from Preferences-> General -> News), **but** be aware that you may get other issues because of the too-new JDK. Noga Rotman just spent several hours working out for me that Eclipse not being able to find JUnit, even though it was installed and correctly on the classpath, was because of using the new JDK (the one that is causing these same issues). You can solve the underlying issue by uninstalling your current version of the JDK and installing an old version, then reinstalling Eclipse. If you have the Oracle JDK you can find uninstall instructions [here](https://docs.oracle.com/javase/10/install/installation-jdk-and-jre-macos.htm#JSJIG-GUID-F575EB4A-70D3-4AB4-A20E-DBE95171AB5F) and and Java SE Development Kit 8u191 (which fixed my issues) is [here](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html).
52,528,695
I have 3 divs that fades sequentially on page load just like on this link: <http://jsfiddle.net/x4qjscgv/6/> However, I want the fade function to happen once the user clicked a button. I tried to use the function: document.getElementById but it does not appear to be working. See full code below: ``` <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> $(document).ready(function() { $('.word1, .word2, .word3').each(function(fadeIn) { $(this).delay(fadeIn * 500).fadeIn(1000); }); }); document.getElementById('btn').onclick = function(e) </script> <style> #chat { display: none; } </style> </head> <body> <button id="btn"> fade divs </button> <div id="chat" class="word1">Word 1</div> <div id="chat" class="word2">Word 2</div> <div id="chat" class="word3">Word 3</div> <div id="" class="">Word 4</div> </body> </html> ```
2018/09/27
[ "https://Stackoverflow.com/questions/52528695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10227293/" ]
This is caused by the <http://openjdk.java.net/jeps/320> - which is removal of Java EE and CORBA Modules from the standard Java 11 version. As mentioned by @Pyves, the simple way would be unchecking "Enable automatic news polling" from the Preferences-> General -> News But if you still need this, you can install "javax.\*" bundles from the eclipse orbit repository. Here is the latest stable repo url: <http://download.eclipse.org/tools/orbit/downloads/drops/R20180905201904/repository> [![enter image description here](https://i.stack.imgur.com/4Plnt.png)](https://i.stack.imgur.com/4Plnt.png)
For windows version Eclipse, 1. Enter search key string "news" 2. Check off "Enable automatic news polling" 3. Click [Apply and Close] button. That's it. [![enter image description here](https://i.stack.imgur.com/3IgiV.png)](https://i.stack.imgur.com/3IgiV.png)
52,528,695
I have 3 divs that fades sequentially on page load just like on this link: <http://jsfiddle.net/x4qjscgv/6/> However, I want the fade function to happen once the user clicked a button. I tried to use the function: document.getElementById but it does not appear to be working. See full code below: ``` <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> $(document).ready(function() { $('.word1, .word2, .word3').each(function(fadeIn) { $(this).delay(fadeIn * 500).fadeIn(1000); }); }); document.getElementById('btn').onclick = function(e) </script> <style> #chat { display: none; } </style> </head> <body> <button id="btn"> fade divs </button> <div id="chat" class="word1">Word 1</div> <div id="chat" class="word2">Word 2</div> <div id="chat" class="word3">Word 3</div> <div id="" class="">Word 4</div> </body> </html> ```
2018/09/27
[ "https://Stackoverflow.com/questions/52528695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10227293/" ]
Turning off the news feed does solve this problem (Per @Pyves, unchecking "Enable automatic news polling" from Preferences-> General -> News), **but** be aware that you may get other issues because of the too-new JDK. Noga Rotman just spent several hours working out for me that Eclipse not being able to find JUnit, even though it was installed and correctly on the classpath, was because of using the new JDK (the one that is causing these same issues). You can solve the underlying issue by uninstalling your current version of the JDK and installing an old version, then reinstalling Eclipse. If you have the Oracle JDK you can find uninstall instructions [here](https://docs.oracle.com/javase/10/install/installation-jdk-and-jre-macos.htm#JSJIG-GUID-F575EB4A-70D3-4AB4-A20E-DBE95171AB5F) and and Java SE Development Kit 8u191 (which fixed my issues) is [here](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html).
For windows version Eclipse, 1. Enter search key string "news" 2. Check off "Enable automatic news polling" 3. Click [Apply and Close] button. That's it. [![enter image description here](https://i.stack.imgur.com/3IgiV.png)](https://i.stack.imgur.com/3IgiV.png)
434,103
I have a 2 layer PCB that carries a microcontroller (Particle Electron), connects to a sensor with an ADC reading, has an ADC comparator IC, a watchdog timer IC, a PNP switch, an power bus and I2C lines. To protect the Analog reading line from EMI, should I be removing the ground pour around certain areas/ICs? For example, I am thinking of removing the ground pour around the watchdog timer IC because it may be introducing some noise. Does removing ground pour in this situation help, or hurt? [![enter image description here](https://i.stack.imgur.com/Xxh9e.png)](https://i.stack.imgur.com/Xxh9e.png)
2019/04/23
[ "https://electronics.stackexchange.com/questions/434103", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/195488/" ]
You don't remove copper pour to reduce noise. An unconnected copper pour will have more noise than no copper pour, but having a grounded copper pour tends to reduce noise or at least keep it the same compared to no copper pour. You remove copper pour to get rid of parasitic capacitance for sensitive circuits like oscillators an RF, and leakage currents for really high impedance circuits which operate on miniscule currents. And even then, it's not a universal rule since the right copper connected to ground can help things in instances with leakage currents. If you're that worried about EMI, you should be using a 4-layer board with a ground plane.
> > Does removing ground pour in this situation help, or hurt? > > > It probably doesn't make a difference. You could think of an unconnected copper pour as a capacitor with one end ungrounded/unconnected as a 1"sq area would have ~10-30pF of capacitance. The area could function like an antenna or resonator, but only at very high frequencies due to the low parasitics that form the antenna. There are a few designs where one would definitely be wise to remove an ungrounded/unconnected copper pour, if the design is going into a high radiation environment, the copper needs to be removed because it can slowly collect a charge in the thousands of volts and then break down in an ESD event. If your worried about it remove it, or ground it.
874,625
I have a module which starts a wxPython app, which loads a `wx.Bitmap` from file for use as a toolbar button. It looks like this: `wx.Bitmap("images\\new.png", wx.BITMAP_TYPE_ANY)`. All works well when I run that module by itself, but when I try to import and run it from a different module which is in a different directory, wxPython raises an exception. (The exception is something internal regarding the toolbar, which I think just means it's not loading the bitmap right.) What should I do?
2009/05/17
[ "https://Stackoverflow.com/questions/874625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76701/" ]
"images\new.png" is a relative path, so when bitmap gets loaded it will depened what is the cur dir so either you set cur dir ``` os.chdir("location to images folder") ``` or have a function which loads relative to your program e.g. ``` def getProgramFolder(): moduleFile = __file__ moduleDir = os.path.split(os.path.abspath(moduleFile))[0] programFolder = os.path.abspath(moduleDir) return programFolder bmpFilePath = os.path.join(getProgramFolder(), "images\\new.png") ```
The [wxPython FAQ](http://wiki.wxpython.org/Frequently%20Asked%20Questions#head-f3905e355271308d301310f0f8c1af64833ed912) recommends using a tool called `img2py.py` to embed icon files into a Python module. This tool comes with the wxPython distribution. Here is an [example of embedding toolbar icons](http://wiki.wxpython.org/WorkingWithToolBars).
2,066,269
**Question**: > > Find the continued fraction for $\sqrt{n^2 − 1}$, where $n \ge 2$ is > an integer. > > > **My attempt**: $n - 1 = \sqrt{n^2} - 1 \lt \sqrt{n^2 − 1} \lt \sqrt{n^2}$ So far, $[n-1; ]$ $\sqrt{n^2 − 1} = n - 1 + \frac{1}{x}$ $\to \frac{1}{x} = \sqrt{n^2 - 1} - (n-1) \to \frac{1}{x^2} = n^2-1-n^2-1+2n-2\times(n-1)\times\sqrt{n^2-1} = 2\times(n-1)\times(1-\sqrt{n^2-1})$ But, it doesn't really help to find continued fraction.
2016/12/20
[ "https://math.stackexchange.com/questions/2066269", "https://math.stackexchange.com", "https://math.stackexchange.com/users/49780/" ]
Writting $\sin x+\cos x = \sqrt{2}\sin \left(\frac{\pi}{4}+x\right)$, the integral can be written as $$\frac{1}{\sqrt 2}\int\_{0}^{\pi/4}\frac{\sin x}{\sin(\pi/4+x)}\,\mathrm{d}x=\frac{1}{\sqrt 2}\int\_{\pi/2}^{\pi/4}\frac{\sin(\pi/4-u)}{\sin u}\,\mathrm{d}u=\frac{1}{2}\int\_{\pi/2}^{\pi/4}\frac{1}{\tan u}\,\mathrm{d}u+\frac{\pi}{8},$$ where we used $\sin(\pi/4-u) = \frac{\sqrt{2}}{2}(\cos u - \sin u)$ in the last equality.
**Hint:** $$\frac{\sin x}{\sin x + \cos x}=\frac{1}{2}(\tan 2x - \sec 2x+1)$$ Proof: $$\frac{\sin x}{\sin x + \cos x}=\frac{\sin x(\cos x-\sin x)}{\cos 2x}=\frac{1}{2}\frac{\sin 2x+\cos 2x -1}{\cos 2x}=\frac{1}{2}(\tan 2x - \sec 2x+1)$$ Now integrate $\tan 2x$, $\sec 2x$ and $1$.
2,066,269
**Question**: > > Find the continued fraction for $\sqrt{n^2 − 1}$, where $n \ge 2$ is > an integer. > > > **My attempt**: $n - 1 = \sqrt{n^2} - 1 \lt \sqrt{n^2 − 1} \lt \sqrt{n^2}$ So far, $[n-1; ]$ $\sqrt{n^2 − 1} = n - 1 + \frac{1}{x}$ $\to \frac{1}{x} = \sqrt{n^2 - 1} - (n-1) \to \frac{1}{x^2} = n^2-1-n^2-1+2n-2\times(n-1)\times\sqrt{n^2-1} = 2\times(n-1)\times(1-\sqrt{n^2-1})$ But, it doesn't really help to find continued fraction.
2016/12/20
[ "https://math.stackexchange.com/questions/2066269", "https://math.stackexchange.com", "https://math.stackexchange.com/users/49780/" ]
Define $I$ = $\int\_{0}^{\pi/4} \frac{\sin x}{\sin x + \cos x} \, dx$ and $J$ = $\int\_{0}^{\pi/4} \frac{\cos x}{\sin x + \cos x} \, dx$ Now, what about $J$ + $I$ and $J$ - $I$ ? Can you get it from here?
**Hint:** $$\frac{\sin x}{\sin x + \cos x}=\frac{1}{2}(\tan 2x - \sec 2x+1)$$ Proof: $$\frac{\sin x}{\sin x + \cos x}=\frac{\sin x(\cos x-\sin x)}{\cos 2x}=\frac{1}{2}\frac{\sin 2x+\cos 2x -1}{\cos 2x}=\frac{1}{2}(\tan 2x - \sec 2x+1)$$ Now integrate $\tan 2x$, $\sec 2x$ and $1$.
22,893
I tried removing noise from the image shown below using Median Blur in OpenCV. But i'm not able to remove the colour noise completely as it is done in Neat Image. Any suggestions.? 1. Original Input Image ![Original Input image](https://i.stack.imgur.com/Plj2y.png) Median Blur Output ![Output after applying medain blur](https://i.stack.imgur.com/1LPi5.png) Neat Image Output ![Neat Image Output](https://i.stack.imgur.com/n2U0i.jpg)
2015/04/21
[ "https://dsp.stackexchange.com/questions/22893", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/13454/" ]
NeatImage probably uses Wavelets based Noise Reduction. You can look for methods based on that. Today you need methods which are "Edge Aware", namely they smooth yet keep edges in tact. Have a look at [Fast Anisotropic Curvature Preserving Smoothing](https://github.com/RoyiAvital/Fast-Anisotropic-Curvature-Preserving-Smoothing).
Well of course the canned filters are rudimentary, and there is a vast literature of more more advanced solutions out there. The only problem is that most of them exist only on paper; you have to implement them yourself. And since you're prepared to do that, then I suggest studying the literature to see what the latest methods are. In my archive I found this survey from 2005: * [A review of image denoising algorithms, with a new one](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.108.6427) I frequently hear about [non-local means](http://en.wikipedia.org/wiki/Non-local_means) methods mentioned in a favorable light, and [it is supported by OpenCV, so I would suggest starting there](http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_photo/py_non_local_means/py_non_local_means.html).
22,893
I tried removing noise from the image shown below using Median Blur in OpenCV. But i'm not able to remove the colour noise completely as it is done in Neat Image. Any suggestions.? 1. Original Input Image ![Original Input image](https://i.stack.imgur.com/Plj2y.png) Median Blur Output ![Output after applying medain blur](https://i.stack.imgur.com/1LPi5.png) Neat Image Output ![Neat Image Output](https://i.stack.imgur.com/n2U0i.jpg)
2015/04/21
[ "https://dsp.stackexchange.com/questions/22893", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/13454/" ]
I've had pretty good luck with using `OpenCV`'s built-in [`fastNlMeansDenoisingColored`](http://docs.opencv.org/modules/photo/doc/denoising.html).
Well of course the canned filters are rudimentary, and there is a vast literature of more more advanced solutions out there. The only problem is that most of them exist only on paper; you have to implement them yourself. And since you're prepared to do that, then I suggest studying the literature to see what the latest methods are. In my archive I found this survey from 2005: * [A review of image denoising algorithms, with a new one](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.108.6427) I frequently hear about [non-local means](http://en.wikipedia.org/wiki/Non-local_means) methods mentioned in a favorable light, and [it is supported by OpenCV, so I would suggest starting there](http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_photo/py_non_local_means/py_non_local_means.html).
22,893
I tried removing noise from the image shown below using Median Blur in OpenCV. But i'm not able to remove the colour noise completely as it is done in Neat Image. Any suggestions.? 1. Original Input Image ![Original Input image](https://i.stack.imgur.com/Plj2y.png) Median Blur Output ![Output after applying medain blur](https://i.stack.imgur.com/1LPi5.png) Neat Image Output ![Neat Image Output](https://i.stack.imgur.com/n2U0i.jpg)
2015/04/21
[ "https://dsp.stackexchange.com/questions/22893", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/13454/" ]
Since you're interested in implementing algorithms yourself, I would suggest it as a very flexible algorithm which can be adapted to a very wide variety of situations - [Adaptive Manifolds for Real Time High Dimensional Filtering](http://inf.ufrgs.br/%7Eeslgastal/AdaptiveManifolds/). The adaptability and flexibility of it is very appealing.
Well of course the canned filters are rudimentary, and there is a vast literature of more more advanced solutions out there. The only problem is that most of them exist only on paper; you have to implement them yourself. And since you're prepared to do that, then I suggest studying the literature to see what the latest methods are. In my archive I found this survey from 2005: * [A review of image denoising algorithms, with a new one](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.108.6427) I frequently hear about [non-local means](http://en.wikipedia.org/wiki/Non-local_means) methods mentioned in a favorable light, and [it is supported by OpenCV, so I would suggest starting there](http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_photo/py_non_local_means/py_non_local_means.html).
22,893
I tried removing noise from the image shown below using Median Blur in OpenCV. But i'm not able to remove the colour noise completely as it is done in Neat Image. Any suggestions.? 1. Original Input Image ![Original Input image](https://i.stack.imgur.com/Plj2y.png) Median Blur Output ![Output after applying medain blur](https://i.stack.imgur.com/1LPi5.png) Neat Image Output ![Neat Image Output](https://i.stack.imgur.com/n2U0i.jpg)
2015/04/21
[ "https://dsp.stackexchange.com/questions/22893", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/13454/" ]
NeatImage probably uses Wavelets based Noise Reduction. You can look for methods based on that. Today you need methods which are "Edge Aware", namely they smooth yet keep edges in tact. Have a look at [Fast Anisotropic Curvature Preserving Smoothing](https://github.com/RoyiAvital/Fast-Anisotropic-Curvature-Preserving-Smoothing).
Have you tried bilateral filtering? [It is also in OpenCV](http://opencvexamples.blogspot.com/2013/10/applying-bilateral-filter.html).
22,893
I tried removing noise from the image shown below using Median Blur in OpenCV. But i'm not able to remove the colour noise completely as it is done in Neat Image. Any suggestions.? 1. Original Input Image ![Original Input image](https://i.stack.imgur.com/Plj2y.png) Median Blur Output ![Output after applying medain blur](https://i.stack.imgur.com/1LPi5.png) Neat Image Output ![Neat Image Output](https://i.stack.imgur.com/n2U0i.jpg)
2015/04/21
[ "https://dsp.stackexchange.com/questions/22893", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/13454/" ]
NeatImage probably uses Wavelets based Noise Reduction. You can look for methods based on that. Today you need methods which are "Edge Aware", namely they smooth yet keep edges in tact. Have a look at [Fast Anisotropic Curvature Preserving Smoothing](https://github.com/RoyiAvital/Fast-Anisotropic-Curvature-Preserving-Smoothing).
I've had pretty good luck with using `OpenCV`'s built-in [`fastNlMeansDenoisingColored`](http://docs.opencv.org/modules/photo/doc/denoising.html).
22,893
I tried removing noise from the image shown below using Median Blur in OpenCV. But i'm not able to remove the colour noise completely as it is done in Neat Image. Any suggestions.? 1. Original Input Image ![Original Input image](https://i.stack.imgur.com/Plj2y.png) Median Blur Output ![Output after applying medain blur](https://i.stack.imgur.com/1LPi5.png) Neat Image Output ![Neat Image Output](https://i.stack.imgur.com/n2U0i.jpg)
2015/04/21
[ "https://dsp.stackexchange.com/questions/22893", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/13454/" ]
NeatImage probably uses Wavelets based Noise Reduction. You can look for methods based on that. Today you need methods which are "Edge Aware", namely they smooth yet keep edges in tact. Have a look at [Fast Anisotropic Curvature Preserving Smoothing](https://github.com/RoyiAvital/Fast-Anisotropic-Curvature-Preserving-Smoothing).
Since you're interested in implementing algorithms yourself, I would suggest it as a very flexible algorithm which can be adapted to a very wide variety of situations - [Adaptive Manifolds for Real Time High Dimensional Filtering](http://inf.ufrgs.br/%7Eeslgastal/AdaptiveManifolds/). The adaptability and flexibility of it is very appealing.
22,893
I tried removing noise from the image shown below using Median Blur in OpenCV. But i'm not able to remove the colour noise completely as it is done in Neat Image. Any suggestions.? 1. Original Input Image ![Original Input image](https://i.stack.imgur.com/Plj2y.png) Median Blur Output ![Output after applying medain blur](https://i.stack.imgur.com/1LPi5.png) Neat Image Output ![Neat Image Output](https://i.stack.imgur.com/n2U0i.jpg)
2015/04/21
[ "https://dsp.stackexchange.com/questions/22893", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/13454/" ]
I've had pretty good luck with using `OpenCV`'s built-in [`fastNlMeansDenoisingColored`](http://docs.opencv.org/modules/photo/doc/denoising.html).
Have you tried bilateral filtering? [It is also in OpenCV](http://opencvexamples.blogspot.com/2013/10/applying-bilateral-filter.html).
22,893
I tried removing noise from the image shown below using Median Blur in OpenCV. But i'm not able to remove the colour noise completely as it is done in Neat Image. Any suggestions.? 1. Original Input Image ![Original Input image](https://i.stack.imgur.com/Plj2y.png) Median Blur Output ![Output after applying medain blur](https://i.stack.imgur.com/1LPi5.png) Neat Image Output ![Neat Image Output](https://i.stack.imgur.com/n2U0i.jpg)
2015/04/21
[ "https://dsp.stackexchange.com/questions/22893", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/13454/" ]
Since you're interested in implementing algorithms yourself, I would suggest it as a very flexible algorithm which can be adapted to a very wide variety of situations - [Adaptive Manifolds for Real Time High Dimensional Filtering](http://inf.ufrgs.br/%7Eeslgastal/AdaptiveManifolds/). The adaptability and flexibility of it is very appealing.
Have you tried bilateral filtering? [It is also in OpenCV](http://opencvexamples.blogspot.com/2013/10/applying-bilateral-filter.html).
22,893
I tried removing noise from the image shown below using Median Blur in OpenCV. But i'm not able to remove the colour noise completely as it is done in Neat Image. Any suggestions.? 1. Original Input Image ![Original Input image](https://i.stack.imgur.com/Plj2y.png) Median Blur Output ![Output after applying medain blur](https://i.stack.imgur.com/1LPi5.png) Neat Image Output ![Neat Image Output](https://i.stack.imgur.com/n2U0i.jpg)
2015/04/21
[ "https://dsp.stackexchange.com/questions/22893", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/13454/" ]
I've had pretty good luck with using `OpenCV`'s built-in [`fastNlMeansDenoisingColored`](http://docs.opencv.org/modules/photo/doc/denoising.html).
Since you're interested in implementing algorithms yourself, I would suggest it as a very flexible algorithm which can be adapted to a very wide variety of situations - [Adaptive Manifolds for Real Time High Dimensional Filtering](http://inf.ufrgs.br/%7Eeslgastal/AdaptiveManifolds/). The adaptability and flexibility of it is very appealing.
47,924,606
I am dockerizing my application. I have two containers now. One of it wants to talk to another, in it's config I have `"mongo": "127.0.0.1"` I suppose they should talk through the bridge network: ``` $ docker network inspect bridge [ { "Name": "bridge", "Id": "f7ab26d71dbd6f557852c7156ae0574bbf62c42f539b50c8ebde0f728a253b6f", "Scope": "local", "Driver": "bridge", "IPAM": { "Driver": "default", "Config": [ { "Subnet": "172.17.0.1/16", "Gateway": "172.17.0.1" } ] }, "Containers": {}, "Options": { "com.docker.network.bridge.default_bridge": "true", "com.docker.network.bridge.enable_icc": "true", "com.docker.network.bridge.enable_ip_masquerade": "true", "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0", "com.docker.network.bridge.name": "docker0", "com.docker.network.driver.mtu": "9001" }, "Labels": {} } ] ``` Should I now change `"mongo": "127.0.0.1"` to `"mongo": "0.0.0.0"`?
2017/12/21
[ "https://Stackoverflow.com/questions/47924606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3014866/" ]
You can check a `container` IP. ``` $ docker inspect $(container_name) -f "{{json .NetworkSettings.Networks}}" ``` You can find `IPAddress` attribute from the output of `json`.
Best way to use is using with --link option to avoid to many changes. > > for ex: --link mongo01:mongo it will instruct Docker to use the container named mongo01 as a linked container, and name it mongo inside your application container > > > So in your application you can use mongo:27017. without making any changes. refer this for more details. > > <https://www.thachmai.info/2015/05/10/docker-container-linking-mongo-node/> > > >
47,924,606
I am dockerizing my application. I have two containers now. One of it wants to talk to another, in it's config I have `"mongo": "127.0.0.1"` I suppose they should talk through the bridge network: ``` $ docker network inspect bridge [ { "Name": "bridge", "Id": "f7ab26d71dbd6f557852c7156ae0574bbf62c42f539b50c8ebde0f728a253b6f", "Scope": "local", "Driver": "bridge", "IPAM": { "Driver": "default", "Config": [ { "Subnet": "172.17.0.1/16", "Gateway": "172.17.0.1" } ] }, "Containers": {}, "Options": { "com.docker.network.bridge.default_bridge": "true", "com.docker.network.bridge.enable_icc": "true", "com.docker.network.bridge.enable_ip_masquerade": "true", "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0", "com.docker.network.bridge.name": "docker0", "com.docker.network.driver.mtu": "9001" }, "Labels": {} } ] ``` Should I now change `"mongo": "127.0.0.1"` to `"mongo": "0.0.0.0"`?
2017/12/21
[ "https://Stackoverflow.com/questions/47924606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3014866/" ]
Yes, you should use a bridge network. The default "bridge" can be used but won't give you DNS resolution, check <https://docs.docker.com/engine/userguide/networking/#user-defined-networks> for details.
Best way to use is using with --link option to avoid to many changes. > > for ex: --link mongo01:mongo it will instruct Docker to use the container named mongo01 as a linked container, and name it mongo inside your application container > > > So in your application you can use mongo:27017. without making any changes. refer this for more details. > > <https://www.thachmai.info/2015/05/10/docker-container-linking-mongo-node/> > > >
47,924,606
I am dockerizing my application. I have two containers now. One of it wants to talk to another, in it's config I have `"mongo": "127.0.0.1"` I suppose they should talk through the bridge network: ``` $ docker network inspect bridge [ { "Name": "bridge", "Id": "f7ab26d71dbd6f557852c7156ae0574bbf62c42f539b50c8ebde0f728a253b6f", "Scope": "local", "Driver": "bridge", "IPAM": { "Driver": "default", "Config": [ { "Subnet": "172.17.0.1/16", "Gateway": "172.17.0.1" } ] }, "Containers": {}, "Options": { "com.docker.network.bridge.default_bridge": "true", "com.docker.network.bridge.enable_icc": "true", "com.docker.network.bridge.enable_ip_masquerade": "true", "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0", "com.docker.network.bridge.name": "docker0", "com.docker.network.driver.mtu": "9001" }, "Labels": {} } ] ``` Should I now change `"mongo": "127.0.0.1"` to `"mongo": "0.0.0.0"`?
2017/12/21
[ "https://Stackoverflow.com/questions/47924606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3014866/" ]
You can check a `container` IP. ``` $ docker inspect $(container_name) -f "{{json .NetworkSettings.Networks}}" ``` You can find `IPAddress` attribute from the output of `json`.
Yes, you should use a bridge network. The default "bridge" can be used but won't give you DNS resolution, check <https://docs.docker.com/engine/userguide/networking/#user-defined-networks> for details.
8,355,982
I am trying to track few rows being deleted from one of the Sql Server table? I am planning to write a trigger to track from which machine or process the delete request was sent. Is it possible to know in a Trigger in Sql Server 2005 to track the machineName and processId from which Sql is invoked?
2011/12/02
[ "https://Stackoverflow.com/questions/8355982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/874520/" ]
You can add other columns from sysprocesses as you see fit, and you need to create the ProcessLog table first. ``` CREATE TRIGGER [dbo].[LogDelete] ON [dbo].[SampleTable] AFTER DELETE AS BEGIN SET NOCOUNT ON; INSERT INTO dbo.ProcessLog SELECT program_name , net_address , hostname FROM sys.sysprocesses WHERE spid = @@SPID END ```
you can do it with SQL Server Profiler [http://i.stack.imgur.com/p7Asn.png](https://i.stack.imgur.com/p7Asn.png) ![enter image description here](https://i.stack.imgur.com/p7Asn.png) try this also : ``` SELECT sqltext.TEXT, req.session_id, req.status, req.command, req.cpu_time, req.total_elapsed_time FROM sys.dm_exec_requests req CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext ```
17,690,103
I want to re-skin ActiveAdmin using a Bootstrap template theme. However I need to change the layout of the page to suit. Is it possible to override the layout of ActiveAdmin to suit what I want? It looks different to normal rails conventions - I'd rather just accomplish it using a regular template and then yield the parts of the content that I need in the order that I need them.
2013/07/17
[ "https://Stackoverflow.com/questions/17690103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778675/" ]
Ive done something similar before. Check out this Gist <https://gist.github.com/bigfive/6017435> Essentially you patch the active admin base controller to use your new layout by overriding their `:determine_active_admin_layout` method ``` # config/initializers/active_admin_patch.rb module ActiveAdmin class BaseController def determine_active_admin_layout 'active_admin_reskin' end end end ``` Then in your `active_admin_reskin` layout you can call methods on the Arbre `view_factory` like so ``` view_factory[#{params[:action]}_page"].new(Arbre::Context.new(assigns, self)).send(:build_header) ``` In the gist(<https://gist.github.com/bigfive/6017435>) Ive made a little view helper for making it easy to call those methods. Have a look through the active admin source code to see which methods are available to you on various Arbre documents, especially here: <https://github.com/gregbell/active_admin/blob/master/lib/active_admin/views/pages/base.rb> Once the markup is changed the way you like, you can `@include 'bootstrap'` into your `active_admin.css.scss` file that the generator created and go nuts.
Depending on what version of AA you are using. (0.6.0 < commit:ec9996406df5c07f4720eabc0120f710ae46c997): Include your scss, but encapsulate your css selectors in the `body.active_admin` group. Furthermore, specificity is important, so if you want to override the default styling of AA, you may need to ensure you are overriding the full selector to get the behavior you want. If you want to find these styles to override them, take a look at [AA's stylesheets](https://github.com/gregbell/active_admin/tree/master/app/assets/stylesheets/active_admin) to see how they style the site be default. Simply include your custom styling after the the AA stylesheet is included. After commit:ec9996406df5c07f4720eabc0120f710ae46c997 The namespacing of stylesheets has been removed recently, and I have not throroughly tested the implication yet.
17,690,103
I want to re-skin ActiveAdmin using a Bootstrap template theme. However I need to change the layout of the page to suit. Is it possible to override the layout of ActiveAdmin to suit what I want? It looks different to normal rails conventions - I'd rather just accomplish it using a regular template and then yield the parts of the content that I need in the order that I need them.
2013/07/17
[ "https://Stackoverflow.com/questions/17690103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778675/" ]
A simple answer would be putting @import "bootstrap"; into active\_admin.css.scss Officially, its not supported for now <https://github.com/gregbell/active_admin/issues/1027>
Depending on what version of AA you are using. (0.6.0 < commit:ec9996406df5c07f4720eabc0120f710ae46c997): Include your scss, but encapsulate your css selectors in the `body.active_admin` group. Furthermore, specificity is important, so if you want to override the default styling of AA, you may need to ensure you are overriding the full selector to get the behavior you want. If you want to find these styles to override them, take a look at [AA's stylesheets](https://github.com/gregbell/active_admin/tree/master/app/assets/stylesheets/active_admin) to see how they style the site be default. Simply include your custom styling after the the AA stylesheet is included. After commit:ec9996406df5c07f4720eabc0120f710ae46c997 The namespacing of stylesheets has been removed recently, and I have not throroughly tested the implication yet.
17,690,103
I want to re-skin ActiveAdmin using a Bootstrap template theme. However I need to change the layout of the page to suit. Is it possible to override the layout of ActiveAdmin to suit what I want? It looks different to normal rails conventions - I'd rather just accomplish it using a regular template and then yield the parts of the content that I need in the order that I need them.
2013/07/17
[ "https://Stackoverflow.com/questions/17690103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778675/" ]
Ive done something similar before. Check out this Gist <https://gist.github.com/bigfive/6017435> Essentially you patch the active admin base controller to use your new layout by overriding their `:determine_active_admin_layout` method ``` # config/initializers/active_admin_patch.rb module ActiveAdmin class BaseController def determine_active_admin_layout 'active_admin_reskin' end end end ``` Then in your `active_admin_reskin` layout you can call methods on the Arbre `view_factory` like so ``` view_factory[#{params[:action]}_page"].new(Arbre::Context.new(assigns, self)).send(:build_header) ``` In the gist(<https://gist.github.com/bigfive/6017435>) Ive made a little view helper for making it easy to call those methods. Have a look through the active admin source code to see which methods are available to you on various Arbre documents, especially here: <https://github.com/gregbell/active_admin/blob/master/lib/active_admin/views/pages/base.rb> Once the markup is changed the way you like, you can `@include 'bootstrap'` into your `active_admin.css.scss` file that the generator created and go nuts.
A simple answer would be putting @import "bootstrap"; into active\_admin.css.scss Officially, its not supported for now <https://github.com/gregbell/active_admin/issues/1027>
17,690,103
I want to re-skin ActiveAdmin using a Bootstrap template theme. However I need to change the layout of the page to suit. Is it possible to override the layout of ActiveAdmin to suit what I want? It looks different to normal rails conventions - I'd rather just accomplish it using a regular template and then yield the parts of the content that I need in the order that I need them.
2013/07/17
[ "https://Stackoverflow.com/questions/17690103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778675/" ]
Ive done something similar before. Check out this Gist <https://gist.github.com/bigfive/6017435> Essentially you patch the active admin base controller to use your new layout by overriding their `:determine_active_admin_layout` method ``` # config/initializers/active_admin_patch.rb module ActiveAdmin class BaseController def determine_active_admin_layout 'active_admin_reskin' end end end ``` Then in your `active_admin_reskin` layout you can call methods on the Arbre `view_factory` like so ``` view_factory[#{params[:action]}_page"].new(Arbre::Context.new(assigns, self)).send(:build_header) ``` In the gist(<https://gist.github.com/bigfive/6017435>) Ive made a little view helper for making it easy to call those methods. Have a look through the active admin source code to see which methods are available to you on various Arbre documents, especially here: <https://github.com/gregbell/active_admin/blob/master/lib/active_admin/views/pages/base.rb> Once the markup is changed the way you like, you can `@include 'bootstrap'` into your `active_admin.css.scss` file that the generator created and go nuts.
BigFive's accepted answer worked for me at the beginning but then produced some bugs when rendering custom partials or when rendering errors in forms. Inspired by his approach I switched to overriding the individual methods that AA uses to dynamically generate the layout (as AA doesn't use a static layout file that can be easily modified). You can find the available methods in the source code, but it's pretty self-explanatory and begins in the [html element](https://github.com/activeadmin/active_admin/blob/8b4c1b5ef65ebdf77413bcaa955c0f7badb26ffb/lib/active_admin/views/pages/base.rb). Example: To add some classes and reorganize the elements: You can put your style in: assets/stylesheets/active\_admin.css.scss And your html description in: config/initializers/active\_admin\_patch.rb: ``` module ActiveAdmin module Views class Header alias_method :original_build_site_title, :build_site_title alias_method :original_build_global_navigation, :build_global_navigation alias_method :original_build_utility_navigation, :build_utility_navigation def build_site_title div class: "side_bar_top" do original_build_site_title end end def build_global_navigation div class: "side_bar_content" do original_build_global_navigation end end def build_utility_navigation div class: "side_bar_footer" do original_build_utility_navigation end end end module Pages class Base alias_method :original_build, :build # This should be the same as add_classes_to_body but for the html main element def add_classes_to_html_tag document.add_class(params[:action]) document.add_class(params[:controller].gsub('/', '_')) document.add_class("active_admin") document.add_class("logged_in") document.add_class(active_admin_namespace.name.to_s + "_namespace") end def build(*args) original_build add_classes_to_html_tag end def build_page within @body do div id: "wrapper" do div id: "details_view" do build_title_bar build_page_content #build_footer end div id: "master_view" do build_header end end end end end end end end ```
17,690,103
I want to re-skin ActiveAdmin using a Bootstrap template theme. However I need to change the layout of the page to suit. Is it possible to override the layout of ActiveAdmin to suit what I want? It looks different to normal rails conventions - I'd rather just accomplish it using a regular template and then yield the parts of the content that I need in the order that I need them.
2013/07/17
[ "https://Stackoverflow.com/questions/17690103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778675/" ]
A simple answer would be putting @import "bootstrap"; into active\_admin.css.scss Officially, its not supported for now <https://github.com/gregbell/active_admin/issues/1027>
BigFive's accepted answer worked for me at the beginning but then produced some bugs when rendering custom partials or when rendering errors in forms. Inspired by his approach I switched to overriding the individual methods that AA uses to dynamically generate the layout (as AA doesn't use a static layout file that can be easily modified). You can find the available methods in the source code, but it's pretty self-explanatory and begins in the [html element](https://github.com/activeadmin/active_admin/blob/8b4c1b5ef65ebdf77413bcaa955c0f7badb26ffb/lib/active_admin/views/pages/base.rb). Example: To add some classes and reorganize the elements: You can put your style in: assets/stylesheets/active\_admin.css.scss And your html description in: config/initializers/active\_admin\_patch.rb: ``` module ActiveAdmin module Views class Header alias_method :original_build_site_title, :build_site_title alias_method :original_build_global_navigation, :build_global_navigation alias_method :original_build_utility_navigation, :build_utility_navigation def build_site_title div class: "side_bar_top" do original_build_site_title end end def build_global_navigation div class: "side_bar_content" do original_build_global_navigation end end def build_utility_navigation div class: "side_bar_footer" do original_build_utility_navigation end end end module Pages class Base alias_method :original_build, :build # This should be the same as add_classes_to_body but for the html main element def add_classes_to_html_tag document.add_class(params[:action]) document.add_class(params[:controller].gsub('/', '_')) document.add_class("active_admin") document.add_class("logged_in") document.add_class(active_admin_namespace.name.to_s + "_namespace") end def build(*args) original_build add_classes_to_html_tag end def build_page within @body do div id: "wrapper" do div id: "details_view" do build_title_bar build_page_content #build_footer end div id: "master_view" do build_header end end end end end end end end ```
27,505,561
I have the following code: ``` <?php $myfile = fopen("code2.css", "w") or die("Unable to open file!"); $txt = "John Doe\n"; fwrite($myfile, $txt); $txt = "Jane Doe\n"; fwrite($myfile, $txt); fclose($myfile); ?> ?> ``` code2.css is in the same folder as my PHP file, but it throws me: > > Unable to open file all the time. > > > How can I fix this? Update: After playing with permissions the error dissapeared, but still my file won't be updated.
2014/12/16
[ "https://Stackoverflow.com/questions/27505561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4325791/" ]
Check the properties of code2.css. You must found the "read only" permission to it, and change it to "Read and Write". After that your code will work. If you are using a Linux system, then execute: ``` sudo chmod 777 code2.css ```
``` <?php $myfile = fopen("code2.css", "w") or die("Unable to open file!"); $txt = "John Doe\n"; fwrite($myfile, $txt); $txt = "Jane Doe\n"; fwrite($myfile, $txt); fclose($myfile);//just removed the closing php tag from here and it is working fine ?> ```
27,505,561
I have the following code: ``` <?php $myfile = fopen("code2.css", "w") or die("Unable to open file!"); $txt = "John Doe\n"; fwrite($myfile, $txt); $txt = "Jane Doe\n"; fwrite($myfile, $txt); fclose($myfile); ?> ?> ``` code2.css is in the same folder as my PHP file, but it throws me: > > Unable to open file all the time. > > > How can I fix this? Update: After playing with permissions the error dissapeared, but still my file won't be updated.
2014/12/16
[ "https://Stackoverflow.com/questions/27505561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4325791/" ]
Check the properties of code2.css. You must found the "read only" permission to it, and change it to "Read and Write". After that your code will work. If you are using a Linux system, then execute: ``` sudo chmod 777 code2.css ```
fopen() returns false **and generates an E\_WARNING alert** on fail. You should begin with displaying all warnings, you'll get more information on the issue: ``` error_reporting(E_ALL); ini_set('display_errors', '1'); ``` Please post the warning. Probably rights on your file or folder. Please make sure your webserver has write rights on it. What system are you running your localhost on?
408,709
I changed a resistor with same color stripes Yellow, Purple, Gold, Gold on a Pioneer surround system but the only difference was that the I put was a bit bigger. The problem is the system went into protected mode because of an error, I forced reset it and the fuse blew up. Was it because of the resistor I changed? UPDATE: It was **not** a fuse that blew up, It was 2 of D5SBA60 silicon bridge rectifier that blew up. There is leakage from there. I have pics of the 2 silicon bridge rectifiers and the resistor that I changed: [![To me it looks like it has leaked?](https://i.stack.imgur.com/vPd1J.jpg)](https://i.stack.imgur.com/vPd1J.jpg) [![enter image description here](https://i.stack.imgur.com/65sef.jpg)](https://i.stack.imgur.com/65sef.jpg) I measured this resistor in ohms and only shows open line, other one is ok, about 5 ohms. I will be replacing it for a good one, to me it looks like it leaked.
2018/11/25
[ "https://electronics.stackexchange.com/questions/408709", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/205386/" ]
> > Is a bigger resistor different from a smaller resistor with same color stripes? > > > In general, a resistor can be characterized by three values: * The resistance * The maximum allowed power * The behavior (change of resistance) when the resistor gets heated The color stripes tell you about the resistance (and about the tolerance of that value). So if the color stripes are the same, the resistor has the same resistance. If the resistor's maximum allowed power is too small, the resistor will heat up and may be destroyed (e.g. burn). There is no problem if the resistor's maximum allowed power is higher than required. Although this is not sure I would expect that a "bigger" resistor allows more power than a smaller one. Typically you can forget about the behavior when the resistor gets heated. > > The problem is the system went into protected mode because of an error, I forced reset it and the fuse blew up. Was it because of the resistor I changed? > > > You didn't change the resistor just for fun but because your system did not work any more. In this case you can nearly be sure that the resistor was not the only part that was destroyed. If you only change the resistor, the other parts that were destroyed still are destroyed. I guess that these parts caused the fuse to be blown - not the resistor.
> > The problem is the system went into protected mode because of an > error, I forced reset it and the fuse blew up. Was it because of the > resistor I changed? > > > Well, you could have inadvertently changed the resistor for an inductor: - [![enter image description here](https://i.stack.imgur.com/6keUQ.gif)](https://i.stack.imgur.com/6keUQ.gif) Or you could have assumed that the component was a resistor when in fact it was an inductor. Either way *might* cause problems.
408,709
I changed a resistor with same color stripes Yellow, Purple, Gold, Gold on a Pioneer surround system but the only difference was that the I put was a bit bigger. The problem is the system went into protected mode because of an error, I forced reset it and the fuse blew up. Was it because of the resistor I changed? UPDATE: It was **not** a fuse that blew up, It was 2 of D5SBA60 silicon bridge rectifier that blew up. There is leakage from there. I have pics of the 2 silicon bridge rectifiers and the resistor that I changed: [![To me it looks like it has leaked?](https://i.stack.imgur.com/vPd1J.jpg)](https://i.stack.imgur.com/vPd1J.jpg) [![enter image description here](https://i.stack.imgur.com/65sef.jpg)](https://i.stack.imgur.com/65sef.jpg) I measured this resistor in ohms and only shows open line, other one is ok, about 5 ohms. I will be replacing it for a good one, to me it looks like it leaked.
2018/11/25
[ "https://electronics.stackexchange.com/questions/408709", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/205386/" ]
> > Is a bigger resistor different from a smaller resistor with same color stripes? > > > In general, a resistor can be characterized by three values: * The resistance * The maximum allowed power * The behavior (change of resistance) when the resistor gets heated The color stripes tell you about the resistance (and about the tolerance of that value). So if the color stripes are the same, the resistor has the same resistance. If the resistor's maximum allowed power is too small, the resistor will heat up and may be destroyed (e.g. burn). There is no problem if the resistor's maximum allowed power is higher than required. Although this is not sure I would expect that a "bigger" resistor allows more power than a smaller one. Typically you can forget about the behavior when the resistor gets heated. > > The problem is the system went into protected mode because of an error, I forced reset it and the fuse blew up. Was it because of the resistor I changed? > > > You didn't change the resistor just for fun but because your system did not work any more. In this case you can nearly be sure that the resistor was not the only part that was destroyed. If you only change the resistor, the other parts that were destroyed still are destroyed. I guess that these parts caused the fuse to be blown - not the resistor.
Typically the larger the resistor, the more power it can handle. For example: [![Image of different resistor sizes and power ratings](https://i.stack.imgur.com/Bzd2g.png)](https://i.stack.imgur.com/Bzd2g.png) ([Image source](https://www.mikroe.com/ebooks/components-of-electronic-devices/resistor-dissipation)) That, however, would not be the source of the problem you are experiencing, because higher power rating at the same resistance just means the resistor is less likely to blow.
408,709
I changed a resistor with same color stripes Yellow, Purple, Gold, Gold on a Pioneer surround system but the only difference was that the I put was a bit bigger. The problem is the system went into protected mode because of an error, I forced reset it and the fuse blew up. Was it because of the resistor I changed? UPDATE: It was **not** a fuse that blew up, It was 2 of D5SBA60 silicon bridge rectifier that blew up. There is leakage from there. I have pics of the 2 silicon bridge rectifiers and the resistor that I changed: [![To me it looks like it has leaked?](https://i.stack.imgur.com/vPd1J.jpg)](https://i.stack.imgur.com/vPd1J.jpg) [![enter image description here](https://i.stack.imgur.com/65sef.jpg)](https://i.stack.imgur.com/65sef.jpg) I measured this resistor in ohms and only shows open line, other one is ok, about 5 ohms. I will be replacing it for a good one, to me it looks like it leaked.
2018/11/25
[ "https://electronics.stackexchange.com/questions/408709", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/205386/" ]
> > The problem is the system went into protected mode because of an > error, I forced reset it and the fuse blew up. Was it because of the > resistor I changed? > > > Well, you could have inadvertently changed the resistor for an inductor: - [![enter image description here](https://i.stack.imgur.com/6keUQ.gif)](https://i.stack.imgur.com/6keUQ.gif) Or you could have assumed that the component was a resistor when in fact it was an inductor. Either way *might* cause problems.
Typically the larger the resistor, the more power it can handle. For example: [![Image of different resistor sizes and power ratings](https://i.stack.imgur.com/Bzd2g.png)](https://i.stack.imgur.com/Bzd2g.png) ([Image source](https://www.mikroe.com/ebooks/components-of-electronic-devices/resistor-dissipation)) That, however, would not be the source of the problem you are experiencing, because higher power rating at the same resistance just means the resistor is less likely to blow.
41,842,310
I was wondering if there is any benefit to training on high resolution images rather than low resolution. I understand that it will take longer to train on larger images and that the dimensions must be a multiple of 32. My current image set is 1440x1920. Would I be better off resizing to 480x640, or is bigger better?
2017/01/25
[ "https://Stackoverflow.com/questions/41842310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5350348/" ]
It's certainly not a requirement that your images be powers of two. There may be some cases where it speeds things up (e.g. GPU allocation) but it's not critical. Smaller images will train significantly faster, and possibly even converge quicker (all other factors held constant) as you will be able to train on bigger batches (e.g. 100-1000 images in one pass, which you might not be able to do on a single machine with high res imagery). As to whether to resize, you need to ask yourself if every pixel in that image is critical to your task. Often this is not the case - you can probably resize a photo of a bus down to say 128x128 and still recognize that it's a bus. Using smaller images can also help your network generalise better, too, as there is less data to overfit. A technique often used in image classification networks is to perform distortions (e.g. random cropping, scaling & brightness adjustment) on images to (a) convert odd-sized images to a constant size, (b) synthesize more data and (c) encourage the network to generalise.
This depends largely on the application. As a rule of thumb, I'd ask myself the question: can I complete the task myself on the resized images? If so, I'd downsize to the lowest resolution before it makes the task more difficult for you yourself. If not... you're going to have to be -very- patient using images 1440 \* 1920. I imagine you'll almost always be better off experimenting with more varied architectures and hyper-parameter sets on smaller images compared to fewer models on full resolution images. Whatever size you choose, you'll have to design your network for the image size you have in mind. If you're using convolutional layers, a larger image will require larger strides, filter sizes and/or layers. The number of parameters will stay the same for each convolution, though the number of features will grow (along with batch normalisation parameters if you're using it).
39,870,368
Following is my js ``` $(document).ready(function() { $.ajax({ url: url + 'project/get_project_list', method:'post', dataType:'xml', success:function(data){ $('#datatable').dataTable({ data:data, columns:[ { "data" : "projectName" }, { data : "projectDescription" }, ] }); } }); }); $('#datatable').DataTable(); </script> <div class="panel-wrapper"> <form id="form1"> <table id="datatable"> <thead> <tr> <th>Project Name</th> <th>Project Description</th> </tr> </thead> </table> </form> </div> ``` My response is as follows ``` <projectList> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <listException>false</listException> <listExceptionId>0</listExceptionId> <listSize>0</listSize> <nextPage>false</nextPage> <pageNumber>0</pageNumber> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription></projectDescription> <projectId>5</projectId> <projectName>Bmw</projectName> </projectBOs> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription>Toyota</projectDescription> <projectId>4</projectId> <projectName>Toyota global</projectName> </projectBOs> <projectBOs> ``` Kindly help how could i bind projectname and projectdescription to the table .currently it says no data available in table. i have no idea in using datatables
2016/10/05
[ "https://Stackoverflow.com/questions/39870368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4332335/" ]
This is how I am using multiple layouts in my ASP.NET core MVC application. You can try like this- In `_ViewStart.cshtml` specify default \_Layout like this- ``` @{ Layout = "_Layout"; } ``` If you want to set page specific layout then in that `page.cshtml`, you can assign other view like this- ``` @{ Layout = "~/Views/Shared/_Layout_2.cshtml"; ViewData["Title"] = "Page Title"; } ``` See if this helps.
If you want to have a different layout based on some condition, you could use this code in the `_ViewStart.cshtml` file: ``` @{ if (some condition) { Layout = "_Layout1"; } else if (some other condition) { Layout = "_Layout2"; } etc. } ``` I use this in one of my projects. In my case the condition is `User.IsInRole("admin")` and my `_ViewStart.cshtml` file is as follows: ``` @{ if (User.IsInRole("admin")) { Layout = "_AdminLayout"; } else { Layout = "_Layout"; } } ``` Since there are only two roles in my project, which result in only one condition, this workaround is not too bad in my case. I hope someone with in a similar situation will find this useful :)
39,870,368
Following is my js ``` $(document).ready(function() { $.ajax({ url: url + 'project/get_project_list', method:'post', dataType:'xml', success:function(data){ $('#datatable').dataTable({ data:data, columns:[ { "data" : "projectName" }, { data : "projectDescription" }, ] }); } }); }); $('#datatable').DataTable(); </script> <div class="panel-wrapper"> <form id="form1"> <table id="datatable"> <thead> <tr> <th>Project Name</th> <th>Project Description</th> </tr> </thead> </table> </form> </div> ``` My response is as follows ``` <projectList> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <listException>false</listException> <listExceptionId>0</listExceptionId> <listSize>0</listSize> <nextPage>false</nextPage> <pageNumber>0</pageNumber> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription></projectDescription> <projectId>5</projectId> <projectName>Bmw</projectName> </projectBOs> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription>Toyota</projectDescription> <projectId>4</projectId> <projectName>Toyota global</projectName> </projectBOs> <projectBOs> ``` Kindly help how could i bind projectname and projectdescription to the table .currently it says no data available in table. i have no idea in using datatables
2016/10/05
[ "https://Stackoverflow.com/questions/39870368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4332335/" ]
This is how I am using multiple layouts in my ASP.NET core MVC application. You can try like this- In `_ViewStart.cshtml` specify default \_Layout like this- ``` @{ Layout = "_Layout"; } ``` If you want to set page specific layout then in that `page.cshtml`, you can assign other view like this- ``` @{ Layout = "~/Views/Shared/_Layout_2.cshtml"; ViewData["Title"] = "Page Title"; } ``` See if this helps.
To have a Multiple Layout in asp.net core is quite easy, follow the steps below: Step 1: Create the layout inside the "Shared Folder located Under Views" and give it a name with prefix "\_" i.e `_myLoginLayout.cshtml` Step 2: Specify your layout at the beginning of the page you want to apply it e.g @{ `Layout = "~/Views/Shared/_myLoginLayout.cshtml"; ViewData["Title"] = "TestMe";`//you can add the title as well... } So when `_ViewStart.cshtml` is loading Layout for your page..it will read the Layout you specify.
39,870,368
Following is my js ``` $(document).ready(function() { $.ajax({ url: url + 'project/get_project_list', method:'post', dataType:'xml', success:function(data){ $('#datatable').dataTable({ data:data, columns:[ { "data" : "projectName" }, { data : "projectDescription" }, ] }); } }); }); $('#datatable').DataTable(); </script> <div class="panel-wrapper"> <form id="form1"> <table id="datatable"> <thead> <tr> <th>Project Name</th> <th>Project Description</th> </tr> </thead> </table> </form> </div> ``` My response is as follows ``` <projectList> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <listException>false</listException> <listExceptionId>0</listExceptionId> <listSize>0</listSize> <nextPage>false</nextPage> <pageNumber>0</pageNumber> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription></projectDescription> <projectId>5</projectId> <projectName>Bmw</projectName> </projectBOs> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription>Toyota</projectDescription> <projectId>4</projectId> <projectName>Toyota global</projectName> </projectBOs> <projectBOs> ``` Kindly help how could i bind projectname and projectdescription to the table .currently it says no data available in table. i have no idea in using datatables
2016/10/05
[ "https://Stackoverflow.com/questions/39870368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4332335/" ]
In ASP.NET Core 2.0, I was inspired by the answer of @Daniel J.G. I made a `ViewLayoutAttribute`: ```cs [AttributeUsage(AttributeTargets.Class)] public class ViewLayoutAttribute : Attribute { public ViewLayoutAttribute(string layoutName) { this.LayoutName = layoutName; } public string LayoutName { get; } } ``` Exemple of a controller class: ```cs [ViewLayout("_Layout2")] public class MyController : Controller { // Code } ``` And I created an extension to get this very attribute from the `ViewContext`: ```cs public static class RazorExtensions { /// <summary> /// Gets the <see cref="ViewLayoutAttribute"/> from the current calling controller of the /// <see cref="ViewContext"/>. /// </summary> public static ViewLayoutAttribute GetLayoutAttribute(this ViewContext viewContext) { // See if Razor Page... if (viewContext.ActionDescriptor is CompiledPageActionDescriptor actionDescriptor) { // We want the attribute no matter what. return Attribute.GetCustomAttribute(actionDescriptor.ModelTypeInfo, typeof(ViewLayoutAttribute)) as ViewLayoutAttribute; } // See if MVC Controller... // Property ControllerTypeInfo can be seen on runtime. var controllerType = (Type)viewContext.ActionDescriptor .GetType() .GetProperty("ControllerTypeInfo")? .GetValue(viewContext.ActionDescriptor); if (controllerType != null && controllerType.IsSubclassOf(typeof(Microsoft.AspNetCore.Mvc.Controller))) { return Attribute.GetCustomAttribute(controllerType, typeof(ViewLayoutAttribute)) as ViewLayoutAttribute; } // Nothing found. return null; } } ``` And in `_ViewStart.cshtml`: ``` @using MyApp.Extensions @{ Layout = ViewContext.GetLayoutAttribute()?.LayoutName ?? "_Layout"; } ```
You can use `IViewLocationExpander` interface to render view as you want. Please refer this link [Working with IViewLocationExpander in mvc](https://stackoverflow.com/questions/39471627/working-with-iviewlocationexpander-in-mvc) for more details Regards, Rohit
39,870,368
Following is my js ``` $(document).ready(function() { $.ajax({ url: url + 'project/get_project_list', method:'post', dataType:'xml', success:function(data){ $('#datatable').dataTable({ data:data, columns:[ { "data" : "projectName" }, { data : "projectDescription" }, ] }); } }); }); $('#datatable').DataTable(); </script> <div class="panel-wrapper"> <form id="form1"> <table id="datatable"> <thead> <tr> <th>Project Name</th> <th>Project Description</th> </tr> </thead> </table> </form> </div> ``` My response is as follows ``` <projectList> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <listException>false</listException> <listExceptionId>0</listExceptionId> <listSize>0</listSize> <nextPage>false</nextPage> <pageNumber>0</pageNumber> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription></projectDescription> <projectId>5</projectId> <projectName>Bmw</projectName> </projectBOs> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription>Toyota</projectDescription> <projectId>4</projectId> <projectName>Toyota global</projectName> </projectBOs> <projectBOs> ``` Kindly help how could i bind projectname and projectdescription to the table .currently it says no data available in table. i have no idea in using datatables
2016/10/05
[ "https://Stackoverflow.com/questions/39870368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4332335/" ]
If you want to have a different layout based on some condition, you could use this code in the `_ViewStart.cshtml` file: ``` @{ if (some condition) { Layout = "_Layout1"; } else if (some other condition) { Layout = "_Layout2"; } etc. } ``` I use this in one of my projects. In my case the condition is `User.IsInRole("admin")` and my `_ViewStart.cshtml` file is as follows: ``` @{ if (User.IsInRole("admin")) { Layout = "_AdminLayout"; } else { Layout = "_Layout"; } } ``` Since there are only two roles in my project, which result in only one condition, this workaround is not too bad in my case. I hope someone with in a similar situation will find this useful :)
You can use `IViewLocationExpander` interface to render view as you want. Please refer this link [Working with IViewLocationExpander in mvc](https://stackoverflow.com/questions/39471627/working-with-iviewlocationexpander-in-mvc) for more details Regards, Rohit
39,870,368
Following is my js ``` $(document).ready(function() { $.ajax({ url: url + 'project/get_project_list', method:'post', dataType:'xml', success:function(data){ $('#datatable').dataTable({ data:data, columns:[ { "data" : "projectName" }, { data : "projectDescription" }, ] }); } }); }); $('#datatable').DataTable(); </script> <div class="panel-wrapper"> <form id="form1"> <table id="datatable"> <thead> <tr> <th>Project Name</th> <th>Project Description</th> </tr> </thead> </table> </form> </div> ``` My response is as follows ``` <projectList> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <listException>false</listException> <listExceptionId>0</listExceptionId> <listSize>0</listSize> <nextPage>false</nextPage> <pageNumber>0</pageNumber> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription></projectDescription> <projectId>5</projectId> <projectName>Bmw</projectName> </projectBOs> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription>Toyota</projectDescription> <projectId>4</projectId> <projectName>Toyota global</projectName> </projectBOs> <projectBOs> ``` Kindly help how could i bind projectname and projectdescription to the table .currently it says no data available in table. i have no idea in using datatables
2016/10/05
[ "https://Stackoverflow.com/questions/39870368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4332335/" ]
You can still do something very similar to your original approach, using `ViewData` to pass around the layout name (Although I would create it as a [Result Filter](https://docs.asp.net/en/latest/mvc/controllers/filters.html?highlight=action%20filters#result-filters)): ``` public class ViewLayoutAttribute : ResultFilterAttribute { private string layout; public ViewLayoutAttribute(string layout) { this.layout = layout; } public override void OnResultExecuting(ResultExecutingContext context) { var viewResult = context.Result as ViewResult; if (viewResult != null) { viewResult.ViewData["Layout"] = this.layout; } } } ``` Then in the `_ViewStart.cshtml` file: ``` @{ Layout = (string)ViewData["Layout"] ?? "_Layout"; } ``` Finally, assuming you create a new layout like `Views/Shared/_CleanLayout.cshtml`, you can use that attribute on any controller or action: ``` [ViewLayout("_CleanLayout")] public IActionResult About() { //... } ```
This is how I am using multiple layouts in my ASP.NET core MVC application. You can try like this- In `_ViewStart.cshtml` specify default \_Layout like this- ``` @{ Layout = "_Layout"; } ``` If you want to set page specific layout then in that `page.cshtml`, you can assign other view like this- ``` @{ Layout = "~/Views/Shared/_Layout_2.cshtml"; ViewData["Title"] = "Page Title"; } ``` See if this helps.
39,870,368
Following is my js ``` $(document).ready(function() { $.ajax({ url: url + 'project/get_project_list', method:'post', dataType:'xml', success:function(data){ $('#datatable').dataTable({ data:data, columns:[ { "data" : "projectName" }, { data : "projectDescription" }, ] }); } }); }); $('#datatable').DataTable(); </script> <div class="panel-wrapper"> <form id="form1"> <table id="datatable"> <thead> <tr> <th>Project Name</th> <th>Project Description</th> </tr> </thead> </table> </form> </div> ``` My response is as follows ``` <projectList> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <listException>false</listException> <listExceptionId>0</listExceptionId> <listSize>0</listSize> <nextPage>false</nextPage> <pageNumber>0</pageNumber> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription></projectDescription> <projectId>5</projectId> <projectName>Bmw</projectName> </projectBOs> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription>Toyota</projectDescription> <projectId>4</projectId> <projectName>Toyota global</projectName> </projectBOs> <projectBOs> ``` Kindly help how could i bind projectname and projectdescription to the table .currently it says no data available in table. i have no idea in using datatables
2016/10/05
[ "https://Stackoverflow.com/questions/39870368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4332335/" ]
You can still do something very similar to your original approach, using `ViewData` to pass around the layout name (Although I would create it as a [Result Filter](https://docs.asp.net/en/latest/mvc/controllers/filters.html?highlight=action%20filters#result-filters)): ``` public class ViewLayoutAttribute : ResultFilterAttribute { private string layout; public ViewLayoutAttribute(string layout) { this.layout = layout; } public override void OnResultExecuting(ResultExecutingContext context) { var viewResult = context.Result as ViewResult; if (viewResult != null) { viewResult.ViewData["Layout"] = this.layout; } } } ``` Then in the `_ViewStart.cshtml` file: ``` @{ Layout = (string)ViewData["Layout"] ?? "_Layout"; } ``` Finally, assuming you create a new layout like `Views/Shared/_CleanLayout.cshtml`, you can use that attribute on any controller or action: ``` [ViewLayout("_CleanLayout")] public IActionResult About() { //... } ```
In ASP.NET Core 2.0, I was inspired by the answer of @Daniel J.G. I made a `ViewLayoutAttribute`: ```cs [AttributeUsage(AttributeTargets.Class)] public class ViewLayoutAttribute : Attribute { public ViewLayoutAttribute(string layoutName) { this.LayoutName = layoutName; } public string LayoutName { get; } } ``` Exemple of a controller class: ```cs [ViewLayout("_Layout2")] public class MyController : Controller { // Code } ``` And I created an extension to get this very attribute from the `ViewContext`: ```cs public static class RazorExtensions { /// <summary> /// Gets the <see cref="ViewLayoutAttribute"/> from the current calling controller of the /// <see cref="ViewContext"/>. /// </summary> public static ViewLayoutAttribute GetLayoutAttribute(this ViewContext viewContext) { // See if Razor Page... if (viewContext.ActionDescriptor is CompiledPageActionDescriptor actionDescriptor) { // We want the attribute no matter what. return Attribute.GetCustomAttribute(actionDescriptor.ModelTypeInfo, typeof(ViewLayoutAttribute)) as ViewLayoutAttribute; } // See if MVC Controller... // Property ControllerTypeInfo can be seen on runtime. var controllerType = (Type)viewContext.ActionDescriptor .GetType() .GetProperty("ControllerTypeInfo")? .GetValue(viewContext.ActionDescriptor); if (controllerType != null && controllerType.IsSubclassOf(typeof(Microsoft.AspNetCore.Mvc.Controller))) { return Attribute.GetCustomAttribute(controllerType, typeof(ViewLayoutAttribute)) as ViewLayoutAttribute; } // Nothing found. return null; } } ``` And in `_ViewStart.cshtml`: ``` @using MyApp.Extensions @{ Layout = ViewContext.GetLayoutAttribute()?.LayoutName ?? "_Layout"; } ```
39,870,368
Following is my js ``` $(document).ready(function() { $.ajax({ url: url + 'project/get_project_list', method:'post', dataType:'xml', success:function(data){ $('#datatable').dataTable({ data:data, columns:[ { "data" : "projectName" }, { data : "projectDescription" }, ] }); } }); }); $('#datatable').DataTable(); </script> <div class="panel-wrapper"> <form id="form1"> <table id="datatable"> <thead> <tr> <th>Project Name</th> <th>Project Description</th> </tr> </thead> </table> </form> </div> ``` My response is as follows ``` <projectList> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <listException>false</listException> <listExceptionId>0</listExceptionId> <listSize>0</listSize> <nextPage>false</nextPage> <pageNumber>0</pageNumber> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription></projectDescription> <projectId>5</projectId> <projectName>Bmw</projectName> </projectBOs> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription>Toyota</projectDescription> <projectId>4</projectId> <projectName>Toyota global</projectName> </projectBOs> <projectBOs> ``` Kindly help how could i bind projectname and projectdescription to the table .currently it says no data available in table. i have no idea in using datatables
2016/10/05
[ "https://Stackoverflow.com/questions/39870368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4332335/" ]
If you want to have a different layout based on some condition, you could use this code in the `_ViewStart.cshtml` file: ``` @{ if (some condition) { Layout = "_Layout1"; } else if (some other condition) { Layout = "_Layout2"; } etc. } ``` I use this in one of my projects. In my case the condition is `User.IsInRole("admin")` and my `_ViewStart.cshtml` file is as follows: ``` @{ if (User.IsInRole("admin")) { Layout = "_AdminLayout"; } else { Layout = "_Layout"; } } ``` Since there are only two roles in my project, which result in only one condition, this workaround is not too bad in my case. I hope someone with in a similar situation will find this useful :)
In ASP.NET Core 2.0, I was inspired by the answer of @Daniel J.G. I made a `ViewLayoutAttribute`: ```cs [AttributeUsage(AttributeTargets.Class)] public class ViewLayoutAttribute : Attribute { public ViewLayoutAttribute(string layoutName) { this.LayoutName = layoutName; } public string LayoutName { get; } } ``` Exemple of a controller class: ```cs [ViewLayout("_Layout2")] public class MyController : Controller { // Code } ``` And I created an extension to get this very attribute from the `ViewContext`: ```cs public static class RazorExtensions { /// <summary> /// Gets the <see cref="ViewLayoutAttribute"/> from the current calling controller of the /// <see cref="ViewContext"/>. /// </summary> public static ViewLayoutAttribute GetLayoutAttribute(this ViewContext viewContext) { // See if Razor Page... if (viewContext.ActionDescriptor is CompiledPageActionDescriptor actionDescriptor) { // We want the attribute no matter what. return Attribute.GetCustomAttribute(actionDescriptor.ModelTypeInfo, typeof(ViewLayoutAttribute)) as ViewLayoutAttribute; } // See if MVC Controller... // Property ControllerTypeInfo can be seen on runtime. var controllerType = (Type)viewContext.ActionDescriptor .GetType() .GetProperty("ControllerTypeInfo")? .GetValue(viewContext.ActionDescriptor); if (controllerType != null && controllerType.IsSubclassOf(typeof(Microsoft.AspNetCore.Mvc.Controller))) { return Attribute.GetCustomAttribute(controllerType, typeof(ViewLayoutAttribute)) as ViewLayoutAttribute; } // Nothing found. return null; } } ``` And in `_ViewStart.cshtml`: ``` @using MyApp.Extensions @{ Layout = ViewContext.GetLayoutAttribute()?.LayoutName ?? "_Layout"; } ```
39,870,368
Following is my js ``` $(document).ready(function() { $.ajax({ url: url + 'project/get_project_list', method:'post', dataType:'xml', success:function(data){ $('#datatable').dataTable({ data:data, columns:[ { "data" : "projectName" }, { data : "projectDescription" }, ] }); } }); }); $('#datatable').DataTable(); </script> <div class="panel-wrapper"> <form id="form1"> <table id="datatable"> <thead> <tr> <th>Project Name</th> <th>Project Description</th> </tr> </thead> </table> </form> </div> ``` My response is as follows ``` <projectList> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <listException>false</listException> <listExceptionId>0</listExceptionId> <listSize>0</listSize> <nextPage>false</nextPage> <pageNumber>0</pageNumber> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription></projectDescription> <projectId>5</projectId> <projectName>Bmw</projectName> </projectBOs> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription>Toyota</projectDescription> <projectId>4</projectId> <projectName>Toyota global</projectName> </projectBOs> <projectBOs> ``` Kindly help how could i bind projectname and projectdescription to the table .currently it says no data available in table. i have no idea in using datatables
2016/10/05
[ "https://Stackoverflow.com/questions/39870368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4332335/" ]
You can still do something very similar to your original approach, using `ViewData` to pass around the layout name (Although I would create it as a [Result Filter](https://docs.asp.net/en/latest/mvc/controllers/filters.html?highlight=action%20filters#result-filters)): ``` public class ViewLayoutAttribute : ResultFilterAttribute { private string layout; public ViewLayoutAttribute(string layout) { this.layout = layout; } public override void OnResultExecuting(ResultExecutingContext context) { var viewResult = context.Result as ViewResult; if (viewResult != null) { viewResult.ViewData["Layout"] = this.layout; } } } ``` Then in the `_ViewStart.cshtml` file: ``` @{ Layout = (string)ViewData["Layout"] ?? "_Layout"; } ``` Finally, assuming you create a new layout like `Views/Shared/_CleanLayout.cshtml`, you can use that attribute on any controller or action: ``` [ViewLayout("_CleanLayout")] public IActionResult About() { //... } ```
To have a Multiple Layout in asp.net core is quite easy, follow the steps below: Step 1: Create the layout inside the "Shared Folder located Under Views" and give it a name with prefix "\_" i.e `_myLoginLayout.cshtml` Step 2: Specify your layout at the beginning of the page you want to apply it e.g @{ `Layout = "~/Views/Shared/_myLoginLayout.cshtml"; ViewData["Title"] = "TestMe";`//you can add the title as well... } So when `_ViewStart.cshtml` is loading Layout for your page..it will read the Layout you specify.
39,870,368
Following is my js ``` $(document).ready(function() { $.ajax({ url: url + 'project/get_project_list', method:'post', dataType:'xml', success:function(data){ $('#datatable').dataTable({ data:data, columns:[ { "data" : "projectName" }, { data : "projectDescription" }, ] }); } }); }); $('#datatable').DataTable(); </script> <div class="panel-wrapper"> <form id="form1"> <table id="datatable"> <thead> <tr> <th>Project Name</th> <th>Project Description</th> </tr> </thead> </table> </form> </div> ``` My response is as follows ``` <projectList> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <listException>false</listException> <listExceptionId>0</listExceptionId> <listSize>0</listSize> <nextPage>false</nextPage> <pageNumber>0</pageNumber> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription></projectDescription> <projectId>5</projectId> <projectName>Bmw</projectName> </projectBOs> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription>Toyota</projectDescription> <projectId>4</projectId> <projectName>Toyota global</projectName> </projectBOs> <projectBOs> ``` Kindly help how could i bind projectname and projectdescription to the table .currently it says no data available in table. i have no idea in using datatables
2016/10/05
[ "https://Stackoverflow.com/questions/39870368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4332335/" ]
If you want to have a different layout based on some condition, you could use this code in the `_ViewStart.cshtml` file: ``` @{ if (some condition) { Layout = "_Layout1"; } else if (some other condition) { Layout = "_Layout2"; } etc. } ``` I use this in one of my projects. In my case the condition is `User.IsInRole("admin")` and my `_ViewStart.cshtml` file is as follows: ``` @{ if (User.IsInRole("admin")) { Layout = "_AdminLayout"; } else { Layout = "_Layout"; } } ``` Since there are only two roles in my project, which result in only one condition, this workaround is not too bad in my case. I hope someone with in a similar situation will find this useful :)
To have a Multiple Layout in asp.net core is quite easy, follow the steps below: Step 1: Create the layout inside the "Shared Folder located Under Views" and give it a name with prefix "\_" i.e `_myLoginLayout.cshtml` Step 2: Specify your layout at the beginning of the page you want to apply it e.g @{ `Layout = "~/Views/Shared/_myLoginLayout.cshtml"; ViewData["Title"] = "TestMe";`//you can add the title as well... } So when `_ViewStart.cshtml` is loading Layout for your page..it will read the Layout you specify.
39,870,368
Following is my js ``` $(document).ready(function() { $.ajax({ url: url + 'project/get_project_list', method:'post', dataType:'xml', success:function(data){ $('#datatable').dataTable({ data:data, columns:[ { "data" : "projectName" }, { data : "projectDescription" }, ] }); } }); }); $('#datatable').DataTable(); </script> <div class="panel-wrapper"> <form id="form1"> <table id="datatable"> <thead> <tr> <th>Project Name</th> <th>Project Description</th> </tr> </thead> </table> </form> </div> ``` My response is as follows ``` <projectList> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <listException>false</listException> <listExceptionId>0</listExceptionId> <listSize>0</listSize> <nextPage>false</nextPage> <pageNumber>0</pageNumber> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription></projectDescription> <projectId>5</projectId> <projectName>Bmw</projectName> </projectBOs> <projectBOs> <exceptionId>0</exceptionId> <id>0</id> <isException>false</isException> <offExptionid>0</offExptionid> <projectDescription>Toyota</projectDescription> <projectId>4</projectId> <projectName>Toyota global</projectName> </projectBOs> <projectBOs> ``` Kindly help how could i bind projectname and projectdescription to the table .currently it says no data available in table. i have no idea in using datatables
2016/10/05
[ "https://Stackoverflow.com/questions/39870368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4332335/" ]
In ASP.NET Core 2.0, I was inspired by the answer of @Daniel J.G. I made a `ViewLayoutAttribute`: ```cs [AttributeUsage(AttributeTargets.Class)] public class ViewLayoutAttribute : Attribute { public ViewLayoutAttribute(string layoutName) { this.LayoutName = layoutName; } public string LayoutName { get; } } ``` Exemple of a controller class: ```cs [ViewLayout("_Layout2")] public class MyController : Controller { // Code } ``` And I created an extension to get this very attribute from the `ViewContext`: ```cs public static class RazorExtensions { /// <summary> /// Gets the <see cref="ViewLayoutAttribute"/> from the current calling controller of the /// <see cref="ViewContext"/>. /// </summary> public static ViewLayoutAttribute GetLayoutAttribute(this ViewContext viewContext) { // See if Razor Page... if (viewContext.ActionDescriptor is CompiledPageActionDescriptor actionDescriptor) { // We want the attribute no matter what. return Attribute.GetCustomAttribute(actionDescriptor.ModelTypeInfo, typeof(ViewLayoutAttribute)) as ViewLayoutAttribute; } // See if MVC Controller... // Property ControllerTypeInfo can be seen on runtime. var controllerType = (Type)viewContext.ActionDescriptor .GetType() .GetProperty("ControllerTypeInfo")? .GetValue(viewContext.ActionDescriptor); if (controllerType != null && controllerType.IsSubclassOf(typeof(Microsoft.AspNetCore.Mvc.Controller))) { return Attribute.GetCustomAttribute(controllerType, typeof(ViewLayoutAttribute)) as ViewLayoutAttribute; } // Nothing found. return null; } } ``` And in `_ViewStart.cshtml`: ``` @using MyApp.Extensions @{ Layout = ViewContext.GetLayoutAttribute()?.LayoutName ?? "_Layout"; } ```
To have a Multiple Layout in asp.net core is quite easy, follow the steps below: Step 1: Create the layout inside the "Shared Folder located Under Views" and give it a name with prefix "\_" i.e `_myLoginLayout.cshtml` Step 2: Specify your layout at the beginning of the page you want to apply it e.g @{ `Layout = "~/Views/Shared/_myLoginLayout.cshtml"; ViewData["Title"] = "TestMe";`//you can add the title as well... } So when `_ViewStart.cshtml` is loading Layout for your page..it will read the Layout you specify.
9,073,440
I am creating a information system that will handle financial information, contacts, etc. I am developing the site from complete scratch using object oriented programming (classes, functions, etc). A majority of the data will be from a MySQL database. Users will be able to get and submit data to the database. I am already using the hash function to encrypt data such as passwords, serial keys. I am also using preg\_replace() function for all other data going to the database. What other security measures do I need to take to insure that submitting and getting data from the database does not compromise security?
2012/01/31
[ "https://Stackoverflow.com/questions/9073440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1029393/" ]
First: good for you for giving attention to security issues. It's a big subject and one that many people overlook until it's too late. So, kudos to you for seeking more understanding about best practices. :-) [OWASP](http://owasp.org) is a good resource for understanding web security issues. Another good resource is the SANS report [The Top Cyber Security Risks](http://www.sans.org/top-cyber-security-risks/). Specifically, [Cross-Site Scripting (XSS)](https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet) and [SQL Injection](https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet) are the top two security risks for most websites. You should read about how to design your code to minimize these risks. I have also designed a presentation [SQL Injection Myths and Fallacies](http://www.slideshare.net/billkarwin/sql-injection-myths-and-fallacies) that goes deeper into the nature of this issue and methods of defense. Read the blog [You're Probably Storing Passwords Incorrectly](http://www.codinghorror.com/blog/2007/09/youre-probably-storing-passwords-incorrectly.html) by StackOverflow founder Jeff Atwood. I also cover SQL injection and password hashing in my book [SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming](https://pragprog.com/titles/bksap1/sql-antipatterns-volume-1/).
You are doing it wrong, because: * md5 is considered broken, * preg\_replace() will not give you much. Consider using already developed, tested and secure frameworks (candidates include Zend Framework, Symphony, Kohana, Yii) for your system. You have a long way before you will achieve security at least nearly as good as standard framework's. Also consider using prepared statements instead of preg\_replace() and salted sha1 instead of simple md5, if you still want to reinvent the wheel. Furthermore: * secure your app against such acronyms as XSS, CSRF, * require SSL at all times (for every request, even for images / styles / scripts), * read security newsletters (you will need them if you want to build secure system for financial activities).
9,073,440
I am creating a information system that will handle financial information, contacts, etc. I am developing the site from complete scratch using object oriented programming (classes, functions, etc). A majority of the data will be from a MySQL database. Users will be able to get and submit data to the database. I am already using the hash function to encrypt data such as passwords, serial keys. I am also using preg\_replace() function for all other data going to the database. What other security measures do I need to take to insure that submitting and getting data from the database does not compromise security?
2012/01/31
[ "https://Stackoverflow.com/questions/9073440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1029393/" ]
`preg_replace()` will not do much in terms of security. You should familiarize yourself with some basic security/crypto before doing this work. Also, consider the use of a standard cryptographic library for encrypting/decrypting data instead of arbitrarily using hash or regex functions. Take a look at this: <http://php.net/manual/en/book.openssl.php>
You are doing it wrong, because: * md5 is considered broken, * preg\_replace() will not give you much. Consider using already developed, tested and secure frameworks (candidates include Zend Framework, Symphony, Kohana, Yii) for your system. You have a long way before you will achieve security at least nearly as good as standard framework's. Also consider using prepared statements instead of preg\_replace() and salted sha1 instead of simple md5, if you still want to reinvent the wheel. Furthermore: * secure your app against such acronyms as XSS, CSRF, * require SSL at all times (for every request, even for images / styles / scripts), * read security newsletters (you will need them if you want to build secure system for financial activities).