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
36,948,316
I am just wondering if there is a way to simulate a "no connection" event in a mocha unit test. I have a method that return a promise that should wait for an internet connection with a polling strategy and I want to test it out with mocha. There is a method to achieve such a result. Some code: ``` it('should wait for connection', function(done) { this.timeout(2500); //simulate an internet connection drop here wait.connection().then(done); setTimeout(//activate connection, 2000); }); ``` Thank you for any response. [EDIT]: Here there is the code I want to test: ``` var wait = { connection: function() { 'use strict'; var settings = {retry: 1000}; return new Promise(function(resolve) { (function poll() { needle.get('https://api.ipify.org', function(error, response) { if(!error && response.statusCode === 200 && /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$|^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$|^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/.test(response.body)) resolve(); else wait.for(settings.retry).then(poll); }); })(); }); } }; ``` In this case the Promise will remain pending since a new connection is available. How can I simulate an error on the `needle` get request?
2016/04/29
[ "https://Stackoverflow.com/questions/36948316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803678/" ]
You can use `nock.disableNetConnect()`: <https://github.com/nock/nock#enabledisable-real-http-requests>
If you have no connection or any problems of connection, use the `reject()` of your promise and catch them. `done` is a function, and if you call the function with a non-null parameter, it means that your test is not good. Maybe you have to try: ``` my_object.wait.connection() .then(() => done(1)) .catch(() => done()); ```
36,948,316
I am just wondering if there is a way to simulate a "no connection" event in a mocha unit test. I have a method that return a promise that should wait for an internet connection with a polling strategy and I want to test it out with mocha. There is a method to achieve such a result. Some code: ``` it('should wait for connection', function(done) { this.timeout(2500); //simulate an internet connection drop here wait.connection().then(done); setTimeout(//activate connection, 2000); }); ``` Thank you for any response. [EDIT]: Here there is the code I want to test: ``` var wait = { connection: function() { 'use strict'; var settings = {retry: 1000}; return new Promise(function(resolve) { (function poll() { needle.get('https://api.ipify.org', function(error, response) { if(!error && response.statusCode === 200 && /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$|^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$|^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/.test(response.body)) resolve(); else wait.for(settings.retry).then(poll); }); })(); }); } }; ``` In this case the Promise will remain pending since a new connection is available. How can I simulate an error on the `needle` get request?
2016/04/29
[ "https://Stackoverflow.com/questions/36948316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803678/" ]
You can use [sinon](http://sinonjs.org/) to stub `needle.get` ``` var needle = require("needle"); var sinon = require("sinon");; before(() => { sinon.stub(needle, "get", (url, calback) => { var dummyError = {}; callback(dummyError); }) }); // Run your 'it' here after(() => { needle.get.restore(); }); ```
You can use `nock.disableNetConnect()`: <https://github.com/nock/nock#enabledisable-real-http-requests>
69,431,410
I've followed [Dynamic nested topnav menu](https://stackblitz.com/edit/dynamic-nested-topnav-menu?file=app%2Fapp.component.ts) to create a navigation bar. It was working perfectly until that I've tried to add an icon to the parents menu by change the code iconName: 'close' to iconName: 'arrow\_circle\_down' for DevFestFL. The icon just cannot be displayed, but it works fine on its children. ``` { displayName: 'DevFestFL', iconName: 'arrow_circle_down', children: [ { displayName: 'Speakers', iconName: 'arrow_circle_down', children: [ { displayName: 'Michael Prentice', iconName: 'person', route: 'michael-prentice', children: [ { displayName: 'Create Enterprise UIs', iconName: 'star_rate', route: 'material-design', }, ], }, ``` --- Thank you Agustin L. Lacuara I have installed the package, and I have tried Angular Material Icons. ``` displayName: 'Reports', iconName: 'arrow_downward', children: [ { displayName: 'Content History Report', iconName: 'arrow_downward', route: 'reports/content-history' }, { displayName: 'Drive History Report', iconName: 'article', route: 'reports/drive-history' } ] ``` However, it only worked for child menu. [Icon is not working for parents menu](https://i.stack.imgur.com/4eMej.png)
2021/10/04
[ "https://Stackoverflow.com/questions/69431410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17068265/" ]
Let's split and join then ```js const div = document.getElementById("text"); let str = div.textContent; let arr = str.split(/ /) console.log(arr) const urls = ["www.stack.com/abc", "www.stack.com"]; arr.forEach((word,i) => { const punctuation = word.match(/(\W$)/) if (punctuation) word = word.slice(0,-1) const idx = urls.indexOf(word); if (idx !=-1) arr[i] = arr[i].replace(word,`<a href="${word}">${word}</a>`) }) console.log(arr) div.innerHTML = arr.join(" ") ``` ```html <div id="text">Check it out at www.stack.com/abc and bookmark the www.stack.com, www.overflow.com.</div> ```
Although the solution provided by mplungjan is clever and works well, I wanted to post an alternative. The algorithm from the accepted answer processes the input string into an array of words and then proceeds to iterate through every word on every URL. Then it needs to see if any word ends with a symbol, and truncate if such. This would be a bit consuming as one can imagine 50 words X 5 possible URLs = 250 combinations and O(n^2) computation. Then to imagine there could be 20 possible URLs and 20 input texts each containing 15+ words. And finally, to mention that algorithm may have issues with case sensitivity. This solution uses a lot of thought from mplungjan's approach, but instead, it's only going to quickly narrow down what it actually needs to process via RegEx, and then loops again to apply what actually matched. Plus, the RegEx corrects the possible case sensitivity issue. ``` let str = 'Check it out at www.stack.com/abc and bookmark the www.stack.com, www.overflow.com.'; let urls = ["www.stack.com", "www.stack.com/abc", "www.not-here.com"]; let arReplace = []; // sort by longest URLs (prevents processing identical root domains on sub-domains) urls = urls.sort((a, b) =>{ if(b.length > a.length) return 1 return -1 }); // find URLs and apply replacement tokens urls.forEach((url) => { if(str.match(new RegExp('\\b' + url + '\\b', 'i'))){ arReplace.push(url); str = str.replace(new RegExp('\\b' + url + '\\b', 'gi'), '%ZZ' + (arReplace.length - 1) + 'ZZ%') } }); // replace tokens arReplace.forEach((url, n) =>{ str = str.replace(new RegExp('%ZZ' + n + 'ZZ%', 'g'), '<a href="' + url + '">' + url + '</a>') }); document.body.innerHTML = str ``` Fiddle link: <https://jsfiddle.net/e05o9cra/>
3,666,833
how to read information inside an excel sheet using C# code......
2010/09/08
[ "https://Stackoverflow.com/questions/3666833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/442238/" ]
You can either use Oledb ``` using System.Data; using System.Data.OleDb; OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Book1.xls;Extended Properties=Excel 8.0"); OleDbDataAdapter da = new OleDbDataAdapter("select * from MyObject", con); DataTable dt = new DataTable(); da.Fill(dt); ``` or you use Office Interop ``` this.openFileDialog1.FileName = "*.xls"; if (this.openFileDialog1.ShowDialog() == DialogResult.OK) { Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open( openFileDialog1.FileName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true); Excel.Sheets sheets = theWorkbook.Worksheets; Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1); for (int i = 1; i <= 10; i++) { Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString()); System.Array myvalues = (System.Array)range.Cells.Value; string[] strArray = ConvertToStringArray(myvalues); } } ```
[**Programming with the C API in Excel 2010**](http://msdn.microsoft.com/en-us/library/bb687829.aspx)
3,666,833
how to read information inside an excel sheet using C# code......
2010/09/08
[ "https://Stackoverflow.com/questions/3666833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/442238/" ]
You can either use Oledb ``` using System.Data; using System.Data.OleDb; OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Book1.xls;Extended Properties=Excel 8.0"); OleDbDataAdapter da = new OleDbDataAdapter("select * from MyObject", con); DataTable dt = new DataTable(); da.Fill(dt); ``` or you use Office Interop ``` this.openFileDialog1.FileName = "*.xls"; if (this.openFileDialog1.ShowDialog() == DialogResult.OK) { Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open( openFileDialog1.FileName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true); Excel.Sheets sheets = theWorkbook.Worksheets; Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1); for (int i = 1; i <= 10; i++) { Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString()); System.Array myvalues = (System.Array)range.Cells.Value; string[] strArray = ConvertToStringArray(myvalues); } } ```
If the data is tabular, use OleDB, otherwise you can use Automation to automate Excel and copy the values over to your app. Or if it's the new XML format excel sheets you might be able to do it via the framework classes. Info about Excel Automation: [How to: Use COM Interop to Create an Excel Spreadsheet](http://msdn.microsoft.com/en-us/library/ms173186%28VS.80%29.aspx) Info about Excel via OleDB: [How To Use ADO.NET to Retrieve and Modify Records in an Excel Workbook With Visual Basic .NET](http://support.microsoft.com/kb/316934)
3,666,833
how to read information inside an excel sheet using C# code......
2010/09/08
[ "https://Stackoverflow.com/questions/3666833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/442238/" ]
You can either use Oledb ``` using System.Data; using System.Data.OleDb; OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Book1.xls;Extended Properties=Excel 8.0"); OleDbDataAdapter da = new OleDbDataAdapter("select * from MyObject", con); DataTable dt = new DataTable(); da.Fill(dt); ``` or you use Office Interop ``` this.openFileDialog1.FileName = "*.xls"; if (this.openFileDialog1.ShowDialog() == DialogResult.OK) { Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open( openFileDialog1.FileName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true); Excel.Sheets sheets = theWorkbook.Worksheets; Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1); for (int i = 1; i <= 10; i++) { Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString()); System.Array myvalues = (System.Array)range.Cells.Value; string[] strArray = ConvertToStringArray(myvalues); } } ```
Excel has an API for programming. You can use it to get range of data using c#. You can use something like: ``` Excel.Application oXL; Excel._Workbook oWB; Excel._Worksheet oSheet; oSheet.get_Range(RangeStart,RangeEnd) ```
3,666,833
how to read information inside an excel sheet using C# code......
2010/09/08
[ "https://Stackoverflow.com/questions/3666833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/442238/" ]
You can either use Oledb ``` using System.Data; using System.Data.OleDb; OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Book1.xls;Extended Properties=Excel 8.0"); OleDbDataAdapter da = new OleDbDataAdapter("select * from MyObject", con); DataTable dt = new DataTable(); da.Fill(dt); ``` or you use Office Interop ``` this.openFileDialog1.FileName = "*.xls"; if (this.openFileDialog1.ShowDialog() == DialogResult.OK) { Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open( openFileDialog1.FileName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true); Excel.Sheets sheets = theWorkbook.Worksheets; Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1); for (int i = 1; i <= 10; i++) { Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString()); System.Array myvalues = (System.Array)range.Cells.Value; string[] strArray = ConvertToStringArray(myvalues); } } ```
[NPOI](http://npoi.codeplex.com/) is the way to go. Using office interop requires that Office (and the right version) be installed on the machine your app is running on. If a web abb, that probably means no, and it's not robust enough for a production environment anyway. OLEDB has serious limitations, unless it's a one-off and the data is really simple I wouldn't use it.
3,666,833
how to read information inside an excel sheet using C# code......
2010/09/08
[ "https://Stackoverflow.com/questions/3666833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/442238/" ]
You can either use Oledb ``` using System.Data; using System.Data.OleDb; OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Book1.xls;Extended Properties=Excel 8.0"); OleDbDataAdapter da = new OleDbDataAdapter("select * from MyObject", con); DataTable dt = new DataTable(); da.Fill(dt); ``` or you use Office Interop ``` this.openFileDialog1.FileName = "*.xls"; if (this.openFileDialog1.ShowDialog() == DialogResult.OK) { Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open( openFileDialog1.FileName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true); Excel.Sheets sheets = theWorkbook.Worksheets; Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1); for (int i = 1; i <= 10; i++) { Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString()); System.Array myvalues = (System.Array)range.Cells.Value; string[] strArray = ConvertToStringArray(myvalues); } } ```
1. Excel COM Interop - via Microsoft.Office.Interop.Excel + Microsoft.Office.Interop.Excel.Extensions 2. ADO.Net via OLEDB data provider for Excel. 3. Use of System.XML and/or Linq to XML and/or Open XML SDK (can also be used to create new books programmatically from scratch). 4. 3rd party library such as NPOI. 5. 3rd party vendor package such as spreadsheetgear
1,402,879
How can I reduce sensitivity of the touchpad? It is way too big so when I type, the part of the palm that extends down from the thumb brushes the touchpad and I get all sorts of gestures I don't want like: -highlight everything I am typing so far and delete If anybody reading this has a choice between an Ideapad or Thinkpad, go for the Thinkpad.
2022/04/17
[ "https://askubuntu.com/questions/1402879", "https://askubuntu.com", "https://askubuntu.com/users/806813/" ]
You can use `synclient` to access your touchpad settings, assuming that you have the Synaptic drivers installed. Check out this question: <https://unix.stackexchange.com/questions/28306/looking-for-a-way-to-improve-synaptic-touchpad-palm-detection>
Tip: (i.e. Sensitivity 0) Install and use <https://github.com/atareao/Touchpad-Indicator> ... to disable the touchpad when you're not using it: > > Install from PPA > > > sudo add-apt-repository ppa:atareao/atareao > > sudo apt update > > sudo apt install touchpad-indicator > > > Alternative: My Asus laptop has an option to turn it off in the Setup (BIOS), but that does not allow any use when set.
31,655,737
How will i change my json result from ``` ["Published with github","ZA Publications","Apress","Really","Neal"] ``` To ``` [ {"Name" : "Published with github"}, {"Name" : "ZA Publications"}, {"Name" : "Apress"}, {"Name" : "Really"}, {"Name" : "Neal"} ] ``` correct me if i am wrong somewhere, if you need much detail Thank you
2015/07/27
[ "https://Stackoverflow.com/questions/31655737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5160974/" ]
Store the font file somewhere on the server. ``` @font-face { font-family: NAME; src: url('/FILEPATH/FILENAME.ttf'); } p { font-family: NAME; } ``` Browser Support: <http://www.w3schools.com/cssref/css3_pr_font-face_rule.asp> EDIT: And, as Alex K. said, make sure you have a license if it's a commercial font.
Can't speak for FireFox but a more important fact is that the font must exist in an appropriate format on all machines viewing the page. If the font does not exist as an installed font it must be embedded in the page, something you need a license for if its a commercial font. I would suggest browsing for something similar and using the boilerplate from <https://www.google.com/fonts>.
19,648,728
I am trying to display the default image as the background of a iOS7 simulator, but its just white. It works on simulators that are older. ``` UIColor *image = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"Default.png"]]; self.view.backgroundColor = image; ```
2013/10/29
[ "https://Stackoverflow.com/questions/19648728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/280602/" ]
Figured it out! `$deals = array_merge($account->deals->all(), $user->deals->all());` Hope this helps someone out in the fugure
Collection object in laravel has method toArray() to represent collection of objects as multi-dimentional array (array of arrays). Try this: ``` $deals = $account->deals->toArray(); ```
3,544,903
I want to use log4j in my web application. I would like to configure log4j in such a way that when the file reaches a certain size, we start writing a new log files, making it easier to open and read. Can you please explain the set up of `RollingFileAppender`?
2010/08/23
[ "https://Stackoverflow.com/questions/3544903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423620/" ]
[Lots of examples](http://magnus-k-karlsson.blogspot.com/2009/08/configure-log4j-dailyrollingfileappende.html) on the internet, e.g. this creates a daily rolling log file that rolls over to `log4jtest.log.2010-08-25` etc ``` # configure the root logger log4j.rootLogger=INFO, DAILY # configure the daily rolling file appender log4j.appender.DAILY=org.apache.log4j.DailyRollingFileAppender log4j.appender.DAILY.File=/tmp/log4j/log4jtest.log log4j.appender.DAILY.DatePattern='.'yyyy-MM-dd log4j.appender.DAILY.layout=org.apache.log4j.PatternLayout log4j.appender.DAILY.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%p] %c:%L - %m%n ```
If you're using XML configuration, you can use the following: ``` <appender name="MyFileAppender" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="my.log" /> <param name="Threshold" value="INFO" /> <param name="DatePattern" value="'.'yyyy-MM-dd" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %-10t [%-40.40c] %x - %m%n"/> </layout> </appender> ``` This rolls the log file over each day. If you wish to roll the log file over when it reaches a certain size, use `RollingFileAppender`. From the docs: > > RollingFileAppender extends FileAppender to backup the log files when they reach a certain size. The default maximum file size is 10MB. > > >
32,094,670
The problem splits into two parts. How to check which working days are missing from my database, if some are missing then add them and fill the row with the values from the closest date. First part, check and find the days. Should i use a gap approach like in the example below? ``` SELECT t1.col1 AS startOfGap, MIN(t2.col1) AS endOfGap FROM (SELECT col1 = theDate + 1 FROM sampleDates tbl1 WHERE NOT EXISTS(SELECT * FROM sampleDates tbl2 WHERE tbl2.theDate = tbl1.theDate + 1) AND theDate <> (SELECT MAX(theDate) FROM sampleDates)) t1 INNER JOIN (SELECT col1 = theDate - 1 FROM sampleDates tbl1 WHERE NOT EXISTS(SELECT * FROM sampleDates tbl2 WHERE tbl1.theDate = tbl2.theDate + 1) AND theDate <> (SELECT MIN(theDate) FROM sampleDates)) t2 ON t1.col1 <= t2.col1 GROUP BY t1.col1; ``` Then i need to see which is the closest date to the one i was missing and fill the new inserted date (the one which was missing) with the values from the closest. Some time ago, I came up with something to get the closest value from a row, but this time i need to adapt it to check both down and upwards. ``` SELECT t,A, C,Y, COALESCE(Y, (SELECT TOP (1) Y FROM tableT AS p2 WHERE p2.Y IS NOT NULL AND p2.[t] <= p.[t] and p.C = p2.C ORDER BY p2.[t] DESC)) as 'YNew' FROM tableT AS p order by c, t ``` How to combine those into one? Thanks **EDIT:** Expected result ``` Date 1mA 20.12.2012 0.152 21.12.2012 0.181 22 weekend so it's skipped (they are skipped automatically) 23 weekend -,- 24 missing 25 missing 26 missing 27.12.2012 0.173 28.12.2012 0.342 Date 1mA 20.12.2012 0.152 21.12.2012 0.181 22 weekend so it's skipped (they are skipped automatically) 23 weekend 0.181 24 missing 0.181 25 missing 0.181 26 missing 0.173 27.12.2012 0.173 28.12.2012 0.342 ``` So, 24,25,26 are not even there with null values. They are simply not there. **EDIT 2:** For taking the closest value, let's consider the scenario in which i'm always looking above. So always going back 1 when it's missing. ``` Date 1mA 20.12.2012 0.152 21.12.2012 0.181 22 weekend so it's skipped (they are skipped automatically) 23 weekend 0.181 24 missing 0.181 25 missing 0.181 26 missing 0.181 27.12.2012 0.173 28.12.2012 0.342 ```
2015/08/19
[ "https://Stackoverflow.com/questions/32094670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5002646/" ]
For these types of query you gain significant performance benefits from creating a calendar table containing every date you'll ever need to test. *(If you're familiar with the term "dimension tables", this is just one such table to enumerate every date of interest.)* Also, the query as a whole can become significantly simpler. ``` SELECT cal.calendar_date AS data_date, CASE WHEN prev_data.gap <= next_data.gap THEN prev_data.data_value ELSE COALESCE(next_data.data_value, prev_data.data_value) END AS data_value FROM calendar AS cal OUTER APPLY ( SELECT TOP(1) data_date, data_value, DATEDIFF(DAY, data_date, cal.calendar_date) AS gap FROM data_table WHERE data_date <= cal.calendar_date ORDER BY data_date DESC ) prev_data OUTER APPLY ( SELECT TOP(1) data_date, data_value, DATEDIFF(DAY, cal.calendar_date, data_date) AS gap FROM data_table WHERE data_date > cal.calendar_date ORDER BY data_date ASC ) next_data WHERE cal.calendar_date BETWEEN '2015-01-01' AND '2015-12-31' ; ``` ***EDIT*** Reply to your comment with a different requirement To always get "the value above" is easier, and to insert those values in to a table is easy enough... ``` INSERT INTO data_table SELECT cal.calendar_date, prev_data.data_value FROM calendar AS cal CROSS APPLY ( SELECT TOP(1) data_date, data_value FROM data_table WHERE data_date <= cal.calendar_date ORDER BY data_date DESC ) prev_data WHERE cal.calendar_date BETWEEN '2015-01-01' AND '2015-12-31' AND cal.calendar_date <> prev_data.data_date ; ``` ***Note:*** You could add `WHERE prev_data.gap > 0` to the bigger query above to only get dates that don't already have data.
using recursive CTE we can generate date sequence: [SQL Fiddle](http://sqlfiddle.com/#!3/27913/4) **MS SQL Server 2008 Schema Setup**: ``` create table sample (date datetime, data money) insert sample (date, data) values ('2015-01-02', 0.2), ('2015-01-03', 0.3), ('2015-01-07', 0.4), ('2015-01-08', 0.5), ('2015-01-09', 0.6), ('2015-01-21', 0.7), ('2015-01-22', 0.8), ('2015-01-27', 0.9), ('2015-01-28', 0.11), ('2015-01-30', 0.12) ``` **Query 1**: ``` declare @d1 datetime = '2015-01-01', @d2 datetime = '2015-01-31' ;with dates as ( select @d1 as date union all select dateadd(day, 1, date) from dates where dateadd(day, 1, date) <= @d2 ), lo_hi as ( select *, (select top 1 date from sample s where s.date <= d.date order by s.date desc) as lower_date, (select top 1 date from sample s where s.date >= d.date order by s.date asc) as higher_date from dates d ), lo_hi_diff as ( select *, isnull(datediff(day, lower_date, date), 100000) as lo_diff, isnull(datediff(day, date, higher_date), 100000) as hi_diff from lo_hi ) select *, case when lo_diff <= hi_diff then (select top 1 data from sample where date = lower_date) else (select top 1 data from sample where date = higher_date) end as new_data from lo_hi_diff d left join sample s on d.date = s.date ``` **[Results](http://sqlfiddle.com/#!3/27913/4/0)**: ``` | date | lower_date | higher_date | lo_diff | hi_diff | date | data | new_data | |---------------------------|---------------------------|---------------------------|---------|---------|---------------------------|--------|----------| | January, 01 2015 00:00:00 | (null) | January, 02 2015 00:00:00 | 100000 | 1 | (null) | (null) | 0.2 | | January, 02 2015 00:00:00 | January, 02 2015 00:00:00 | January, 02 2015 00:00:00 | 0 | 0 | January, 02 2015 00:00:00 | 0.2 | 0.2 | | January, 03 2015 00:00:00 | January, 03 2015 00:00:00 | January, 03 2015 00:00:00 | 0 | 0 | January, 03 2015 00:00:00 | 0.3 | 0.3 | | January, 04 2015 00:00:00 | January, 03 2015 00:00:00 | January, 07 2015 00:00:00 | 1 | 3 | (null) | (null) | 0.3 | | January, 05 2015 00:00:00 | January, 03 2015 00:00:00 | January, 07 2015 00:00:00 | 2 | 2 | (null) | (null) | 0.3 | | January, 06 2015 00:00:00 | January, 03 2015 00:00:00 | January, 07 2015 00:00:00 | 3 | 1 | (null) | (null) | 0.4 | | January, 07 2015 00:00:00 | January, 07 2015 00:00:00 | January, 07 2015 00:00:00 | 0 | 0 | January, 07 2015 00:00:00 | 0.4 | 0.4 | | January, 08 2015 00:00:00 | January, 08 2015 00:00:00 | January, 08 2015 00:00:00 | 0 | 0 | January, 08 2015 00:00:00 | 0.5 | 0.5 | | January, 09 2015 00:00:00 | January, 09 2015 00:00:00 | January, 09 2015 00:00:00 | 0 | 0 | January, 09 2015 00:00:00 | 0.6 | 0.6 | | January, 10 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 1 | 11 | (null) | (null) | 0.6 | | January, 11 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 2 | 10 | (null) | (null) | 0.6 | | January, 12 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 3 | 9 | (null) | (null) | 0.6 | | January, 13 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 4 | 8 | (null) | (null) | 0.6 | | January, 14 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 5 | 7 | (null) | (null) | 0.6 | | January, 15 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 6 | 6 | (null) | (null) | 0.6 | | January, 16 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 7 | 5 | (null) | (null) | 0.7 | | January, 17 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 8 | 4 | (null) | (null) | 0.7 | | January, 18 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 9 | 3 | (null) | (null) | 0.7 | | January, 19 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 10 | 2 | (null) | (null) | 0.7 | | January, 20 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 11 | 1 | (null) | (null) | 0.7 | | January, 21 2015 00:00:00 | January, 21 2015 00:00:00 | January, 21 2015 00:00:00 | 0 | 0 | January, 21 2015 00:00:00 | 0.7 | 0.7 | | January, 22 2015 00:00:00 | January, 22 2015 00:00:00 | January, 22 2015 00:00:00 | 0 | 0 | January, 22 2015 00:00:00 | 0.8 | 0.8 | | January, 23 2015 00:00:00 | January, 22 2015 00:00:00 | January, 27 2015 00:00:00 | 1 | 4 | (null) | (null) | 0.8 | | January, 24 2015 00:00:00 | January, 22 2015 00:00:00 | January, 27 2015 00:00:00 | 2 | 3 | (null) | (null) | 0.8 | | January, 25 2015 00:00:00 | January, 22 2015 00:00:00 | January, 27 2015 00:00:00 | 3 | 2 | (null) | (null) | 0.9 | | January, 26 2015 00:00:00 | January, 22 2015 00:00:00 | January, 27 2015 00:00:00 | 4 | 1 | (null) | (null) | 0.9 | | January, 27 2015 00:00:00 | January, 27 2015 00:00:00 | January, 27 2015 00:00:00 | 0 | 0 | January, 27 2015 00:00:00 | 0.9 | 0.9 | | January, 28 2015 00:00:00 | January, 28 2015 00:00:00 | January, 28 2015 00:00:00 | 0 | 0 | January, 28 2015 00:00:00 | 0.11 | 0.11 | | January, 29 2015 00:00:00 | January, 28 2015 00:00:00 | January, 30 2015 00:00:00 | 1 | 1 | (null) | (null) | 0.11 | | January, 30 2015 00:00:00 | January, 30 2015 00:00:00 | January, 30 2015 00:00:00 | 0 | 0 | January, 30 2015 00:00:00 | 0.12 | 0.12 | | January, 31 2015 00:00:00 | January, 30 2015 00:00:00 | (null) | 1 | 100000 | (null) | (null) | 0.12 | ```
32,094,670
The problem splits into two parts. How to check which working days are missing from my database, if some are missing then add them and fill the row with the values from the closest date. First part, check and find the days. Should i use a gap approach like in the example below? ``` SELECT t1.col1 AS startOfGap, MIN(t2.col1) AS endOfGap FROM (SELECT col1 = theDate + 1 FROM sampleDates tbl1 WHERE NOT EXISTS(SELECT * FROM sampleDates tbl2 WHERE tbl2.theDate = tbl1.theDate + 1) AND theDate <> (SELECT MAX(theDate) FROM sampleDates)) t1 INNER JOIN (SELECT col1 = theDate - 1 FROM sampleDates tbl1 WHERE NOT EXISTS(SELECT * FROM sampleDates tbl2 WHERE tbl1.theDate = tbl2.theDate + 1) AND theDate <> (SELECT MIN(theDate) FROM sampleDates)) t2 ON t1.col1 <= t2.col1 GROUP BY t1.col1; ``` Then i need to see which is the closest date to the one i was missing and fill the new inserted date (the one which was missing) with the values from the closest. Some time ago, I came up with something to get the closest value from a row, but this time i need to adapt it to check both down and upwards. ``` SELECT t,A, C,Y, COALESCE(Y, (SELECT TOP (1) Y FROM tableT AS p2 WHERE p2.Y IS NOT NULL AND p2.[t] <= p.[t] and p.C = p2.C ORDER BY p2.[t] DESC)) as 'YNew' FROM tableT AS p order by c, t ``` How to combine those into one? Thanks **EDIT:** Expected result ``` Date 1mA 20.12.2012 0.152 21.12.2012 0.181 22 weekend so it's skipped (they are skipped automatically) 23 weekend -,- 24 missing 25 missing 26 missing 27.12.2012 0.173 28.12.2012 0.342 Date 1mA 20.12.2012 0.152 21.12.2012 0.181 22 weekend so it's skipped (they are skipped automatically) 23 weekend 0.181 24 missing 0.181 25 missing 0.181 26 missing 0.173 27.12.2012 0.173 28.12.2012 0.342 ``` So, 24,25,26 are not even there with null values. They are simply not there. **EDIT 2:** For taking the closest value, let's consider the scenario in which i'm always looking above. So always going back 1 when it's missing. ``` Date 1mA 20.12.2012 0.152 21.12.2012 0.181 22 weekend so it's skipped (they are skipped automatically) 23 weekend 0.181 24 missing 0.181 25 missing 0.181 26 missing 0.181 27.12.2012 0.173 28.12.2012 0.342 ```
2015/08/19
[ "https://Stackoverflow.com/questions/32094670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5002646/" ]
For these types of query you gain significant performance benefits from creating a calendar table containing every date you'll ever need to test. *(If you're familiar with the term "dimension tables", this is just one such table to enumerate every date of interest.)* Also, the query as a whole can become significantly simpler. ``` SELECT cal.calendar_date AS data_date, CASE WHEN prev_data.gap <= next_data.gap THEN prev_data.data_value ELSE COALESCE(next_data.data_value, prev_data.data_value) END AS data_value FROM calendar AS cal OUTER APPLY ( SELECT TOP(1) data_date, data_value, DATEDIFF(DAY, data_date, cal.calendar_date) AS gap FROM data_table WHERE data_date <= cal.calendar_date ORDER BY data_date DESC ) prev_data OUTER APPLY ( SELECT TOP(1) data_date, data_value, DATEDIFF(DAY, cal.calendar_date, data_date) AS gap FROM data_table WHERE data_date > cal.calendar_date ORDER BY data_date ASC ) next_data WHERE cal.calendar_date BETWEEN '2015-01-01' AND '2015-12-31' ; ``` ***EDIT*** Reply to your comment with a different requirement To always get "the value above" is easier, and to insert those values in to a table is easy enough... ``` INSERT INTO data_table SELECT cal.calendar_date, prev_data.data_value FROM calendar AS cal CROSS APPLY ( SELECT TOP(1) data_date, data_value FROM data_table WHERE data_date <= cal.calendar_date ORDER BY data_date DESC ) prev_data WHERE cal.calendar_date BETWEEN '2015-01-01' AND '2015-12-31' AND cal.calendar_date <> prev_data.data_date ; ``` ***Note:*** You could add `WHERE prev_data.gap > 0` to the bigger query above to only get dates that don't already have data.
As suggested by [Aaron Bertrand](https://stackoverflow.com/questions/21189369/better-way-to-generate-months-year-table) you can write a query as: ``` -- create a calendar table at run time if you don't have one: DECLARE @FromDate DATETIME, @ToDate DATETIME; SET @FromDate = (select min(Date) from test); SET @ToDate = (select max(Date) from test); --Get final result: select Tblfinal.Date, case when Tblfinal.[1mA] is null then ( select top 1 T2.[1mA] from Test T2 where T2.Date < Tblfinal.Date and T2.[1mA] > 0 order by T2.Date desc) else Tblfinal.[1mA] end as [1mA] from ( select isnull( C.TheDate, T.Date) as Date ,T.[1mA] from Test T right join ( -- all days in that period SELECT TOP (DATEDIFF(DAY, @FromDate, @ToDate)+1) TheDate = DATEADD(DAY, number, @FromDate) FROM [master].dbo.spt_values WHERE [type] = N'P' )C on T.Date= C.TheDate ) Tblfinal ``` `[DEMO](http://rextester.com/KLUA16369)`
32,094,670
The problem splits into two parts. How to check which working days are missing from my database, if some are missing then add them and fill the row with the values from the closest date. First part, check and find the days. Should i use a gap approach like in the example below? ``` SELECT t1.col1 AS startOfGap, MIN(t2.col1) AS endOfGap FROM (SELECT col1 = theDate + 1 FROM sampleDates tbl1 WHERE NOT EXISTS(SELECT * FROM sampleDates tbl2 WHERE tbl2.theDate = tbl1.theDate + 1) AND theDate <> (SELECT MAX(theDate) FROM sampleDates)) t1 INNER JOIN (SELECT col1 = theDate - 1 FROM sampleDates tbl1 WHERE NOT EXISTS(SELECT * FROM sampleDates tbl2 WHERE tbl1.theDate = tbl2.theDate + 1) AND theDate <> (SELECT MIN(theDate) FROM sampleDates)) t2 ON t1.col1 <= t2.col1 GROUP BY t1.col1; ``` Then i need to see which is the closest date to the one i was missing and fill the new inserted date (the one which was missing) with the values from the closest. Some time ago, I came up with something to get the closest value from a row, but this time i need to adapt it to check both down and upwards. ``` SELECT t,A, C,Y, COALESCE(Y, (SELECT TOP (1) Y FROM tableT AS p2 WHERE p2.Y IS NOT NULL AND p2.[t] <= p.[t] and p.C = p2.C ORDER BY p2.[t] DESC)) as 'YNew' FROM tableT AS p order by c, t ``` How to combine those into one? Thanks **EDIT:** Expected result ``` Date 1mA 20.12.2012 0.152 21.12.2012 0.181 22 weekend so it's skipped (they are skipped automatically) 23 weekend -,- 24 missing 25 missing 26 missing 27.12.2012 0.173 28.12.2012 0.342 Date 1mA 20.12.2012 0.152 21.12.2012 0.181 22 weekend so it's skipped (they are skipped automatically) 23 weekend 0.181 24 missing 0.181 25 missing 0.181 26 missing 0.173 27.12.2012 0.173 28.12.2012 0.342 ``` So, 24,25,26 are not even there with null values. They are simply not there. **EDIT 2:** For taking the closest value, let's consider the scenario in which i'm always looking above. So always going back 1 when it's missing. ``` Date 1mA 20.12.2012 0.152 21.12.2012 0.181 22 weekend so it's skipped (they are skipped automatically) 23 weekend 0.181 24 missing 0.181 25 missing 0.181 26 missing 0.181 27.12.2012 0.173 28.12.2012 0.342 ```
2015/08/19
[ "https://Stackoverflow.com/questions/32094670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5002646/" ]
For these types of query you gain significant performance benefits from creating a calendar table containing every date you'll ever need to test. *(If you're familiar with the term "dimension tables", this is just one such table to enumerate every date of interest.)* Also, the query as a whole can become significantly simpler. ``` SELECT cal.calendar_date AS data_date, CASE WHEN prev_data.gap <= next_data.gap THEN prev_data.data_value ELSE COALESCE(next_data.data_value, prev_data.data_value) END AS data_value FROM calendar AS cal OUTER APPLY ( SELECT TOP(1) data_date, data_value, DATEDIFF(DAY, data_date, cal.calendar_date) AS gap FROM data_table WHERE data_date <= cal.calendar_date ORDER BY data_date DESC ) prev_data OUTER APPLY ( SELECT TOP(1) data_date, data_value, DATEDIFF(DAY, cal.calendar_date, data_date) AS gap FROM data_table WHERE data_date > cal.calendar_date ORDER BY data_date ASC ) next_data WHERE cal.calendar_date BETWEEN '2015-01-01' AND '2015-12-31' ; ``` ***EDIT*** Reply to your comment with a different requirement To always get "the value above" is easier, and to insert those values in to a table is easy enough... ``` INSERT INTO data_table SELECT cal.calendar_date, prev_data.data_value FROM calendar AS cal CROSS APPLY ( SELECT TOP(1) data_date, data_value FROM data_table WHERE data_date <= cal.calendar_date ORDER BY data_date DESC ) prev_data WHERE cal.calendar_date BETWEEN '2015-01-01' AND '2015-12-31' AND cal.calendar_date <> prev_data.data_date ; ``` ***Note:*** You could add `WHERE prev_data.gap > 0` to the bigger query above to only get dates that don't already have data.
Use a Tally Table to generate all dates from `@startDate` to `@endDate`. Then with that, use a `LEFT JOIN` and `OUTER APPLY` to achieve the desired result: [**SQL Fiddle**](http://sqlfiddle.com/#!3/da650/2/0) ``` ;WITH E1(N) AS( SELECT 1 FROM(VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))t(N) ), E2(N) AS(SELECT 1 FROM E1 a CROSS JOIN E1 b), E4(N) AS(SELECT 1 FROM E2 a CROSS JOIN E2 b), CteTally(N) AS( SELECT TOP(DATEDIFF(DAY, @startDate, @endDate) + 1) ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) FROM E4 ), CteDates(dt) AS( SELECT DATEADD(DAY, N-1, @startDate) FROM CteTally ct ) SELECT d.dt, [1mA] = ISNULL(t.[1mA], x.[1mA]) FROM CteDates d LEFT JOIN tbl t ON t.Date = d.dt OUTER APPLY( SELECT TOP 1 [1mA] FROM tbl WHERE [Date] < d.dt ORDER BY [Date] DESC )x WHERE ((DATEPART(dw, d.dt) + @@DATEFIRST) % 7) NOT IN (0, 1) ``` The `WHERE` clause ``` ((DATEPART(dw, d.dt) + @@DATEFIRST) % 7) NOT IN (0, 1) ``` excludes weekends regardless of `@@DATEFIRST`. **RESULT** ``` | dt | 1mA | |------------|-------| | 2012-12-20 | 0.152 | | 2012-12-21 | 0.181 | | 2012-12-24 | 0.181 | | 2012-12-25 | 0.181 | | 2012-12-26 | 0.181 | | 2012-12-27 | 0.173 | | 2012-12-28 | 0.342 | ```
32,094,670
The problem splits into two parts. How to check which working days are missing from my database, if some are missing then add them and fill the row with the values from the closest date. First part, check and find the days. Should i use a gap approach like in the example below? ``` SELECT t1.col1 AS startOfGap, MIN(t2.col1) AS endOfGap FROM (SELECT col1 = theDate + 1 FROM sampleDates tbl1 WHERE NOT EXISTS(SELECT * FROM sampleDates tbl2 WHERE tbl2.theDate = tbl1.theDate + 1) AND theDate <> (SELECT MAX(theDate) FROM sampleDates)) t1 INNER JOIN (SELECT col1 = theDate - 1 FROM sampleDates tbl1 WHERE NOT EXISTS(SELECT * FROM sampleDates tbl2 WHERE tbl1.theDate = tbl2.theDate + 1) AND theDate <> (SELECT MIN(theDate) FROM sampleDates)) t2 ON t1.col1 <= t2.col1 GROUP BY t1.col1; ``` Then i need to see which is the closest date to the one i was missing and fill the new inserted date (the one which was missing) with the values from the closest. Some time ago, I came up with something to get the closest value from a row, but this time i need to adapt it to check both down and upwards. ``` SELECT t,A, C,Y, COALESCE(Y, (SELECT TOP (1) Y FROM tableT AS p2 WHERE p2.Y IS NOT NULL AND p2.[t] <= p.[t] and p.C = p2.C ORDER BY p2.[t] DESC)) as 'YNew' FROM tableT AS p order by c, t ``` How to combine those into one? Thanks **EDIT:** Expected result ``` Date 1mA 20.12.2012 0.152 21.12.2012 0.181 22 weekend so it's skipped (they are skipped automatically) 23 weekend -,- 24 missing 25 missing 26 missing 27.12.2012 0.173 28.12.2012 0.342 Date 1mA 20.12.2012 0.152 21.12.2012 0.181 22 weekend so it's skipped (they are skipped automatically) 23 weekend 0.181 24 missing 0.181 25 missing 0.181 26 missing 0.173 27.12.2012 0.173 28.12.2012 0.342 ``` So, 24,25,26 are not even there with null values. They are simply not there. **EDIT 2:** For taking the closest value, let's consider the scenario in which i'm always looking above. So always going back 1 when it's missing. ``` Date 1mA 20.12.2012 0.152 21.12.2012 0.181 22 weekend so it's skipped (they are skipped automatically) 23 weekend 0.181 24 missing 0.181 25 missing 0.181 26 missing 0.181 27.12.2012 0.173 28.12.2012 0.342 ```
2015/08/19
[ "https://Stackoverflow.com/questions/32094670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5002646/" ]
As suggested by [Aaron Bertrand](https://stackoverflow.com/questions/21189369/better-way-to-generate-months-year-table) you can write a query as: ``` -- create a calendar table at run time if you don't have one: DECLARE @FromDate DATETIME, @ToDate DATETIME; SET @FromDate = (select min(Date) from test); SET @ToDate = (select max(Date) from test); --Get final result: select Tblfinal.Date, case when Tblfinal.[1mA] is null then ( select top 1 T2.[1mA] from Test T2 where T2.Date < Tblfinal.Date and T2.[1mA] > 0 order by T2.Date desc) else Tblfinal.[1mA] end as [1mA] from ( select isnull( C.TheDate, T.Date) as Date ,T.[1mA] from Test T right join ( -- all days in that period SELECT TOP (DATEDIFF(DAY, @FromDate, @ToDate)+1) TheDate = DATEADD(DAY, number, @FromDate) FROM [master].dbo.spt_values WHERE [type] = N'P' )C on T.Date= C.TheDate ) Tblfinal ``` `[DEMO](http://rextester.com/KLUA16369)`
using recursive CTE we can generate date sequence: [SQL Fiddle](http://sqlfiddle.com/#!3/27913/4) **MS SQL Server 2008 Schema Setup**: ``` create table sample (date datetime, data money) insert sample (date, data) values ('2015-01-02', 0.2), ('2015-01-03', 0.3), ('2015-01-07', 0.4), ('2015-01-08', 0.5), ('2015-01-09', 0.6), ('2015-01-21', 0.7), ('2015-01-22', 0.8), ('2015-01-27', 0.9), ('2015-01-28', 0.11), ('2015-01-30', 0.12) ``` **Query 1**: ``` declare @d1 datetime = '2015-01-01', @d2 datetime = '2015-01-31' ;with dates as ( select @d1 as date union all select dateadd(day, 1, date) from dates where dateadd(day, 1, date) <= @d2 ), lo_hi as ( select *, (select top 1 date from sample s where s.date <= d.date order by s.date desc) as lower_date, (select top 1 date from sample s where s.date >= d.date order by s.date asc) as higher_date from dates d ), lo_hi_diff as ( select *, isnull(datediff(day, lower_date, date), 100000) as lo_diff, isnull(datediff(day, date, higher_date), 100000) as hi_diff from lo_hi ) select *, case when lo_diff <= hi_diff then (select top 1 data from sample where date = lower_date) else (select top 1 data from sample where date = higher_date) end as new_data from lo_hi_diff d left join sample s on d.date = s.date ``` **[Results](http://sqlfiddle.com/#!3/27913/4/0)**: ``` | date | lower_date | higher_date | lo_diff | hi_diff | date | data | new_data | |---------------------------|---------------------------|---------------------------|---------|---------|---------------------------|--------|----------| | January, 01 2015 00:00:00 | (null) | January, 02 2015 00:00:00 | 100000 | 1 | (null) | (null) | 0.2 | | January, 02 2015 00:00:00 | January, 02 2015 00:00:00 | January, 02 2015 00:00:00 | 0 | 0 | January, 02 2015 00:00:00 | 0.2 | 0.2 | | January, 03 2015 00:00:00 | January, 03 2015 00:00:00 | January, 03 2015 00:00:00 | 0 | 0 | January, 03 2015 00:00:00 | 0.3 | 0.3 | | January, 04 2015 00:00:00 | January, 03 2015 00:00:00 | January, 07 2015 00:00:00 | 1 | 3 | (null) | (null) | 0.3 | | January, 05 2015 00:00:00 | January, 03 2015 00:00:00 | January, 07 2015 00:00:00 | 2 | 2 | (null) | (null) | 0.3 | | January, 06 2015 00:00:00 | January, 03 2015 00:00:00 | January, 07 2015 00:00:00 | 3 | 1 | (null) | (null) | 0.4 | | January, 07 2015 00:00:00 | January, 07 2015 00:00:00 | January, 07 2015 00:00:00 | 0 | 0 | January, 07 2015 00:00:00 | 0.4 | 0.4 | | January, 08 2015 00:00:00 | January, 08 2015 00:00:00 | January, 08 2015 00:00:00 | 0 | 0 | January, 08 2015 00:00:00 | 0.5 | 0.5 | | January, 09 2015 00:00:00 | January, 09 2015 00:00:00 | January, 09 2015 00:00:00 | 0 | 0 | January, 09 2015 00:00:00 | 0.6 | 0.6 | | January, 10 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 1 | 11 | (null) | (null) | 0.6 | | January, 11 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 2 | 10 | (null) | (null) | 0.6 | | January, 12 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 3 | 9 | (null) | (null) | 0.6 | | January, 13 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 4 | 8 | (null) | (null) | 0.6 | | January, 14 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 5 | 7 | (null) | (null) | 0.6 | | January, 15 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 6 | 6 | (null) | (null) | 0.6 | | January, 16 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 7 | 5 | (null) | (null) | 0.7 | | January, 17 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 8 | 4 | (null) | (null) | 0.7 | | January, 18 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 9 | 3 | (null) | (null) | 0.7 | | January, 19 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 10 | 2 | (null) | (null) | 0.7 | | January, 20 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 11 | 1 | (null) | (null) | 0.7 | | January, 21 2015 00:00:00 | January, 21 2015 00:00:00 | January, 21 2015 00:00:00 | 0 | 0 | January, 21 2015 00:00:00 | 0.7 | 0.7 | | January, 22 2015 00:00:00 | January, 22 2015 00:00:00 | January, 22 2015 00:00:00 | 0 | 0 | January, 22 2015 00:00:00 | 0.8 | 0.8 | | January, 23 2015 00:00:00 | January, 22 2015 00:00:00 | January, 27 2015 00:00:00 | 1 | 4 | (null) | (null) | 0.8 | | January, 24 2015 00:00:00 | January, 22 2015 00:00:00 | January, 27 2015 00:00:00 | 2 | 3 | (null) | (null) | 0.8 | | January, 25 2015 00:00:00 | January, 22 2015 00:00:00 | January, 27 2015 00:00:00 | 3 | 2 | (null) | (null) | 0.9 | | January, 26 2015 00:00:00 | January, 22 2015 00:00:00 | January, 27 2015 00:00:00 | 4 | 1 | (null) | (null) | 0.9 | | January, 27 2015 00:00:00 | January, 27 2015 00:00:00 | January, 27 2015 00:00:00 | 0 | 0 | January, 27 2015 00:00:00 | 0.9 | 0.9 | | January, 28 2015 00:00:00 | January, 28 2015 00:00:00 | January, 28 2015 00:00:00 | 0 | 0 | January, 28 2015 00:00:00 | 0.11 | 0.11 | | January, 29 2015 00:00:00 | January, 28 2015 00:00:00 | January, 30 2015 00:00:00 | 1 | 1 | (null) | (null) | 0.11 | | January, 30 2015 00:00:00 | January, 30 2015 00:00:00 | January, 30 2015 00:00:00 | 0 | 0 | January, 30 2015 00:00:00 | 0.12 | 0.12 | | January, 31 2015 00:00:00 | January, 30 2015 00:00:00 | (null) | 1 | 100000 | (null) | (null) | 0.12 | ```
32,094,670
The problem splits into two parts. How to check which working days are missing from my database, if some are missing then add them and fill the row with the values from the closest date. First part, check and find the days. Should i use a gap approach like in the example below? ``` SELECT t1.col1 AS startOfGap, MIN(t2.col1) AS endOfGap FROM (SELECT col1 = theDate + 1 FROM sampleDates tbl1 WHERE NOT EXISTS(SELECT * FROM sampleDates tbl2 WHERE tbl2.theDate = tbl1.theDate + 1) AND theDate <> (SELECT MAX(theDate) FROM sampleDates)) t1 INNER JOIN (SELECT col1 = theDate - 1 FROM sampleDates tbl1 WHERE NOT EXISTS(SELECT * FROM sampleDates tbl2 WHERE tbl1.theDate = tbl2.theDate + 1) AND theDate <> (SELECT MIN(theDate) FROM sampleDates)) t2 ON t1.col1 <= t2.col1 GROUP BY t1.col1; ``` Then i need to see which is the closest date to the one i was missing and fill the new inserted date (the one which was missing) with the values from the closest. Some time ago, I came up with something to get the closest value from a row, but this time i need to adapt it to check both down and upwards. ``` SELECT t,A, C,Y, COALESCE(Y, (SELECT TOP (1) Y FROM tableT AS p2 WHERE p2.Y IS NOT NULL AND p2.[t] <= p.[t] and p.C = p2.C ORDER BY p2.[t] DESC)) as 'YNew' FROM tableT AS p order by c, t ``` How to combine those into one? Thanks **EDIT:** Expected result ``` Date 1mA 20.12.2012 0.152 21.12.2012 0.181 22 weekend so it's skipped (they are skipped automatically) 23 weekend -,- 24 missing 25 missing 26 missing 27.12.2012 0.173 28.12.2012 0.342 Date 1mA 20.12.2012 0.152 21.12.2012 0.181 22 weekend so it's skipped (they are skipped automatically) 23 weekend 0.181 24 missing 0.181 25 missing 0.181 26 missing 0.173 27.12.2012 0.173 28.12.2012 0.342 ``` So, 24,25,26 are not even there with null values. They are simply not there. **EDIT 2:** For taking the closest value, let's consider the scenario in which i'm always looking above. So always going back 1 when it's missing. ``` Date 1mA 20.12.2012 0.152 21.12.2012 0.181 22 weekend so it's skipped (they are skipped automatically) 23 weekend 0.181 24 missing 0.181 25 missing 0.181 26 missing 0.181 27.12.2012 0.173 28.12.2012 0.342 ```
2015/08/19
[ "https://Stackoverflow.com/questions/32094670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5002646/" ]
Use a Tally Table to generate all dates from `@startDate` to `@endDate`. Then with that, use a `LEFT JOIN` and `OUTER APPLY` to achieve the desired result: [**SQL Fiddle**](http://sqlfiddle.com/#!3/da650/2/0) ``` ;WITH E1(N) AS( SELECT 1 FROM(VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))t(N) ), E2(N) AS(SELECT 1 FROM E1 a CROSS JOIN E1 b), E4(N) AS(SELECT 1 FROM E2 a CROSS JOIN E2 b), CteTally(N) AS( SELECT TOP(DATEDIFF(DAY, @startDate, @endDate) + 1) ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) FROM E4 ), CteDates(dt) AS( SELECT DATEADD(DAY, N-1, @startDate) FROM CteTally ct ) SELECT d.dt, [1mA] = ISNULL(t.[1mA], x.[1mA]) FROM CteDates d LEFT JOIN tbl t ON t.Date = d.dt OUTER APPLY( SELECT TOP 1 [1mA] FROM tbl WHERE [Date] < d.dt ORDER BY [Date] DESC )x WHERE ((DATEPART(dw, d.dt) + @@DATEFIRST) % 7) NOT IN (0, 1) ``` The `WHERE` clause ``` ((DATEPART(dw, d.dt) + @@DATEFIRST) % 7) NOT IN (0, 1) ``` excludes weekends regardless of `@@DATEFIRST`. **RESULT** ``` | dt | 1mA | |------------|-------| | 2012-12-20 | 0.152 | | 2012-12-21 | 0.181 | | 2012-12-24 | 0.181 | | 2012-12-25 | 0.181 | | 2012-12-26 | 0.181 | | 2012-12-27 | 0.173 | | 2012-12-28 | 0.342 | ```
using recursive CTE we can generate date sequence: [SQL Fiddle](http://sqlfiddle.com/#!3/27913/4) **MS SQL Server 2008 Schema Setup**: ``` create table sample (date datetime, data money) insert sample (date, data) values ('2015-01-02', 0.2), ('2015-01-03', 0.3), ('2015-01-07', 0.4), ('2015-01-08', 0.5), ('2015-01-09', 0.6), ('2015-01-21', 0.7), ('2015-01-22', 0.8), ('2015-01-27', 0.9), ('2015-01-28', 0.11), ('2015-01-30', 0.12) ``` **Query 1**: ``` declare @d1 datetime = '2015-01-01', @d2 datetime = '2015-01-31' ;with dates as ( select @d1 as date union all select dateadd(day, 1, date) from dates where dateadd(day, 1, date) <= @d2 ), lo_hi as ( select *, (select top 1 date from sample s where s.date <= d.date order by s.date desc) as lower_date, (select top 1 date from sample s where s.date >= d.date order by s.date asc) as higher_date from dates d ), lo_hi_diff as ( select *, isnull(datediff(day, lower_date, date), 100000) as lo_diff, isnull(datediff(day, date, higher_date), 100000) as hi_diff from lo_hi ) select *, case when lo_diff <= hi_diff then (select top 1 data from sample where date = lower_date) else (select top 1 data from sample where date = higher_date) end as new_data from lo_hi_diff d left join sample s on d.date = s.date ``` **[Results](http://sqlfiddle.com/#!3/27913/4/0)**: ``` | date | lower_date | higher_date | lo_diff | hi_diff | date | data | new_data | |---------------------------|---------------------------|---------------------------|---------|---------|---------------------------|--------|----------| | January, 01 2015 00:00:00 | (null) | January, 02 2015 00:00:00 | 100000 | 1 | (null) | (null) | 0.2 | | January, 02 2015 00:00:00 | January, 02 2015 00:00:00 | January, 02 2015 00:00:00 | 0 | 0 | January, 02 2015 00:00:00 | 0.2 | 0.2 | | January, 03 2015 00:00:00 | January, 03 2015 00:00:00 | January, 03 2015 00:00:00 | 0 | 0 | January, 03 2015 00:00:00 | 0.3 | 0.3 | | January, 04 2015 00:00:00 | January, 03 2015 00:00:00 | January, 07 2015 00:00:00 | 1 | 3 | (null) | (null) | 0.3 | | January, 05 2015 00:00:00 | January, 03 2015 00:00:00 | January, 07 2015 00:00:00 | 2 | 2 | (null) | (null) | 0.3 | | January, 06 2015 00:00:00 | January, 03 2015 00:00:00 | January, 07 2015 00:00:00 | 3 | 1 | (null) | (null) | 0.4 | | January, 07 2015 00:00:00 | January, 07 2015 00:00:00 | January, 07 2015 00:00:00 | 0 | 0 | January, 07 2015 00:00:00 | 0.4 | 0.4 | | January, 08 2015 00:00:00 | January, 08 2015 00:00:00 | January, 08 2015 00:00:00 | 0 | 0 | January, 08 2015 00:00:00 | 0.5 | 0.5 | | January, 09 2015 00:00:00 | January, 09 2015 00:00:00 | January, 09 2015 00:00:00 | 0 | 0 | January, 09 2015 00:00:00 | 0.6 | 0.6 | | January, 10 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 1 | 11 | (null) | (null) | 0.6 | | January, 11 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 2 | 10 | (null) | (null) | 0.6 | | January, 12 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 3 | 9 | (null) | (null) | 0.6 | | January, 13 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 4 | 8 | (null) | (null) | 0.6 | | January, 14 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 5 | 7 | (null) | (null) | 0.6 | | January, 15 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 6 | 6 | (null) | (null) | 0.6 | | January, 16 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 7 | 5 | (null) | (null) | 0.7 | | January, 17 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 8 | 4 | (null) | (null) | 0.7 | | January, 18 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 9 | 3 | (null) | (null) | 0.7 | | January, 19 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 10 | 2 | (null) | (null) | 0.7 | | January, 20 2015 00:00:00 | January, 09 2015 00:00:00 | January, 21 2015 00:00:00 | 11 | 1 | (null) | (null) | 0.7 | | January, 21 2015 00:00:00 | January, 21 2015 00:00:00 | January, 21 2015 00:00:00 | 0 | 0 | January, 21 2015 00:00:00 | 0.7 | 0.7 | | January, 22 2015 00:00:00 | January, 22 2015 00:00:00 | January, 22 2015 00:00:00 | 0 | 0 | January, 22 2015 00:00:00 | 0.8 | 0.8 | | January, 23 2015 00:00:00 | January, 22 2015 00:00:00 | January, 27 2015 00:00:00 | 1 | 4 | (null) | (null) | 0.8 | | January, 24 2015 00:00:00 | January, 22 2015 00:00:00 | January, 27 2015 00:00:00 | 2 | 3 | (null) | (null) | 0.8 | | January, 25 2015 00:00:00 | January, 22 2015 00:00:00 | January, 27 2015 00:00:00 | 3 | 2 | (null) | (null) | 0.9 | | January, 26 2015 00:00:00 | January, 22 2015 00:00:00 | January, 27 2015 00:00:00 | 4 | 1 | (null) | (null) | 0.9 | | January, 27 2015 00:00:00 | January, 27 2015 00:00:00 | January, 27 2015 00:00:00 | 0 | 0 | January, 27 2015 00:00:00 | 0.9 | 0.9 | | January, 28 2015 00:00:00 | January, 28 2015 00:00:00 | January, 28 2015 00:00:00 | 0 | 0 | January, 28 2015 00:00:00 | 0.11 | 0.11 | | January, 29 2015 00:00:00 | January, 28 2015 00:00:00 | January, 30 2015 00:00:00 | 1 | 1 | (null) | (null) | 0.11 | | January, 30 2015 00:00:00 | January, 30 2015 00:00:00 | January, 30 2015 00:00:00 | 0 | 0 | January, 30 2015 00:00:00 | 0.12 | 0.12 | | January, 31 2015 00:00:00 | January, 30 2015 00:00:00 | (null) | 1 | 100000 | (null) | (null) | 0.12 | ```
33,420,918
I am trying to run my Django Application without Django admin panel because I don't need it right now but getting an exception value: > > Put 'django.contrib.admin' in your INSTALLED\_APPS setting in order to > use the admin application. > > > Could I ran my application without `django.contrib.admin` ? Even if go my `localhost:8000` it is showing you need to add `django.contrib.admin` in your installed\_apps?
2015/10/29
[ "https://Stackoverflow.com/questions/33420918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593743/" ]
`django.contrib.admin` is simply a Django app. Remove or comment `django.contrib.admin` from `INSTALLED_APPS` in `settings.py` file. Also remove or comment `from django.contrib import admin` from `admin.py'`,`urls.py` and all the files having this import statement. Remove `url(r'^admin/', include(admin.site.urls)` from `urlpatterns` in `urls.py`.
I have resolved this issue. I had `#url(r'^admin/', include(admin.site.urls)),` in my `urls.py` which I just commented out.
18,065,894
I am having trouble using `<include>` in conjunction with `<merge>`. I am developing on Eclipse with the latest Android SDK (4.3). Here is my sample code: *test\_merge.xml* ``` <merge xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <View android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#FFFF0000" > </View> </merge> ``` *test\_main.xml* ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <include layout="@layout/test_merge" android:layout_width="100dp" android:layout_height="100dp"/> </LinearLayout> ``` *MyActivity.java* ``` public class MyActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.test_main); } } ``` The problem is that I should see a red square on the top left corner, 100x100dp. Instead, the whole screen is red. Thus, for some reason the `android:layout_width` and `android:layout_height` attributes in the `<include>` have no effect. I have read the documentation and it said that in order to override attributes via the `<include>` tag, I must override `android:layout_width` and `android:layout_height`, which I have done. What am I doing wrong?
2013/08/05
[ "https://Stackoverflow.com/questions/18065894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2566395/" ]
When using `merge`, there is no parent to apply `100dp`s to. Try switching to `FrameLayout` instead of `merge` or (even better) in this case you may just remove `merge` and have `View` be the root. **Edit:** Change test\_merge.xml to: ``` <View xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#FFFF0000" > </View> ```
Try making those attributes 0 in your included `layout` ``` <merge xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="0dp" android:layout_height="0dp" > <View android:layout_width="0dp" android:layout_height="0dp" android:background="#FFFF0000" > </View> </merge> ```
75,786
*Disclaimer: This does not do any justice on the rich topic of elliptic curves. It is simplified a lot. As elliptic curves recently got a lot of media attention in the context of encryption, I wanted to provide some small insight how "calculating" on an elliptic curve actually works.* ### Introduction Elliptic curves are sets of points \$(x,y)\$ in the plane of the form \$y^2 = x^3+Ax+B\$. (Additionally, \$4A^3+27B^2 ≠ 0\$ to avoid nasty singularities.) You can consider these curves in any field. If you use the field of real numbers, the curves can be visualized and they look like this: [![two examples of elliptic curves](https://i.stack.imgur.com/vf8mP.png)](https://i.stack.imgur.com/vf8mP.png) [Source](https://commons.wikimedia.org/wiki/File:ECClines-3.svg) The special thing about these curves is that they have a *built in* arithmetic operation that is the analogue of addition. You can add and subtract points, and this operation is both associative and commutative (an abelian group). ### How does addition work? Note: addition of points on elliptic curves is not intuitive. This kind of addition is defined the way it is because it has certain nice properties. It's weird, but it works. As elliptic curves form a group, there is an *additive identity* that is the equivalent of 0. That is, adding \$0\$ to any point will not change the result. This additive identity is the "point" at infinity. All lines on the plane include this point at infinity, so adding it makes no difference. Let's say that any given line intersects the curve at three points, which may be \$0\$, and that the sum of these three points is \$0\$. Keeping that in mind, take a look at this image. [![elliptic curve addition special cases](https://i.stack.imgur.com/bspCG.png)](https://i.stack.imgur.com/bspCG.png) [Source](https://en.wikipedia.org/wiki/File:ECClines.svg) Now, the natural question is, what is \$P+Q\$? Well, if \$P+Q+R = 0\$, then \$P+Q = -R\$ (alternatively written as \$R'\$). Where is \$-R\$? It is where \$R + (-R) = 0\$, which is on the other side of the x-axis from \$R\$ so that the line through them is vertical, intersecting only \$R\$, \$-R\$, and \$0\$. You can see this in the first part of this image: [![diagram of various additions on elliptic curves](https://i.stack.imgur.com/iwBHR.png)](https://i.stack.imgur.com/iwBHR.png) [Source](https://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/ECClines-2.svg/1000px-ECClines-2.svg.png) Another thing you can see in these images is that the sum of a point with itself means the line is tangent to the curve. ### How to find intersections of lines and elliptic curves **In the case of two distinct points** Generally there is exactly one line through two points \$P=(x\_0,y\_0), Q=(x\_1,y\_1)\$. Assuming it is not vertical and the two points are distinct, we can write it as \$y = mx+q\$. When we want to find the points of intersection with the elliptic curve we can just write $$0 = x^3+Ax+B-y^2 = x^3+Ax+B-(mx+q)^2$$ which is a third degree polynomial. These are generally not that easy to solve, but we already know two zeros of this polynomial: The two \$x\$-coordinates \$x\_0, x\_1\$ of the two points we want to add! That way we factor out the linear factors \$(x-x\_0)\$ and \$(x-x\_1)\$ and are left with a third linear factor whose root is the \$x\$-coordinate of the point \$R\$. (\$-R\$ too because of the symmetry. Note that if \$R = (x\_2,y\_2)\$ then \$-R = (x\_2,-y\_2)\$. The \$-\$ is from the group; it is not a vectorial minus.) **In the case of adding one point \$P\$ to itself** In this case we have to calculate the tangent of the curve at \$P=(x\_0,y\_0)\$. We can directly write \$m\$ and \$q\$ in terms of \$A,B,x\_0\$ and \$y\_0\$: $$m = \frac{3x\_0^2+A}{2y\_0}$$ $$q = \frac{-x\_0^3+Ax\_0+2B}{2y\_0}$$ We get the equation \$y = mx+q\$ and can proceed the same way as in the paragraph above. ### A complete case tree This is a complete list of how to handle all those cases: Let \$P,Q\$ be points on the elliptic curve (including the "infinity" point \$0\$) * If \$P = 0\$ or \$Q = 0\$, then \$P+Q = Q\$ or \$P+Q = P\$, respectively * Else \$P ≠ 0\$ and \$Q ≠ 0\$, so let \$P = (x\_0,y\_0)\$ and \$Q = (x\_1,y\_1)\$: + If \$P = -Q\$ (that means \$x\_0 = x\_1\$ and \$y\_0 = -y\_1\$) then \$P+Q = 0\$ + Else \$P ≠ -Q\$ - If \$x\_0 = x\_1\$ then we have \$P=Q\$ and we calculate the tangent (see section above) in order to get \$R\$. Then \$P+Q = P+P = 2P = -R\$ - Else: We can construct a line of the form \$y = mx+q\$ through those two points (see section above) in order to calculate \$R\$. Then \$P+Q=-R\$ ### Finite fields For this challenge we will only consider fields of size \$p\$ where \$p\$ is prime (and because of some details \$p ≠ 2, p ≠ 3\$). This has the advantage that you can simply calculate \$\bmod p\$. The arithmetic in other fields is much more complicated. This in this example we set \$p = 5\$ and all equalities here are congruences \$\bmod 5\$. ``` 2+4 ≡ 6 ≡ 1 2-4 ≡ -2 ≡ 3 2*4 ≡ 8 ≡ 3 2/4 ≡ 2*4 ≡ 3 because 4*4 ≡ 16 ≡ 1, therefore 1/4 ≡ 4 ``` Challenge ========= Given the parameters \$A,B\$ of an elliptic curve, a prime field characteristic \$p\$ and two points \$P,Q\$ on the elliptic curve, return their sum. * You can assume that the parameters \$A,B\$ actually describe an elliptic curve, that means that \$4A^3+27B^2 ≠ 0\$. * You can assume that \$P,Q\$ are actually points on the elliptic curve or the \$0\$-point. * You can assume that \$p ≠ 2,3\$ is prime. ### Test Cases I made a (not very elegant) implementation in MATLAB/Octave, that you can use for your own test cases: [ideone.com](http://ideone.com/SSB68P) I hope it is correct. It did at least reproduce a few calculations I made by hand. Note the trivial test cases that work for all curves we consider here: * Adding zero: \$P+0 = P\$ * Adding the inverse: \$(x,y) + (x,-y) = 0\$ --- For \$p = 7, A = 0, B = 5\$ the two points \$P = (3,2)\$ and \$Q = (6,2)\$ are on the elliptic curve. Then following holds: ``` 2*Q = Q+Q = P 2*P = P+P = (5,2) 3*P = P+P+P = (5,2)+P = (6,5) 4*P = P+P+P+P = (5,2)+(5,2) = (6,5)+(5,2) = Q ``` All the points on the elliptic curve are \$(3,2),(5,2),(6,2),(3,5),(5,5),(6,5),0\$ --- For \$p = 13, A = 3, B = 8\$ we get ``` (1,8)+(9,7) = (2,10) (2,3)+(12,11) = (9,7) 2*(9,6) = (9,7) 3*(9,6) = 0 ``` --- For \$p = 17, A = 2, B = 2\$ and \$P=(5,1)\$ we get ``` 2*P = (6,3) 3*P = (10,6) 4*P = (3,1) 5*P = (9,16) 6*P = (16,13) 7*P = (0,6) 8*P = (13,7) 9*P = (7,6) 10*P = (7,11) ``` --- If you are really ambitious, take ``` p = 1550031797834347859248576414813139942411 A = 1009296542191532464076260367525816293976 x0 = 1317953763239595888465524145589872695690 y0 = 434829348619031278460656303481105428081 x1 = 1247392211317907151303247721489640699240 y1 = 207534858442090452193999571026315995117 ``` and try to find a natural number \$n\$ such that \$n\times(x\_0,y\_0) = (x\_1,y\_1)\$. [Further information here.](https://web.archive.org/web/20150818152514/https://www.certicom.com/index.php/the-certicom-ecc-challenge "https://www.certicom.com/index.php/the-certicom-ecc-challenge") Appendix ======== First of all a big THANK YOU to @El'endiaStarman for reviewing and editing my draft! ### Why elliptic curves? Well it might appear like some kind of arbitrary equation, but it is not, it is quite general: Generally we consider those geometric "shapes" in the [projective plane](https://en.wikipedia.org/wiki/Projective_geometry) (that is where the "infinity" is coming from. There we consider all [homogeneous polynomials](https://en.wikipedia.org/wiki/Homogeneous_polynomial) of third degree. (Those of lower or higher degree would be too difficult or just trivial to examine.) After applying some restrictions in order to get the nice properties we want, and after dehomogenizing those polynomials (projecting into one of three affine planes) we end up with equations like \$y^2+axy+by = x^3+cx^2+dx+e\$ This is an elliptic curve in the long Weierstrass form. These are basically the same curves as we considered, but just somewhat skewed. With a linear coordinate transform, you can easily make a short Weierstras equation out of that. [example](https://math.stackexchange.com/questions/1259490/weierstrass-equation-long-vs-normal-form), which still hold all the interesting properties. ### Why did we exclude \$p=2,3\$? This has to do with the fact that for the short Weierstrass form we need the restriction \$4A^3+27B^2 ≠ 0\$ in order to avoid singularities (more on that below). In a field of characteristic 2 we have \$4 = 0\$ and in a field of characteristic 3 we have \$27 = 0\$, this makes it impossible to have curves in short Weierstrass form for those kinds of fields. ### What are singularities? If the equation \$4A^3+27B^2=0\$ holds, we have singularities like following: As you see at those points you cannot find a derivative and therefore no tangent, which "kills" the operation. You might look at the equations \$y^2 = x^3\$ or \$y^2 = x^3-3x+2\$ ### Why are they called *elliptic curves* anyway? The reason is that equations of this shape pop up in elliptic integrals, e.g. which are what you get when you want to caclulate the e.g. the arclength of an ellipse. [A short slideshow about the origin of the name.](https://www.math.rochester.edu/people/faculty/doug/mypapers/wayne1.pdf) ### What do they have to do with cryptography? There are ways to compute \$nP = P+P+...+P\$ very efficiently. This can be used for example in the [Diffie Hellman key exchange](https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange). The modular arithmetic can be replaced by the addition on torsion subgroups, these are just the points on the curve that have finite order. (That means that \$mP = 0\$ for some \$m\$, which is basically just calculating \$\bmod m\$ ).
2016/03/18
[ "https://codegolf.stackexchange.com/questions/75786", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/24877/" ]
Pyth, ~~105~~ 100 bytes ======================= ``` A,@Q3eQ?qGZH?qHZG?&=YqhHhGqeG%_eHhQZ_m%dhQ,-*J?Y*+*3^hG2@Q1^*2eG-hQ2*-eGeH^-hGhH-hQ2-hGK--^J2hGhHeGK ``` Input is expected as `(p, A, P, Q)`, where `P` and `Q` are the two points of the form `(x, y)` or, if they are the special `0` point, just as `0`. You can try it out online [here](https://pyth.herokuapp.com/?code=A%2C%40Q3eQ%3FqGZH%3FqHZG%3F%26%3DYqhHhGqeG%25_eHhQZ_m%25dhQ%2C-%2aJ%3FY%2a%2B%2a3%5EhG2%40Q1%5E%2a2eG-hQ2%2a-eGeH%5E-hGhH-hQ2-hGK--%5EJ2hGhHeGK&input=%2813%2C+3%2C+%281%2C+8%29%2C+%289%2C+7%29%29&test_suite=1&test_suite_input=%287%2C+0%2C+5%2C+%286%2C+2%29%2C+%286%2C+2%29%29%0A%287%2C+0%2C+5%2C+%283%2C+2%29%2C+%283%2C+2%29%29%0A%2813%2C+3%2C+8%2C+%281%2C8%29%2C%289%2C7%29%29%0A%2813%2C+3%2C+8%2C+%282%2C3%29%2C%2812%2C11%29%29%0A%2813%2C+3%2C+8%2C+%289%2C6%29%2C+%289%2C6%29%29%0A%2813%2C+3%2C+0%2C+%289%2C+7%29%2C+%289%2C+6%29%29%0A%2813%2C+3%2C+8%2C+%289%2C+7%29%2C+0%29&debug=0). The last two examples show how the special `0` works. In order to save a few bytes, I only use `mod p` on the final answer. This means that it does things like `x0^p` a few times without doing modular exponentiation, so it might be very slow. It works by following roughly the same logic as this Python function: ```py def add_ellip(p, A, P, Q): # points are in format (x, y) z = 0 # representing special 0 point if (P == z): return Q if (Q == z): return P if P[0] == Q[0]: if (P == (Q[0], -Q[1] % p)): return z else: m = ((3*pow(P[0], 2, p) + A)*pow(2*P[1], p-2, p)) % p else: m = (P[1] - Q[1])*pow(P[0] - Q[0], p-2, p) % p x = (pow(m, 2, p) - P[0] - Q[0]) % p y = (m*(P[0] - x) - P[1]) % p return (x, y) ``` This is heavily reliant on the fact that the modular multiplicative inverse of `x` is equal to `x^(p-2) mod p` if `p` is prime. Thus we are able to compute `m`, the slope of the line, by finding the modular multiplicative inverse of the denominator and multiplying it by numerator. Pretty handy. The Python function should calculate larger problems a little more efficiently because of the use of `pow`. I also used the shortcuts shown on the [Wikipedia page on this subject](https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication#Point_addition). It's quite interesting I only end up using `A` once, and `B` not at all. Also just for fun: ```py def pow2floor(x): p = 1 x >>= 1 while (x > 0): x >>= 1 p <<= 1 return p def multi_nP(p, A, n, P): d = {} def rec_helper(n, P): if (n == 0): return (0, 0) elif (n == 1): return P elif (n in d): return d[n] else: p2f = pow2floor(n) remainder = n - p2f lower_half = rec_helper(p2f//2, P) d[p2f//2] = lower_half nP = add_ellip(p, A, lower_half, lower_half) if (remainder): nP = add_ellip(p, A, nP, rec_helper(remainder, P)) d[n] = nP return nP return rec_helper(n, P) ``` The `multi_nP` function computes `n*P` for a given integer `n` and point `P`. It uses a recursive strategy by splitting `n` into two parts `p2f` and `remainder` such that `p2f + remainder = n` and that `p2f = 2^k`. Then we call the function again on those parts, adding the result with `add_ellip`. I also used basic dynamic programming approach by saving already computed values in the dict `d`. The next function would theoretically solve the bonus question using the same strategy: ```py def find_nPQ(p, A, P, Q): # P is input point, Q is what we're looking for d = {} found_Q = False def rec_helper(n, P): if (n == 0): return (0, 0) elif (n == 1): return P elif (n in d): return d[n] else: p2f = pow2floor(n) remainder = n - p2f lower_half = rec_helper(p2f//2, P) d[p2f//2] = lower_half nP = add_ellip(p, A, lower_half, lower_half) if (remainder): nP = add_ellip(p, A, nP, rec_helper(remainder, P)) d[n] = nP return nP for x in range(p): xP = rec_helper(x, P) if (xP == Q): return x ``` Unfortunately, it runs nowhere near quickly enough to compute it. I'm guessing there might be much more efficient ways to do this, especially if we don't have to iterate through every possibly value for `n`.
Python 3, ~~193~~ 191 bytes =========================== A solution based on [Rhyzomatic's Pyth answer](https://codegolf.stackexchange.com/a/76113/47581) and their Python logic. In particular. I liked how they found the third root of a monic cubic polynomial `x^3 + bx^2 + cx + d` when you have two roots `x_1` and `x_2` by noting that `b == x_1 + x_2 + x_3` and subtracting accordingly. I plan to add an explanation, golf this, and perhaps transpile it into Ruby, if Ruby turns out to be shorter. ```python def e(p,A,B,P,Q): if P==0:return Q if Q==0:return P f,g=P;j,k=Q if f==j: if g==-k%p:return 0 m=(3*f*f+A)*pow(2*j,p-2) else:m=(g-k)*pow(f-j,p-2) x=m*m-f-j;y=m*(f-x)-g;return(x%p,y%p) ``` **Ungolfing:** ```python def elliptic_curve_addition(p, A, B, P, Q): if P == 0: return Q if Q == 0: return P f,q = P j,k = Q if f==j: if g == (-k) % p: return 0 m = (3 * f**2 + A) * pow(2*j, p-2) else: m = (g-k) * pow(f-j, p-2) x = m**2 - f - j y = m * (f-x) - g return (x%p, y%p) ```
75,786
*Disclaimer: This does not do any justice on the rich topic of elliptic curves. It is simplified a lot. As elliptic curves recently got a lot of media attention in the context of encryption, I wanted to provide some small insight how "calculating" on an elliptic curve actually works.* ### Introduction Elliptic curves are sets of points \$(x,y)\$ in the plane of the form \$y^2 = x^3+Ax+B\$. (Additionally, \$4A^3+27B^2 ≠ 0\$ to avoid nasty singularities.) You can consider these curves in any field. If you use the field of real numbers, the curves can be visualized and they look like this: [![two examples of elliptic curves](https://i.stack.imgur.com/vf8mP.png)](https://i.stack.imgur.com/vf8mP.png) [Source](https://commons.wikimedia.org/wiki/File:ECClines-3.svg) The special thing about these curves is that they have a *built in* arithmetic operation that is the analogue of addition. You can add and subtract points, and this operation is both associative and commutative (an abelian group). ### How does addition work? Note: addition of points on elliptic curves is not intuitive. This kind of addition is defined the way it is because it has certain nice properties. It's weird, but it works. As elliptic curves form a group, there is an *additive identity* that is the equivalent of 0. That is, adding \$0\$ to any point will not change the result. This additive identity is the "point" at infinity. All lines on the plane include this point at infinity, so adding it makes no difference. Let's say that any given line intersects the curve at three points, which may be \$0\$, and that the sum of these three points is \$0\$. Keeping that in mind, take a look at this image. [![elliptic curve addition special cases](https://i.stack.imgur.com/bspCG.png)](https://i.stack.imgur.com/bspCG.png) [Source](https://en.wikipedia.org/wiki/File:ECClines.svg) Now, the natural question is, what is \$P+Q\$? Well, if \$P+Q+R = 0\$, then \$P+Q = -R\$ (alternatively written as \$R'\$). Where is \$-R\$? It is where \$R + (-R) = 0\$, which is on the other side of the x-axis from \$R\$ so that the line through them is vertical, intersecting only \$R\$, \$-R\$, and \$0\$. You can see this in the first part of this image: [![diagram of various additions on elliptic curves](https://i.stack.imgur.com/iwBHR.png)](https://i.stack.imgur.com/iwBHR.png) [Source](https://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/ECClines-2.svg/1000px-ECClines-2.svg.png) Another thing you can see in these images is that the sum of a point with itself means the line is tangent to the curve. ### How to find intersections of lines and elliptic curves **In the case of two distinct points** Generally there is exactly one line through two points \$P=(x\_0,y\_0), Q=(x\_1,y\_1)\$. Assuming it is not vertical and the two points are distinct, we can write it as \$y = mx+q\$. When we want to find the points of intersection with the elliptic curve we can just write $$0 = x^3+Ax+B-y^2 = x^3+Ax+B-(mx+q)^2$$ which is a third degree polynomial. These are generally not that easy to solve, but we already know two zeros of this polynomial: The two \$x\$-coordinates \$x\_0, x\_1\$ of the two points we want to add! That way we factor out the linear factors \$(x-x\_0)\$ and \$(x-x\_1)\$ and are left with a third linear factor whose root is the \$x\$-coordinate of the point \$R\$. (\$-R\$ too because of the symmetry. Note that if \$R = (x\_2,y\_2)\$ then \$-R = (x\_2,-y\_2)\$. The \$-\$ is from the group; it is not a vectorial minus.) **In the case of adding one point \$P\$ to itself** In this case we have to calculate the tangent of the curve at \$P=(x\_0,y\_0)\$. We can directly write \$m\$ and \$q\$ in terms of \$A,B,x\_0\$ and \$y\_0\$: $$m = \frac{3x\_0^2+A}{2y\_0}$$ $$q = \frac{-x\_0^3+Ax\_0+2B}{2y\_0}$$ We get the equation \$y = mx+q\$ and can proceed the same way as in the paragraph above. ### A complete case tree This is a complete list of how to handle all those cases: Let \$P,Q\$ be points on the elliptic curve (including the "infinity" point \$0\$) * If \$P = 0\$ or \$Q = 0\$, then \$P+Q = Q\$ or \$P+Q = P\$, respectively * Else \$P ≠ 0\$ and \$Q ≠ 0\$, so let \$P = (x\_0,y\_0)\$ and \$Q = (x\_1,y\_1)\$: + If \$P = -Q\$ (that means \$x\_0 = x\_1\$ and \$y\_0 = -y\_1\$) then \$P+Q = 0\$ + Else \$P ≠ -Q\$ - If \$x\_0 = x\_1\$ then we have \$P=Q\$ and we calculate the tangent (see section above) in order to get \$R\$. Then \$P+Q = P+P = 2P = -R\$ - Else: We can construct a line of the form \$y = mx+q\$ through those two points (see section above) in order to calculate \$R\$. Then \$P+Q=-R\$ ### Finite fields For this challenge we will only consider fields of size \$p\$ where \$p\$ is prime (and because of some details \$p ≠ 2, p ≠ 3\$). This has the advantage that you can simply calculate \$\bmod p\$. The arithmetic in other fields is much more complicated. This in this example we set \$p = 5\$ and all equalities here are congruences \$\bmod 5\$. ``` 2+4 ≡ 6 ≡ 1 2-4 ≡ -2 ≡ 3 2*4 ≡ 8 ≡ 3 2/4 ≡ 2*4 ≡ 3 because 4*4 ≡ 16 ≡ 1, therefore 1/4 ≡ 4 ``` Challenge ========= Given the parameters \$A,B\$ of an elliptic curve, a prime field characteristic \$p\$ and two points \$P,Q\$ on the elliptic curve, return their sum. * You can assume that the parameters \$A,B\$ actually describe an elliptic curve, that means that \$4A^3+27B^2 ≠ 0\$. * You can assume that \$P,Q\$ are actually points on the elliptic curve or the \$0\$-point. * You can assume that \$p ≠ 2,3\$ is prime. ### Test Cases I made a (not very elegant) implementation in MATLAB/Octave, that you can use for your own test cases: [ideone.com](http://ideone.com/SSB68P) I hope it is correct. It did at least reproduce a few calculations I made by hand. Note the trivial test cases that work for all curves we consider here: * Adding zero: \$P+0 = P\$ * Adding the inverse: \$(x,y) + (x,-y) = 0\$ --- For \$p = 7, A = 0, B = 5\$ the two points \$P = (3,2)\$ and \$Q = (6,2)\$ are on the elliptic curve. Then following holds: ``` 2*Q = Q+Q = P 2*P = P+P = (5,2) 3*P = P+P+P = (5,2)+P = (6,5) 4*P = P+P+P+P = (5,2)+(5,2) = (6,5)+(5,2) = Q ``` All the points on the elliptic curve are \$(3,2),(5,2),(6,2),(3,5),(5,5),(6,5),0\$ --- For \$p = 13, A = 3, B = 8\$ we get ``` (1,8)+(9,7) = (2,10) (2,3)+(12,11) = (9,7) 2*(9,6) = (9,7) 3*(9,6) = 0 ``` --- For \$p = 17, A = 2, B = 2\$ and \$P=(5,1)\$ we get ``` 2*P = (6,3) 3*P = (10,6) 4*P = (3,1) 5*P = (9,16) 6*P = (16,13) 7*P = (0,6) 8*P = (13,7) 9*P = (7,6) 10*P = (7,11) ``` --- If you are really ambitious, take ``` p = 1550031797834347859248576414813139942411 A = 1009296542191532464076260367525816293976 x0 = 1317953763239595888465524145589872695690 y0 = 434829348619031278460656303481105428081 x1 = 1247392211317907151303247721489640699240 y1 = 207534858442090452193999571026315995117 ``` and try to find a natural number \$n\$ such that \$n\times(x\_0,y\_0) = (x\_1,y\_1)\$. [Further information here.](https://web.archive.org/web/20150818152514/https://www.certicom.com/index.php/the-certicom-ecc-challenge "https://www.certicom.com/index.php/the-certicom-ecc-challenge") Appendix ======== First of all a big THANK YOU to @El'endiaStarman for reviewing and editing my draft! ### Why elliptic curves? Well it might appear like some kind of arbitrary equation, but it is not, it is quite general: Generally we consider those geometric "shapes" in the [projective plane](https://en.wikipedia.org/wiki/Projective_geometry) (that is where the "infinity" is coming from. There we consider all [homogeneous polynomials](https://en.wikipedia.org/wiki/Homogeneous_polynomial) of third degree. (Those of lower or higher degree would be too difficult or just trivial to examine.) After applying some restrictions in order to get the nice properties we want, and after dehomogenizing those polynomials (projecting into one of three affine planes) we end up with equations like \$y^2+axy+by = x^3+cx^2+dx+e\$ This is an elliptic curve in the long Weierstrass form. These are basically the same curves as we considered, but just somewhat skewed. With a linear coordinate transform, you can easily make a short Weierstras equation out of that. [example](https://math.stackexchange.com/questions/1259490/weierstrass-equation-long-vs-normal-form), which still hold all the interesting properties. ### Why did we exclude \$p=2,3\$? This has to do with the fact that for the short Weierstrass form we need the restriction \$4A^3+27B^2 ≠ 0\$ in order to avoid singularities (more on that below). In a field of characteristic 2 we have \$4 = 0\$ and in a field of characteristic 3 we have \$27 = 0\$, this makes it impossible to have curves in short Weierstrass form for those kinds of fields. ### What are singularities? If the equation \$4A^3+27B^2=0\$ holds, we have singularities like following: As you see at those points you cannot find a derivative and therefore no tangent, which "kills" the operation. You might look at the equations \$y^2 = x^3\$ or \$y^2 = x^3-3x+2\$ ### Why are they called *elliptic curves* anyway? The reason is that equations of this shape pop up in elliptic integrals, e.g. which are what you get when you want to caclulate the e.g. the arclength of an ellipse. [A short slideshow about the origin of the name.](https://www.math.rochester.edu/people/faculty/doug/mypapers/wayne1.pdf) ### What do they have to do with cryptography? There are ways to compute \$nP = P+P+...+P\$ very efficiently. This can be used for example in the [Diffie Hellman key exchange](https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange). The modular arithmetic can be replaced by the addition on torsion subgroups, these are just the points on the curve that have finite order. (That means that \$mP = 0\$ for some \$m\$, which is basically just calculating \$\bmod m\$ ).
2016/03/18
[ "https://codegolf.stackexchange.com/questions/75786", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/24877/" ]
Pyth, ~~105~~ 100 bytes ======================= ``` A,@Q3eQ?qGZH?qHZG?&=YqhHhGqeG%_eHhQZ_m%dhQ,-*J?Y*+*3^hG2@Q1^*2eG-hQ2*-eGeH^-hGhH-hQ2-hGK--^J2hGhHeGK ``` Input is expected as `(p, A, P, Q)`, where `P` and `Q` are the two points of the form `(x, y)` or, if they are the special `0` point, just as `0`. You can try it out online [here](https://pyth.herokuapp.com/?code=A%2C%40Q3eQ%3FqGZH%3FqHZG%3F%26%3DYqhHhGqeG%25_eHhQZ_m%25dhQ%2C-%2aJ%3FY%2a%2B%2a3%5EhG2%40Q1%5E%2a2eG-hQ2%2a-eGeH%5E-hGhH-hQ2-hGK--%5EJ2hGhHeGK&input=%2813%2C+3%2C+%281%2C+8%29%2C+%289%2C+7%29%29&test_suite=1&test_suite_input=%287%2C+0%2C+5%2C+%286%2C+2%29%2C+%286%2C+2%29%29%0A%287%2C+0%2C+5%2C+%283%2C+2%29%2C+%283%2C+2%29%29%0A%2813%2C+3%2C+8%2C+%281%2C8%29%2C%289%2C7%29%29%0A%2813%2C+3%2C+8%2C+%282%2C3%29%2C%2812%2C11%29%29%0A%2813%2C+3%2C+8%2C+%289%2C6%29%2C+%289%2C6%29%29%0A%2813%2C+3%2C+0%2C+%289%2C+7%29%2C+%289%2C+6%29%29%0A%2813%2C+3%2C+8%2C+%289%2C+7%29%2C+0%29&debug=0). The last two examples show how the special `0` works. In order to save a few bytes, I only use `mod p` on the final answer. This means that it does things like `x0^p` a few times without doing modular exponentiation, so it might be very slow. It works by following roughly the same logic as this Python function: ```py def add_ellip(p, A, P, Q): # points are in format (x, y) z = 0 # representing special 0 point if (P == z): return Q if (Q == z): return P if P[0] == Q[0]: if (P == (Q[0], -Q[1] % p)): return z else: m = ((3*pow(P[0], 2, p) + A)*pow(2*P[1], p-2, p)) % p else: m = (P[1] - Q[1])*pow(P[0] - Q[0], p-2, p) % p x = (pow(m, 2, p) - P[0] - Q[0]) % p y = (m*(P[0] - x) - P[1]) % p return (x, y) ``` This is heavily reliant on the fact that the modular multiplicative inverse of `x` is equal to `x^(p-2) mod p` if `p` is prime. Thus we are able to compute `m`, the slope of the line, by finding the modular multiplicative inverse of the denominator and multiplying it by numerator. Pretty handy. The Python function should calculate larger problems a little more efficiently because of the use of `pow`. I also used the shortcuts shown on the [Wikipedia page on this subject](https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication#Point_addition). It's quite interesting I only end up using `A` once, and `B` not at all. Also just for fun: ```py def pow2floor(x): p = 1 x >>= 1 while (x > 0): x >>= 1 p <<= 1 return p def multi_nP(p, A, n, P): d = {} def rec_helper(n, P): if (n == 0): return (0, 0) elif (n == 1): return P elif (n in d): return d[n] else: p2f = pow2floor(n) remainder = n - p2f lower_half = rec_helper(p2f//2, P) d[p2f//2] = lower_half nP = add_ellip(p, A, lower_half, lower_half) if (remainder): nP = add_ellip(p, A, nP, rec_helper(remainder, P)) d[n] = nP return nP return rec_helper(n, P) ``` The `multi_nP` function computes `n*P` for a given integer `n` and point `P`. It uses a recursive strategy by splitting `n` into two parts `p2f` and `remainder` such that `p2f + remainder = n` and that `p2f = 2^k`. Then we call the function again on those parts, adding the result with `add_ellip`. I also used basic dynamic programming approach by saving already computed values in the dict `d`. The next function would theoretically solve the bonus question using the same strategy: ```py def find_nPQ(p, A, P, Q): # P is input point, Q is what we're looking for d = {} found_Q = False def rec_helper(n, P): if (n == 0): return (0, 0) elif (n == 1): return P elif (n in d): return d[n] else: p2f = pow2floor(n) remainder = n - p2f lower_half = rec_helper(p2f//2, P) d[p2f//2] = lower_half nP = add_ellip(p, A, lower_half, lower_half) if (remainder): nP = add_ellip(p, A, nP, rec_helper(remainder, P)) d[n] = nP return nP for x in range(p): xP = rec_helper(x, P) if (xP == Q): return x ``` Unfortunately, it runs nowhere near quickly enough to compute it. I'm guessing there might be much more efficient ways to do this, especially if we don't have to iterate through every possibly value for `n`.
[PARI/GP](https://pari.math.u-bordeaux.fr), 46 bytes ==================================================== ``` f(a,b,p,P,Q)=elladd(ellinit(Mod([a,b],p)),P,Q) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ddFBasMwEAVQehORlQw_JWNhy14kNwikayGKWtfFIBIRnEXOkk26KD1TcppOZZfGQd2MpKeZ0YBOX8Htu-f3cD5_Hvp2Xl0eW-nwgoANnrLlm_euaSQv3bbr5XrXSMPXFiHLYsZQdX34cCH4o3RivhJh32173s5-DjPx6ryXLYTjEmHMAgU0TIncDtGyjqgiqikW_2MxokIFUjCEirWGnmgOxUo5iCZeo7RDnKq-0RxcFt8jO8RbLWPne6VFbHzPKtmiBqWSqeRhEp5uzXPrBOu_ZDv-1O8_fwM) Using built-ins. The zero point is represented by `[0]`. --- [PARI/GP](https://pari.math.u-bordeaux.fr), 114 bytes ===================================================== ``` f(a,b,p,P,Q)=if(!#P,Q,!#Q,P,[x,y]=Mod(P,p);[x,-y]-[w,z]=Q,m=if(d=x-w,(y-z)/d,(3*x^2+a)/2/y);[t=m^2-x-w,m*x-m*t-y]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ddLRasIwFAZg9iZVb5LuD5qEtsro3mBgr0Mc2aRDsFuQDltfZTfuYuyZtqfZsVW00t0czvk45ySQfHx7t1k9vvj9_uu9zMX0Z5Mzhyd4zJHxdJWzwYgyDEYZialQ2_Thbcnm8PyOSlFbYbbY2TRDcWhfppXYgtVix8dLMB1WC3Xr-FiNaxoo02KhxKGjCCtRhCXN8_bk35tP5_26Zi4Q94HfrF5LSoeHYhg8u_Wa5Qgc5wiMmSBCAhND2TZa0iPqBnUXo_8xOqLGFFLDSExJZ0g6qqBJpYKUHZ8htm3sanKhCjTWnCdtGy81bjZfq5w0i69Z966YQfY1y5gu0-P9q-neSQ8n5-bTS53-yh8) A port of [@Rhyzomatic's Pyth answer](https://codegolf.stackexchange.com/a/76113/9288). The zero point is represented by `0`.
75,786
*Disclaimer: This does not do any justice on the rich topic of elliptic curves. It is simplified a lot. As elliptic curves recently got a lot of media attention in the context of encryption, I wanted to provide some small insight how "calculating" on an elliptic curve actually works.* ### Introduction Elliptic curves are sets of points \$(x,y)\$ in the plane of the form \$y^2 = x^3+Ax+B\$. (Additionally, \$4A^3+27B^2 ≠ 0\$ to avoid nasty singularities.) You can consider these curves in any field. If you use the field of real numbers, the curves can be visualized and they look like this: [![two examples of elliptic curves](https://i.stack.imgur.com/vf8mP.png)](https://i.stack.imgur.com/vf8mP.png) [Source](https://commons.wikimedia.org/wiki/File:ECClines-3.svg) The special thing about these curves is that they have a *built in* arithmetic operation that is the analogue of addition. You can add and subtract points, and this operation is both associative and commutative (an abelian group). ### How does addition work? Note: addition of points on elliptic curves is not intuitive. This kind of addition is defined the way it is because it has certain nice properties. It's weird, but it works. As elliptic curves form a group, there is an *additive identity* that is the equivalent of 0. That is, adding \$0\$ to any point will not change the result. This additive identity is the "point" at infinity. All lines on the plane include this point at infinity, so adding it makes no difference. Let's say that any given line intersects the curve at three points, which may be \$0\$, and that the sum of these three points is \$0\$. Keeping that in mind, take a look at this image. [![elliptic curve addition special cases](https://i.stack.imgur.com/bspCG.png)](https://i.stack.imgur.com/bspCG.png) [Source](https://en.wikipedia.org/wiki/File:ECClines.svg) Now, the natural question is, what is \$P+Q\$? Well, if \$P+Q+R = 0\$, then \$P+Q = -R\$ (alternatively written as \$R'\$). Where is \$-R\$? It is where \$R + (-R) = 0\$, which is on the other side of the x-axis from \$R\$ so that the line through them is vertical, intersecting only \$R\$, \$-R\$, and \$0\$. You can see this in the first part of this image: [![diagram of various additions on elliptic curves](https://i.stack.imgur.com/iwBHR.png)](https://i.stack.imgur.com/iwBHR.png) [Source](https://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/ECClines-2.svg/1000px-ECClines-2.svg.png) Another thing you can see in these images is that the sum of a point with itself means the line is tangent to the curve. ### How to find intersections of lines and elliptic curves **In the case of two distinct points** Generally there is exactly one line through two points \$P=(x\_0,y\_0), Q=(x\_1,y\_1)\$. Assuming it is not vertical and the two points are distinct, we can write it as \$y = mx+q\$. When we want to find the points of intersection with the elliptic curve we can just write $$0 = x^3+Ax+B-y^2 = x^3+Ax+B-(mx+q)^2$$ which is a third degree polynomial. These are generally not that easy to solve, but we already know two zeros of this polynomial: The two \$x\$-coordinates \$x\_0, x\_1\$ of the two points we want to add! That way we factor out the linear factors \$(x-x\_0)\$ and \$(x-x\_1)\$ and are left with a third linear factor whose root is the \$x\$-coordinate of the point \$R\$. (\$-R\$ too because of the symmetry. Note that if \$R = (x\_2,y\_2)\$ then \$-R = (x\_2,-y\_2)\$. The \$-\$ is from the group; it is not a vectorial minus.) **In the case of adding one point \$P\$ to itself** In this case we have to calculate the tangent of the curve at \$P=(x\_0,y\_0)\$. We can directly write \$m\$ and \$q\$ in terms of \$A,B,x\_0\$ and \$y\_0\$: $$m = \frac{3x\_0^2+A}{2y\_0}$$ $$q = \frac{-x\_0^3+Ax\_0+2B}{2y\_0}$$ We get the equation \$y = mx+q\$ and can proceed the same way as in the paragraph above. ### A complete case tree This is a complete list of how to handle all those cases: Let \$P,Q\$ be points on the elliptic curve (including the "infinity" point \$0\$) * If \$P = 0\$ or \$Q = 0\$, then \$P+Q = Q\$ or \$P+Q = P\$, respectively * Else \$P ≠ 0\$ and \$Q ≠ 0\$, so let \$P = (x\_0,y\_0)\$ and \$Q = (x\_1,y\_1)\$: + If \$P = -Q\$ (that means \$x\_0 = x\_1\$ and \$y\_0 = -y\_1\$) then \$P+Q = 0\$ + Else \$P ≠ -Q\$ - If \$x\_0 = x\_1\$ then we have \$P=Q\$ and we calculate the tangent (see section above) in order to get \$R\$. Then \$P+Q = P+P = 2P = -R\$ - Else: We can construct a line of the form \$y = mx+q\$ through those two points (see section above) in order to calculate \$R\$. Then \$P+Q=-R\$ ### Finite fields For this challenge we will only consider fields of size \$p\$ where \$p\$ is prime (and because of some details \$p ≠ 2, p ≠ 3\$). This has the advantage that you can simply calculate \$\bmod p\$. The arithmetic in other fields is much more complicated. This in this example we set \$p = 5\$ and all equalities here are congruences \$\bmod 5\$. ``` 2+4 ≡ 6 ≡ 1 2-4 ≡ -2 ≡ 3 2*4 ≡ 8 ≡ 3 2/4 ≡ 2*4 ≡ 3 because 4*4 ≡ 16 ≡ 1, therefore 1/4 ≡ 4 ``` Challenge ========= Given the parameters \$A,B\$ of an elliptic curve, a prime field characteristic \$p\$ and two points \$P,Q\$ on the elliptic curve, return their sum. * You can assume that the parameters \$A,B\$ actually describe an elliptic curve, that means that \$4A^3+27B^2 ≠ 0\$. * You can assume that \$P,Q\$ are actually points on the elliptic curve or the \$0\$-point. * You can assume that \$p ≠ 2,3\$ is prime. ### Test Cases I made a (not very elegant) implementation in MATLAB/Octave, that you can use for your own test cases: [ideone.com](http://ideone.com/SSB68P) I hope it is correct. It did at least reproduce a few calculations I made by hand. Note the trivial test cases that work for all curves we consider here: * Adding zero: \$P+0 = P\$ * Adding the inverse: \$(x,y) + (x,-y) = 0\$ --- For \$p = 7, A = 0, B = 5\$ the two points \$P = (3,2)\$ and \$Q = (6,2)\$ are on the elliptic curve. Then following holds: ``` 2*Q = Q+Q = P 2*P = P+P = (5,2) 3*P = P+P+P = (5,2)+P = (6,5) 4*P = P+P+P+P = (5,2)+(5,2) = (6,5)+(5,2) = Q ``` All the points on the elliptic curve are \$(3,2),(5,2),(6,2),(3,5),(5,5),(6,5),0\$ --- For \$p = 13, A = 3, B = 8\$ we get ``` (1,8)+(9,7) = (2,10) (2,3)+(12,11) = (9,7) 2*(9,6) = (9,7) 3*(9,6) = 0 ``` --- For \$p = 17, A = 2, B = 2\$ and \$P=(5,1)\$ we get ``` 2*P = (6,3) 3*P = (10,6) 4*P = (3,1) 5*P = (9,16) 6*P = (16,13) 7*P = (0,6) 8*P = (13,7) 9*P = (7,6) 10*P = (7,11) ``` --- If you are really ambitious, take ``` p = 1550031797834347859248576414813139942411 A = 1009296542191532464076260367525816293976 x0 = 1317953763239595888465524145589872695690 y0 = 434829348619031278460656303481105428081 x1 = 1247392211317907151303247721489640699240 y1 = 207534858442090452193999571026315995117 ``` and try to find a natural number \$n\$ such that \$n\times(x\_0,y\_0) = (x\_1,y\_1)\$. [Further information here.](https://web.archive.org/web/20150818152514/https://www.certicom.com/index.php/the-certicom-ecc-challenge "https://www.certicom.com/index.php/the-certicom-ecc-challenge") Appendix ======== First of all a big THANK YOU to @El'endiaStarman for reviewing and editing my draft! ### Why elliptic curves? Well it might appear like some kind of arbitrary equation, but it is not, it is quite general: Generally we consider those geometric "shapes" in the [projective plane](https://en.wikipedia.org/wiki/Projective_geometry) (that is where the "infinity" is coming from. There we consider all [homogeneous polynomials](https://en.wikipedia.org/wiki/Homogeneous_polynomial) of third degree. (Those of lower or higher degree would be too difficult or just trivial to examine.) After applying some restrictions in order to get the nice properties we want, and after dehomogenizing those polynomials (projecting into one of three affine planes) we end up with equations like \$y^2+axy+by = x^3+cx^2+dx+e\$ This is an elliptic curve in the long Weierstrass form. These are basically the same curves as we considered, but just somewhat skewed. With a linear coordinate transform, you can easily make a short Weierstras equation out of that. [example](https://math.stackexchange.com/questions/1259490/weierstrass-equation-long-vs-normal-form), which still hold all the interesting properties. ### Why did we exclude \$p=2,3\$? This has to do with the fact that for the short Weierstrass form we need the restriction \$4A^3+27B^2 ≠ 0\$ in order to avoid singularities (more on that below). In a field of characteristic 2 we have \$4 = 0\$ and in a field of characteristic 3 we have \$27 = 0\$, this makes it impossible to have curves in short Weierstrass form for those kinds of fields. ### What are singularities? If the equation \$4A^3+27B^2=0\$ holds, we have singularities like following: As you see at those points you cannot find a derivative and therefore no tangent, which "kills" the operation. You might look at the equations \$y^2 = x^3\$ or \$y^2 = x^3-3x+2\$ ### Why are they called *elliptic curves* anyway? The reason is that equations of this shape pop up in elliptic integrals, e.g. which are what you get when you want to caclulate the e.g. the arclength of an ellipse. [A short slideshow about the origin of the name.](https://www.math.rochester.edu/people/faculty/doug/mypapers/wayne1.pdf) ### What do they have to do with cryptography? There are ways to compute \$nP = P+P+...+P\$ very efficiently. This can be used for example in the [Diffie Hellman key exchange](https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange). The modular arithmetic can be replaced by the addition on torsion subgroups, these are just the points on the curve that have finite order. (That means that \$mP = 0\$ for some \$m\$, which is basically just calculating \$\bmod m\$ ).
2016/03/18
[ "https://codegolf.stackexchange.com/questions/75786", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/24877/" ]
Python 3, ~~193~~ 191 bytes =========================== A solution based on [Rhyzomatic's Pyth answer](https://codegolf.stackexchange.com/a/76113/47581) and their Python logic. In particular. I liked how they found the third root of a monic cubic polynomial `x^3 + bx^2 + cx + d` when you have two roots `x_1` and `x_2` by noting that `b == x_1 + x_2 + x_3` and subtracting accordingly. I plan to add an explanation, golf this, and perhaps transpile it into Ruby, if Ruby turns out to be shorter. ```python def e(p,A,B,P,Q): if P==0:return Q if Q==0:return P f,g=P;j,k=Q if f==j: if g==-k%p:return 0 m=(3*f*f+A)*pow(2*j,p-2) else:m=(g-k)*pow(f-j,p-2) x=m*m-f-j;y=m*(f-x)-g;return(x%p,y%p) ``` **Ungolfing:** ```python def elliptic_curve_addition(p, A, B, P, Q): if P == 0: return Q if Q == 0: return P f,q = P j,k = Q if f==j: if g == (-k) % p: return 0 m = (3 * f**2 + A) * pow(2*j, p-2) else: m = (g-k) * pow(f-j, p-2) x = m**2 - f - j y = m * (f-x) - g return (x%p, y%p) ```
[PARI/GP](https://pari.math.u-bordeaux.fr), 46 bytes ==================================================== ``` f(a,b,p,P,Q)=elladd(ellinit(Mod([a,b],p)),P,Q) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ddFBasMwEAVQehORlQw_JWNhy14kNwikayGKWtfFIBIRnEXOkk26KD1TcppOZZfGQd2MpKeZ0YBOX8Htu-f3cD5_Hvp2Xl0eW-nwgoANnrLlm_euaSQv3bbr5XrXSMPXFiHLYsZQdX34cCH4o3RivhJh32173s5-DjPx6ryXLYTjEmHMAgU0TIncDtGyjqgiqikW_2MxokIFUjCEirWGnmgOxUo5iCZeo7RDnKq-0RxcFt8jO8RbLWPne6VFbHzPKtmiBqWSqeRhEp5uzXPrBOu_ZDv-1O8_fwM) Using built-ins. The zero point is represented by `[0]`. --- [PARI/GP](https://pari.math.u-bordeaux.fr), 114 bytes ===================================================== ``` f(a,b,p,P,Q)=if(!#P,Q,!#Q,P,[x,y]=Mod(P,p);[x,-y]-[w,z]=Q,m=if(d=x-w,(y-z)/d,(3*x^2+a)/2/y);[t=m^2-x-w,m*x-m*t-y]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ddLRasIwFAZg9iZVb5LuD5qEtsro3mBgr0Mc2aRDsFuQDltfZTfuYuyZtqfZsVW00t0czvk45ySQfHx7t1k9vvj9_uu9zMX0Z5Mzhyd4zJHxdJWzwYgyDEYZialQ2_Thbcnm8PyOSlFbYbbY2TRDcWhfppXYgtVix8dLMB1WC3Xr-FiNaxoo02KhxKGjCCtRhCXN8_bk35tP5_26Zi4Q94HfrF5LSoeHYhg8u_Wa5Qgc5wiMmSBCAhND2TZa0iPqBnUXo_8xOqLGFFLDSExJZ0g6qqBJpYKUHZ8htm3sanKhCjTWnCdtGy81bjZfq5w0i69Z966YQfY1y5gu0-P9q-neSQ8n5-bTS53-yh8) A port of [@Rhyzomatic's Pyth answer](https://codegolf.stackexchange.com/a/76113/9288). The zero point is represented by `0`.
19,405,815
I need to run a create table query, every time it takes more than one hour and a half and then it will show the error message like ora\_01652: unable to extend temp segment by 8192 in tablespace xyz, how can I fix it?
2013/10/16
[ "https://Stackoverflow.com/questions/19405815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2770977/" ]
First, you may want to `alter session set resumable_timeout = 86400`. This will pause the query instead of letting it simply fail, giving you time to look at the situation while it's happening. As @davek mentioned, you may need to add space somewhere. And you need to figure out why it is using so much space. Temporary tablespace is used mostly for sorting and hashing data. For example, if you are sorting or hash-joining a 50GB table, you will need about 50GB of temporary tablespace. As @tbone suggested, a really bad query or execution plan could have a cross join that tries to create a massive result set that won't fit on any disk. Make sure your joins are correct and the execution plan looks sane. Some things to look for are `MERGE JOIN (CARTESIAN)`, or perhaps if there are some filters that are applied after hashing or sorting instead of before. Re-gathering statistics is usually a good first step if the plan is bad. If the query and plan are OK and you just don't have enough space, you'll need to break the query up somehow. This could be multiple inserts instead of a single CTAS. Breaking up queries is usually a bad idea, but is necessary in some rare cases where resources are scarce. Or you may want to look at using [partition-wise joins](http://docs.oracle.com/cd/E11882_01/server.112/e25523/part_warehouse.htm) to reduce the the amount of space required.
Either your disk is full (or almost full) or you do not have permission to extend the relevant tablespace.
4,291,040
This question originally comes from the following problem: > > Let $ABC$ be a triangle with integer side lengths with $\angle ABC = 60^{\circ}$. Suppose length $\overline{AB}$ and $\overline{BC}$ are prime numbers. Determine and prove what kind of triangle $ABC$ is. > > > I suspect $ABC$ must be an isosceles triangle where $\overline{AB} = \overline{BC}$. By the law of cosine we have $$ \overline{AC}^2 = \overline{AB}^2 + \overline{BC}^2 - 2\overline{AB}\overline{BC}\cos 60^{\circ}.$$ Let $p = \overline{AB}$ and $q = \overline{BC}$ the above statement is equivalent to $p^2 + q^2 - pq$ being a perfect square. My job will be proving that this statement holds for $p \neq q$(where $p=q$ corresponds to the case where $\overline{AB} = \overline{BC}$ i.e. $ABC$ being isoceles triangle). I tried factorizing and discussing case by case and did not work out for me. How can I approach this problem?
2021/10/29
[ "https://math.stackexchange.com/questions/4291040", "https://math.stackexchange.com", "https://math.stackexchange.com/users/824408/" ]
Your expression is $(p-q)^2+pq$. Suppose that was $N^2$ for some natural number $N$. Without loss of generality, suppose that $p>q$. Starting with $$N^2-(p-q)^2=pq$$ we deduce that $$(N-(p-q))(N+(p-q))=pq$$ Now, it is not possible for $N-(p-q)$ to be $1$ since that would entail $2(p-q)+1=pq$ and the left hand is less that $2p$. Hence we must have $$N-(p-q)=q\quad \&\quad N+(p-q)=p$$ but this is plainly not possible.
Multiply given equation with $4$. Then we have $$4c^2 = (2q-p)^2+3p^2$$ and thus $$(2c-2q+p)(2c+2q-p)=3p^2$$ Now you don't have a lot of cases... > > $$2c+2q-p\in\{1,3,p,3p,p^2,3p^2\}$$ > > >
4,291,040
This question originally comes from the following problem: > > Let $ABC$ be a triangle with integer side lengths with $\angle ABC = 60^{\circ}$. Suppose length $\overline{AB}$ and $\overline{BC}$ are prime numbers. Determine and prove what kind of triangle $ABC$ is. > > > I suspect $ABC$ must be an isosceles triangle where $\overline{AB} = \overline{BC}$. By the law of cosine we have $$ \overline{AC}^2 = \overline{AB}^2 + \overline{BC}^2 - 2\overline{AB}\overline{BC}\cos 60^{\circ}.$$ Let $p = \overline{AB}$ and $q = \overline{BC}$ the above statement is equivalent to $p^2 + q^2 - pq$ being a perfect square. My job will be proving that this statement holds for $p \neq q$(where $p=q$ corresponds to the case where $\overline{AB} = \overline{BC}$ i.e. $ABC$ being isoceles triangle). I tried factorizing and discussing case by case and did not work out for me. How can I approach this problem?
2021/10/29
[ "https://math.stackexchange.com/questions/4291040", "https://math.stackexchange.com", "https://math.stackexchange.com/users/824408/" ]
Multiply given equation with $4$. Then we have $$4c^2 = (2q-p)^2+3p^2$$ and thus $$(2c-2q+p)(2c+2q-p)=3p^2$$ Now you don't have a lot of cases... > > $$2c+2q-p\in\{1,3,p,3p,p^2,3p^2\}$$ > > >
We have: $$(p-q)^2<p^2-pq+q^2<(p+q)^2.$$ If $p>q>0$ and $p^2-pq+q^2=c^2,$ for $c>0,$ then then $q^2\equiv c^2\pmod p,$ so $$c\equiv \pm q\pmod p$$ Now, since $0<p-q< c<p+q,$ this means our options are $c=q$ or $c=2p-q.$ In both cases, $c$ is in the range only if $p<2q.$ If $c=q,$ then $p^2-qp=0,$ so $p=0$ or $p=q.$ If $c=2p-q$ then $$p^2-pq+q^2=4p^2-4pq+q^2\\\implies3p^2-3pq=0$$ and again $p=q$ or $p=0.$ --- So we’ve only really used that the larger of $p,q$ is prime (to conclude $c\equiv\pm q\pmod p.$) Indeed, we could restrict it to the larger of the two being a power of a prime. So we get: > > If $1<m<n$ are relatively prime, and $n$ is the power of an odd prime, or $n=2,4$ then $m^2-mn+n^2$ is not a perfect square. > > > We can’t use other powers of $2$ because $1$ has more than $2$ square roots modulo $2^n$ for $n>2.$ --- Not sure if it is possible for $m$ to be an odd prime power if $q$ is not. --- We can apply the usual technique to find a formula for all rational solutions to $$x^2-xy+y^2=1.$$ Pick one rational solution $(x,y)=(1,1).$ Every other rational solution is on a line $(1+at,1+bt)$ for some $a,b$ integers and $t\neq 0.$ But given $a,b$ you get: $$ \begin{align} 1&=(1+at)^2-(1+at)(1+bt)+(1+bt)^2\\&=1+(2a-(a+b)+2b)t+(a^2-ab+b^2)t^2\\ t&=-\frac{a+b}{a^2-ab+b^2} \end{align} $$ Now $$\gcd(a+b,a^2-ab+b^2)=1,3$$ with $3$ if $a\equiv $b\pmod 3,$ and $1$ otherwise. So $$x=1+at=\frac{b^2-2ab}{a^2-ab+b^2},\\ y=1+bt=\frac{a^2-2ab}{a^2-ab+b^2}.$$ So, at least for relatively prime $(m,n)$ if $m^2-nm+n^2$ is a perfect square, then:$$m=b^2-2ab\\n=a^2-2ab$$ for some relatively prime $a,b,$ with $a+b\not\equiv 0\pmod 3,$ or $$m=\frac{b^2-2ab}3\\n=\frac{a^2-2ab}{3}$$ for some relatively prime $a,b$ with $a+b\equiv 0\pmod 3.$ This shows why it is hard for $m,n$ to be prime.
4,291,040
This question originally comes from the following problem: > > Let $ABC$ be a triangle with integer side lengths with $\angle ABC = 60^{\circ}$. Suppose length $\overline{AB}$ and $\overline{BC}$ are prime numbers. Determine and prove what kind of triangle $ABC$ is. > > > I suspect $ABC$ must be an isosceles triangle where $\overline{AB} = \overline{BC}$. By the law of cosine we have $$ \overline{AC}^2 = \overline{AB}^2 + \overline{BC}^2 - 2\overline{AB}\overline{BC}\cos 60^{\circ}.$$ Let $p = \overline{AB}$ and $q = \overline{BC}$ the above statement is equivalent to $p^2 + q^2 - pq$ being a perfect square. My job will be proving that this statement holds for $p \neq q$(where $p=q$ corresponds to the case where $\overline{AB} = \overline{BC}$ i.e. $ABC$ being isoceles triangle). I tried factorizing and discussing case by case and did not work out for me. How can I approach this problem?
2021/10/29
[ "https://math.stackexchange.com/questions/4291040", "https://math.stackexchange.com", "https://math.stackexchange.com/users/824408/" ]
Your expression is $(p-q)^2+pq$. Suppose that was $N^2$ for some natural number $N$. Without loss of generality, suppose that $p>q$. Starting with $$N^2-(p-q)^2=pq$$ we deduce that $$(N-(p-q))(N+(p-q))=pq$$ Now, it is not possible for $N-(p-q)$ to be $1$ since that would entail $2(p-q)+1=pq$ and the left hand is less that $2p$. Hence we must have $$N-(p-q)=q\quad \&\quad N+(p-q)=p$$ but this is plainly not possible.
We have: $$(p-q)^2<p^2-pq+q^2<(p+q)^2.$$ If $p>q>0$ and $p^2-pq+q^2=c^2,$ for $c>0,$ then then $q^2\equiv c^2\pmod p,$ so $$c\equiv \pm q\pmod p$$ Now, since $0<p-q< c<p+q,$ this means our options are $c=q$ or $c=2p-q.$ In both cases, $c$ is in the range only if $p<2q.$ If $c=q,$ then $p^2-qp=0,$ so $p=0$ or $p=q.$ If $c=2p-q$ then $$p^2-pq+q^2=4p^2-4pq+q^2\\\implies3p^2-3pq=0$$ and again $p=q$ or $p=0.$ --- So we’ve only really used that the larger of $p,q$ is prime (to conclude $c\equiv\pm q\pmod p.$) Indeed, we could restrict it to the larger of the two being a power of a prime. So we get: > > If $1<m<n$ are relatively prime, and $n$ is the power of an odd prime, or $n=2,4$ then $m^2-mn+n^2$ is not a perfect square. > > > We can’t use other powers of $2$ because $1$ has more than $2$ square roots modulo $2^n$ for $n>2.$ --- Not sure if it is possible for $m$ to be an odd prime power if $q$ is not. --- We can apply the usual technique to find a formula for all rational solutions to $$x^2-xy+y^2=1.$$ Pick one rational solution $(x,y)=(1,1).$ Every other rational solution is on a line $(1+at,1+bt)$ for some $a,b$ integers and $t\neq 0.$ But given $a,b$ you get: $$ \begin{align} 1&=(1+at)^2-(1+at)(1+bt)+(1+bt)^2\\&=1+(2a-(a+b)+2b)t+(a^2-ab+b^2)t^2\\ t&=-\frac{a+b}{a^2-ab+b^2} \end{align} $$ Now $$\gcd(a+b,a^2-ab+b^2)=1,3$$ with $3$ if $a\equiv $b\pmod 3,$ and $1$ otherwise. So $$x=1+at=\frac{b^2-2ab}{a^2-ab+b^2},\\ y=1+bt=\frac{a^2-2ab}{a^2-ab+b^2}.$$ So, at least for relatively prime $(m,n)$ if $m^2-nm+n^2$ is a perfect square, then:$$m=b^2-2ab\\n=a^2-2ab$$ for some relatively prime $a,b,$ with $a+b\not\equiv 0\pmod 3,$ or $$m=\frac{b^2-2ab}3\\n=\frac{a^2-2ab}{3}$$ for some relatively prime $a,b$ with $a+b\equiv 0\pmod 3.$ This shows why it is hard for $m,n$ to be prime.
11,330,147
I want to use my `DataGridView` only to show things, and I want the user not to be able to select any row, field or anything from the `DataGridView`. How can I do this?
2012/07/04
[ "https://Stackoverflow.com/questions/11330147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471381/" ]
I fixed this by setting the `Enabled` property to `false`.
I liked user4101525's answer best in theory but it doesn't actually work. Selection is not an overlay so you see whatever is under the control Ramgy Borja's answer doesn't deal with the fact that default style is not actually a color at all so applying it doesn't help. This handles the default style and works if applying your own colors (which may be what edhubbell refers to as nasty results) ``` dgv.RowsDefaultCellStyle.SelectionBackColor = dgv.RowsDefaultCellStyle.BackColor.IsEmpty ? System.Drawing.Color.White : dgv.RowsDefaultCellStyle.BackColor; dgv.RowsDefaultCellStyle.SelectionForeColor = dgv.RowsDefaultCellStyle.ForeColor.IsEmpty ? System.Drawing.Color.Black : dgv.RowsDefaultCellStyle.ForeColor; ```
11,330,147
I want to use my `DataGridView` only to show things, and I want the user not to be able to select any row, field or anything from the `DataGridView`. How can I do this?
2012/07/04
[ "https://Stackoverflow.com/questions/11330147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471381/" ]
`Enabled` property to `false` or ``` this.dataGridView1.DefaultCellStyle.SelectionBackColor = this.dataGridView1.DefaultCellStyle.BackColor; this.dataGridView1.DefaultCellStyle.SelectionForeColor = this.dataGridView1.DefaultCellStyle.ForeColor; ```
This worked for me like a charm: ``` row.DataGridView.Enabled = false; row.DefaultCellStyle.BackColor = Color.LightGray; row.DefaultCellStyle.ForeColor = Color.DarkGray; ``` (where row = DataGridView.NewRow(appropriate overloads);)
11,330,147
I want to use my `DataGridView` only to show things, and I want the user not to be able to select any row, field or anything from the `DataGridView`. How can I do this?
2012/07/04
[ "https://Stackoverflow.com/questions/11330147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471381/" ]
I found setting all `AllowUser...` properties to `false`, `ReadOnly` to `true`, `RowHeadersVisible` to `false`, `ScollBars` to `None`, then [faking the prevention of selection](https://stackoverflow.com/questions/1745272/disable-cell-highlighting-in-a-datagridview#1745295) worked best for me. Not setting `Enabled` to `false` still allows the user to copy the data from the grid. The following code also cleans up the look when you want a simple display grid (assuming rows are the same height): ``` int width = 0; for (int i = 0; i < dataGridView1.Columns.Count; i++) { width += dataGridView1.Columns[i].Width; } dataGridView1.Width = width; dataGridView1.Height = dataGridView1.Rows[0].Height*(dataGridView1.Rows.Count+1); ```
Use the [`DataGridView.ReadOnly` property](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.readonly.aspx) The code in the [MSDN example](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.readonly.aspx) illustrates the use of this property in a `DataGridView` control **intended primarily for display**. In this example, the visual appearance of the control is customized in several ways and **the control is configured for limited interactivity**. Observe these settings in the sample code: ``` // Set property values appropriate for read-only // display and limited interactivity dataGridView1.AllowUserToAddRows = false; dataGridView1.AllowUserToDeleteRows = false; dataGridView1.AllowUserToOrderColumns = true; dataGridView1.ReadOnly = true; dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView1.MultiSelect = false; dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None; dataGridView1.AllowUserToResizeColumns = false; dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing; dataGridView1.AllowUserToResizeRows = false; dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing; ```
11,330,147
I want to use my `DataGridView` only to show things, and I want the user not to be able to select any row, field or anything from the `DataGridView`. How can I do this?
2012/07/04
[ "https://Stackoverflow.com/questions/11330147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471381/" ]
This worked for me like a charm: ``` row.DataGridView.Enabled = false; row.DefaultCellStyle.BackColor = Color.LightGray; row.DefaultCellStyle.ForeColor = Color.DarkGray; ``` (where row = DataGridView.NewRow(appropriate overloads);)
I found setting all `AllowUser...` properties to `false`, `ReadOnly` to `true`, `RowHeadersVisible` to `false`, `ScollBars` to `None`, then [faking the prevention of selection](https://stackoverflow.com/questions/1745272/disable-cell-highlighting-in-a-datagridview#1745295) worked best for me. Not setting `Enabled` to `false` still allows the user to copy the data from the grid. The following code also cleans up the look when you want a simple display grid (assuming rows are the same height): ``` int width = 0; for (int i = 0; i < dataGridView1.Columns.Count; i++) { width += dataGridView1.Columns[i].Width; } dataGridView1.Width = width; dataGridView1.Height = dataGridView1.Rows[0].Height*(dataGridView1.Rows.Count+1); ```
11,330,147
I want to use my `DataGridView` only to show things, and I want the user not to be able to select any row, field or anything from the `DataGridView`. How can I do this?
2012/07/04
[ "https://Stackoverflow.com/questions/11330147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471381/" ]
I'd go with this: ``` private void myDataGridView_SelectionChanged(Object sender, EventArgs e) { dgvSomeDataGridView.ClearSelection(); } ``` I don't agree with the broad assertion that no `DataGridView` should be unselectable. Some UIs are built for tools or touchsreens, and allowing a selection misleads the user to think that selecting will actually get them somewhere. Setting `ReadOnly = true` on the control has no impact on whether a cell or row can be selected. And there are visual and functional downsides to setting `Enabled = false`. Another option is to set the control selected colors to be exactly what the non-selected colors are, but if you happen to be manipulating the back color of the cell, then this method yields some nasty results as well.
I found setting all `AllowUser...` properties to `false`, `ReadOnly` to `true`, `RowHeadersVisible` to `false`, `ScollBars` to `None`, then [faking the prevention of selection](https://stackoverflow.com/questions/1745272/disable-cell-highlighting-in-a-datagridview#1745295) worked best for me. Not setting `Enabled` to `false` still allows the user to copy the data from the grid. The following code also cleans up the look when you want a simple display grid (assuming rows are the same height): ``` int width = 0; for (int i = 0; i < dataGridView1.Columns.Count; i++) { width += dataGridView1.Columns[i].Width; } dataGridView1.Width = width; dataGridView1.Height = dataGridView1.Rows[0].Height*(dataGridView1.Rows.Count+1); ```
11,330,147
I want to use my `DataGridView` only to show things, and I want the user not to be able to select any row, field or anything from the `DataGridView`. How can I do this?
2012/07/04
[ "https://Stackoverflow.com/questions/11330147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471381/" ]
I'd go with this: ``` private void myDataGridView_SelectionChanged(Object sender, EventArgs e) { dgvSomeDataGridView.ClearSelection(); } ``` I don't agree with the broad assertion that no `DataGridView` should be unselectable. Some UIs are built for tools or touchsreens, and allowing a selection misleads the user to think that selecting will actually get them somewhere. Setting `ReadOnly = true` on the control has no impact on whether a cell or row can be selected. And there are visual and functional downsides to setting `Enabled = false`. Another option is to set the control selected colors to be exactly what the non-selected colors are, but if you happen to be manipulating the back color of the cell, then this method yields some nasty results as well.
Its in VB, but shouldnt be difficult to translate to C#: If you want to lock datagridview, use `dg.ReadOnly == True;` If you want to prevent user from selecting another row, just remember old selection and based on condition set or not set the row which shall be selected. Assuming, that multiselection is turned off: ``` Private Sub dg_SelectionChanged(sender As Object, e As EventArgs) Handles dg.SelectionChanged Static OldSelection As Integer If dg.Rows.Count > 0 Then If dg.SelectedRows(0).Index <> OldSelection And YOURCONDITION Then dg.Rows(OldSelection).Selected = True End If OldSelection = dg.SelectedRows(0).Index End If End Sub ```
11,330,147
I want to use my `DataGridView` only to show things, and I want the user not to be able to select any row, field or anything from the `DataGridView`. How can I do this?
2012/07/04
[ "https://Stackoverflow.com/questions/11330147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471381/" ]
This worked for me like a charm: ``` row.DataGridView.Enabled = false; row.DefaultCellStyle.BackColor = Color.LightGray; row.DefaultCellStyle.ForeColor = Color.DarkGray; ``` (where row = DataGridView.NewRow(appropriate overloads);)
I liked user4101525's answer best in theory but it doesn't actually work. Selection is not an overlay so you see whatever is under the control Ramgy Borja's answer doesn't deal with the fact that default style is not actually a color at all so applying it doesn't help. This handles the default style and works if applying your own colors (which may be what edhubbell refers to as nasty results) ``` dgv.RowsDefaultCellStyle.SelectionBackColor = dgv.RowsDefaultCellStyle.BackColor.IsEmpty ? System.Drawing.Color.White : dgv.RowsDefaultCellStyle.BackColor; dgv.RowsDefaultCellStyle.SelectionForeColor = dgv.RowsDefaultCellStyle.ForeColor.IsEmpty ? System.Drawing.Color.Black : dgv.RowsDefaultCellStyle.ForeColor; ```
11,330,147
I want to use my `DataGridView` only to show things, and I want the user not to be able to select any row, field or anything from the `DataGridView`. How can I do this?
2012/07/04
[ "https://Stackoverflow.com/questions/11330147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471381/" ]
If you don't need to use the information in the selected cell then clearing selection works but if you need to still use the information in the selected cell you can do this to make it appear there is no selection and the back color will still be visible. ``` private void dataGridView_SelectionChanged(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridView.SelectedRows) { dataGridView.RowsDefaultCellStyle.SelectionBackColor = row.DefaultCellStyle.BackColor; } } ```
Its in VB, but shouldnt be difficult to translate to C#: If you want to lock datagridview, use `dg.ReadOnly == True;` If you want to prevent user from selecting another row, just remember old selection and based on condition set or not set the row which shall be selected. Assuming, that multiselection is turned off: ``` Private Sub dg_SelectionChanged(sender As Object, e As EventArgs) Handles dg.SelectionChanged Static OldSelection As Integer If dg.Rows.Count > 0 Then If dg.SelectedRows(0).Index <> OldSelection And YOURCONDITION Then dg.Rows(OldSelection).Selected = True End If OldSelection = dg.SelectedRows(0).Index End If End Sub ```
11,330,147
I want to use my `DataGridView` only to show things, and I want the user not to be able to select any row, field or anything from the `DataGridView`. How can I do this?
2012/07/04
[ "https://Stackoverflow.com/questions/11330147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471381/" ]
`Enabled` property to `false` or ``` this.dataGridView1.DefaultCellStyle.SelectionBackColor = this.dataGridView1.DefaultCellStyle.BackColor; this.dataGridView1.DefaultCellStyle.SelectionForeColor = this.dataGridView1.DefaultCellStyle.ForeColor; ```
Its in VB, but shouldnt be difficult to translate to C#: If you want to lock datagridview, use `dg.ReadOnly == True;` If you want to prevent user from selecting another row, just remember old selection and based on condition set or not set the row which shall be selected. Assuming, that multiselection is turned off: ``` Private Sub dg_SelectionChanged(sender As Object, e As EventArgs) Handles dg.SelectionChanged Static OldSelection As Integer If dg.Rows.Count > 0 Then If dg.SelectedRows(0).Index <> OldSelection And YOURCONDITION Then dg.Rows(OldSelection).Selected = True End If OldSelection = dg.SelectedRows(0).Index End If End Sub ```
11,330,147
I want to use my `DataGridView` only to show things, and I want the user not to be able to select any row, field or anything from the `DataGridView`. How can I do this?
2012/07/04
[ "https://Stackoverflow.com/questions/11330147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471381/" ]
Here's what has always worked for me to disable the default selection in a class inherited from DataGridView: ``` // REQUIRES: SelectionMode = DataGridViewSelectionMode.FullRowSelect protected override void SetSelectedRowCore(int rowIndex, bool selected) { base.SetSelectedRowCore(rowIndex, selected && ALLOW_DEFAULT_SELECTION); } bool ALLOW_DEFAULT_SELECTION = false; ``` Usually the goal is to disable it entirely (in order to implement our own custom selection and drawing process). When the goal is to allow the default selection only at specific times the boolean can be wrapped like so: ``` public void SelectRowExplicitly(int index, bool selected = true) { try { ALLOW_DEFAULT_SELECTION = true; Rows[index].Selected = selected; } finally { ALLOW_DEFAULT_SELECTION = false; } } ```
Use the [`DataGridView.ReadOnly` property](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.readonly.aspx) The code in the [MSDN example](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.readonly.aspx) illustrates the use of this property in a `DataGridView` control **intended primarily for display**. In this example, the visual appearance of the control is customized in several ways and **the control is configured for limited interactivity**. Observe these settings in the sample code: ``` // Set property values appropriate for read-only // display and limited interactivity dataGridView1.AllowUserToAddRows = false; dataGridView1.AllowUserToDeleteRows = false; dataGridView1.AllowUserToOrderColumns = true; dataGridView1.ReadOnly = true; dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView1.MultiSelect = false; dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None; dataGridView1.AllowUserToResizeColumns = false; dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing; dataGridView1.AllowUserToResizeRows = false; dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing; ```
728,925
Trying to install Windows 2012 R2 on a new ProLiant server using Intelligent Provisioning. Using SSA I created a RAID 5 array. IP wants to install the OS on the full drive, I want to create a 150GB partition to install the OS on and use the rest as a data volume. I can't find anywhere in IP either in tools or the OS install process where I can specify disk partitions. Am I missing something here? Thanks!
2015/10/14
[ "https://serverfault.com/questions/728925", "https://serverfault.com", "https://serverfault.com/users/81603/" ]
Use the **HP Smart Storage Administrator** utility from the Intelligent Provisioning "Maintenance" menu. Delete your logical drive. Create a Logical drive of the size and RAID level you wish. I don't recommend RAID5, but feel free to do that. Make the size 150GB. From there, create a new logical drive to fill the remaining space. *Now*, you can run your Intelligent Provisioning Windows installer and point it to the 150GB block device.
RAID5 is fine for SAS 10k/15k drives just not for SATA especially from HP with their terrible 1yr warranty policy (compared to DELL/Lenovo/manufacturer wrty). But, all that aside Intelligent provision is messed up in gen10 servers. So within the array mgmt software make the logical volume 150GB ish and then run the windows install. Then go back and expand the logical volume within the array software, just as if you had added a new drive and had finished the RAID5 expansion. Once the volume is expanded then windows will see the unallocated space and you can create a proper server with a separate data partition/volume. Hard to figure out what HP is thinking here!!!!
2,248,950
I have need to communicate between two iframes of the same domain, which live inside a parent page on a different domain that I have no control over. This is a Facebook app and the basic layout is this apps.facebook.com/myapp L iframe1 (src='mysite.com/foo') L iframe2 (src='mysite.com/bar') I need frame1 to talk to frame2, but in Opera I can't access window.parent.frames['frame2'] to do the usual cross-domain methods (updating location.hash for example) Is there an alternate way to accomplish this in Opera? Thanks for your help in advance
2010/02/12
[ "https://Stackoverflow.com/questions/2248950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Did you try using [HTML5 web messaging](http://dev.opera.com/articles/view/window-postmessage-messagechannel/). It is quite well supported currently by recent versions of browsers. ``` iframe.contentWindow.postMessage('Your message','http://mysite.com'); ``` The `postMessage` property will need the origin `http://mysite.com`.
Generally no. Same Origin Policy denies you the possibility of communicating upwards to the parent, which would be necessary to then step downwards to the other frame. This is true in any browser. If the parent document has given your frame-to-be-contacted a unique `name`, there is a limited form of communication possible with it by getting the user to click a link with `href="otherurl#message" target="name"`, which will navigate the target frame by changing the hash without reloading the page, as long as the URL matches exactly. In Mozilla you can also do this with a `form target`, allowing you to script its submission (since link clicking cannot be automated), but not in Opera. Probably not much use... don't know if FB gives you a frame target `name` in any case. You can make a communication channel between scripts in the same domain by using cookies(\*): one script writes a session cookie, the other script polls for changes to `document.cookie` to find messages in it. But it's super-ugly and requires some annoying work to control signalling which messages are meant for whom when there are multiple documents open simultaneously. And there are further limitations for cookies in third-party frames (you will probably need to write a P3P policy to get IE to co-operate). (\*: or, presumably, HTML5 web storage, where available.)
2,248,950
I have need to communicate between two iframes of the same domain, which live inside a parent page on a different domain that I have no control over. This is a Facebook app and the basic layout is this apps.facebook.com/myapp L iframe1 (src='mysite.com/foo') L iframe2 (src='mysite.com/bar') I need frame1 to talk to frame2, but in Opera I can't access window.parent.frames['frame2'] to do the usual cross-domain methods (updating location.hash for example) Is there an alternate way to accomplish this in Opera? Thanks for your help in advance
2010/02/12
[ "https://Stackoverflow.com/questions/2248950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Did you try using [HTML5 web messaging](http://dev.opera.com/articles/view/window-postmessage-messagechannel/). It is quite well supported currently by recent versions of browsers. ``` iframe.contentWindow.postMessage('Your message','http://mysite.com'); ``` The `postMessage` property will need the origin `http://mysite.com`.
As others have said, use `window.postMessage`. But instead of using `window.parent.frames['frame2']`, try `window.parent.frames[x]` where *x* is the position in the node list of the other iframe. You can see an example of doing this across origins here: <http://webinista.s3.amazonaws.com/postmessage>
264,873
Reading the blog of Sean Carroll (I recognize he isn't the only voice) has made me more sympathetic to the notion of many worlds, but reading Susskind (also not the only voice) has made me think that time-reversibility is important. I understand that collapse theories aren't reversible, but I've been wondering about the [MWI](http://en.wikipedia.org/wiki/Many-worlds_interpretation). Does decoherence of worlds occur "backwards"? I'm trying to imagine this, and I'm coming up with weird mental images wherein several different quantum states cohere into the same one, but this doesn't really make sense and there doesn't seem to be any reason for it to occur. Yet if it doesn't occur, (it seems to me) that MWI is not time-symmetric as (it seems to me) it should be. Have a lot of other people thought about this before? What do they have to say? EDIT: Is this, and other reversibility concerns in QM, related to our other familiar asymmetry -- entropy? Or is that crazy?
2016/06/27
[ "https://physics.stackexchange.com/questions/264873", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/121846/" ]
Yes, the many-worlds interpretation is supposed to be time symmetric. Consider this toy example with a particle than can be in either of the states $\left|1\right\rangle$ or $\left|2\right\rangle$. Additionally, we denote the no particle state as $\left|0\right\rangle$. The particle gets emitted by our source $S$ that can be in its ground state $\left|S\_0\right\rangle$, in a state $\left|S\_1\right\rangle$ ready to emit a particle in state $\left|1\right\rangle$ or in a state $\left|S\_2\right\rangle$ ready to emit a particle in state $\left|2\right\rangle$. Eventually, the particle gets absorbed by a detector $D$ that can be in its ground state $\left|D\_0\right\rangle$, in a state $\left|D\_1\right\rangle$ after absorption of a particle in state $\left|1\right\rangle$ or in a state $\left|D\_2\right\rangle$ after absorption of a particle in state $\left|2\right\rangle$. Let the time evolution of the states of interest be given by the discrete steps $$ \left|S\_1\right\rangle\otimes\left|0\right\rangle\otimes\left|D\_0\right\rangle \longrightarrow \left|S\_0\right\rangle\otimes\left|1\right\rangle\otimes\left|D\_0\right\rangle \longrightarrow \left|S\_0\right\rangle\otimes\left|0\right\rangle\otimes\left|D\_1\right\rangle $$ and $$ \left|S\_2\right\rangle\otimes\left|0\right\rangle\otimes\left|D\_0\right\rangle \longrightarrow \left|S\_0\right\rangle\otimes\left|2\right\rangle\otimes\left|D\_0\right\rangle \longrightarrow \left|S\_0\right\rangle\otimes\left|0\right\rangle\otimes\left|D\_2\right\rangle $$ Note that this is not how unitary time evolution works in quantum mechanics, and I'll get back to that at the end. So, what happens if we start out in a state $\left|S\_1\right\rangle + \left|S\_2\right\rangle$?1 $$ \left(\left|S\_1\right\rangle+\left|S\_2\right\rangle\right)\otimes\left|0\right\rangle\otimes\left|D\_0\right\rangle \\\longrightarrow \left|S\_0\right\rangle\otimes\left(\left|1\right\rangle+\left|2\right\rangle\right)\otimes\left|D\_0\right\rangle \\\longrightarrow \left|S\_0\right\rangle\otimes\left|0\right\rangle\otimes\left(\left|D\_1\right\rangle+\left|D\_2\right\rangle\right) $$ This is symmetric in source and detector and time symmetry is manifest. However, in our subjective experience, we only ever see detectors in a state $\left|D\_1\right\rangle$ *or* $\left|D\_2\right\rangle$ - we have no concept of a detector in a superposition of states $\left|D\_1\right\rangle+\left|D\_2\right\rangle$, its pointer indicating two values simultaneously. Some people argue (or at the very least, have done so historically) that the state must have collapsed through one of the (non-unitary) physical processes $$ \left(\left|1\right\rangle+\left|2\right\rangle\right)\otimes\left|D\_0\right\rangle \longrightarrow \left|0\right\rangle\otimes\left|D\_1\right\rangle $$ or $$ \left(\left|1\right\rangle+\left|2\right\rangle\right)\otimes\left|D\_0\right\rangle \longrightarrow \left|0\right\rangle\otimes\left|D\_2\right\rangle $$ Others claim that the 'collapse' is merely apparent, a Bayesian update of our information about the world, and the quest for ways to achieve objective collapse is indicative of a fundamental misunderstanding of the nature of reality as revealed by modern physics. Proponents of the MWI argue that the most sensible resolution is to consider the observer (including their subjective state of mind) as intrinsically liked to $D$, ie we can consider the detector with its macroscopically distinct pointer states as a proxy for the relevant parts of the environment. The asymmetry arises because the observer was blind to the microscopic state of the source, but sensitive to the macroscopic state of the detector, and a time reversal would include a process of memory erasure. It should be noted that the toy model I presented is cheating, which is why I had deleted my answer: Emission and absorption are not just given by unitary time evolution like $$ U(t\_i, t\_f) \left( \left|S\_1\right\rangle\otimes\left|0\right\rangle \right) = \left|S\_0\right\rangle\otimes\left|1\right\rangle $$ Instead, we're dealing with stochastic processes (the source could in principle stay in its excited state indefinitely), and there's already a 'collapse' implied by the discrete time evolution of the toy model that was glossed over. However, I suspect the line of reasoning I presented here would make sense in a [consistent histories](https://en.wikipedia.org/wiki/Consistent_histories) approach to the many-worlds interpretation. For now, I'll leave the answer as-is - I'm not sure I can come up with a better one without a few sessions of late-night (or beer-fueled) philosophizing... --- 1 we ignore issues of phase and normalization
The MWI interprets quantum physics roughly as follows: 1. Everything everywhere and at all times evolves via Schrodinger's equation. 2. What constitutes physical reality, and is described by quantum physics, is not so much a set of things as a set of correlations. An example of item 2 here is given by entangled states. When a particle decay results in the death of a cat, for example, then the final situation is not one in which cat is alive or dead, but rather one in which there is a correlation between the state of the particle and the state of the cat, says MWI. This seems plausible at first, but in order to make it consistent one has to also solve the preferred basis problem and make sense of the concept of probability. I feel that since one has to solve the preferred basis problem anyway, one may as well say there is just one branch as say there are vast numbers of branches and all but one of them are irrelevant to our present and future experience. The latter claim does not sound like good physics to me. This makes MWI, for me, not a strong contender for a correct account of physics. But it is not easy to argue convincingly for either view in our present state of knowledge. The main thing in answer to your question is that in view of item (1) above, the MWI interpretation is time-reversible. (I can't resist adding that I personally don't think the physical universe is time-reversible, so to me this is a major weakness of MWI, but I don't have a sufficiently persuasive model to resolve this debate.) If one takes some physical process and runs it backwards, then we get weird things such as broken eggs coming back together and leaping off the floor. But any view of physics should conclude that time running backwards is weird, simply because it genuinely would be weird as soon as processes of sufficient complexity are involved. So it is ok that the MWI suggests very odd things would happen if we applied a time-reversal to the dynamics of the universe. The MWI interpretation would account for the odd observations in the same way that classical physics would account for reducing entropy in a time-reversed dynamics: one would say there were many very special correlations in the conditions from which the time-reversed dynamics set out (the conditions which were final conditions really, but which we are turning into initial conditions in this thought-experiment).
34,293,165
I have oracle user defined types and tables which has these types as columns. I am trying to insert simple data into a table that has user defined type column. But i get invalid identifier error. I found a way to insert successfully. But i need simple method for this. Or maybe i did something wrong while creating the table at the beginning. ``` CREATE OR REPLACE TYPE SCHEMA.A_TYPE as object ( column1 varchar2(4), column2 varchar2(5) ) create table SCHEMA.TABLE1 ( recordid NUMBER, typedata SCHEMA.A_TYPE ); ``` First i try to insert like ``` insert schema.table1(recordid, typedata.column1, typedata.column2) values (1, 'aaaa', 'bbbbb'); ``` But i get invalid identifier for typedata.column1, typedata.column2 column names. Then i insert like ``` declare v_type schema.a_type := new schema.a_type('aaaa', 'bbbbb'); begin insert into scheme.table1(recordid, typedata) values (1, v_type); commit; end; ``` But it is a problem for larger column size tables. Is there any way to solve this problem?
2015/12/15
[ "https://Stackoverflow.com/questions/34293165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5585923/" ]
You can use syntax similar to the following: ``` insert into schema.table1(recordid, typedata) values ( 1, schema.a_type('aaaa','bbbbb')); ``` The thing to remember is that to insert the object type data you need to use the object constructor. You can extend that to other forms of the insert statement as well: ``` insert into schema.table1(recordid, typedata) select rownum, schema.a_type(owner, object_name) from all_objects where length(owner) <=4 and length(object_name) <= 5; ```
I have created an example for: * create multi level user defined types * insert into a table with these types * how to find the path for the attributes of types * select without variable * you can find a picture attached with the structure of the types. --- ``` create or replace type place_type as object (city varchar2(20), street varchar2(20)); create or replace type birth_type as object (birth_place place_type, zipcode number); create or replace type name_type as object (fi_name varchar2(20), la_name varchar2(20)); create table customer_x (birth_info birth_type, cust_name name_type); INSERT INTO customer_x VALUES (birth_type(place_type('London', 'Magic Str.'), 5400), name_type('Henry', 'Big')); select * from customer_x ``` ```html <table style="width:70%"> <tr> <td><b>BIRTH_INFO<b></td> <td><b>CUST_NAME<b></td> </tr> <tr> <td>[SCHEMA1.BIRTH_TYPE]</td> <td>[SCHEMA1.NAME_TYPE]</td> </tr> </table> ``` To find the current values of the columns use the table *USER\_TYPE\_ATTR* ``` select type_name, attr_name, attr_type_name from user_type_attrs where type_name = 'BIRTH_TYPE' ``` ```html <table style="width:70%"> <tr> <td><b>TYPE_NAME<b></td> <td><b>ATTR_NAME<b></td> <td><b>ATTR_TYPE_NAME<b></td> <tr> <td>BIRTH_TYPE</td> <td>ZIPCODE</td> <td>NUMBER</td> </tr> <tr> <td>BIRTH_TYPE</td> <td>BIRTH_PLACE</td> <td>PLACE_TYPE</td> </tr> </table> ``` Let’s find the type PLACE\_TYPE: ``` select type_name, attr_name, attr_type_name from user_type_attrs where type_name = 'PLACE_TYPE' ``` ```html <table style="width:70%"> <tr> <td><b>TYPE_NAME<b></td> <td><b>ATTR_NAME<b></td> <td><b>ATTR_TYPE_NAME<b></td> </tr> <tr> <td>PLACE_TYPE</td> <td>CITY</td> <td>VARCHAR2</td> </tr> </tr> <td>PLACE_TYPE</td> <td>STREET</td> <td>VARCHAR2</td> </tr> </table> ``` So the correct path is: ``` select a.birth_info.birth_place.city from customer_x a ``` [enter image description here](https://i.stack.imgur.com/c6OiB.png)
29,468,656
I'm new to Yii2 Framework and just configured Yii2 Advance application. Now I want to configure [adminLTE](http://almsaeedstudio.com/AdminLTE/) theme in my Yii2 Advance application without using the Composer. Somehow Composer is not getting installed on my machine. Ref: <http://www.yiiframework.com/wiki/729/tutorial-about-how-to-integrate-yii2-with-fantastic-theme-adminlte/>
2015/04/06
[ "https://Stackoverflow.com/questions/29468656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1197047/" ]
1) Go to <https://github.com/almasaeed2010/AdminLTE/releases> and download last version. 2) Create folder `bower` in `vendor` path. And in `bower` create new folder `admin-lte` again. 3) Extract archive from first step to `/vendor/bower/admin-lte`. 4) Change your `AppAsset` (it is location in `backend/assets` folder) and add this code: ``` class AppAsset extends AssetBundle { public $sourcePath = '@bower/'; public $css = ['admin-lte/dist/css/AdminLTE.css']; public $js = ['admin-lte/dist/js/AdminLTE/app.js']; public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', 'yii\bootstrap\BootstrapPluginAsset', ]; } ```
Embeding admin lte theme i yii2 basic 1) create yii project using composer sudo du cd /var/www/html composer create-project yiisoft/yii2-app-basic basic 2.0.4 2)now create it accessible chmod 777 -R project name 3) download admin lte theme by using git clone <https://github.com/bmsrox/baseapp-yii2basic-adminlte.git> copy and past all file to your basic root folder 4) now update composer composer update if token error then create account in git and create token in setting tab by clicking genarate new token copy and provide it to composer 5) update your web.php file in config ``` <?php $params = require(__DIR__ . '/params.php'); $config = [ 'id' => 'basic', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'layout'=>'column2', 'layoutPath'=>'@app/themes/adminLTE/layouts', 'components' => [ 'urlManager' => [ 'class' => 'yii\web\UrlManager', 'enablePrettyUrl' => true, 'showScriptName' => false, 'rules' => [ ''=>'site/index', '<action:(index|login|logout)>'=>'site/<action>', '<controller:\w+>/<id:\d+>' => '<controller>/view', '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>', '<controller:\w+>/<action:\w+>' => '<controller>/<action>' ], ], 'view' => [ 'theme' => [ 'pathMap' => ['@app/views' => '@app/themes/adminLTE'], 'baseUrl' => '@web/../themes/adminLTE', ], ], 'request' => [ // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation 'cookieValidationKey' => 'n0VkMX1RmIa_ovJmwR3Gn_hdZyQ7SyKe', ], 'cache' => [ 'class' => 'yii\caching\FileCache', ], 'user' => [ 'identityClass' => 'app\models\User', 'enableAutoLogin' => true, ], 'errorHandler' => [ 'errorAction' => 'site/error', ], 'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', // send all mails to a file by default. You have to set // 'useFileTransport' to false and configure a transport // for the mailer to send real emails. 'useFileTransport' => true, ], 'log' => [ 'traceLevel' => YII_DEBUG ? 3 : 0, 'targets' => [ [ 'class' => 'yii\log\FileTarget', 'levels' => ['error', 'warning'], ], ], ], 'db' => require(__DIR__ . '/db.php'), ], 'params' => $params, ]; if (YII_ENV_DEV) { // configuration adjustments for 'dev' environment $config['bootstrap'][] = 'debug'; $config['modules']['debug'] = 'yii\debug\Module'; $config['bootstrap'][] = 'gii'; //$config['modules']['gii'] = 'yii\gii\Module'; $config['modules']['gii'] = [ 'class' => 'yii\gii\Module', 'generators' => [ //here 'crud' => [ // generator name 'class' => 'yii\gii\generators\crud\Generator', // generator class 'templates' => [ //setting for out templates 'custom' => '@vendor/bmsrox/yii-adminlte-crud-template', // template name => path to template ] ] ], ]; } return $config; ``` 6) update SiteController. Php in controller folder replace actionLogout with following code ``` public function actionLogout() { Yii::$app->user->logout(); return $this->redirect(Yii::$app->user->loginUrl); } public function beforeAction($action) { if (parent::beforeAction($action)) { // change layout for error action if ($action->id=='login') $this->layout = 'login'; return true; } else { return false; } } ``` 7) if misconfiguration error then update apche2 by using command a2enmod rewrite and restrart apache using service apache2 restart finished........... best of luck
23,285,753
In one of MVA videos i saw next construction: ``` static void Main(string[] args) { Action testAction = async () => { Console.WriteLine("In"); await Task.Delay(100); Console.WriteLine("After first delay"); await Task.Delay(100); Console.WriteLine("After second delay"); }; testAction.Invoke(); } ``` Result of execution will be: ``` In Press any key to continue . . . ``` It's perfectly compiles, but right now i don't see any way to await it. I might put `Thread.Sleep` or `Console.ReadKey` after invocation, but that's not what i want. So how this delegate should be modified to become awaitable?(or at least how can i track that execution completed?) Is there are any practical usage of such delegates?
2014/04/25
[ "https://Stackoverflow.com/questions/23285753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1017161/" ]
In order for something to be awaited, it has to be **awaitable**. As `void` is not so, you cannot await on any `Action` delegate. An awaitable is any type that implements a `GetAwaiter` method, which returns a type that implements either `INotifyCompletion` or `ICriticalNotifyCompletion`, like `Task` and `Task<T>`, for example. If you want to wait on a delegate, use `Func<Task>`, which is an equivalent to a named method with the following signature: ``` public Task Func() ``` So, in order to await, change your method to: ``` static void Main(string[] args) { Func<Task> testFunc = async () => { Console.WriteLine("In"); await Task.Delay(100); Console.WriteLine("First delay"); await Task.Delay(100); Console.WriteLine("Second delay"); }; } ``` And now you can await it: ``` await testFunc(); ```
"Async void is for top-level event-handlers only", <https://learn.microsoft.com/en-us/shows/three-essential-tips-for-async/tip-1-async-void-top-level-event-handlers-only>
23,285,753
In one of MVA videos i saw next construction: ``` static void Main(string[] args) { Action testAction = async () => { Console.WriteLine("In"); await Task.Delay(100); Console.WriteLine("After first delay"); await Task.Delay(100); Console.WriteLine("After second delay"); }; testAction.Invoke(); } ``` Result of execution will be: ``` In Press any key to continue . . . ``` It's perfectly compiles, but right now i don't see any way to await it. I might put `Thread.Sleep` or `Console.ReadKey` after invocation, but that's not what i want. So how this delegate should be modified to become awaitable?(or at least how can i track that execution completed?) Is there are any practical usage of such delegates?
2014/04/25
[ "https://Stackoverflow.com/questions/23285753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1017161/" ]
"Async void is for top-level event-handlers only", <https://learn.microsoft.com/en-us/shows/three-essential-tips-for-async/tip-1-async-void-top-level-event-handlers-only>
Recently I found that NUnit able to `await` `async void`tests. Here is good description how it works: [How does nunit successfully wait for async void methods to complete?](https://stackoverflow.com/questions/15031681/how-does-nunit-successfully-wait-for-async-void-methods-to-complete) You won't use it in regular tasks, but it's good to know that it is possible
23,285,753
In one of MVA videos i saw next construction: ``` static void Main(string[] args) { Action testAction = async () => { Console.WriteLine("In"); await Task.Delay(100); Console.WriteLine("After first delay"); await Task.Delay(100); Console.WriteLine("After second delay"); }; testAction.Invoke(); } ``` Result of execution will be: ``` In Press any key to continue . . . ``` It's perfectly compiles, but right now i don't see any way to await it. I might put `Thread.Sleep` or `Console.ReadKey` after invocation, but that's not what i want. So how this delegate should be modified to become awaitable?(or at least how can i track that execution completed?) Is there are any practical usage of such delegates?
2014/04/25
[ "https://Stackoverflow.com/questions/23285753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1017161/" ]
In order for something to be awaited, it has to be **awaitable**. As `void` is not so, you cannot await on any `Action` delegate. An awaitable is any type that implements a `GetAwaiter` method, which returns a type that implements either `INotifyCompletion` or `ICriticalNotifyCompletion`, like `Task` and `Task<T>`, for example. If you want to wait on a delegate, use `Func<Task>`, which is an equivalent to a named method with the following signature: ``` public Task Func() ``` So, in order to await, change your method to: ``` static void Main(string[] args) { Func<Task> testFunc = async () => { Console.WriteLine("In"); await Task.Delay(100); Console.WriteLine("First delay"); await Task.Delay(100); Console.WriteLine("Second delay"); }; } ``` And now you can await it: ``` await testFunc(); ```
Recently I found that NUnit able to `await` `async void`tests. Here is good description how it works: [How does nunit successfully wait for async void methods to complete?](https://stackoverflow.com/questions/15031681/how-does-nunit-successfully-wait-for-async-void-methods-to-complete) You won't use it in regular tasks, but it's good to know that it is possible
27,226,606
I have a scenario where I need to construct a powershell path as `$RemotePath = '$($env:USERPROFILE)\Desktop\Shell.lnk'`. This variable gets passed to a remote machine where it needs to be executed. The remote machine receives this as a string variable. How do I expand the string to evaluate `$env:USERPROFILE`?
2014/12/01
[ "https://Stackoverflow.com/questions/27226606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/928228/" ]
[Expand the string](https://stackoverflow.com/a/4836913/1630171) on the remote side: ``` $ExecutionContext.InvokeCommand.ExpandString($RemotePath) ```
By using a double quotes. PowerShell won't expand variables inside single-quoted strings.
34,820,941
Am having a hard time trying to figure why I cannot get the images here to change color on hover. The images themselves are svg files and should just adopt the color. The code: HTML: ``` <div class="toolTile col-md-3"> <a href="#/cards"> <img src="ppt/assets/toolIcons/requestnewcard.svg" > <p>Manage my debit card</p> </a> </div> <div class="toolTile col-md-3"> <a href="#/recurClaim"> <img src="ppt/assets/toolIcons/recurring.svg" > <p>Recurring Claims</p> </a> </div> ``` And associated CSS: ``` .toolTile { height: 200px; float: left; } .toolTile img { color: #ab2328; height: 100px; width: 93px; margin-left: auto; margin-right: auto; display: block; } .toolTile img:hover { color: yellow; } ```
2016/01/15
[ "https://Stackoverflow.com/questions/34820941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1840365/" ]
I'm speaking for Linux here, not sure about Windows. Environment variables don't work that way. They are a part of the process (which is what you modify by changing os.environ), and they will propagate to child processes of your process (and their children obviously). They are in-memory only, and there is no way to "set and persist" them directly. There are however several configuration files which allow you to set the environment on a more granular basis. These are read by various processes, and can be system-wide, specific to a user, specific to a shell, to a particular type of process etc. Some of them are: * /etc/environment for system-wide variables * /etc/profile for shells (and their children) * Several other shell-specific files in /etc * Various dot-files in a user's home directory such as .profile, .bashrc, .bash\_profile, .tcshrc and so on. Read your shell's documentation. * I believe that there are also various ways to configure environment variables launched from GUIs (e.g. from the gnome panel or something like that). Most of the time you'll want to set environment variables for the current user only. If you only care about shells, append them to ~/.profile in this format: `NAME="VALUE"`
The standard way to 'persist' an environment variable is with a configuration file. Write your application to open the configuration file and set every NAME=VARIABLE pair that it finds. Optionally this step could be done in a wrapper startup script. If you wish to 'save' the state of a variable, you need to open the configuration file and modify its contents. Then when it's read in again, your application will set the environment accordingly. You could of course store the configuration in some other way. For example in a configuration\_settings class that you pickle/shelve. Then on program startup you read in the pickled class and set the environment. The important thing to understand is that **when a process exits its environment is not saved**. Environments are inherited from the parent process as an intentional byproduct of forking. Config file could look like: ``` NAME=VALUE NAME2=VALUE2 ... ``` Or your config class could look like: ``` class Configuration(): env_vars = {} import os def set(name, val): env_vars[name] = val os.environ[name] = val def unset(name): del env_vars[name] del os.environ[name] def init(): for name in env_vars: os.environ[name] = env_vars[name] ``` Somewhere else in our application ``` import shelve filename = "config.db" d = shelve.open(filename) # get our configuration out of shelve config = d['configuration'] # initialize environment config.init() # setting an environment variable config.set("MY_VARIABLE", "TRUE") #unsetting config.unset("MY_VARIABLE") # save our configuration d['configuration'] = config ``` Code is not tested but I think you get the jist.
48,769,880
I want to use the `for` loops with iterators while using maps and want to run it for a specified range not from `begin()` end `end()`. I would want to use it for a range like from 3rd element to 5th element
2018/02/13
[ "https://Stackoverflow.com/questions/48769880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9145917/" ]
> > I would want to use it for a range like from 3rd element to 5th > element > > > Since `std::map`'s iterator is not a `RandomAccessIterator`, but only a `BidirectionalIterator` (you cannot write `.begin() + 3`), you can use `std::next` for this purpose: ``` for (auto it = std::next(m.begin(), 2); it != std::next(m.begin(), 5); ++it) { // ... } ``` --- And remember - check your ranges to ensure, that you iterate over a valid scope.
This code should be pretty optimal and safe for corner cases: ``` int count = 0; for( auto it = m.begin(); it != m.end(); ++it ) { if( ++count <= 3 ) continue; if( count > 5 ) break; // use iterator } ``` but the fact you are iterating an `std::map` this way shows most probably you are using a wrong container (or your logic for 3rd to 5th element is wrong)
214,948
I am using either a chromium or firefox web browser in kiosk mode to log in to a website from boot up, and I want to use a javascript to send in a command to login to a website automatically. I know how to write the javascript, but I do not know how to "pipe" the javascript into the web browser from a terminal bash file. Also, I am working in Linux.
2015/07/09
[ "https://unix.stackexchange.com/questions/214948", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/119638/" ]
In OS X you can use AppleScript to run JavaScript in Chrome: `xj(){ osascript -e'on run{a}' -e'tell app"google chrome"to tell active tab of window 1 to execute javascript a' -eend "$1"; }` Firefox does not support AppleScript.
I am not sure Firefox is capable of doing what you want here even though there are [lots of command line options](https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options#-app_.2Fpath.2Fto.2Fapplication.ini) for launching Firefox from a script. Chrome has [even more options](http://peter.sh/experiments/chromium-command-line-switches/) and may be able to pull off executing javascript from a local source, but I doubt it. If you could somehow pass javascript in through the developer console then you could definitely execute arbitrary code in a web browser session (i.e. an automated login or what not). A Hack ------ Since you can definitely specify a starting url from a script for both browsers, perhaps the following will work 1: 1. Write a script that automatically navigates to the web page that you want to login to and completes the login process, (i.e. `POST` the login form, whatever). 2. Save this file to your disk and make sure that the user can read it. 3. Launch Firefox and point it to this file: ``` ./firefox -url "file:///home/thisUser/desktop/foo.html" ``` I am not sure that the url scheme `file:///` will work in all situations but I did test it on OSX. This should load the file and try to render the content. The `file:///` thing is just a way not to have to run a web server on localhost, but that could work too. You might run into XSS problems or other obstacles to doing a remote login so you may have to revert to a server side script and just point the browser at a `localhost` web server. Best of luck! 1 I haven't tested this all the way just tossing out an idea.
130,842
When interviewing with a company where all the interviewers have lower educational backgrounds from lower ranking schools than the interviewee, should the interviewee appear modest, weaker and reserve (not show off) part of his/her repertoire? The reason behind is that employers might prefer hiring people less or as smart people as they are, or those who don't look too different from themselves. As the saying goes, those who are neither the smartest nor too bad get a job.
2019/03/05
[ "https://workplace.stackexchange.com/questions/130842", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/100877/" ]
The candidate should behave reasonably, regardless of the interviewers. Think about this: how should Einstein behave during a job interview? Of course, almost everybody on Earth would look stupid by comparison, regardless of University degrees. By "reasonably" I mean: * be polite and civilized; * answer the answers as truthfully as possible, while selling yourself in the best way possible; * do not boast about yourself; * let the interviewers deal with what / who they want to hire for the job they have to offer.
Copying the manners of the people you are talking to is actually a pretty neat psychological trick to make yourself appear more likeable. People generally like people more when they are similar to them. This is called [mirroring](https://en.wikipedia.org/wiki/Mirroring_(psychology)). And besides, nobody likes arrogant know-it-alls. Talking in a way which is appropriate to the audience is an important social skill. But keep a few things in mind: * Using psychological tricks to your advantage raises ethical problems. You are literally manipulating people into liking you. * They might know that trick and realize you are trying to pull it off, which would be a red flag. * They might actually be consciously looking for someone who is smarter than they are (or as smart as they think they are). Remember the job description and consider what kind of person they are likely looking for. * If you have to "play dumb" in the interview in order to get the job, you will have to to "play dump" for the rest of the time you are working there. Do you really want to keep up this charade? Or wouldn't you be more comfortable working for someone who accepts you the way you really are?
130,842
When interviewing with a company where all the interviewers have lower educational backgrounds from lower ranking schools than the interviewee, should the interviewee appear modest, weaker and reserve (not show off) part of his/her repertoire? The reason behind is that employers might prefer hiring people less or as smart people as they are, or those who don't look too different from themselves. As the saying goes, those who are neither the smartest nor too bad get a job.
2019/03/05
[ "https://workplace.stackexchange.com/questions/130842", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/100877/" ]
Here's something you probably haven't realized yet: 1 year in the workforce is equivalent to about 3 years in college. You divide your attention in college. You are given problems that the answers to are already known (unless you're pursuing doctoral / PHD degrees), and there is far less "on the line" than in a real job. The one advantage "good schools" have is a lifelong network of other graduates that you share a connection with. That person who's been working 5 years from "Average Joe Tech" knows as much, if not more than any high-end bachelor's degree holder, and he knows more about what is needed in that situation than ANY applicant could possible glean from a job description. So you go in there with your best shot, but you go in there understanding that they need you to fit the job, and they're not going to make the job fit you. I've hired good and bad graduates with "top school degrees," but I've also hired a fair number of people with no or unrelated degrees who turned into phenomenal individual contributors.
While you don't want to appear arrogant or a "show-off" there's no reason to appear weaker or less intelligent/capable then you actually are. I *always* want to hire the best person for the job, regardless of their relative intelligence vis a vis myself, in fact hiring people smarter than yourself is what we call "good management".
130,842
When interviewing with a company where all the interviewers have lower educational backgrounds from lower ranking schools than the interviewee, should the interviewee appear modest, weaker and reserve (not show off) part of his/her repertoire? The reason behind is that employers might prefer hiring people less or as smart people as they are, or those who don't look too different from themselves. As the saying goes, those who are neither the smartest nor too bad get a job.
2019/03/05
[ "https://workplace.stackexchange.com/questions/130842", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/100877/" ]
Other answers have pointed out that the educational background detail is loaded with naive assumptions, but putting that aside and addressing your core question: Should you purposefully make yourself appear less capable in order to get hired somewhere where you suspect your hiring manager(s) *won't* hire somebody more capable than they are? Unless you have a *really* compelling reason to want to get hired for this particular organisation / role, if you suspect this is the case you're better off walking away. Managers not hiring people more capable than them is a huge red flag that the team / organisation's culture is not a good one. Both your immediate day-to-day and longer term career growth prospects will likely be much worse in such a culture than in one where managers are simply looking to hire the best people they can find, at all levels. If you are confident in your abilities, as you seem to be, you likely have other, better options. If you even have to ask this question going into an interview, it's a signal you should just decline it and look elsewhere.
> > As the saying goes, those who are neither the smartest nor too bad get > a job. > > > Where does that saying come from? I've never heard it. I've never seen anyone acting according to it. Now it is of course possible that someone is very smart but has problems that make them hard to employ, but in general the smartest person has definitely an advantage to everyone else.
130,842
When interviewing with a company where all the interviewers have lower educational backgrounds from lower ranking schools than the interviewee, should the interviewee appear modest, weaker and reserve (not show off) part of his/her repertoire? The reason behind is that employers might prefer hiring people less or as smart people as they are, or those who don't look too different from themselves. As the saying goes, those who are neither the smartest nor too bad get a job.
2019/03/05
[ "https://workplace.stackexchange.com/questions/130842", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/100877/" ]
Sell yourself as who you are. No more, no less, because your actual credentials will come out during the course of employment. If you misled the people you will be working with, you will not do well on the job.
I have seen the hiring process quite a few times from both sides (first hand and second hand). In general you don't need to worry about appearing too smart/capable, as long as it avoids rubbing people the wrong way on a personal level. If you appear arrogant, or completely unable to connect with the people that are hiring you that is bad, but otherwise you should be good. The real reason that I have seen people not get hired is because they are 'overqualified'. Note that intelligence is only a small part in this, as experience and extreme ambition count heavily as well. **If you get a candidate that will be bored with the challenges the job presents, or dissatisfied with the career possibilities, then you would often not choose them as you know you will have to start hiring again in no time.** The good news is, that unless you are purposely and covertly looking for a job for a short time, you should also not *want* to get hired in such a position. Hence my conclusion: In most cases showing your capabilities in a positive way, will result in the best OUTCOME for all involved. ============================================================================================================ Whether it results in you getting hired or not!
130,842
When interviewing with a company where all the interviewers have lower educational backgrounds from lower ranking schools than the interviewee, should the interviewee appear modest, weaker and reserve (not show off) part of his/her repertoire? The reason behind is that employers might prefer hiring people less or as smart people as they are, or those who don't look too different from themselves. As the saying goes, those who are neither the smartest nor too bad get a job.
2019/03/05
[ "https://workplace.stackexchange.com/questions/130842", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/100877/" ]
The candidate should behave reasonably, regardless of the interviewers. Think about this: how should Einstein behave during a job interview? Of course, almost everybody on Earth would look stupid by comparison, regardless of University degrees. By "reasonably" I mean: * be polite and civilized; * answer the answers as truthfully as possible, while selling yourself in the best way possible; * do not boast about yourself; * let the interviewers deal with what / who they want to hire for the job they have to offer.
> > As the saying goes, those who are neither the smartest nor too bad get > a job. > > > Where does that saying come from? I've never heard it. I've never seen anyone acting according to it. Now it is of course possible that someone is very smart but has problems that make them hard to employ, but in general the smartest person has definitely an advantage to everyone else.
130,842
When interviewing with a company where all the interviewers have lower educational backgrounds from lower ranking schools than the interviewee, should the interviewee appear modest, weaker and reserve (not show off) part of his/her repertoire? The reason behind is that employers might prefer hiring people less or as smart people as they are, or those who don't look too different from themselves. As the saying goes, those who are neither the smartest nor too bad get a job.
2019/03/05
[ "https://workplace.stackexchange.com/questions/130842", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/100877/" ]
A good life lesson is, **don't make assumptions.** I'm saying this because **your question is rife with them:** * You're assuming that you know the educational background of everyone at the table. * You're assuming that educational background is an indicator of smartness. * You're assuming that the person who appears the smartest doesn't get the job (your last sentence, which references a saying I've never actually heard). * You're assuming the interviewer won't want to hire someone who appears smarter than them in the interview. * You're assuming that you're skilled enough at modesty that you would be able to "hide" your smarts from the interviewers at will, if you so choose. * You're assuming that "smartness" is an important factor in the interview process (versus, say, *skills* or *the ability to complete tasks* for instance). * You're assuming that the interviewers are all inherently comparing you to themselves (versus, say, comparing you to *other candidates* or *people currently performing that role* for the employer). Regardless of whether each of these are true or not (and I think there are strong arguments that they're pretty much all patently false), **the biggest mistake you've made is making so many assumptions in the first place.** Every time you make an assumption about an interview, you run the risk of being wrong, and blowing the interview over something that could have been avoided. When preparing for an interview, you need to be able to show *actual worth* in terms of performing work. Instead of focusing on the appearance of smartness, *focus on the requirements of the job,* and your ability to practically show that you have the skills they're looking for. The good news is, by taking this approach, it's actually easy to prepare for an interview. **The employer has given you a template of what they're looking for** (the job description), so *you don't need to make assumptions.* If you go in to an interview ready to show how you match that template, you'll do well.
The candidate should behave reasonably, regardless of the interviewers. Think about this: how should Einstein behave during a job interview? Of course, almost everybody on Earth would look stupid by comparison, regardless of University degrees. By "reasonably" I mean: * be polite and civilized; * answer the answers as truthfully as possible, while selling yourself in the best way possible; * do not boast about yourself; * let the interviewers deal with what / who they want to hire for the job they have to offer.
130,842
When interviewing with a company where all the interviewers have lower educational backgrounds from lower ranking schools than the interviewee, should the interviewee appear modest, weaker and reserve (not show off) part of his/her repertoire? The reason behind is that employers might prefer hiring people less or as smart people as they are, or those who don't look too different from themselves. As the saying goes, those who are neither the smartest nor too bad get a job.
2019/03/05
[ "https://workplace.stackexchange.com/questions/130842", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/100877/" ]
Here's something you probably haven't realized yet: 1 year in the workforce is equivalent to about 3 years in college. You divide your attention in college. You are given problems that the answers to are already known (unless you're pursuing doctoral / PHD degrees), and there is far less "on the line" than in a real job. The one advantage "good schools" have is a lifelong network of other graduates that you share a connection with. That person who's been working 5 years from "Average Joe Tech" knows as much, if not more than any high-end bachelor's degree holder, and he knows more about what is needed in that situation than ANY applicant could possible glean from a job description. So you go in there with your best shot, but you go in there understanding that they need you to fit the job, and they're not going to make the job fit you. I've hired good and bad graduates with "top school degrees," but I've also hired a fair number of people with no or unrelated degrees who turned into phenomenal individual contributors.
> > As the saying goes, those who are neither the smartest nor too bad get > a job. > > > Where does that saying come from? I've never heard it. I've never seen anyone acting according to it. Now it is of course possible that someone is very smart but has problems that make them hard to employ, but in general the smartest person has definitely an advantage to everyone else.
130,842
When interviewing with a company where all the interviewers have lower educational backgrounds from lower ranking schools than the interviewee, should the interviewee appear modest, weaker and reserve (not show off) part of his/her repertoire? The reason behind is that employers might prefer hiring people less or as smart people as they are, or those who don't look too different from themselves. As the saying goes, those who are neither the smartest nor too bad get a job.
2019/03/05
[ "https://workplace.stackexchange.com/questions/130842", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/100877/" ]
The candidate should behave reasonably, regardless of the interviewers. Think about this: how should Einstein behave during a job interview? Of course, almost everybody on Earth would look stupid by comparison, regardless of University degrees. By "reasonably" I mean: * be polite and civilized; * answer the answers as truthfully as possible, while selling yourself in the best way possible; * do not boast about yourself; * let the interviewers deal with what / who they want to hire for the job they have to offer.
I agree that employers might prefer hiring people less or as smart people as they are. *I think that the answer depends on what **really** you want.* Are you over-educated for that job? And, despite this, do you really want that job? I have been in this situation, and I tried to reserve part of my repertoire. But, after getting the job, I recognized the mismatch. The employer also recognized the mismatch. And I had to find a new job. After making the same error twice, now I am in a position when my reportoire is appreciated in full. To sum up: if you reserve your repertoire maybe you get the work. But it won't last.
130,842
When interviewing with a company where all the interviewers have lower educational backgrounds from lower ranking schools than the interviewee, should the interviewee appear modest, weaker and reserve (not show off) part of his/her repertoire? The reason behind is that employers might prefer hiring people less or as smart people as they are, or those who don't look too different from themselves. As the saying goes, those who are neither the smartest nor too bad get a job.
2019/03/05
[ "https://workplace.stackexchange.com/questions/130842", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/100877/" ]
A good life lesson is, **don't make assumptions.** I'm saying this because **your question is rife with them:** * You're assuming that you know the educational background of everyone at the table. * You're assuming that educational background is an indicator of smartness. * You're assuming that the person who appears the smartest doesn't get the job (your last sentence, which references a saying I've never actually heard). * You're assuming the interviewer won't want to hire someone who appears smarter than them in the interview. * You're assuming that you're skilled enough at modesty that you would be able to "hide" your smarts from the interviewers at will, if you so choose. * You're assuming that "smartness" is an important factor in the interview process (versus, say, *skills* or *the ability to complete tasks* for instance). * You're assuming that the interviewers are all inherently comparing you to themselves (versus, say, comparing you to *other candidates* or *people currently performing that role* for the employer). Regardless of whether each of these are true or not (and I think there are strong arguments that they're pretty much all patently false), **the biggest mistake you've made is making so many assumptions in the first place.** Every time you make an assumption about an interview, you run the risk of being wrong, and blowing the interview over something that could have been avoided. When preparing for an interview, you need to be able to show *actual worth* in terms of performing work. Instead of focusing on the appearance of smartness, *focus on the requirements of the job,* and your ability to practically show that you have the skills they're looking for. The good news is, by taking this approach, it's actually easy to prepare for an interview. **The employer has given you a template of what they're looking for** (the job description), so *you don't need to make assumptions.* If you go in to an interview ready to show how you match that template, you'll do well.
Sell yourself as who you are. No more, no less, because your actual credentials will come out during the course of employment. If you misled the people you will be working with, you will not do well on the job.
130,842
When interviewing with a company where all the interviewers have lower educational backgrounds from lower ranking schools than the interviewee, should the interviewee appear modest, weaker and reserve (not show off) part of his/her repertoire? The reason behind is that employers might prefer hiring people less or as smart people as they are, or those who don't look too different from themselves. As the saying goes, those who are neither the smartest nor too bad get a job.
2019/03/05
[ "https://workplace.stackexchange.com/questions/130842", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/100877/" ]
> > *When interviewing with a company where all the interviewers have lower educational backgrounds from lower ranking schools than the interviewee,* > > > Wait, hang on. While this is a common assumption that reputed schools produce good grades, it does not necessarily imply that the second or third-tier schools are of lower grade. Moreover, it's not only the formal education that matters, there are many proficient engineers you'll meet who are self-taught (up to a very great extent). Some may not have a prestigious alma mater, but they may certainly have brilliant on-job work experience and learning. > > *The reason behind is that employers might prefer hiring people less or as smart people as they are.* > > > That's almost never true, rather quite the opposite. If I'm hiring someone, I'd expect a smart and capable person, not a "weaker and reserve" one. To add, don't judge your interviewer by their background - in an interview, always give your best shot. --- Note 1: That said, when you say "**all** the interviewers have lower educational backgrounds...." - maybe you should be worried about the organization and their work, not the individuals. Note 2: ***Don't make assumptions.*** In case you **feel** that you need to underplay your abilities to get a job- ask yourself: "Is it worth it?". Even if you get the job by downplaying your abilities, you can be certain that you will have zero job satisfaction, working in that organization, as you would have to suppress your natural abilities and capabilities and skills to survive also. The scope for your career and personal growth will also be almost non-existent. So, don't bother about the interviewer's capabilities - they are not under your control. Focus on your capabilities to show the interviewer why you are the "best match" for the requirement they have. Leave the rest to them.
This question makes assumptions that are worth being picked apart in detail. First, if the company wanted to hire people stupider than themselves, and believed that the quality of school was a proxy for how smart the applicant is, and that the school on the transcript was a school smart people go to, ***they wouldn’t have brought the candidate in for an interview in the first place.*** Well managed companies typically want to hire people **who are smarter/better than the people already working there**, because they **need people to do work that they cannot already do**. If a company wants to hire people who are stupider than the people who work there out of some sort of inadequacy that normal adults grow out of after leaving school, then that is a company you should avoid working for. That would imply acting more smart, rather than less. But even then, **you shouldn’t try to “game” these aspects of interviewing**. You *don’t know* in advance what sort of preferences the interviewers have. You *don’t know* whether they want smart people or whether they want dumb people out of their own insecurity. You *don’t know* whether they want people who went to good schools or people who went to bad schools. You *don’t know* if they’re virtuous or vicious. Because you don’t know these these things, it’s hard to play a game to get them right. It’s hard to pretend. What you do know, is if you take an offer, you’re going *to have to work there for a time long enough that everyone is going to see through your pretending ability*. So, **don’t waste their time and yours pretending to be something that you are not**.
449,656
How can I move files from user account to another in OS X 10.6.8? Every time I attempt access another users contents eg images, music, and the like. It keeps telling I don't have permission to view the contents. What do I do to move the files from one user account to another?
2012/07/16
[ "https://superuser.com/questions/449656", "https://superuser.com", "https://superuser.com/users/19082/" ]
> > According to [Vintage Technology](http://www.vintage-technology.info/pages/calculators/keys/buttons.htm), both buttons are a way to clear or cancel an entry. The C button will clear all input to the calculator. The CE button clears the most recent entry, so if you make a mistake in a long computation, you don't need to start all over again. > > > [Source](http://ask.yahoo.com/20070314.html) Example ------- ![enter image description here](https://i.stack.imgur.com/HDEEp.png) If I now press the **CE** button, only the `5` is erased. The rest of my computation is still *stored*. ![enter image description here](https://i.stack.imgur.com/YYT4P.png) If I press the **C** button, my whole computation will be cleared: ![enter image description here](https://i.stack.imgur.com/NHqmi.png) History ------- One might ask why we have these specific keys on our Windows calculator? Why are they not labeled differently? Luckily, the guys over at [Vintage Calculators](http://www.vintagecalculators.com) have an amazing collection of information on the subject. According to their site, the first **electronic** calculator was released by [Bell Punch Co., Uxbridge, England in 1961](http://www.vintagecalculators.com/html/calculator_time-line.html). This were the **Anita Mk VII** and the **Anita Mk 8**. ### Anita Mk VII ![Anita Mk VII](https://i.stack.imgur.com/d9ayw.jpg) [Source](http://www.vintagecalculators.com/html/anita_mk_vii.html) ### Anita Mk 8 ![Anita Mk 8](https://i.stack.imgur.com/9lxgm.jpg) [Source](http://www.vintagecalculators.com/html/anita_mk_8.html) For the **Mk 8** we get an additional schema: ![Schema of the Anita Mk8](https://i.stack.imgur.com/TrYFX.jpg) [Source](http://www.vintagecalculators.com/html/anita_mk_8.html) We can see it has a **Clear Register** and **Clear Keyboard** button. Please keep in mind, to my knowledge, this is one of the first electronic calculators that was ever designed. The terminology was also used in later models, like the **Sanyo ICC-0081**, which seemed to have a **CK** (Clear Keyboard) and **CA** (Clear All) button. ![Sanyo ICC-0081](https://i.stack.imgur.com/Cihz8.jpg) [Source](http://www.vintagecalculators.com/html/sanyo_icc-0081_mini_calculator.html) Later models just continue the pattern. For example, the ### Canon Pocketronic ![Canon Pocketronic](https://i.stack.imgur.com/XUnOl.jpg) [Source](http://www.vintagecalculators.com/html/canon_pocketronic.html) We can see a **C** (Clear) and **CI** (Cancel Input) button.
CE means "Clear entry" it just clears the last number typed into the display C means "Clear" (more) It clears the display and any partial calculation. Example: you enter 25 + 3 If you hit CE, it erases the 3, but remembers you were adding something to 25. You can now enter 8 and =, and you'll see 33. If you hit C, it forgets the whole thing, and if you now enter 8 and =, you will see 8 still there. MC clears the separate value stored in memory, which is not affected by C or CE.
2,565,646
> > Let $f$ be defined by: > > > $f(x)= \frac{x-\lfloor x\rfloor}{\sqrt x}$ > > > 1. Prove that $f$ is bounded in $\mathbb{R+}$ > > > I have no idea where to start, I can see by graphing it [here (desmos)](https://www.desmos.com/calculator/6xrf5kqvhw) that it is bounded by $0$ and $1$, but here we are not presented with a graph.
2017/12/13
[ "https://math.stackexchange.com/questions/2565646", "https://math.stackexchange.com", "https://math.stackexchange.com/users/279667/" ]
Hints: * for all $\,x \in \mathbb{R}^+\,$ you have $0 \le x - \lfloor x \rfloor \lt 1\,$, so $\,0 \le f(x) \lt \frac{1}{\sqrt{x}}$ * for $x \in (0,1)\,$ you have $\,\lfloor x \rfloor = 0\,$, so $\;f(x) = \sqrt{x} \lt 1$
To prove that a function is bounded you need to **use inequalities**. Note that > > $$x\in(0,1) \quad f(x)= \frac{x-\lfloor x\rfloor}{\sqrt x}\leq\frac{1}{\sqrt x}$$ > > > $$\forall x\geq 0 \quad f(x)= \frac{x}{\sqrt x}={\sqrt x}\leq1$$ > > > $\implies$ $\forall x \in \mathbb{R^+}$ **f is bounded**.
899,159
My computer (a modern one, with Windows 8.1) is equipped with a DVD drive and a SD card reader. I'm considering assigning letters A and B to DVD and card reader. I know well that those letters **were** reserved for floppy disk drives (I'm old enough to remember the floppy disks era), but I am 99.99% sure that I will never use floppy disk drive. Is there any rational reason not to use A and B letters for DVD and card reader then? To be perfectly clear: I am not asking what is the story behind letters A and B - I know it already. I just want to know the consequences of assign A or B to drive that is not a real floppy drive.
2015/04/08
[ "https://superuser.com/questions/899159", "https://superuser.com", "https://superuser.com/users/-1/" ]
As @Fazer87 mentioned, it's perfectly OK to use these drive letters, and you can use Disk Manager to reassign them. There is one benefit to using these drive letters that is not commonly known and that may be useful in some circumstances. Generally Windows likes to assign the same drive letter to removable drives upon each insertion - e.g. if the drive was assigned to G last time, Windows will try to assign it to G the next time it's reinserted. This can be problematic if your removable drive contains programs or data that expect a certain drive letter mapping, and if your drive list changes from time to time. Your expected G mapping may become F or H (or something else). Since Windows *never* assigns drives to A or B unless you specifically direct it to, you can use these drive letters to map a removable drive with complete confidence that the drive letter mapping will be maintained over multiple removals and inserts.
There is nothing wrong with using A and B drive letters at all. I personally use A: and B: on my 8.1 and 7 PCs as mapped drives.. **A** being **A**ll-my-stuff and **B**: being **B**ackup-Target (on a second nas) If Windows will let you do it, there's no reason not to. You can always use disk manager to reassign them to pretty much whatever you want to (see <http://www.intowindows.com/how-to-change-drive-letter-in-windows-8-1/> for more information)
2,171,568
I have a doubt regarding HttpServlet class is an abstract class even though there is not any abstract method in the class , all methods are concrete. Can class be abstract even if does not have any abstract methods? If yes Whats the use? Thanks
2010/01/31
[ "https://Stackoverflow.com/questions/2171568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/240698/" ]
One cannot instantiate abstract classes so you have to subclass them in order to use it. In the subclass you can still implement your own methods or override parent methods. Maybe it doesn't make sense to use `HttpServlet` as standalone, but it provides necessary default functionality in a certain context. You can subclass `HttpServlet` to serve this context and to have access to its functionality. A subclass of `HttpServlet` doesn't have to implement methods in order to make its own functionality work.
It's a matter of intent. If the class is abstract, you can't create an instance of that class - only of a subclass. I'm not strong on Java, but my guess is that HttpServlet provides default implementations of it's methods, but that you're expected to override some of them. It still makes little sense to have an unspecialised instance of that class, so it's abstract so the compiler drops a hint to anyone who tries.
2,171,568
I have a doubt regarding HttpServlet class is an abstract class even though there is not any abstract method in the class , all methods are concrete. Can class be abstract even if does not have any abstract methods? If yes Whats the use? Thanks
2010/01/31
[ "https://Stackoverflow.com/questions/2171568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/240698/" ]
One cannot instantiate abstract classes so you have to subclass them in order to use it. In the subclass you can still implement your own methods or override parent methods. Maybe it doesn't make sense to use `HttpServlet` as standalone, but it provides necessary default functionality in a certain context. You can subclass `HttpServlet` to serve this context and to have access to its functionality. A subclass of `HttpServlet` doesn't have to implement methods in order to make its own functionality work.
Marking a class as an abstract even when there is a concrete implementation for all methods would be helpful in cases where you are not sure if the class design is complete or there are chances that you plan to add some methods later. Changing a class that has been declared abstract to be made not abstract later doesn't break the compatibility with pre-existing binaries where as other way round breaks compatibility.
2,171,568
I have a doubt regarding HttpServlet class is an abstract class even though there is not any abstract method in the class , all methods are concrete. Can class be abstract even if does not have any abstract methods? If yes Whats the use? Thanks
2010/01/31
[ "https://Stackoverflow.com/questions/2171568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/240698/" ]
In the case of `HttpServlet`, the point is that servlet programmers typically don't want their servlet to support all 4 oft the main HTTP methods (POST, GET, PUT, DELETE), so it would be annoying to make the `doGet()`, `doPost()`, etc. methods abstract, since programmers would be forced to implement methods that they don't need. Therefore, `HttpServlet` provides a default implementation for all those methods that does nothing except return an error statuscode to the client. Programmers can override the methods they need and not worry about the rest. But actually using the `HttpServlet` class itself make no sense (since it does nothing useful), so it's `abstract`. And there you have a great example for when it can make sense to have an abstract class without any abstract method.
One cannot instantiate abstract classes so you have to subclass them in order to use it. In the subclass you can still implement your own methods or override parent methods. Maybe it doesn't make sense to use `HttpServlet` as standalone, but it provides necessary default functionality in a certain context. You can subclass `HttpServlet` to serve this context and to have access to its functionality. A subclass of `HttpServlet` doesn't have to implement methods in order to make its own functionality work.
2,171,568
I have a doubt regarding HttpServlet class is an abstract class even though there is not any abstract method in the class , all methods are concrete. Can class be abstract even if does not have any abstract methods? If yes Whats the use? Thanks
2010/01/31
[ "https://Stackoverflow.com/questions/2171568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/240698/" ]
In the case of `HttpServlet`, the point is that servlet programmers typically don't want their servlet to support all 4 oft the main HTTP methods (POST, GET, PUT, DELETE), so it would be annoying to make the `doGet()`, `doPost()`, etc. methods abstract, since programmers would be forced to implement methods that they don't need. Therefore, `HttpServlet` provides a default implementation for all those methods that does nothing except return an error statuscode to the client. Programmers can override the methods they need and not worry about the rest. But actually using the `HttpServlet` class itself make no sense (since it does nothing useful), so it's `abstract`. And there you have a great example for when it can make sense to have an abstract class without any abstract method.
It's a matter of intent. If the class is abstract, you can't create an instance of that class - only of a subclass. I'm not strong on Java, but my guess is that HttpServlet provides default implementations of it's methods, but that you're expected to override some of them. It still makes little sense to have an unspecialised instance of that class, so it's abstract so the compiler drops a hint to anyone who tries.
2,171,568
I have a doubt regarding HttpServlet class is an abstract class even though there is not any abstract method in the class , all methods are concrete. Can class be abstract even if does not have any abstract methods? If yes Whats the use? Thanks
2010/01/31
[ "https://Stackoverflow.com/questions/2171568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/240698/" ]
In the case of `HttpServlet`, the point is that servlet programmers typically don't want their servlet to support all 4 oft the main HTTP methods (POST, GET, PUT, DELETE), so it would be annoying to make the `doGet()`, `doPost()`, etc. methods abstract, since programmers would be forced to implement methods that they don't need. Therefore, `HttpServlet` provides a default implementation for all those methods that does nothing except return an error statuscode to the client. Programmers can override the methods they need and not worry about the rest. But actually using the `HttpServlet` class itself make no sense (since it does nothing useful), so it's `abstract`. And there you have a great example for when it can make sense to have an abstract class without any abstract method.
Marking a class as an abstract even when there is a concrete implementation for all methods would be helpful in cases where you are not sure if the class design is complete or there are chances that you plan to add some methods later. Changing a class that has been declared abstract to be made not abstract later doesn't break the compatibility with pre-existing binaries where as other way round breaks compatibility.
10,486
I am a 3D printing beginner but wanted to get stuck in straight away and design my own 3D objects. I used Sketchup to design a badge of one of my logos. I make sure that all faces of my object are not inside out and show a white face in Sketchup. I also make my entire object a component before exporting into a .stl file. However, when I import into Ultimaker Cura, the base of the object is red. This to my understanding means there is an issue with that face.I have played around with Sketchup several times by not creating a component, reversing the face and I still have no luck. When I reverse the base face in Sketchup so that it is grey, it then shows up in Ultimaker Cura as okay (not red). But when I 3D print it, it still prints it very strangely. I would like to note I am 3D printing with a raft and when I do not use a raft, the object prints fine. Also I have tested printing a small 3D cube with the same settings and the results are exactly the same. Surely you can design objects in Sketchup and print with a raft? [![Reverse of object](https://i.stack.imgur.com/WdSYa.jpg)](https://i.stack.imgur.com/WdSYa.jpg) [![Front of object](https://i.stack.imgur.com/t8seY.jpg)](https://i.stack.imgur.com/t8seY.jpg)
2019/07/04
[ "https://3dprinting.stackexchange.com/questions/10486", "https://3dprinting.stackexchange.com", "https://3dprinting.stackexchange.com/users/16947/" ]
A red surface coloring is normal for the bottom when viewed in Ultimaker Cura, nothing to worry about that (e.i. when that face is touching the build plate; if it is unsupported, you should add support structures but a raft is generally not necessary for PLA). Rafts are useful when you print high temperature materials that have a large shrinkage when cooled from print to bed temperature (this somewhat mitigates the problems of curling up corners or warping prints), for PLA it is not needed. As seen from the print that is printed on the raft, it's clear that the print to raft distance is to large, the first print object layer is not adhering to the top raft layer very well. The print that is printed without a raft doesn't look too bad. Some printer [extruder calibration](/q/6483) could further improve the quality.
Note: This answer is curently wrong because I mentally reversed your "with raft" and "without raft" columns. I'll attempt to fix it soon. This doesn't look like a problem with your model, but rather a problem with your bed height or slicer settings (possibly both) that may be affecting your particular model worse than others. It's clear from the photo of the bottom of your print that the extrusions that were supposed to be circular failed to adhere to the bed, and instead got pulled to chords between points they happened to adhere at. This could be caused by a mix of: * Excessive print speed for the first layer. Generally I would limit it to 30 mm/s or less to give the material the best chance to stick. * Excess space between the nozzle and bed. Could be caused by improper adjustment of bed height ("leveling"), or by using a layer thickness that's too high (roughly, more than 75-80% of nozzle width). * Underextrusion, possibly caused by insufficient print temperature, incorrect filament diameter setting, or poor quality filament with wrong diameter, among other things. Using a raft mitigates these things by moving the potential problem to the interface between the raft and the bed; once there's a raft sticking to the bed, printing of the model can ignore the problem. But you *should never need a raft*. It's a waste of plastic and a workaround for problems that have better fixes, not a necessary part of 3D printing. The "red" in Cura is not a problem; as I understand it, Cura shows all parts of the model that aren't supported *by other parts of the model* in red, and this includes the base. However, it is possible that your model has some stray part extruding below the bottom, causing the whole thing (except that stray part) to be printed starting one layer above the print bed with nothing to adhere to. You can check if this is the case in Cura by switching to layer view and looking at the first layer. You should see the whole surface that you want to adhere to the bed; if instead you see just one or a few small blobs, that's your problem.
12,112
Hi I'm trying to use this plugin: <http://wordpress.org/extend/plugins/wordpress-simple-website-screenshot/> I am supposed to use the shortcode: `[screenshot url="www.example.com"]` Because I am writing the code in the single.php file I am using: `<?php echo do_shortcode( '[screenshot url="www.example.com"]' ); ?>` But, my problem is that the URL is defined in the title of the post, so I tried: `<?php echo do_shortcode( '[screenshot url="<?php the_title(); ?>"]' ); ?>` with no luck. Is it possible to do a workaround on this?
2011/03/15
[ "https://wordpress.stackexchange.com/questions/12112", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/2188/" ]
You're trying to execute PHP inside a string! Instead, concat the string; ``` <?php echo do_shortcode( '[screenshot url="' . get_the_title() . '"]' ); ?> ```
Your problem is that `<?php the_title(); ?>` inside quotation marks doesn't really works change: ``` <?php echo do_shortcode( '[screenshot url="<?php the_title(); ?>"]' ); ?> ``` to : ``` <?php echo do_shortcode( '[screenshot url="'.the_title().'"]' ); ?> ```
67,528,971
I am trying to login to this website using my credentials. However, although I'm providing what they have in their html, it's not working Currently, I have ``` from selenium import webdriver from selenium.webdriver.chrome.options import Options CHROMEDRIVER_PATH = './chromedriver' chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("start-maximized") chrome_options.add_argument("--disable-blink-features") chrome_options.add_argument("--disable-blink-features=AutomationControlled") LOGIN_PAGE = "https://www.seekingalpha.com/login" ACCOUNT = "account.com" PASSWORD = "password" driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, chrome_options=chrome_options) driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})") driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.53 Safari/537.36'}) driver.get("https://www.seekingalpha.com/login") username = driver.find_element_by_name("email") username.send_keys(ACCOUNT) password = driver.find_element_by_name("password") password.send_keys(PASSWORD) submit_button = driver.find_element_by_css_selector("button._60b46-2mbi1 _60b46-2LbhQ _60b46-1HfKK _60b46-qZydf _60b46-1uOHx _60b46-2NDcV _60b46-3YvwX _60b46-22lGb _60b46-1qE-_ _60b46-3DOuR _60b46-1UPRS _12b23-2JWwg _60b46-EQJB_") submit_button.click() driver.get("https://seekingalpha.com/article/4414043-agenus-inc-agen-ceo-garo-armen-on-q4-2020-results-earnings-call-transcript") text_element = driver.find_elements_by_xpath('//*') text = text_element for t in text: print(t.text) ``` and I keep getting ``` selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[name="email"]"} (Session info: headless chrome=90.0.4430.212) ```
2021/05/14
[ "https://Stackoverflow.com/questions/67528971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15846416/" ]
This problem can be solved with the help of explicit wait. See the code below : ``` driver = webdriver.Chrome("C:\\Users\\etc\\Desktop\\Selenium+Python\\chromedriver.exe", options=options) wait = WebDriverWait(driver, 30) driver.get("https://www.seekingalpha.com/login") wait.until(EC.element_to_be_clickable((By.NAME, "email"))).send_keys("some user name") wait.until(EC.element_to_be_clickable((By.ID, "signInPasswordField"))).send_keys("your password") wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Sign in']"))).click() print("Logged in") ``` Read more about explicit wait [here](https://www.selenium.dev/documentation/en/webdriver/waits/#explicit-wait)
Maybe you need to wait after going to the URL for the element to appear, instead of trying immediately to identify it. You could add it like this: ``` from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # all of your current code driver.get("https://www.seekingalpha.com/login") username = WebDriverWait(driver, 20).until( EC.element_to_be_clickable(driver.find_element_by_name("email"))) username.send_keys(ACCOUNT) # rest of your code ```
67,528,971
I am trying to login to this website using my credentials. However, although I'm providing what they have in their html, it's not working Currently, I have ``` from selenium import webdriver from selenium.webdriver.chrome.options import Options CHROMEDRIVER_PATH = './chromedriver' chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("start-maximized") chrome_options.add_argument("--disable-blink-features") chrome_options.add_argument("--disable-blink-features=AutomationControlled") LOGIN_PAGE = "https://www.seekingalpha.com/login" ACCOUNT = "account.com" PASSWORD = "password" driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, chrome_options=chrome_options) driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})") driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.53 Safari/537.36'}) driver.get("https://www.seekingalpha.com/login") username = driver.find_element_by_name("email") username.send_keys(ACCOUNT) password = driver.find_element_by_name("password") password.send_keys(PASSWORD) submit_button = driver.find_element_by_css_selector("button._60b46-2mbi1 _60b46-2LbhQ _60b46-1HfKK _60b46-qZydf _60b46-1uOHx _60b46-2NDcV _60b46-3YvwX _60b46-22lGb _60b46-1qE-_ _60b46-3DOuR _60b46-1UPRS _12b23-2JWwg _60b46-EQJB_") submit_button.click() driver.get("https://seekingalpha.com/article/4414043-agenus-inc-agen-ceo-garo-armen-on-q4-2020-results-earnings-call-transcript") text_element = driver.find_elements_by_xpath('//*') text = text_element for t in text: print(t.text) ``` and I keep getting ``` selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[name="email"]"} (Session info: headless chrome=90.0.4430.212) ```
2021/05/14
[ "https://Stackoverflow.com/questions/67528971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15846416/" ]
This problem can be solved with the help of explicit wait. See the code below : ``` driver = webdriver.Chrome("C:\\Users\\etc\\Desktop\\Selenium+Python\\chromedriver.exe", options=options) wait = WebDriverWait(driver, 30) driver.get("https://www.seekingalpha.com/login") wait.until(EC.element_to_be_clickable((By.NAME, "email"))).send_keys("some user name") wait.until(EC.element_to_be_clickable((By.ID, "signInPasswordField"))).send_keys("your password") wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Sign in']"))).click() print("Logged in") ``` Read more about explicit wait [here](https://www.selenium.dev/documentation/en/webdriver/waits/#explicit-wait)
It's absolutely clear from the code you showing that you are missing wait / delay between ``` driver.get("https://www.seekingalpha.com/login") ``` and the ``` driver.get("https://www.seekingalpha.com/login") ``` lines. So, you can simply add ``` time.sleep(3) ``` there or if you wish to make it properly use something like ``` username = WebDriverWait(driver, 30).until(EC.element_to_be_clickable(driver.find_element_by_name("email"))) ``` as already mentioned by C.Peck
61,966,245
Suppose I have a JavaScript script named `foo.js` in a GitHub repo. I need to know what sites (domains) are using this script. Thus, for instance, if a website `www.example.com` is referencing my script... ``` <html> <head> <script src="https://myGitHubRepo/foo.js"></script> </head> etc... </html> ``` I'd like to get, track or list `example.com` as a domain. To be more clear, I don't want to track actual users visiting `www.example.com` nor their IPs nor anything like this, I just want to track or make a list of the sites (domains) referencing my script in their HTMLs. Is that possible? --- PS: some hypothetical solutions and their problems: 1. The first idea that comes to mind is using an analytics tool; however, despite being the owner of my code, I'm not the owner of the site containing the repo: GitHub is the owner. Therefore, using an analytics tools seems to be impossible. 2. I can't do calls to my server: again, I don't have a server, it's a GitHub repo. 3. A simple `window.location.hostname` in the script would get what I want, but it would get it on the client side. I don't know if it's possible sending that information back to me... actually, I don't even know if that is legal.
2020/05/23
[ "https://Stackoverflow.com/questions/61966245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12273078/" ]
Without addressing the legal aspect, you could ~~embed [PAT (Personal Access Key)](https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line) in your script~~, which would enable said script to make GitHub API calls. Typically: "[Create or update a file (`PUT /repos/:owner/:repo/contents/:path`)](https://developer.github.com/v3/repos/contents/#create-or-update-a-file)" (I [mentioned it here](https://stackoverflow.com/a/16412371/6309)) You would replace the content of a file in a dedicated user/repository with the domain name you get from the script. Each version of that file would represent one instance of the script execution, with the associated domain written in it. The drawback is that anyone could use that key for accessing the repository, so you need to monitor its content and usage carefully (again, using a dedicated user account/repository just for that one usage). As noted below by [bk2204](https://stackoverflow.com/users/8705432/bk2204), this is too insecure. Instead of a PAT, you can adopt a similar workflow as a GitHub webhook: your script would call a dedicate URL, with a JSON event, which would then register the call.
Don't do it. Telemetry is tricky - and people will opt to not use your script. Also without "place" to gather this information you cannot do it on github. You can try leveraging "code" search engines like: <https://publicwww.com/> <https://www.nerdydata.com/> and similars
39,152,949
everybody. I've the following issue, when someone makes a new pull request and I leave certain comments, if this someone, does update the pull request, TFS instead of moving my comments with the code changes, it is left on the line number, rather than the code snippet. If someone knows how this to be fixed, as it cause enormous efforts to track if the issue was solved.
2016/08/25
[ "https://Stackoverflow.com/questions/39152949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6758583/" ]
Thanks for reporting this issue. This is a new feature that is only available in TFS 15 RC1 and VSTS. Older servers do not have this feature. This feature is called comment tracking and it is mentioned in the release notes [here](https://www.visualstudio.com/en-us/news/2016-jul-7-vso.aspx).
When you click to add a comment as the screenshot below, you would be able to add a comment for a line of code: [![enter image description here](https://i.stack.imgur.com/E70dm.png)](https://i.stack.imgur.com/E70dm.png) Then you'll see your comment under the line: [![enter image description here](https://i.stack.imgur.com/DBJK8.png)](https://i.stack.imgur.com/DBJK8.png)
57,693,907
How can I call function `f2` from `f1` method in `class A` from `f3` method in `class B` which inherited from `class A`? ``` class A(): def f1(self): return 'f1' def f2(self, x): return 'f2' + str(x) class B(A): def f3(self): # Call f1 method work fine self.y = self.f1() # Call f2 method won't work self.z = self.f1.f2('XoXo') return 'f3' + self.y + self.z b = B() print(b.f3()) ``` I expect the output to be `'f3f1f2XoXo'`, but I got this error: > > AttributeError: 'function' object has no attribute 'f2' > > >
2019/08/28
[ "https://Stackoverflow.com/questions/57693907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11392333/" ]
You should enclose your scripts on a `<script>` tag: ``` <head> <script> var calendar = $('#calendar').fullCalendar({ editable:true, header:{ left:'prev,next today', center:'title', right:'month,agendaWeek,agendaDay' }, events:'load', selectable:true, select: function(start, end, allDay) { $('#myModal').modal('show'); }, </script> </head> ```
Instead of 'select', try using 'dateClick' event when you click on an empty date cell, or 'eventClick' when you click on an event -perhaps you'd like to edit it.
74,666,392
New to C here, I am creating an insert function that will insert any value to an array provided I give the position of the array. For example, here is what I have tried: ``` #include <stdio.h> #include <stdlib.h> int insert(int A[], int N, int P, int KEY){ int i = N - 1; while(i >= P){ A[i+1] = A[i]; i += 1; } A[P] = KEY; N = N+1; return *A; } int main(void){ int arr[5] = { 1, 2, 3, 4, 5 }; size_t n = sizeof(arr)/sizeof(arr[0]); int p = 3; int K = 2; int result; result = insert(arr, n, p, K); printf("Insert values: %d", result); return 0; } ``` However, I get the following error: > > zsh: segmentation fault ./insert > > >
2022/12/03
[ "https://Stackoverflow.com/questions/74666392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19136165/" ]
Try to add the mock to your `global` in your `setupTest.js` file: ``` global.TagCanvas = { Start: () => "this is the mocked implementation" } ```
Thanks to Marek response I have it now working. It also worked if I do this global definition inside the `beforeAll` process. [![enter image description here](https://i.stack.imgur.com/rEbYj.png)](https://i.stack.imgur.com/rEbYj.png) I haven't jest configured to read the `setupTest.js` file. Since I am working in next in this project here is how I added it: ``` //jest.config.js const nextJest = require('next/jest'); const createJestConfig = nextJest({ dir: './', }); // Add any custom config to be passed to Jest const customJestConfig = { moduleDirectories: ['node_modules', '<rootDir>/'], testEnvironment: 'jest-environment-jsdom', // Define setupTest file here setupFiles: ['<rootDir>/setupTest.js'], }; module.exports = createJestConfig(customJestConfig); ```
25,129,119
I'm trying to change the background color of each of the segments of a polar chart. It's easy to set a singular color for the background, but is it possible to set a different color for each piece of the polar pie? An example would be 8 different colors for the chart segments below: <http://www.highcharts.com/demo/polar> Thanks
2014/08/04
[ "https://Stackoverflow.com/questions/25129119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3847081/" ]
To my knowledge there is no easy way to do this within the API. I'll present a solution that utilizes the `chart.renderer` to draw a single color for each slice of your polar chart: ``` var colors = [ "pink", "yellow", "blue", "red", "green", "cyan", "teal", "indigo" ]; var parts = 8; for(var i = 0; i < parts; i++) { chart.renderer.arc(chart.plotLeft + chart.yAxis[0].center[0], chart.plotTop + chart.yAxis[0].center[1], chart.yAxis[0].height, 0, -Math.PI + (Math.PI/(parts/2) * i), -Math.PI + (Math.PI/(parts/2) * (i+1))).attr({ fill: colors[i % colors.length], 'stroke-width': 1, 'opacity': 1 }).add(); } ``` Click [this JSFiddle link](http://jsfiddle.net/U72kp/3/) to see a live demonstration. It uses the [`renderer.arc`](http://api.highcharts.com/highcharts#Renderer.arc) to draw each slice with the information from `chart` about center and axis height. The arcs are drawn using start and end angle, given in radians. The various slices can be colored using the `colors` array, and the number of slices can be controlled with the `parts` variable. If there are more parts than colors it will start from the beginning of the `colors` array when it runs out of colors, using `colors[i % colors.length]`.
You can add a fake column series with differently colored points and set yAxis.maxPadding to 0: ``` chart: { polar: true, events: { load: function() { var chart = this, max = chart.yAxis[0].max; chart.addSeries({ type: 'column', data: [{ y: max, color: 'rgba(255, 255, 0, 0.2)' }, { y: max, color: 'rgba(255, 0, 255, 0.2)' }, { y: max, color: 'rgba(0, 255, 255, 0.2)' }, { y: max, color: 'rgba(255, 0, 0, 0.2)' }, { y: max, color: 'rgba(0, 255, 0, 0.2)' }, { y: max, color: 'rgba(0, 0, 255, 0.2)' }, { y: max, color: 'rgba(130, 70, 150, 0.2)' }, { y: max, color: 'rgba(0, 0, 0, 0.2)' }], pointPadding: 0, groupPadding: 0, zIndex: 0, showInLegend: false, enableMouseTracking: false, animation: false }) } } }, yAxis: { maxPadding: 0 }, ``` jsFiddle: <https://jsfiddle.net/BlackLabel/tsj9pomq> API Reference: <https://api.highcharts.com/highcharts/series.column> <https://api.highcharts.com/highcharts/yAxis.maxPadding>
17,867
Generically speaking, how would you handle a huge 2D Map of which only a part is displayed? Imagine the old top-down racing games like [Micro Machines](http://www.youtube.com/watch?v=UvtRClROoiY). I would know how to do something with a tile-based map, but I want to create completely custom Maps. Target Devices are iOS, Windows Phone 7, Android, Mac and PC. Assume the Map is too big to fit to fit into a single Texture. Would I have multiple textures, 4096x4096 each and load them all into RAM? Seems wasteful, and if textures are uncompressed I might actually run out of graphics memory. Would I only load the max. 4 Textures that I need at any given point (when I'm at the intersection)? Or would I have one huge image file and load parts of it? In that case, are there any image formats that make it easy (O(1)) to find the file offset and length which I would have to load? Or is there a completely different algorhithm? Are textures the wrong idea? How would you implement a game like Micro Machines?
2011/09/29
[ "https://gamedev.stackexchange.com/questions/17867", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/849/" ]
In a map that is built from tiles, I have given a fairly full explanation of the approach I've found to work best down on the low end devices: [How should I represent a tile in OpenGL-es](https://gamedev.stackexchange.com/questions/17488/how-should-i-represent-a-tile-in-opengl-es/17490#17490) Memory is the memory used by the tiles (not how many times they are reused) and the relatively small amount of memory used to index where to place each tile. Maps like [Terraria](http://www.escapistmagazine.com/articles/view/editorials/reviews/9005-Terraria-Review) are entirely possible!
If you're not making use of tiles, but draw your entire map by hand, just split it into pieces - or tiles (-8 You need to experiment a bit with tile sizes,to balance constant loading/unloading of tiles (when tiles are small) and using more memory (when tiles are large). For example, on iPhone4 with 960x640 resolution, you may use 1024x1024 tiles and have no more than 4 of them loaded at any given moment. Or have 9 512x512 tiles, arranged in a 3x3 grid.
28,673
What is the difference between responding with "*Alaikum Salaam/علیکم السلام*" and responding with "*Walaikum Salaam/وعلیکم السلام*"? Is it wrong to say "*Alaikum Salaam*" in reply to "*Assalamu Alaikum*"?
2015/11/16
[ "https://islam.stackexchange.com/questions/28673", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/14755/" ]
Well you can answer: Alaikum as-salam عليكم السلام or wa alaikum as-salam وعليكم السلام Both are perfectly fine and good answers! Also available are the singular forms: * 'alaika as-salam عليك السلام and * wa 'alaika as-salam [وعليك السلام](http://sunnah.com/adab/42/71) and also to repeat with the same word * 'alaika as-salam السلام عليك ... etc. all this five expressions can be referenced from the sunna, even if i only referenced one! But what you should never do is greet or begin greeting by saying 'alaika ('alaikum) as-salam see [here](https://sunnah.com/riyadussalihin:856). Note that this has it's origin in Arabic costumes of the time as they used to greet or send a greeting to a dead person this way, as the poet said: > > عليك سلام الله قيس بن عاصم \* ورحمته ما شاء أن يترحما > > فما كان قيس هلكه هلك واحد \* ولكنه بنيان قوم تهدما > > > while the Prophet (Peace be upon him) in his sunna also used the wording with "as-Salaamu alaikum السلام عليكم أهل دار قوم مؤمنين" when visiting the gravyard. So according to a quote of al-Khattabi in [tuhfat al ahodi](http://library.islamweb.net/newlibrary/display_book.php?idfrom=5225&idto=5230&bk_no=56&ID=1719) (a commentary on sunan at-Tirmidhi) on this hadith. Muslims don't make a difference between greeting dead and living people. The only difference between the two possibilities you mentioned is the letter/character "Waw" or "wa", "و" this additional character gives a direct answer to the greeting, as when you say * as-salamu 'alaikum = peace be upon you you express a kind of wish, therefore saying * *wa* 'alaikum as-salam = peace be upon you *too* or literally translated *and* peace be upon you * ('alaikum as-salam = peace be upon you) As an answer makes a small but meaningful difference! As you somehow "include" the greeting of the other person in your answer! And Allah knows best!
**In the name of Allah, the most compassionate, the most merciful** Briefly speaking, typically, the first person who intends to say hello (as a greeting), he or she says: * Assalamu Alaikum/Alaik But the second one who want to reply to his or her Salam, tells: * Alaikum/Alaika Salam (which demonstrates being the second part who is saying back his/her hello Otherwise seemingly you can use both of these two forms in replying, although "Alaikumo Salam looks to be more accurate/formal in compare with the other form (in reply).
28,157,387
``` #grid-breadcrumbs-Focus-ST{ ... } #grid-breadcrumbs-F-150-EcoBoost{ ... } #grid-breadcrumbs-Mustang-EcoBoost{ ... } #grid-breadcrumbs-fiesta{ ... } ``` All of these are extremely similar differing only in the background image that is projected. Is there a way to simply?
2015/01/26
[ "https://Stackoverflow.com/questions/28157387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4271904/" ]
You can offset all the same attributes into a CSS class. CSS: ``` .myClass{ //your css } ``` HTML: ``` <div class="myClass"></div> <div class="myClass"></div> <div class="myClass"></div> ```
``` .class{ #blah } #Focus-ST{ background-image: url("img1.png"); } #fiesta{ background-image: url("img2.png"); } ``` and so on. group all the same attributes in that .class
28,157,387
``` #grid-breadcrumbs-Focus-ST{ ... } #grid-breadcrumbs-F-150-EcoBoost{ ... } #grid-breadcrumbs-Mustang-EcoBoost{ ... } #grid-breadcrumbs-fiesta{ ... } ``` All of these are extremely similar differing only in the background image that is projected. Is there a way to simply?
2015/01/26
[ "https://Stackoverflow.com/questions/28157387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4271904/" ]
Use attribute start with selector: ``` [id^="grid-breadcrumbs"]{ /* Represents an element with an attribute name of attr and whose value is prefixed by "value".*/ } ``` More on [attribute selector](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors)
``` .class{ #blah } #Focus-ST{ background-image: url("img1.png"); } #fiesta{ background-image: url("img2.png"); } ``` and so on. group all the same attributes in that .class
28,157,387
``` #grid-breadcrumbs-Focus-ST{ ... } #grid-breadcrumbs-F-150-EcoBoost{ ... } #grid-breadcrumbs-Mustang-EcoBoost{ ... } #grid-breadcrumbs-fiesta{ ... } ``` All of these are extremely similar differing only in the background image that is projected. Is there a way to simply?
2015/01/26
[ "https://Stackoverflow.com/questions/28157387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4271904/" ]
For example you could do something like this: ``` .grid-breadcrumbs{/*common properties here*/} .grid-breadcrumbs .focus-st{/*different properties for each case here*/} .grid-breadcrumbs .f-150-EcoBoost{} .grid-breadcrumbs .Mustang-EcoBoost{} .grid-breadcrumbs .fiesta{} ``` Your html will be something like this: ``` <div class="breadcrumb"> <div class="grid-breadcrumbs focus-st"></div> <div class="grid-breadcrumbs fiesta"></div> </div> ```
``` .class{ #blah } #Focus-ST{ background-image: url("img1.png"); } #fiesta{ background-image: url("img2.png"); } ``` and so on. group all the same attributes in that .class
98,983
I have a problem that I don't really know how to solve (I mean, I know how to solve it in an ugly way but I'd prefer a cool one :)) Premise: I'm using Unitymedia, a German Internet, TV and phone (the last two over internet) provider. They sent me the Horizon HD[1], a big box which does everything. Data connection is made over a cable, specifically this[2] one. I only have one internet plug, which is downstairs. For space reasons, I want to have the TV upstairs. But this means that: 1. I have to buy a 20mt data cable, for connecting the plug to the Horizon HD which will be upstairs. (Ugly solution) 2. I have to...what? :-) * I was thinking about connecting the data plug to the Horizon HD downstairs and then plug into the decoder an HDMI-WiFi (like a miracast or something similar) stick. Do you think it is possible to transmit the decoder UI over WiFi? Or am I forced to connect the HDMI cable to the TV? * sub-problem: how can I change channels if the TV is upstairs and the decoder downstairs? :-( * I connect the data plug downstairs to a small WiFi router, then I'd connect the Horizon HD to this WiFi router. Again, do you think it is possible? * please, tell me what you would do :-) [1] <https://i.ytimg.com/vi/_08_I38TOu8/maxresdefault.jpg> [2] <http://www.antennenland.net/bilder/produkte/gross/Horizon-Kabel-Cabelcon-10m.jpg>
2016/09/09
[ "https://diy.stackexchange.com/questions/98983", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/59898/" ]
Rather than use WiFi, you can use a specific transmission system. These are known as videosenders or digisenders. I use a German made system for sending the signal from my Sky satellite box to the television in the bedroom. They are available in the 2.4GHz and 5GHz bands. For the HD that you require I suggest that you would need to use the 5GHz variant. You will also need to ensure that the version you buy has suitable input connections for the feed that you can provide. All videosenders have a backchannel for sending signals from the remote control to the box downstairs. They are quite common in the UK, there is some information [here](http://www.radioandtelly.co.uk/videosenders.html) but it refers mostly to the 2.4GHz variety.
**The general solution** Get two pieces of hardware: 1. A standard wifi router 2. A wifi extender with an ethernet port (I like the Netgear N300) This is fairly cost effective and it gets you a few multi-tasking tools. The wifi router gives you wireless internet throughout your home. The extender acts as a wireless-to-wired bridge to service your TV decoder. **The cheapest and most direct solution** Buy the 20m ethernet cable and just run it and be done with the job. Running a cable properly isn't hard, isn't expensive, and this will give you the best connection to the TV decoder
9,414,990
I have 3 classes: ``` public class Alpha { public Number number; } public class Beta extends Alpha { public String number; } public class Gama extends Beta { public int number; } ``` Why does the following code compile? And, why does the test pass without any runtime errors? ``` @Test public void test() { final Beta a = new Gama(); a.number = "its a string"; ((Alpha) a).number = 13; ((Gama) a).number = 42; assertEquals("its a string", a.number); assertEquals(13, ((Alpha) a).number); assertEquals(42, ((Gama) a).number); } ```
2012/02/23
[ "https://Stackoverflow.com/questions/9414990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/526836/" ]
Member variables cannot be overridden like methods. The `number` variables in your classes `Beta` and `Gama` are **hiding** (not overriding) the member variable `number` of the superclass. By casting you can access the hidden member in the superclass.
Fields can't be *overridden*; they're not accessed polymorphically in the first place - you're just declaring a new field in each case. It compiles because in each case the compile-time type of the expression is enough to determine *which* field called `number` you mean. In real-world programming, you would avoid this by two means: * Common-sense: shadowing fields makes your code harder to read, so just don't do it * Visibility: if you make all your fields private, subclasses won't know about them anyway
9,414,990
I have 3 classes: ``` public class Alpha { public Number number; } public class Beta extends Alpha { public String number; } public class Gama extends Beta { public int number; } ``` Why does the following code compile? And, why does the test pass without any runtime errors? ``` @Test public void test() { final Beta a = new Gama(); a.number = "its a string"; ((Alpha) a).number = 13; ((Gama) a).number = 42; assertEquals("its a string", a.number); assertEquals(13, ((Alpha) a).number); assertEquals(42, ((Gama) a).number); } ```
2012/02/23
[ "https://Stackoverflow.com/questions/9414990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/526836/" ]
Fields can't be *overridden*; they're not accessed polymorphically in the first place - you're just declaring a new field in each case. It compiles because in each case the compile-time type of the expression is enough to determine *which* field called `number` you mean. In real-world programming, you would avoid this by two means: * Common-sense: shadowing fields makes your code harder to read, so just don't do it * Visibility: if you make all your fields private, subclasses won't know about them anyway
**Java Hiding a field** When successor has a **field** with the same **name** as a superclass's field it is called - **Hiding a field** Java's field does not support polymorphism and does not take a field's type into account ``` class A { String field = "A: field"; String foo() { return "A: foo()"; } } class B extends A { //B's field hides A's field String field = "B: field"; String foo() { return "B: foo()"; } } @Test public void testPoly() { A a = new A(); assertEquals("A: field", a.field); assertEquals("A: foo()", a.foo()); B b = new B(); assertEquals("B: field", b.field); assertEquals("B: foo()", b.foo()); //B cast to A assertEquals("A: field", ((A)b).field); //<-- assertEquals("B: foo()", ((A)b).foo()); } ``` [[Swift override property]](https://stackoverflow.com/a/61374973/4770877)
9,414,990
I have 3 classes: ``` public class Alpha { public Number number; } public class Beta extends Alpha { public String number; } public class Gama extends Beta { public int number; } ``` Why does the following code compile? And, why does the test pass without any runtime errors? ``` @Test public void test() { final Beta a = new Gama(); a.number = "its a string"; ((Alpha) a).number = 13; ((Gama) a).number = 42; assertEquals("its a string", a.number); assertEquals(13, ((Alpha) a).number); assertEquals(42, ((Gama) a).number); } ```
2012/02/23
[ "https://Stackoverflow.com/questions/9414990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/526836/" ]
Fields can't be *overridden*; they're not accessed polymorphically in the first place - you're just declaring a new field in each case. It compiles because in each case the compile-time type of the expression is enough to determine *which* field called `number` you mean. In real-world programming, you would avoid this by two means: * Common-sense: shadowing fields makes your code harder to read, so just don't do it * Visibility: if you make all your fields private, subclasses won't know about them anyway
As a workaround, you can use getter methods: ``` class A { private String field = "A: field"; String getField() { return field; } } class B extends A { private String field = "B: field"; @Override String getField() { return field; } } ```
9,414,990
I have 3 classes: ``` public class Alpha { public Number number; } public class Beta extends Alpha { public String number; } public class Gama extends Beta { public int number; } ``` Why does the following code compile? And, why does the test pass without any runtime errors? ``` @Test public void test() { final Beta a = new Gama(); a.number = "its a string"; ((Alpha) a).number = 13; ((Gama) a).number = 42; assertEquals("its a string", a.number); assertEquals(13, ((Alpha) a).number); assertEquals(42, ((Gama) a).number); } ```
2012/02/23
[ "https://Stackoverflow.com/questions/9414990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/526836/" ]
Member variables cannot be overridden like methods. The `number` variables in your classes `Beta` and `Gama` are **hiding** (not overriding) the member variable `number` of the superclass. By casting you can access the hidden member in the superclass.
**Java Hiding a field** When successor has a **field** with the same **name** as a superclass's field it is called - **Hiding a field** Java's field does not support polymorphism and does not take a field's type into account ``` class A { String field = "A: field"; String foo() { return "A: foo()"; } } class B extends A { //B's field hides A's field String field = "B: field"; String foo() { return "B: foo()"; } } @Test public void testPoly() { A a = new A(); assertEquals("A: field", a.field); assertEquals("A: foo()", a.foo()); B b = new B(); assertEquals("B: field", b.field); assertEquals("B: foo()", b.foo()); //B cast to A assertEquals("A: field", ((A)b).field); //<-- assertEquals("B: foo()", ((A)b).foo()); } ``` [[Swift override property]](https://stackoverflow.com/a/61374973/4770877)
9,414,990
I have 3 classes: ``` public class Alpha { public Number number; } public class Beta extends Alpha { public String number; } public class Gama extends Beta { public int number; } ``` Why does the following code compile? And, why does the test pass without any runtime errors? ``` @Test public void test() { final Beta a = new Gama(); a.number = "its a string"; ((Alpha) a).number = 13; ((Gama) a).number = 42; assertEquals("its a string", a.number); assertEquals(13, ((Alpha) a).number); assertEquals(42, ((Gama) a).number); } ```
2012/02/23
[ "https://Stackoverflow.com/questions/9414990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/526836/" ]
Member variables cannot be overridden like methods. The `number` variables in your classes `Beta` and `Gama` are **hiding** (not overriding) the member variable `number` of the superclass. By casting you can access the hidden member in the superclass.
As a workaround, you can use getter methods: ``` class A { private String field = "A: field"; String getField() { return field; } } class B extends A { private String field = "B: field"; @Override String getField() { return field; } } ```
11,175,575
I'm wondering why C99 allows conversions between incompatible pointer types: ``` void f(int* p) { } void c(char* p) { f(p); } ``` Does C11 also allow them? Are conforming implementations required to diagnose such conversions?
2012/06/24
[ "https://Stackoverflow.com/questions/11175575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1477730/" ]
C99 doesn't permit implicit conversion between pointers of different types (except to/from `void*`). here's what the C99 Rationale says: > > It is invalid to convert a pointer to an object of any type to a pointer to an object of a different type without an explicit cast. > > > This is a consequence of the rules for assignment, which has a constraint that one of the following shall hold (when pointers are involved) (C99 6.5.16.1 "Simple assignment"): > > * both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the > qualifiers of the type pointed to by the right; > * one operand is a pointer to an object or incomplete type and the other is a pointer to a qualified or unqualified version of void, and > the type pointed to by the left has all the qualifiers of the type > pointed to by the right; > * the left operand is a pointer and the right is a null pointer constant > > > Passing a pointer as an argument to a prototyped function follows the same rules because (C99 6.5.2.2/7 "Function calls"): > > If the expression that denotes the called function has a type that > does include a prototype, the arguments are implicitly converted, as > if by assignment, to the types of the corresponding parameters > > > Both C90 and C11 have similar wording. I believe that many compilers (including GCC) relax this constraint to issue only a warning because there's too much legacy code that depends on it. Keep in mind that `void*` was an invention of the ANSI C standard, so pre-standard, and probably a lot of post-standard, code generally used `char*` or `int*` as a 'generic' pointer type.
There is no such thing as "incompatible" pointer types. The beauty of C is that it allows the programmer to do what they want. It is up to the programmer to decide what is compatible vs. incompatible. Other languages that claim to force "`class`" or "`type`" cohesion do so in a limited way. The moment that the objects are allowed to be referenced a pointer is used and a class mismanagement can kick in.
31,073,005
I am little bit new at AutoLayout.I know already tons of question and tutorial available regarding this autoLayout but I have not found my solution.So Thanks in advance for any help. What is my requirement? I have to make UIView which will come to screen after pressing a button from the bottom side of the screen with animation.(Like Keyboard).I have made this UIView in a xib file using autoLayout.So far i have done like this. In ViewDidLoad: ``` //Loading custom UIView containerView = [[SharingPickerView alloc] init]; [containerView loadingMenus:pickerData]; [self.view addSubview:containerView]; ``` In this view it contatains (a scrollview then a page controller then a cancel button) In ViewWillLayoutSubviews: ``` -(void)viewWillLayoutSubviews{ [super viewWillLayoutSubviews]; //Changing the frame of view to bottom side of the screen so that we can animate it later from bottom to top later. containerView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, containerView.frame.size.height); [containerView setBackgroundColor:[[UIColor colorWithRed:231.0/255.0f green:231.0/255.0f blue:231.0/255.0f alpha:1.0f] colorWithAlphaComponent:0.3]]; } ``` Now on press for animation. ``` -(void)sharePickerView{ [UIView animateWithDuration:1 animations:^(){ containerView.frame = CGRectMake(0,self.view.frame.size.height-containerView.frame.size.height, self.view.frame.size.width, containerView.frame.size.width); } completion:^(BOOL isFinished){ NSLog(@"Animation Finish"); }]; } ``` Here i am re-framing the View for showing that animation but some bottom portion(cancel button of that view) is not showing in iPhone 6 simulator but it is showing perfectly iPhone 5s device. Regards Emon.
2015/06/26
[ "https://Stackoverflow.com/questions/31073005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1275581/" ]
try to use size constraints as outlets. Then you can easy change values of those constraints. It's not really recommended to modify frame when using auto-layout. declare a property: ``` @property (strong, nonatomic) IBOutlet NSLayoutConstraint *heightConstraint; ``` and in the implementation: ``` heightConstraint = self.view.frame.size.height; ``` Also this post may be helpful: [AutoLayout, Constraints and Animation](https://stackoverflow.com/questions/19899323/autolayout-constraints-and-animation)
i suggest you to add constraints programmatically 1. First, set your `translatesAutoresizingMaskIntoConstraints` to `NO` ``` containerView = [[SharingPickerView alloc] init]; containerView.translatesAutoresizingMaskIntoConstraints = NO; [containerView loadingMenus:pickerData]; [self.view addSubview:containerView]; ``` 2. second, add constraints for height ``` // for example, half height as view. self.heightConstraint = [NSLayoutConstraint constraintWithItem:containerView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:0.5 constant:0.0] [self.view addConstraint:self.heightConstraint];` ``` Hold this constraint as property: ``` @property (nonatomic, strong) NSLayoutConstraint *heightConstraint; ``` Animate constraint changes as ``` [UIView animateWithDuration:0.5 animations:^{ self.heightConstraint.constant += Value_to_change; [self.view layoutIfNeeded]; }]; ``` Also, do not forget to add trailing and leading constraints + top constraint Here is good tutorial for you <http://www.thinkandbuild.it/learn-to-love-auto-layout-programmatically/> Hope this helps
31,073,005
I am little bit new at AutoLayout.I know already tons of question and tutorial available regarding this autoLayout but I have not found my solution.So Thanks in advance for any help. What is my requirement? I have to make UIView which will come to screen after pressing a button from the bottom side of the screen with animation.(Like Keyboard).I have made this UIView in a xib file using autoLayout.So far i have done like this. In ViewDidLoad: ``` //Loading custom UIView containerView = [[SharingPickerView alloc] init]; [containerView loadingMenus:pickerData]; [self.view addSubview:containerView]; ``` In this view it contatains (a scrollview then a page controller then a cancel button) In ViewWillLayoutSubviews: ``` -(void)viewWillLayoutSubviews{ [super viewWillLayoutSubviews]; //Changing the frame of view to bottom side of the screen so that we can animate it later from bottom to top later. containerView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, containerView.frame.size.height); [containerView setBackgroundColor:[[UIColor colorWithRed:231.0/255.0f green:231.0/255.0f blue:231.0/255.0f alpha:1.0f] colorWithAlphaComponent:0.3]]; } ``` Now on press for animation. ``` -(void)sharePickerView{ [UIView animateWithDuration:1 animations:^(){ containerView.frame = CGRectMake(0,self.view.frame.size.height-containerView.frame.size.height, self.view.frame.size.width, containerView.frame.size.width); } completion:^(BOOL isFinished){ NSLog(@"Animation Finish"); }]; } ``` Here i am re-framing the View for showing that animation but some bottom portion(cancel button of that view) is not showing in iPhone 6 simulator but it is showing perfectly iPhone 5s device. Regards Emon.
2015/06/26
[ "https://Stackoverflow.com/questions/31073005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1275581/" ]
try to use size constraints as outlets. Then you can easy change values of those constraints. It's not really recommended to modify frame when using auto-layout. declare a property: ``` @property (strong, nonatomic) IBOutlet NSLayoutConstraint *heightConstraint; ``` and in the implementation: ``` heightConstraint = self.view.frame.size.height; ``` Also this post may be helpful: [AutoLayout, Constraints and Animation](https://stackoverflow.com/questions/19899323/autolayout-constraints-and-animation)
This answer <https://stackoverflow.com/a/26040569/2654425> may be very helpul as it deals with a similar situation.
31,073,005
I am little bit new at AutoLayout.I know already tons of question and tutorial available regarding this autoLayout but I have not found my solution.So Thanks in advance for any help. What is my requirement? I have to make UIView which will come to screen after pressing a button from the bottom side of the screen with animation.(Like Keyboard).I have made this UIView in a xib file using autoLayout.So far i have done like this. In ViewDidLoad: ``` //Loading custom UIView containerView = [[SharingPickerView alloc] init]; [containerView loadingMenus:pickerData]; [self.view addSubview:containerView]; ``` In this view it contatains (a scrollview then a page controller then a cancel button) In ViewWillLayoutSubviews: ``` -(void)viewWillLayoutSubviews{ [super viewWillLayoutSubviews]; //Changing the frame of view to bottom side of the screen so that we can animate it later from bottom to top later. containerView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, containerView.frame.size.height); [containerView setBackgroundColor:[[UIColor colorWithRed:231.0/255.0f green:231.0/255.0f blue:231.0/255.0f alpha:1.0f] colorWithAlphaComponent:0.3]]; } ``` Now on press for animation. ``` -(void)sharePickerView{ [UIView animateWithDuration:1 animations:^(){ containerView.frame = CGRectMake(0,self.view.frame.size.height-containerView.frame.size.height, self.view.frame.size.width, containerView.frame.size.width); } completion:^(BOOL isFinished){ NSLog(@"Animation Finish"); }]; } ``` Here i am re-framing the View for showing that animation but some bottom portion(cancel button of that view) is not showing in iPhone 6 simulator but it is showing perfectly iPhone 5s device. Regards Emon.
2015/06/26
[ "https://Stackoverflow.com/questions/31073005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1275581/" ]
You shouldn't reframe if you are using `NSAutoLayout`. 1. You have to install a constraint at bottom of the screen with the scroll and the view parent. Remember set translatesAutoresizingMaskIntoConstraints to NO when you instance the custom view. ![enter image description here](https://i.stack.imgur.com/1LHWL.png) 2. Create an Outlet of this constraint. 3. When you need change animating ``` _ctScrollBottom.constant = self.view.frame.size.height-containerView.frame.size.height; [UIView animateWithDuration:animationDuration animations:^(){ [self.view layoutIfNeeded]; }]; ``` I took your "y" position calculation but I have not tested it ;) Hope this helps!
i suggest you to add constraints programmatically 1. First, set your `translatesAutoresizingMaskIntoConstraints` to `NO` ``` containerView = [[SharingPickerView alloc] init]; containerView.translatesAutoresizingMaskIntoConstraints = NO; [containerView loadingMenus:pickerData]; [self.view addSubview:containerView]; ``` 2. second, add constraints for height ``` // for example, half height as view. self.heightConstraint = [NSLayoutConstraint constraintWithItem:containerView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:0.5 constant:0.0] [self.view addConstraint:self.heightConstraint];` ``` Hold this constraint as property: ``` @property (nonatomic, strong) NSLayoutConstraint *heightConstraint; ``` Animate constraint changes as ``` [UIView animateWithDuration:0.5 animations:^{ self.heightConstraint.constant += Value_to_change; [self.view layoutIfNeeded]; }]; ``` Also, do not forget to add trailing and leading constraints + top constraint Here is good tutorial for you <http://www.thinkandbuild.it/learn-to-love-auto-layout-programmatically/> Hope this helps
31,073,005
I am little bit new at AutoLayout.I know already tons of question and tutorial available regarding this autoLayout but I have not found my solution.So Thanks in advance for any help. What is my requirement? I have to make UIView which will come to screen after pressing a button from the bottom side of the screen with animation.(Like Keyboard).I have made this UIView in a xib file using autoLayout.So far i have done like this. In ViewDidLoad: ``` //Loading custom UIView containerView = [[SharingPickerView alloc] init]; [containerView loadingMenus:pickerData]; [self.view addSubview:containerView]; ``` In this view it contatains (a scrollview then a page controller then a cancel button) In ViewWillLayoutSubviews: ``` -(void)viewWillLayoutSubviews{ [super viewWillLayoutSubviews]; //Changing the frame of view to bottom side of the screen so that we can animate it later from bottom to top later. containerView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, containerView.frame.size.height); [containerView setBackgroundColor:[[UIColor colorWithRed:231.0/255.0f green:231.0/255.0f blue:231.0/255.0f alpha:1.0f] colorWithAlphaComponent:0.3]]; } ``` Now on press for animation. ``` -(void)sharePickerView{ [UIView animateWithDuration:1 animations:^(){ containerView.frame = CGRectMake(0,self.view.frame.size.height-containerView.frame.size.height, self.view.frame.size.width, containerView.frame.size.width); } completion:^(BOOL isFinished){ NSLog(@"Animation Finish"); }]; } ``` Here i am re-framing the View for showing that animation but some bottom portion(cancel button of that view) is not showing in iPhone 6 simulator but it is showing perfectly iPhone 5s device. Regards Emon.
2015/06/26
[ "https://Stackoverflow.com/questions/31073005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1275581/" ]
You shouldn't reframe if you are using `NSAutoLayout`. 1. You have to install a constraint at bottom of the screen with the scroll and the view parent. Remember set translatesAutoresizingMaskIntoConstraints to NO when you instance the custom view. ![enter image description here](https://i.stack.imgur.com/1LHWL.png) 2. Create an Outlet of this constraint. 3. When you need change animating ``` _ctScrollBottom.constant = self.view.frame.size.height-containerView.frame.size.height; [UIView animateWithDuration:animationDuration animations:^(){ [self.view layoutIfNeeded]; }]; ``` I took your "y" position calculation but I have not tested it ;) Hope this helps!
This answer <https://stackoverflow.com/a/26040569/2654425> may be very helpul as it deals with a similar situation.
33,721,429
I know how to pass a simple function as parameter to another function - but how do I pass "nested" functions? I'm trying to do something like this: ``` def do(func): print (func(6)) def a(x): return x*2 def b(x): return x*3 do(a(b)) ```
2015/11/15
[ "https://Stackoverflow.com/questions/33721429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4129091/" ]
Using function composition approach: ``` def compose(f, g): return lambda x: f(g(x)) def do(func): print (func(6)) def a(x): return x*2 def b(x): return x*3 combinedAB = compose(a,b) do(combinedAB) ```
Well the main problem here is that `do(a(b))` will pass the function `b` in the `a` and result in a `TypeError`. The main issue here is that whatever you pass to function `do` *has to be a callable* or else the `print(func(6))` statement will fail for the appropriate reasons (lack of a `__call__` method) so I don't think the way this is structured fits what you're trying to do. As a solution you could either do what @Doorknob suggested (essentially pass in a callable) or consider returning function `b` from function `a` which will then be used in function `do`. So, if you change function `a` as so: ``` def do(func): print (func(6)) def a(x): x = x * 2 def b(y): return x * (y * 3) return b do(a(2)) ``` You'll get a nice result of `72`. Even though I'm not sure if this is strictly what you mean by "nested" functions.
16,353,729
I have some problems with the Pandas apply function, when using multiple columns with the following dataframe ``` df = DataFrame ({'a' : np.random.randn(6), 'b' : ['foo', 'bar'] * 3, 'c' : np.random.randn(6)}) ``` and the following function ``` def my_test(a, b): return a % b ``` When I try to apply this function with : ``` df['Value'] = df.apply(lambda row: my_test(row[a], row[c]), axis=1) ``` I get the error message: ``` NameError: ("global name 'a' is not defined", u'occurred at index 0') ``` I do not understand this message, I defined the name properly. I would highly appreciate any help on this issue Update Thanks for your help. I made indeed some syntax mistakes with the code, the index should be put ''. However I still get the same issue using a more complex function such as: ``` def my_test(a): cum_diff = 0 for ix in df.index(): cum_diff = cum_diff + (a - df['a'][ix]) return cum_diff ```
2013/05/03
[ "https://Stackoverflow.com/questions/16353729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2331506/" ]
All of the suggestions above work, but if you want your computations to by more efficient, you should take advantage of numpy vector operations [(as pointed out here)](https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6). ``` import pandas as pd import numpy as np df = pd.DataFrame ({'a' : np.random.randn(6), 'b' : ['foo', 'bar'] * 3, 'c' : np.random.randn(6)}) ``` Example 1: looping with `pandas.apply()`: ``` %%timeit def my_test2(row): return row['a'] % row['c'] df['Value'] = df.apply(my_test2, axis=1) ``` > > The slowest run took 7.49 times longer than the fastest. This could > mean that an intermediate result is being cached. 1000 loops, best of > 3: 481 µs per loop > > > Example 2: vectorize using `pandas.apply()`: ``` %%timeit df['a'] % df['c'] ``` > > The slowest run took 458.85 times longer than the fastest. This could > mean that an intermediate result is being cached. 10000 loops, best of > 3: 70.9 µs per loop > > > Example 3: vectorize using numpy arrays: ``` %%timeit df['a'].values % df['c'].values ``` > > The slowest run took 7.98 times longer than the fastest. This could > mean that an intermediate result is being cached. 100000 loops, best > of 3: 6.39 µs per loop > > > So vectorizing using numpy arrays improved the speed by almost two orders of magnitude.
I have given the comparison of all three discussed above. **Using values** ``` %timeit df['value'] = df['a'].values % df['c'].values ``` 139 µs ± 1.91 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) **Without values** ``` %timeit df['value'] = df['a']%df['c'] ``` 216 µs ± 1.86 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) **Apply function** ``` %timeit df['Value'] = df.apply(lambda row: row['a']%row['c'], axis=1) ``` 474 µs ± 5.07 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
16,353,729
I have some problems with the Pandas apply function, when using multiple columns with the following dataframe ``` df = DataFrame ({'a' : np.random.randn(6), 'b' : ['foo', 'bar'] * 3, 'c' : np.random.randn(6)}) ``` and the following function ``` def my_test(a, b): return a % b ``` When I try to apply this function with : ``` df['Value'] = df.apply(lambda row: my_test(row[a], row[c]), axis=1) ``` I get the error message: ``` NameError: ("global name 'a' is not defined", u'occurred at index 0') ``` I do not understand this message, I defined the name properly. I would highly appreciate any help on this issue Update Thanks for your help. I made indeed some syntax mistakes with the code, the index should be put ''. However I still get the same issue using a more complex function such as: ``` def my_test(a): cum_diff = 0 for ix in df.index(): cum_diff = cum_diff + (a - df['a'][ix]) return cum_diff ```
2013/05/03
[ "https://Stackoverflow.com/questions/16353729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2331506/" ]
Let's say we want to apply a function add5 to columns 'a' and 'b' of DataFrame df ``` def add5(x): return x+5 df[['a', 'b']].apply(add5) ```
This is same as the previous solution but I have defined the function in df.apply itself: ``` df['Value'] = df.apply(lambda row: row['a']%row['c'], axis=1) ```
16,353,729
I have some problems with the Pandas apply function, when using multiple columns with the following dataframe ``` df = DataFrame ({'a' : np.random.randn(6), 'b' : ['foo', 'bar'] * 3, 'c' : np.random.randn(6)}) ``` and the following function ``` def my_test(a, b): return a % b ``` When I try to apply this function with : ``` df['Value'] = df.apply(lambda row: my_test(row[a], row[c]), axis=1) ``` I get the error message: ``` NameError: ("global name 'a' is not defined", u'occurred at index 0') ``` I do not understand this message, I defined the name properly. I would highly appreciate any help on this issue Update Thanks for your help. I made indeed some syntax mistakes with the code, the index should be put ''. However I still get the same issue using a more complex function such as: ``` def my_test(a): cum_diff = 0 for ix in df.index(): cum_diff = cum_diff + (a - df['a'][ix]) return cum_diff ```
2013/05/03
[ "https://Stackoverflow.com/questions/16353729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2331506/" ]
Seems you forgot the `''` of your string. ``` In [43]: df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1) In [44]: df Out[44]: a b c Value 0 -1.674308 foo 0.343801 0.044698 1 -2.163236 bar -2.046438 -0.116798 2 -0.199115 foo -0.458050 -0.199115 3 0.918646 bar -0.007185 -0.001006 4 1.336830 foo 0.534292 0.268245 5 0.976844 bar -0.773630 -0.570417 ``` BTW, in my opinion, following way is more elegant: ``` In [53]: def my_test2(row): ....: return row['a'] % row['c'] ....: In [54]: df['Value'] = df.apply(my_test2, axis=1) ```
All of the suggestions above work, but if you want your computations to by more efficient, you should take advantage of numpy vector operations [(as pointed out here)](https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6). ``` import pandas as pd import numpy as np df = pd.DataFrame ({'a' : np.random.randn(6), 'b' : ['foo', 'bar'] * 3, 'c' : np.random.randn(6)}) ``` Example 1: looping with `pandas.apply()`: ``` %%timeit def my_test2(row): return row['a'] % row['c'] df['Value'] = df.apply(my_test2, axis=1) ``` > > The slowest run took 7.49 times longer than the fastest. This could > mean that an intermediate result is being cached. 1000 loops, best of > 3: 481 µs per loop > > > Example 2: vectorize using `pandas.apply()`: ``` %%timeit df['a'] % df['c'] ``` > > The slowest run took 458.85 times longer than the fastest. This could > mean that an intermediate result is being cached. 10000 loops, best of > 3: 70.9 µs per loop > > > Example 3: vectorize using numpy arrays: ``` %%timeit df['a'].values % df['c'].values ``` > > The slowest run took 7.98 times longer than the fastest. This could > mean that an intermediate result is being cached. 100000 loops, best > of 3: 6.39 µs per loop > > > So vectorizing using numpy arrays improved the speed by almost two orders of magnitude.
16,353,729
I have some problems with the Pandas apply function, when using multiple columns with the following dataframe ``` df = DataFrame ({'a' : np.random.randn(6), 'b' : ['foo', 'bar'] * 3, 'c' : np.random.randn(6)}) ``` and the following function ``` def my_test(a, b): return a % b ``` When I try to apply this function with : ``` df['Value'] = df.apply(lambda row: my_test(row[a], row[c]), axis=1) ``` I get the error message: ``` NameError: ("global name 'a' is not defined", u'occurred at index 0') ``` I do not understand this message, I defined the name properly. I would highly appreciate any help on this issue Update Thanks for your help. I made indeed some syntax mistakes with the code, the index should be put ''. However I still get the same issue using a more complex function such as: ``` def my_test(a): cum_diff = 0 for ix in df.index(): cum_diff = cum_diff + (a - df['a'][ix]) return cum_diff ```
2013/05/03
[ "https://Stackoverflow.com/questions/16353729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2331506/" ]
All of the suggestions above work, but if you want your computations to by more efficient, you should take advantage of numpy vector operations [(as pointed out here)](https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6). ``` import pandas as pd import numpy as np df = pd.DataFrame ({'a' : np.random.randn(6), 'b' : ['foo', 'bar'] * 3, 'c' : np.random.randn(6)}) ``` Example 1: looping with `pandas.apply()`: ``` %%timeit def my_test2(row): return row['a'] % row['c'] df['Value'] = df.apply(my_test2, axis=1) ``` > > The slowest run took 7.49 times longer than the fastest. This could > mean that an intermediate result is being cached. 1000 loops, best of > 3: 481 µs per loop > > > Example 2: vectorize using `pandas.apply()`: ``` %%timeit df['a'] % df['c'] ``` > > The slowest run took 458.85 times longer than the fastest. This could > mean that an intermediate result is being cached. 10000 loops, best of > 3: 70.9 µs per loop > > > Example 3: vectorize using numpy arrays: ``` %%timeit df['a'].values % df['c'].values ``` > > The slowest run took 7.98 times longer than the fastest. This could > mean that an intermediate result is being cached. 100000 loops, best > of 3: 6.39 µs per loop > > > So vectorizing using numpy arrays improved the speed by almost two orders of magnitude.
This is same as the previous solution but I have defined the function in df.apply itself: ``` df['Value'] = df.apply(lambda row: row['a']%row['c'], axis=1) ```
16,353,729
I have some problems with the Pandas apply function, when using multiple columns with the following dataframe ``` df = DataFrame ({'a' : np.random.randn(6), 'b' : ['foo', 'bar'] * 3, 'c' : np.random.randn(6)}) ``` and the following function ``` def my_test(a, b): return a % b ``` When I try to apply this function with : ``` df['Value'] = df.apply(lambda row: my_test(row[a], row[c]), axis=1) ``` I get the error message: ``` NameError: ("global name 'a' is not defined", u'occurred at index 0') ``` I do not understand this message, I defined the name properly. I would highly appreciate any help on this issue Update Thanks for your help. I made indeed some syntax mistakes with the code, the index should be put ''. However I still get the same issue using a more complex function such as: ``` def my_test(a): cum_diff = 0 for ix in df.index(): cum_diff = cum_diff + (a - df['a'][ix]) return cum_diff ```
2013/05/03
[ "https://Stackoverflow.com/questions/16353729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2331506/" ]
If you just want to compute (column a) % (column b), you don't need `apply`, just do it directly: ``` In [7]: df['a'] % df['c'] Out[7]: 0 -1.132022 1 -0.939493 2 0.201931 3 0.511374 4 -0.694647 5 -0.023486 Name: a ```
Let's say we want to apply a function add5 to columns 'a' and 'b' of DataFrame df ``` def add5(x): return x+5 df[['a', 'b']].apply(add5) ```
16,353,729
I have some problems with the Pandas apply function, when using multiple columns with the following dataframe ``` df = DataFrame ({'a' : np.random.randn(6), 'b' : ['foo', 'bar'] * 3, 'c' : np.random.randn(6)}) ``` and the following function ``` def my_test(a, b): return a % b ``` When I try to apply this function with : ``` df['Value'] = df.apply(lambda row: my_test(row[a], row[c]), axis=1) ``` I get the error message: ``` NameError: ("global name 'a' is not defined", u'occurred at index 0') ``` I do not understand this message, I defined the name properly. I would highly appreciate any help on this issue Update Thanks for your help. I made indeed some syntax mistakes with the code, the index should be put ''. However I still get the same issue using a more complex function such as: ``` def my_test(a): cum_diff = 0 for ix in df.index(): cum_diff = cum_diff + (a - df['a'][ix]) return cum_diff ```
2013/05/03
[ "https://Stackoverflow.com/questions/16353729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2331506/" ]
If you just want to compute (column a) % (column b), you don't need `apply`, just do it directly: ``` In [7]: df['a'] % df['c'] Out[7]: 0 -1.132022 1 -0.939493 2 0.201931 3 0.511374 4 -0.694647 5 -0.023486 Name: a ```
This is same as the previous solution but I have defined the function in df.apply itself: ``` df['Value'] = df.apply(lambda row: row['a']%row['c'], axis=1) ```
16,353,729
I have some problems with the Pandas apply function, when using multiple columns with the following dataframe ``` df = DataFrame ({'a' : np.random.randn(6), 'b' : ['foo', 'bar'] * 3, 'c' : np.random.randn(6)}) ``` and the following function ``` def my_test(a, b): return a % b ``` When I try to apply this function with : ``` df['Value'] = df.apply(lambda row: my_test(row[a], row[c]), axis=1) ``` I get the error message: ``` NameError: ("global name 'a' is not defined", u'occurred at index 0') ``` I do not understand this message, I defined the name properly. I would highly appreciate any help on this issue Update Thanks for your help. I made indeed some syntax mistakes with the code, the index should be put ''. However I still get the same issue using a more complex function such as: ``` def my_test(a): cum_diff = 0 for ix in df.index(): cum_diff = cum_diff + (a - df['a'][ix]) return cum_diff ```
2013/05/03
[ "https://Stackoverflow.com/questions/16353729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2331506/" ]
Let's say we want to apply a function add5 to columns 'a' and 'b' of DataFrame df ``` def add5(x): return x+5 df[['a', 'b']].apply(add5) ```
I have given the comparison of all three discussed above. **Using values** ``` %timeit df['value'] = df['a'].values % df['c'].values ``` 139 µs ± 1.91 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) **Without values** ``` %timeit df['value'] = df['a']%df['c'] ``` 216 µs ± 1.86 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) **Apply function** ``` %timeit df['Value'] = df.apply(lambda row: row['a']%row['c'], axis=1) ``` 474 µs ± 5.07 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)