qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
1,360,248
I'm trying to get Windows 10 to emulate the new "Digital Wellbeing" feature that Google released alongside Android 9. Basically it changes the screen to grey-scale at night-time to try and incentivize people to get off their phone and go to sleep. When I learned of Windows 10's "color filter" feature (which also allows you to set the color profile to grey-scale), I thought scripting this might be easy, but I can't seem to find a way to do this in a script directly. At the moment, I basically have it working by turning on the `Win`+`Ctrl`+`C` toggle hotkey, and have a scheduled task set to run an AutoHotkey script that essentially hits those keys to trigger the shortcut. This works ok, but I'd like to be able to leave the shortcut key disabled so I don't accidentally hit it, or have such an easy way to disable the feature (and weaken the "Digital Wellbeing" effect). Also, the script has no way to know what the state of the setting is. If it runs twice, it undoes itself. Currently I don't have the machine scripted to unset the feature, but if I created a task to do that, and I shut the machine off before the nightly trigger, it might go grey-scale in the morning. My question is to ask if there is any way I might be able to explicitly set "color filter on", or "color filter off" directly (via PowerShell, Batch, VBS, whatever) that doesn't depend on the shortcut key, and preferably that doesn't toggle?
2018/09/21
[ "https://superuser.com/questions/1360248", "https://superuser.com", "https://superuser.com/users/927750/" ]
I had exactly the same need. I used [AutoHotKey](https://www.autohotkey.com/) for this. This script checks every 10 min. If the time between 10:30 - 10:39 pm, it presses `Win`+`Ctrl`+`C`. ``` #Persistent SetTimer, ToggleGreyscaleFilter, 600000 ; Check every 10 min ToggleGreyscaleFilter: TheTime = %A_Hour%%A_Min% If TheTime Between 2230 and 2239 ; If it is between 10:30 and 10:39 pm { MsgBox, "Sleep" ; Optional popup message Send #^c ; Press Win-Ctrl-C to toggle greyscale } ``` For this to work, in Settings > Ease of Access > Color Filters: * Allow the shortcut key to toggle filter on or off (Win-Ctrl-C) * Select Greyscale filter
For those who looking for simple solution on Windows: You may use [WinMagnification](https://pypi.org/project/WinMagnification/) Python 3.8+ lib. It supports a grayscale color effect, and also you can animate transition with it (by changing effect power over time). ``` import win_magnification as mag mag_api = mag.WinMagnificationAPI() # Set grayscale color filter mag_api.fullscreen.color_effect.raw = mag.const.COLOR_GRAYSCALE_EFFECT # Animate from normal to grayscale import time mag_api.fullscreen.color_effect.reset() mag_api.fullscreen.color_effect.make_transition( end=mag.const.COLOR_GRAYSCALE_EFFECT, initial_power=0, ) for i in range(100): mag_api.fullscreen.color_effect.transition_power += 0.01 time.sleep(0.05) ```
22,467,142
I am relatively new to T4 templates. I am working in visual studio 2012 and using the tangible T4 editor. I have my text templates in one project and I want to read a class in another project and do some processing and write the generated code to a third project. I want to pass in the class file path to my template For example "C:/Code/Project2/ClassFooBar.cs" and the template will read the class from the given location and do some processing with the class properties and write the generated code to project3. I want to pass in the file path since my project has a number of class files and there is not a pattern that I can specify in the template. My solution structure is: ``` SolutionFoo: - Project1 -TextTemplate.tt - Project2 - ClassFooBar.cs - Project3 -GeneratedCode.cs ``` anyone can guide me with a clean way of passing in the class path and a way to writing the generated code to Project3?
2014/03/17
[ "https://Stackoverflow.com/questions/22467142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1527762/" ]
In the form action, you are directing to **<https://www.paypal.com/cgi-bin/webscr>** But In the IPN code your ``` $ch = curl_init('https://www.sandbox.paypal.com/cgi-bin/webscr'); ``` So one points to the sandbox, but not the other. That should be the problem.
The problem is in your IPN handler, not in this code. It should be obvious that this code must work, otherwise no IPN would have happened at all. You need to post the *relevant* code. Probably you haven't built the validation callback URL correctly, or you aren't sending it to the right URL (sandbox or live).
18,553,214
I can't figure out what the 'bytes' method is complaining about. In the code below, i am trying to generate an authentication key for my client and i keep getting this error [1] ``` import hmac import hashlib import base64 message = bytes("Message", 'utf-8') # errors here secret = bytes("secret", 'utf-8') signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest()); print(signature) ``` [1] ``` Traceback (most recent call last): File "API/test/auth-client.py", line 11, in <module> message = bytes("Message", 'utf-8') TypeError: str() takes at most 1 argument (2 given) ```
2013/08/31
[ "https://Stackoverflow.com/questions/18553214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/643954/" ]
`bytes()` in Python 2.x is the same as `str()` and it accepts only one string argument. Use just `message = "Message"` and `secret = "secret"`. You don't even need `bytes()` here.
try, ``` import hmac import hashlib import base64 message = bytes("Message") secret = bytes("secret") signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest()) print(signature) ```
18,553,214
I can't figure out what the 'bytes' method is complaining about. In the code below, i am trying to generate an authentication key for my client and i keep getting this error [1] ``` import hmac import hashlib import base64 message = bytes("Message", 'utf-8') # errors here secret = bytes("secret", 'utf-8') signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest()); print(signature) ``` [1] ``` Traceback (most recent call last): File "API/test/auth-client.py", line 11, in <module> message = bytes("Message", 'utf-8') TypeError: str() takes at most 1 argument (2 given) ```
2013/08/31
[ "https://Stackoverflow.com/questions/18553214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/643954/" ]
The likely reason you encountered this problem is the code you were using was written for Python 3.x and you executed it under Python 2.x. *I know someone has already partially stated this, but I thought it might be helpful to make it clearer to people new to Python who may not realize why the 'utf-8' argument was being used as the person asking the question noted that they did not know what the argument was for.* *Anyone who comes here may find that useful in understanding why there was an argument of 'utf-8'.*
try, ``` import hmac import hashlib import base64 message = bytes("Message") secret = bytes("secret") signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest()) print(signature) ```
18,553,214
I can't figure out what the 'bytes' method is complaining about. In the code below, i am trying to generate an authentication key for my client and i keep getting this error [1] ``` import hmac import hashlib import base64 message = bytes("Message", 'utf-8') # errors here secret = bytes("secret", 'utf-8') signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest()); print(signature) ``` [1] ``` Traceback (most recent call last): File "API/test/auth-client.py", line 11, in <module> message = bytes("Message", 'utf-8') TypeError: str() takes at most 1 argument (2 given) ```
2013/08/31
[ "https://Stackoverflow.com/questions/18553214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/643954/" ]
`bytes()` in Python 2.x is the same as `str()` and it accepts only one string argument. Use just `message = "Message"` and `secret = "secret"`. You don't even need `bytes()` here.
The likely reason you encountered this problem is the code you were using was written for Python 3.x and you executed it under Python 2.x. *I know someone has already partially stated this, but I thought it might be helpful to make it clearer to people new to Python who may not realize why the 'utf-8' argument was being used as the person asking the question noted that they did not know what the argument was for.* *Anyone who comes here may find that useful in understanding why there was an argument of 'utf-8'.*
16,766,490
please help me for my coding. I want to make a program like this. sorry bad english. Given input: ``` N where N is an integer. ``` return: ``` True if N = 2^x, where x is an integer. ``` I've tried to do this but it doesn't work as i want. ``` using namespace std; int main() { float a,b,c; cin>>a; c=log10(a)/log10(2.0); b=pow(2,c); if(b==a) { cout<<"TRUE"<<endl;} else cout<<"FALSE"<<endl;{ } } ``` Help me please. Thank you.
2013/05/27
[ "https://Stackoverflow.com/questions/16766490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2423694/" ]
As [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) explains, floating point numbers in computer programs pretend they can represent any real number, but actually have only 32 or 64 bits, so you will get rounded off to the nearest representation. Even numbers that look simple, like 0.1, have an endless representation in binary and so will get rounded off. Functions that operate on floating point numbers like `cos` and `pow` will, by their nature, sometimes give you the 'wrong' result simply because the 'right' result is not a representible floating point. Sometimes the solution is complex. However in this case the solution is quite simple - check that the two numbers' difference is less than epsilon, where epsilon is a small enough number to give you the accuracy you need. e.g. ``` float epsilon = 0.0001; if(abs(b-a) < epsilon) ``` Also, whenever you need accuracy more than speed and size, use `double` in preference to `float`. It's twice as big and thus many significant places more precise.
Declare the values a,b,c as double if you want to use this c=log10(a)/log10(2.0); Declare the values a,b,c as float if u want to use this c=log10(a)/log10(2.0f); I executed the program with both these changes ,one by one .Its working for both check the syntax and example [here](http://www.cplusplus.com/reference/cmath/log10/)
16,766,490
please help me for my coding. I want to make a program like this. sorry bad english. Given input: ``` N where N is an integer. ``` return: ``` True if N = 2^x, where x is an integer. ``` I've tried to do this but it doesn't work as i want. ``` using namespace std; int main() { float a,b,c; cin>>a; c=log10(a)/log10(2.0); b=pow(2,c); if(b==a) { cout<<"TRUE"<<endl;} else cout<<"FALSE"<<endl;{ } } ``` Help me please. Thank you.
2013/05/27
[ "https://Stackoverflow.com/questions/16766490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2423694/" ]
As [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) explains, floating point numbers in computer programs pretend they can represent any real number, but actually have only 32 or 64 bits, so you will get rounded off to the nearest representation. Even numbers that look simple, like 0.1, have an endless representation in binary and so will get rounded off. Functions that operate on floating point numbers like `cos` and `pow` will, by their nature, sometimes give you the 'wrong' result simply because the 'right' result is not a representible floating point. Sometimes the solution is complex. However in this case the solution is quite simple - check that the two numbers' difference is less than epsilon, where epsilon is a small enough number to give you the accuracy you need. e.g. ``` float epsilon = 0.0001; if(abs(b-a) < epsilon) ``` Also, whenever you need accuracy more than speed and size, use `double` in preference to `float`. It's twice as big and thus many significant places more precise.
I think the code should read (given the problem description.) You want to know if N is a power of 2? **Edit to code** ``` #include <iostream> int main() { unsigned int N; std::cout << "Input a number "; std::cin >> N; unsigned int two_to_the_power_of_bit = 0; do { std::cout << "Working on " << two_to_the_power_of_bit << std::endl; if (two_to_the_power_of_bit == N) { std::cout << "TRUE" << std::endl; return 0; } if (two_to_the_power_of_bit > N) { std::cout << "FALSE" << std::endl; return 1; } if (two_to_the_power_of_bit == 0) { two_to_the_power_of_bit = 1; } else { two_to_the_power_of_bit <<= 1; } } while(two_to_the_power_of_bit); } ``` If I got your problem wrong can you please clarify? ``` Output: Input a number 3 Working on 0 Working on 1 Working on 2 Working on 4 FALSE mehoggan@mehoggan-Precision-WorkStation-T5500:~/Devel/test$ ./a.out Input a number 4 Working on 0 Working on 1 Working on 2 Working on 4 TRUE mehoggan@mehoggan-Precision-WorkStation-T5500:~/Devel/test$ ./a.out 5 Input a number 5 Working on 0 Working on 1 Working on 2 Working on 4 Working on 8 FALSE mehoggan@mehoggan-Precision-WorkStation-T5500:~/Devel/test$ ```
475,162
I'm trying without any luck to use [**NTSysLog**](http://troy.jdmz.net/syslogwin/) in order to grab my network computers *Security Logs* and send them into a Log Service ([**Loggly**](http://loggly.com/) in this case). I can install and run NTSysLog from a Windows 7 Professional machine ![enter image description here](https://i.stack.imgur.com/riiCI.png) from Loggly I only have Unix related setup help and they specify: ``` :: Syslog :: For UDP, put this in /etc/syslog.conf: *.* @logs.loggly.com:46031 To restart: /etc/init.d/syslogd restart :: rsyslog :: For UDP, put this in rsyslog.conf: *.* @logs.loggly.com:46031 ``` From this, **How can I setup a Windows machine** correctly without the need of setting up a Linux machine to be the SysLog server from then I would send the messages to the Log Service? Setting the **Primary Syslog Daemon** as it shows in the image above, does not log it.
2013/02/04
[ "https://serverfault.com/questions/475162", "https://serverfault.com", "https://serverfault.com/users/711/" ]
You can't install a certificate on a machine unless the corresponding private key is already installed. Even if you could, what would the point be? A certificate binds a key to an identity. Without the key, the certificate is useless. (The certificate is public. The key is private.) Likely the server it worked on has the private key already, possibly because the private key was generated on that machine. The instructions in the support blog you link assume the private key is already installed on the machine. You need to export the private key from the machine that generated the CSR. Then you can import that private key on other machines so that they can use the certificate to identify themselves.
mmc is not very user friendly with the snap in module etc. If you going to do operations like exporting and reimporting certs on IIS like David suggested you may want to look at other more user friendly tools like [SSLTools Manager](http://www.ssltools.com/manager)
7,746,016
I've been trying to make an icon that has transparency. I've tried Axialis but the documentation is crummy and the ui is somewhat inscrutable. Everytime I think I've figured out how to set transparency, it's coming in with white space. MS documenation mentions using magenta as the background, so I also tried that and got transparency but at the price of a pink halo. I've tried a Photoshop plugin and it came out correctly but I can't figure out how to stuff multiple sizes in there. This must be a common problem and yet Google is not being my friend.
2011/10/12
[ "https://Stackoverflow.com/questions/7746016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/992205/" ]
Just use GIMP (<http://www.gimp.org/>). Start off with a transparent background and the size you would like. I use it for all my Android applications.
Try Evan Old's plugin for Paint.NET. YMMV. <http://forums.getpaint.net/index.php?/topic/927-icon-cursor-and-animated-cursor-format-v37-may-2010/page-1>
11,600,301
I have code which is roughly as follows (I removed some parts, as they are irrelevant): ``` Library.focus = function(event) { var element, paragraph; element = event.srcElement; paragraph = document.createElement("p"); paragraph.innerText = element.innerText; element.parentNode.insertBefore(paragraph, element); // Line #1 element.parentNode.removeChild(element); // Line #2 }; ``` The issue I have, is that the last call which I've numbered as line #2 throws this: ``` Uncaught Error: NOT_FOUND_ERR: DOM Exception 8 ``` Note that the previous line #1 works fine, and inserts the paragraph node before it. Element is an existing element, and both element.parentNode and element.parentNode.removeChild exist as well. I find this illogical, as element is by definition a child of its parentNode. Maybe StackOverflow will be able to help me out, here?
2012/07/22
[ "https://Stackoverflow.com/questions/11600301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/697108/" ]
From [mdn docs](https://developer.mozilla.org/En/DOM/Node.removeChild): > > If child is actually not a child of the element node, the method > throws an exception. This will also happen if child was in fact a > child of element at the time of the call, but was removed by an event > handler invoked in the course of trying to remove the element (eg, > blur.) > > > I can reproduce this error in [jsfiddle](http://jsfiddle.net/rz3XM/1/) Basically, you focus the element, which triggers a remove, which triggers a blur, which moves the element, which makes the element not the parent anymore.
Dont pass the event as parameter for Library.focus function. it will work. ``` Library.focus = function() { var element, paragraph; element = event.srcElement; paragraph = document.createElement("p"); paragraph.innerText = element.innerText; element.parentNode.insertBefore(paragraph, element); // Line #1 element.parentNode.removeChild(element); // Line #2 }; ```
11,600,301
I have code which is roughly as follows (I removed some parts, as they are irrelevant): ``` Library.focus = function(event) { var element, paragraph; element = event.srcElement; paragraph = document.createElement("p"); paragraph.innerText = element.innerText; element.parentNode.insertBefore(paragraph, element); // Line #1 element.parentNode.removeChild(element); // Line #2 }; ``` The issue I have, is that the last call which I've numbered as line #2 throws this: ``` Uncaught Error: NOT_FOUND_ERR: DOM Exception 8 ``` Note that the previous line #1 works fine, and inserts the paragraph node before it. Element is an existing element, and both element.parentNode and element.parentNode.removeChild exist as well. I find this illogical, as element is by definition a child of its parentNode. Maybe StackOverflow will be able to help me out, here?
2012/07/22
[ "https://Stackoverflow.com/questions/11600301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/697108/" ]
If you're trying to modify, in an onblur handler, the same node you're trying to remove in another handler (eg onfocus, keydown etc) then the first call to `removeChild` will fire the onblur handler before actually removing the node. If the onblur handler then modifies the node so that its parent changes, control will return from the onblur handler to the `removeChild` call in your onfocus handler which will then try to remove the node and fail with the exception you describe. Any amount of checking for the presence of the child before calling `removeChild` in your onfocus handler will be fruitless, since those checks will happen before the onblur handler is triggered. Apart from re-arranging your event handling and node modifications, your best bet is probably to just handle the exception in a try catch block. The following code will show how the onblur event handler runs before `removeChild` in onfocus actually removes the child. It is also on [jsfiddle](http://jsfiddle.net/FBs4b/11/) html ``` <div id="iParent"> <input id="i"> </div> ``` js ``` var input = document.querySelector("#i"), inputParent = document.querySelector('#iParent'); input.onblur = function() { console.log('onblur : input ' + (input.parentNode ? 'has' : 'doesnt have') + ' a parent BEFORE delete'); try { inputParent.removeChild(input); } catch (err) { console.log('onblur : removeChild failed, input ' + (input.parentNode ? 'has' : 'doesnt have') + ' a parent'); return false; } console.log('onblur : child removed'); }; input.onfocus = function() { console.log('onfocus : input ' + (input.parentNode ? 'has' : 'doesnt have') + ' a parent BEFORE delete'); try { inputParent.removeChild(input); } catch (err) { console.log('onfocus : removeChild failed, input ' + (input.parentNode ? 'has' : 'doesnt have') + ' a parent'); return false; } console.log('onfocus : child removed'); };​ ``` Console output after focusing on the input field will be ``` onfocus : input has a parent BEFORE delete onblur : input has a parent BEFORE delete onblur : child removed onfocus : removeChild failed, input doesnt have a parent ```
Dont pass the event as parameter for Library.focus function. it will work. ``` Library.focus = function() { var element, paragraph; element = event.srcElement; paragraph = document.createElement("p"); paragraph.innerText = element.innerText; element.parentNode.insertBefore(paragraph, element); // Line #1 element.parentNode.removeChild(element); // Line #2 }; ```
11,600,301
I have code which is roughly as follows (I removed some parts, as they are irrelevant): ``` Library.focus = function(event) { var element, paragraph; element = event.srcElement; paragraph = document.createElement("p"); paragraph.innerText = element.innerText; element.parentNode.insertBefore(paragraph, element); // Line #1 element.parentNode.removeChild(element); // Line #2 }; ``` The issue I have, is that the last call which I've numbered as line #2 throws this: ``` Uncaught Error: NOT_FOUND_ERR: DOM Exception 8 ``` Note that the previous line #1 works fine, and inserts the paragraph node before it. Element is an existing element, and both element.parentNode and element.parentNode.removeChild exist as well. I find this illogical, as element is by definition a child of its parentNode. Maybe StackOverflow will be able to help me out, here?
2012/07/22
[ "https://Stackoverflow.com/questions/11600301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/697108/" ]
From [mdn docs](https://developer.mozilla.org/En/DOM/Node.removeChild): > > If child is actually not a child of the element node, the method > throws an exception. This will also happen if child was in fact a > child of element at the time of the call, but was removed by an event > handler invoked in the course of trying to remove the element (eg, > blur.) > > > I can reproduce this error in [jsfiddle](http://jsfiddle.net/rz3XM/1/) Basically, you focus the element, which triggers a remove, which triggers a blur, which moves the element, which makes the element not the parent anymore.
If you're trying to modify, in an onblur handler, the same node you're trying to remove in another handler (eg onfocus, keydown etc) then the first call to `removeChild` will fire the onblur handler before actually removing the node. If the onblur handler then modifies the node so that its parent changes, control will return from the onblur handler to the `removeChild` call in your onfocus handler which will then try to remove the node and fail with the exception you describe. Any amount of checking for the presence of the child before calling `removeChild` in your onfocus handler will be fruitless, since those checks will happen before the onblur handler is triggered. Apart from re-arranging your event handling and node modifications, your best bet is probably to just handle the exception in a try catch block. The following code will show how the onblur event handler runs before `removeChild` in onfocus actually removes the child. It is also on [jsfiddle](http://jsfiddle.net/FBs4b/11/) html ``` <div id="iParent"> <input id="i"> </div> ``` js ``` var input = document.querySelector("#i"), inputParent = document.querySelector('#iParent'); input.onblur = function() { console.log('onblur : input ' + (input.parentNode ? 'has' : 'doesnt have') + ' a parent BEFORE delete'); try { inputParent.removeChild(input); } catch (err) { console.log('onblur : removeChild failed, input ' + (input.parentNode ? 'has' : 'doesnt have') + ' a parent'); return false; } console.log('onblur : child removed'); }; input.onfocus = function() { console.log('onfocus : input ' + (input.parentNode ? 'has' : 'doesnt have') + ' a parent BEFORE delete'); try { inputParent.removeChild(input); } catch (err) { console.log('onfocus : removeChild failed, input ' + (input.parentNode ? 'has' : 'doesnt have') + ' a parent'); return false; } console.log('onfocus : child removed'); };​ ``` Console output after focusing on the input field will be ``` onfocus : input has a parent BEFORE delete onblur : input has a parent BEFORE delete onblur : child removed onfocus : removeChild failed, input doesnt have a parent ```
38,530,983
Is it possible to loop a json object one by one ? let's say I have this object (text). I want to loop on `text` and get **next** item every 1 minute until I get them all. How can I do this in javascript ? ``` var text = { "name":"John Johnson", "street":"Oslo West 16", "determine":"555 1234567", "JSON":"concernant", "you":"value" }; setInterval(function(){ //text.getnext }, 1000); ``` sorry if it is duplicated I have not found solution.
2016/07/22
[ "https://Stackoverflow.com/questions/38530983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6608257/" ]
You can use `Object.keys` if the order is not important: ``` var keys = Object.keys(text), i = 0; var myInterval = setInterval(function(){ if(i >= keys.length) clearInterval(myInterval); // You need to clear the interval ;) var current = text[keys[i++]]; //..... }, 1000*60); //1 minute ``` I hope this will help you.
**Native:** You can get a list of keys in an array by using `Object.keys` and `setTimeout` built-in functions. `Object.keys` returns an array of keys an an object `setTimeout` takes a function and executes it after certain number of milliseconds (1000) in this case So in your case ``` var keys = Object.keys(array); function iterate(keys, index){ if(index == keys.length) return; else{ console.log("current is " + array[keys[index]]); setTimeout(function(){iterate(keys, index + 1)}, 1000); } } ``` Then call `itterate(text, 0);`
38,530,983
Is it possible to loop a json object one by one ? let's say I have this object (text). I want to loop on `text` and get **next** item every 1 minute until I get them all. How can I do this in javascript ? ``` var text = { "name":"John Johnson", "street":"Oslo West 16", "determine":"555 1234567", "JSON":"concernant", "you":"value" }; setInterval(function(){ //text.getnext }, 1000); ``` sorry if it is duplicated I have not found solution.
2016/07/22
[ "https://Stackoverflow.com/questions/38530983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6608257/" ]
You can use `Object.keys` if the order is not important: ``` var keys = Object.keys(text), i = 0; var myInterval = setInterval(function(){ if(i >= keys.length) clearInterval(myInterval); // You need to clear the interval ;) var current = text[keys[i++]]; //..... }, 1000*60); //1 minute ``` I hope this will help you.
You could use the superb example of MDN for [Iterators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterators) and use it for the properties. For every interval, the iterator is called with `next()` and then the value is checked. if done, clear the interval or display the property. ```js function makeIterator(array) { var nextIndex = 0; return { next: function () { return nextIndex < array.length ? { value: array[nextIndex++], done: false } : { done: true }; } }; } var text = { "name": "John Johnson", "street": "Oslo West 16", "determine": "555 1234567", "JSON": "concernant", "you": "value" }, iterator = makeIterator(Object.keys(text)), interval = setInterval(function () { var k = iterator.next(); if (k.done) { clearInterval(interval); } else { console.log(text[k.value]); } // this value is for demo purpose }, 1000); // for a minute interval change to 60000 ```
38,530,983
Is it possible to loop a json object one by one ? let's say I have this object (text). I want to loop on `text` and get **next** item every 1 minute until I get them all. How can I do this in javascript ? ``` var text = { "name":"John Johnson", "street":"Oslo West 16", "determine":"555 1234567", "JSON":"concernant", "you":"value" }; setInterval(function(){ //text.getnext }, 1000); ``` sorry if it is duplicated I have not found solution.
2016/07/22
[ "https://Stackoverflow.com/questions/38530983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6608257/" ]
You can use `Object.keys` if the order is not important: ``` var keys = Object.keys(text), i = 0; var myInterval = setInterval(function(){ if(i >= keys.length) clearInterval(myInterval); // You need to clear the interval ;) var current = text[keys[i++]]; //..... }, 1000*60); //1 minute ``` I hope this will help you.
You should first solve the generic problem of sending out the element of an array with some delay. Once you've done that, it's easy enough to apply that to the keys of an object. Here's a simple version using `setTimeout`: ``` function emitWithDelay(array, callback) { var n = 0; function emitOne() { if (n >= array.length) return; setTimeout(function() { callback(array[n++]); emitOne(); }, 1000); } emitOne(); } ``` Now you can just do ``` emitWithDelay(Object.keys(obj), myCallback); ``` ### Streams This is a good problem for using streams, or observables. It is as simple as ``` Observable.from(Object.keys(obj)) .delay(1000) .subscribe(elt => console.log("got elt", elt)); ``` ### Async approach Another idea is to use async functions, an ES7 feature, as follows: ``` async function emitWithDelay(array, callback) { for (elt of array) { callback(elt); await sleep(1000); } } ``` Where `sleep` is something like ``` function sleep(n) { return new Promise(resolve => setTimeout(resolve, n)); } ``` As you can see, the possibilities are endless.
38,530,983
Is it possible to loop a json object one by one ? let's say I have this object (text). I want to loop on `text` and get **next** item every 1 minute until I get them all. How can I do this in javascript ? ``` var text = { "name":"John Johnson", "street":"Oslo West 16", "determine":"555 1234567", "JSON":"concernant", "you":"value" }; setInterval(function(){ //text.getnext }, 1000); ``` sorry if it is duplicated I have not found solution.
2016/07/22
[ "https://Stackoverflow.com/questions/38530983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6608257/" ]
You could use the superb example of MDN for [Iterators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterators) and use it for the properties. For every interval, the iterator is called with `next()` and then the value is checked. if done, clear the interval or display the property. ```js function makeIterator(array) { var nextIndex = 0; return { next: function () { return nextIndex < array.length ? { value: array[nextIndex++], done: false } : { done: true }; } }; } var text = { "name": "John Johnson", "street": "Oslo West 16", "determine": "555 1234567", "JSON": "concernant", "you": "value" }, iterator = makeIterator(Object.keys(text)), interval = setInterval(function () { var k = iterator.next(); if (k.done) { clearInterval(interval); } else { console.log(text[k.value]); } // this value is for demo purpose }, 1000); // for a minute interval change to 60000 ```
**Native:** You can get a list of keys in an array by using `Object.keys` and `setTimeout` built-in functions. `Object.keys` returns an array of keys an an object `setTimeout` takes a function and executes it after certain number of milliseconds (1000) in this case So in your case ``` var keys = Object.keys(array); function iterate(keys, index){ if(index == keys.length) return; else{ console.log("current is " + array[keys[index]]); setTimeout(function(){iterate(keys, index + 1)}, 1000); } } ``` Then call `itterate(text, 0);`
38,530,983
Is it possible to loop a json object one by one ? let's say I have this object (text). I want to loop on `text` and get **next** item every 1 minute until I get them all. How can I do this in javascript ? ``` var text = { "name":"John Johnson", "street":"Oslo West 16", "determine":"555 1234567", "JSON":"concernant", "you":"value" }; setInterval(function(){ //text.getnext }, 1000); ``` sorry if it is duplicated I have not found solution.
2016/07/22
[ "https://Stackoverflow.com/questions/38530983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6608257/" ]
You could use the superb example of MDN for [Iterators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterators) and use it for the properties. For every interval, the iterator is called with `next()` and then the value is checked. if done, clear the interval or display the property. ```js function makeIterator(array) { var nextIndex = 0; return { next: function () { return nextIndex < array.length ? { value: array[nextIndex++], done: false } : { done: true }; } }; } var text = { "name": "John Johnson", "street": "Oslo West 16", "determine": "555 1234567", "JSON": "concernant", "you": "value" }, iterator = makeIterator(Object.keys(text)), interval = setInterval(function () { var k = iterator.next(); if (k.done) { clearInterval(interval); } else { console.log(text[k.value]); } // this value is for demo purpose }, 1000); // for a minute interval change to 60000 ```
You should first solve the generic problem of sending out the element of an array with some delay. Once you've done that, it's easy enough to apply that to the keys of an object. Here's a simple version using `setTimeout`: ``` function emitWithDelay(array, callback) { var n = 0; function emitOne() { if (n >= array.length) return; setTimeout(function() { callback(array[n++]); emitOne(); }, 1000); } emitOne(); } ``` Now you can just do ``` emitWithDelay(Object.keys(obj), myCallback); ``` ### Streams This is a good problem for using streams, or observables. It is as simple as ``` Observable.from(Object.keys(obj)) .delay(1000) .subscribe(elt => console.log("got elt", elt)); ``` ### Async approach Another idea is to use async functions, an ES7 feature, as follows: ``` async function emitWithDelay(array, callback) { for (elt of array) { callback(elt); await sleep(1000); } } ``` Where `sleep` is something like ``` function sleep(n) { return new Promise(resolve => setTimeout(resolve, n)); } ``` As you can see, the possibilities are endless.
59,564,296
I created new column in table and wrote an inner join function which fills that column with values. But now i figured it out that i need that value added for each repeated `NUMBER` in table `CART`. ``` ALTER TABLE [HEADERS] ADD [SUM] [DECIMAL] GO UPDATE [HEADERS] SET [HEADERS].[SUM] = [CART].[AMOUNT]*[CART].[PRICE] FROM [HEADERS] INNER JOIN [CART] ON [HEADERS].[NUMBER] = [CART].[NUMBER] GO ``` Column `NUMBER` is unique in `HEADERS` but is not unique and repeated in `CART`. So what i need is to count `[CART].[AMOUNT]*[CART].[PRICE]` for each identical `NUMBER` in `CART`, summary this, and then fill in this value into suitable verse of table `HEADERS`- where `[HEADERS].[NUMBER] = [CART].[NUMBER]`. I'm not rly good at databases, but i know there is no foreach loop and i need help with that task. How can i achieve my goal?
2020/01/02
[ "https://Stackoverflow.com/questions/59564296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11598253/" ]
Use aggregation before the `JOIN`: ``` UPDATE h SET h.[SUM] = c.total FROM HEADERS h JOIN (SELECT c.NUMBER, SUM(C.AMOUNT * C.PRICE) as total FROM CART c GROUP BY c.NUMBER ) c ON c.NUMBER = h.NUMBER; ```
You probably need to add the TableName C to fix the query-error and make it work: ``` UPDATE h SET h.[SUM] = c.[CART].[AMOUNT]*c.[CART].[PRICE] FROM HEADERS h JOIN (SELECT c.NUMBER, SUM(C.AMOUNT * C.PRICE) as total FROM CART c GROUP BY c.NUMBER ) c ON c.NUMBER = h.NUMBER; ``` Alternatively this might fix the problem: ``` UPDATE h SET h.[SUM] = c.total FROM HEADERS h JOIN (SELECT c.NUMBER, SUM(C.AMOUNT * C.PRICE) as total FROM CART c GROUP BY c.NUMBER ) c ON c.NUMBER = h.NUMBER; ```
1,239,311
I'm a very long time ubuntu user (over a decade) but have not been here as I've had no issues with Ubuntu. With the arrival of 20.04 LTS I decided to encrypt my data (or system if needed). I'm looking for the following: * Method to reinstall ubuntu with LUKS encryption on a previous LUKS encrypted ubuntu install on a dual boot system with Win10. * Keep all my personal files (ie `/home` folder) intact, with or without a separate partition. I do not wish to move everything out, reinstall and then move stuff back in. * Simple GUI based approach through the standard installer. I know how to use the command line but I'd rather not, especially for something as sensitive as encryption. What I'm looking for is basically the same as this document: (<https://help.ubuntu.com/community/UbuntuReinstallation>) except that I need it on an LUKS encrypted system/partition. I tried doing this on a spare system with 20.04, and I could not find a way of telling the installer the passphrase to the encrypted system. The end result was a reinstall that wouldn't boot or the encrypted partition gets wiped out. I also tried to run installer with and without pre-unlocking the encrypted partition but to no avail'. I am able to do all of the above with Fedora,OpenSUSE,Manjaro, (although they only do this when /home is on separate partition, which is fine for me) so I'm not sure what I'm doing wrong in Ubuntu. Thanks!
2020/05/14
[ "https://askubuntu.com/questions/1239311", "https://askubuntu.com", "https://askubuntu.com/users/1082019/" ]
For video playback in the browser you only need to install the package `ubuntu-restricted-extras`. To do so open a terminal and type: ``` sudo apt install ubuntu-restricted-extras ``` Should that still fail with the error message you posted above, reboot and try again. Should the error persist, a previous update might have been interrupted and left the lock file in place, as Pilot6 commented above. To fix that: 1. In a fresh terminal type `sudo rm /var/lib/dpkg/lock-frontend` 2. Then make sure, all packages are installed correctly with `sudo apt-get -f install` 3. Make sure the codecs are installed correctly with `sudo apt install ubuntu-restricted-extras`. When you are prompted to accept the EULA for the Microsoft fonts package, use `Tab` and `Enter` to agree. After restarting your browser, video playback should work.
I tried and failed to get videos to work. I install both clv and mpv and found that both worked. I chose to set music and video in Settings -> Default Applications to mpv. Whist I was fighting videos I may have install various codex which might just be essential to mpv.
1,239,311
I'm a very long time ubuntu user (over a decade) but have not been here as I've had no issues with Ubuntu. With the arrival of 20.04 LTS I decided to encrypt my data (or system if needed). I'm looking for the following: * Method to reinstall ubuntu with LUKS encryption on a previous LUKS encrypted ubuntu install on a dual boot system with Win10. * Keep all my personal files (ie `/home` folder) intact, with or without a separate partition. I do not wish to move everything out, reinstall and then move stuff back in. * Simple GUI based approach through the standard installer. I know how to use the command line but I'd rather not, especially for something as sensitive as encryption. What I'm looking for is basically the same as this document: (<https://help.ubuntu.com/community/UbuntuReinstallation>) except that I need it on an LUKS encrypted system/partition. I tried doing this on a spare system with 20.04, and I could not find a way of telling the installer the passphrase to the encrypted system. The end result was a reinstall that wouldn't boot or the encrypted partition gets wiped out. I also tried to run installer with and without pre-unlocking the encrypted partition but to no avail'. I am able to do all of the above with Fedora,OpenSUSE,Manjaro, (although they only do this when /home is on separate partition, which is fine for me) so I'm not sure what I'm doing wrong in Ubuntu. Thanks!
2020/05/14
[ "https://askubuntu.com/questions/1239311", "https://askubuntu.com", "https://askubuntu.com/users/1082019/" ]
I can now play videos thanks to the input of Bene and Pilot6. Solution was as follows: 1. $ sudo apt install ubuntu-restricted-extras On prompt/ message/ question by command terminal I typed in: 2. $ sudo dpkg --configure -a I accepted MS license by pressing tab, enter Package installed successfully
I tried and failed to get videos to work. I install both clv and mpv and found that both worked. I chose to set music and video in Settings -> Default Applications to mpv. Whist I was fighting videos I may have install various codex which might just be essential to mpv.
229,939
Running Snow Leopard. Completely inexplicably, I seem to have enabled the OSX root user by accident. I honestly have no idea how it happened, but if memory serves I was looking at the login pane (with my two user accounts) when I must have hit something, and suddenly the two accounts were replaced by one that just said "Other..." Clicking the "Other..." account allows me to type a username and password, but neither of the normal two accounts would work. Since I never set a root password, it wouldn't let me in that way either. So I booted into Single User mode and ran these commands: ``` /sbin/mount -uw / fsck -fy launchctl load /System/Library/LaunchDaemons/com.apple.DirectoryServices.plist dscl . -passwd /Users/root newpassword ``` and that let me login as root. Then, I went to System Preferences, Accounts, Login Options, clicked Join, Open Directory Utility, and lastly in the Edit menu I clicked "Disable Root User" Great, I thought, back to normal. Except rebooting, I still only have the Other... account visible, and the root password I set beforehand doesn't work anymore! I have to reboot into Single User Mode and go through the whole process again just to get back into the system (as root) How on Earth did I accidentally enable this? I didn't even know about the Directory Utility before now. And most importantly, why the heck would it be re-enabling the root user on boot? Thanks in advance to any help!
2011/01/06
[ "https://superuser.com/questions/229939", "https://superuser.com", "https://superuser.com/users/58051/" ]
The problem turned out to be that the /Users folder, or some related configuration became corrupt. My user home folders were still there but the Accounts pane of System Preferences didn't list them. Running ls -lah on /Users showed that my two normal accounts had "501" and "502" as the user and "staff" as the group, rather than the expected shortnames as the users. This was resolved by simply re-creating the user accounts and opting to use the existing home folder. Wish I'd thought to do that. All is well now though.
Revert to an old Time Machine backup, or failing that, an Archive and Install and repair your installation. It sounds like you've broken it irreparably.
1,345,575
I know there is this [post](https://stackoverflow.com/questions/495050/list-of-css-features-not-supported-by-ie6), but I still want to know more and learn from other ppl that have a lot more experience than I do. So I was wondering *what CSS-features or Javascript-functions or anything else I am not thinking of right now do not work in IE6+ or have you experience to not work with IE6+?* And maybe you have a hack for it (except my favorite one: use a different browser)? I'd really appriciate your opinion. Thnx.
2009/08/28
[ "https://Stackoverflow.com/questions/1345575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109948/" ]
If you need a list of IE bugs refer this [Explorer Exposed!](http://www.positioniseverything.net/explorer.html) Another CSS that won't work with IE is [Border-radius: create rounded corners with CSS!](http://www.css3.info/preview/rounded-border/) And also read this one from msdn [CSS Compatibility and Internet Explorer](http://msdn.microsoft.com/en-us/library/cc351024%28VS.85%29.aspx)
There's always [quirks mode](http://www.quirksmode.org/bugreports/archives/explorer_windows/)
1,345,575
I know there is this [post](https://stackoverflow.com/questions/495050/list-of-css-features-not-supported-by-ie6), but I still want to know more and learn from other ppl that have a lot more experience than I do. So I was wondering *what CSS-features or Javascript-functions or anything else I am not thinking of right now do not work in IE6+ or have you experience to not work with IE6+?* And maybe you have a hack for it (except my favorite one: use a different browser)? I'd really appriciate your opinion. Thnx.
2009/08/28
[ "https://Stackoverflow.com/questions/1345575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109948/" ]
If you need a list of IE bugs refer this [Explorer Exposed!](http://www.positioniseverything.net/explorer.html) Another CSS that won't work with IE is [Border-radius: create rounded corners with CSS!](http://www.css3.info/preview/rounded-border/) And also read this one from msdn [CSS Compatibility and Internet Explorer](http://msdn.microsoft.com/en-us/library/cc351024%28VS.85%29.aspx)
IE (not only 6 though, think I've seen this on 7 as well) has this thing where it will not evaluate values in loops until it's out of the method. That is, this code (example of setting ids on cells in a table row): ``` putids = function (cells) { for (var i = 0; i < 5; i++) { cells[i].id = "cellid" + i; } } ``` would give you 5 cells, all with the id "cellid5". You actually need to move the assignment to a different method and call that in the loop in order to have different ids. As for CSS, I remember the "absolute" versus "fixed" trouble: they're exactly opposite from any other browser (although yui for example deals with this properly). Also, IE6 has no support for transparent png files. These are just from the top of my head.
1,345,575
I know there is this [post](https://stackoverflow.com/questions/495050/list-of-css-features-not-supported-by-ie6), but I still want to know more and learn from other ppl that have a lot more experience than I do. So I was wondering *what CSS-features or Javascript-functions or anything else I am not thinking of right now do not work in IE6+ or have you experience to not work with IE6+?* And maybe you have a hack for it (except my favorite one: use a different browser)? I'd really appriciate your opinion. Thnx.
2009/08/28
[ "https://Stackoverflow.com/questions/1345575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109948/" ]
If you need a list of IE bugs refer this [Explorer Exposed!](http://www.positioniseverything.net/explorer.html) Another CSS that won't work with IE is [Border-radius: create rounded corners with CSS!](http://www.css3.info/preview/rounded-border/) And also read this one from msdn [CSS Compatibility and Internet Explorer](http://msdn.microsoft.com/en-us/library/cc351024%28VS.85%29.aspx)
More advanced CSS selectors, such as *element > immediate-child*, `element[attribute=value]`, etc., do not appear to work in IE (tested on IE8) for elements dynamically added to the page. I've seen stuff like `div#something > p {color: red}` not working in IE once the `p` nodes were added dynamically as a child of `div#something`. I guess this is an issue you should be concerned with when creating tight CSS for dynamically created content: stick to simple stuff.
1,345,575
I know there is this [post](https://stackoverflow.com/questions/495050/list-of-css-features-not-supported-by-ie6), but I still want to know more and learn from other ppl that have a lot more experience than I do. So I was wondering *what CSS-features or Javascript-functions or anything else I am not thinking of right now do not work in IE6+ or have you experience to not work with IE6+?* And maybe you have a hack for it (except my favorite one: use a different browser)? I'd really appriciate your opinion. Thnx.
2009/08/28
[ "https://Stackoverflow.com/questions/1345575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109948/" ]
If you need a list of IE bugs refer this [Explorer Exposed!](http://www.positioniseverything.net/explorer.html) Another CSS that won't work with IE is [Border-radius: create rounded corners with CSS!](http://www.css3.info/preview/rounded-border/) And also read this one from msdn [CSS Compatibility and Internet Explorer](http://msdn.microsoft.com/en-us/library/cc351024%28VS.85%29.aspx)
Quirksmode is good. You can also get a full run-down of what is supported by whom over at SitePoint: <http://reference.sitepoint.com/css>
1,345,575
I know there is this [post](https://stackoverflow.com/questions/495050/list-of-css-features-not-supported-by-ie6), but I still want to know more and learn from other ppl that have a lot more experience than I do. So I was wondering *what CSS-features or Javascript-functions or anything else I am not thinking of right now do not work in IE6+ or have you experience to not work with IE6+?* And maybe you have a hack for it (except my favorite one: use a different browser)? I'd really appriciate your opinion. Thnx.
2009/08/28
[ "https://Stackoverflow.com/questions/1345575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109948/" ]
There's always [quirks mode](http://www.quirksmode.org/bugreports/archives/explorer_windows/)
IE (not only 6 though, think I've seen this on 7 as well) has this thing where it will not evaluate values in loops until it's out of the method. That is, this code (example of setting ids on cells in a table row): ``` putids = function (cells) { for (var i = 0; i < 5; i++) { cells[i].id = "cellid" + i; } } ``` would give you 5 cells, all with the id "cellid5". You actually need to move the assignment to a different method and call that in the loop in order to have different ids. As for CSS, I remember the "absolute" versus "fixed" trouble: they're exactly opposite from any other browser (although yui for example deals with this properly). Also, IE6 has no support for transparent png files. These are just from the top of my head.
1,345,575
I know there is this [post](https://stackoverflow.com/questions/495050/list-of-css-features-not-supported-by-ie6), but I still want to know more and learn from other ppl that have a lot more experience than I do. So I was wondering *what CSS-features or Javascript-functions or anything else I am not thinking of right now do not work in IE6+ or have you experience to not work with IE6+?* And maybe you have a hack for it (except my favorite one: use a different browser)? I'd really appriciate your opinion. Thnx.
2009/08/28
[ "https://Stackoverflow.com/questions/1345575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109948/" ]
There's always [quirks mode](http://www.quirksmode.org/bugreports/archives/explorer_windows/)
More advanced CSS selectors, such as *element > immediate-child*, `element[attribute=value]`, etc., do not appear to work in IE (tested on IE8) for elements dynamically added to the page. I've seen stuff like `div#something > p {color: red}` not working in IE once the `p` nodes were added dynamically as a child of `div#something`. I guess this is an issue you should be concerned with when creating tight CSS for dynamically created content: stick to simple stuff.
1,345,575
I know there is this [post](https://stackoverflow.com/questions/495050/list-of-css-features-not-supported-by-ie6), but I still want to know more and learn from other ppl that have a lot more experience than I do. So I was wondering *what CSS-features or Javascript-functions or anything else I am not thinking of right now do not work in IE6+ or have you experience to not work with IE6+?* And maybe you have a hack for it (except my favorite one: use a different browser)? I'd really appriciate your opinion. Thnx.
2009/08/28
[ "https://Stackoverflow.com/questions/1345575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109948/" ]
There's always [quirks mode](http://www.quirksmode.org/bugreports/archives/explorer_windows/)
Quirksmode is good. You can also get a full run-down of what is supported by whom over at SitePoint: <http://reference.sitepoint.com/css>
1,345,575
I know there is this [post](https://stackoverflow.com/questions/495050/list-of-css-features-not-supported-by-ie6), but I still want to know more and learn from other ppl that have a lot more experience than I do. So I was wondering *what CSS-features or Javascript-functions or anything else I am not thinking of right now do not work in IE6+ or have you experience to not work with IE6+?* And maybe you have a hack for it (except my favorite one: use a different browser)? I'd really appriciate your opinion. Thnx.
2009/08/28
[ "https://Stackoverflow.com/questions/1345575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109948/" ]
More advanced CSS selectors, such as *element > immediate-child*, `element[attribute=value]`, etc., do not appear to work in IE (tested on IE8) for elements dynamically added to the page. I've seen stuff like `div#something > p {color: red}` not working in IE once the `p` nodes were added dynamically as a child of `div#something`. I guess this is an issue you should be concerned with when creating tight CSS for dynamically created content: stick to simple stuff.
IE (not only 6 though, think I've seen this on 7 as well) has this thing where it will not evaluate values in loops until it's out of the method. That is, this code (example of setting ids on cells in a table row): ``` putids = function (cells) { for (var i = 0; i < 5; i++) { cells[i].id = "cellid" + i; } } ``` would give you 5 cells, all with the id "cellid5". You actually need to move the assignment to a different method and call that in the loop in order to have different ids. As for CSS, I remember the "absolute" versus "fixed" trouble: they're exactly opposite from any other browser (although yui for example deals with this properly). Also, IE6 has no support for transparent png files. These are just from the top of my head.
1,345,575
I know there is this [post](https://stackoverflow.com/questions/495050/list-of-css-features-not-supported-by-ie6), but I still want to know more and learn from other ppl that have a lot more experience than I do. So I was wondering *what CSS-features or Javascript-functions or anything else I am not thinking of right now do not work in IE6+ or have you experience to not work with IE6+?* And maybe you have a hack for it (except my favorite one: use a different browser)? I'd really appriciate your opinion. Thnx.
2009/08/28
[ "https://Stackoverflow.com/questions/1345575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109948/" ]
Quirksmode is good. You can also get a full run-down of what is supported by whom over at SitePoint: <http://reference.sitepoint.com/css>
IE (not only 6 though, think I've seen this on 7 as well) has this thing where it will not evaluate values in loops until it's out of the method. That is, this code (example of setting ids on cells in a table row): ``` putids = function (cells) { for (var i = 0; i < 5; i++) { cells[i].id = "cellid" + i; } } ``` would give you 5 cells, all with the id "cellid5". You actually need to move the assignment to a different method and call that in the loop in order to have different ids. As for CSS, I remember the "absolute" versus "fixed" trouble: they're exactly opposite from any other browser (although yui for example deals with this properly). Also, IE6 has no support for transparent png files. These are just from the top of my head.
56,089,509
I got this error when I try to generate signed apk for my project > > Duplicate class com.google.android.gms.measurement.AppMeasurement > found in modules classes.jar > (com.google.android.gms:play-services-measurement-impl:16.5.0) and > classes.jar (com.google.firebase:firebase-analytics-impl:10.0.1) > Duplicate class com.google.firebase.analytics.FirebaseAnalytics found > in modules classes.jar > (com.google.android.gms:play-services-measurement-api:16.5.0) and > classes.jar (com.google.firebase:firebase-analytics-impl:10.0.1) > Duplicate class com.google.firebase.analytics.FirebaseAnalytics$Event > found in modules classes.jar > (com.google.android.gms:play-services-measurement-api:16.5.0) and > classes.jar (com.google.firebase:firebase-analytics-impl:10.0.1) > Duplicate class com.google.firebase.analytics.FirebaseAnalytics$Param > found in modules classes.jar > (com.google.android.gms:play-services-measurement-api:16.5.0) and > classes.jar (com.google.firebase:firebase-analytics-impl:10.0.1) > Duplicate class > com.google.firebase.analytics.FirebaseAnalytics$UserProperty found in > modules classes.jar > (com.google.android.gms:play-services-measurement-api:16.5.0) and > classes.jar (com.google.firebase:firebase-analytics-impl:10.0.1) > > > Go to the documentation to learn how to Fix dependency resolution errors. how do I fix It?
2019/05/11
[ "https://Stackoverflow.com/questions/56089509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11484860/" ]
Try with ``` implementation("com.google.android.gms:play-services-gcm:$project.playServicesVersion") { exclude group: 'com.google.android.gms' } ``` You can Try including one by one the one which brings errors you apply ``` implementation("**API**") { exclude group: 'com.google.android.gms' } ``` **NB** `$project.playServicesVersion` could be any of your versions you are using
For those who face this type of issue in the future Ensure that you are using the specific dependency of play services according to your requirements. In my case, I need a map dependency but I am importing the play service dependency which causes duplicate class issues with another firebase dependency. Use this ``` def playServiceVersion = "17.0.0" implementation "com.google.android.gms:play-services-maps:$playServiceVersion" ``` Instead of ``` def playServiceVersion = "17.0.0" implementation "com.google.android.gms:play-services:$playServiceVersion" ``` For further information check the link below <https://developers.google.com/android/guides/setup>
56,089,509
I got this error when I try to generate signed apk for my project > > Duplicate class com.google.android.gms.measurement.AppMeasurement > found in modules classes.jar > (com.google.android.gms:play-services-measurement-impl:16.5.0) and > classes.jar (com.google.firebase:firebase-analytics-impl:10.0.1) > Duplicate class com.google.firebase.analytics.FirebaseAnalytics found > in modules classes.jar > (com.google.android.gms:play-services-measurement-api:16.5.0) and > classes.jar (com.google.firebase:firebase-analytics-impl:10.0.1) > Duplicate class com.google.firebase.analytics.FirebaseAnalytics$Event > found in modules classes.jar > (com.google.android.gms:play-services-measurement-api:16.5.0) and > classes.jar (com.google.firebase:firebase-analytics-impl:10.0.1) > Duplicate class com.google.firebase.analytics.FirebaseAnalytics$Param > found in modules classes.jar > (com.google.android.gms:play-services-measurement-api:16.5.0) and > classes.jar (com.google.firebase:firebase-analytics-impl:10.0.1) > Duplicate class > com.google.firebase.analytics.FirebaseAnalytics$UserProperty found in > modules classes.jar > (com.google.android.gms:play-services-measurement-api:16.5.0) and > classes.jar (com.google.firebase:firebase-analytics-impl:10.0.1) > > > Go to the documentation to learn how to Fix dependency resolution errors. how do I fix It?
2019/05/11
[ "https://Stackoverflow.com/questions/56089509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11484860/" ]
Try with ``` implementation("com.google.android.gms:play-services-gcm:$project.playServicesVersion") { exclude group: 'com.google.android.gms' } ``` You can Try including one by one the one which brings errors you apply ``` implementation("**API**") { exclude group: 'com.google.android.gms' } ``` **NB** `$project.playServicesVersion` could be any of your versions you are using
Reason: This error usually occurs due to depedencies using same functionality. Solution: To revolve such issue is to comment: play-services because play-services-maps has same functions like play-services and also display locations on our android UI system. Please see below for solution. //implementation 'com.google.android.gms:play-services:12.0.1' implementation 'com.google.android.gms:play-services-maps:17.0.0' Also checkout notable transitive dependencies: <https://github.com/firebase/FirebaseUI-Android/releases> I hope its help solve so many developers project issues.
56,089,509
I got this error when I try to generate signed apk for my project > > Duplicate class com.google.android.gms.measurement.AppMeasurement > found in modules classes.jar > (com.google.android.gms:play-services-measurement-impl:16.5.0) and > classes.jar (com.google.firebase:firebase-analytics-impl:10.0.1) > Duplicate class com.google.firebase.analytics.FirebaseAnalytics found > in modules classes.jar > (com.google.android.gms:play-services-measurement-api:16.5.0) and > classes.jar (com.google.firebase:firebase-analytics-impl:10.0.1) > Duplicate class com.google.firebase.analytics.FirebaseAnalytics$Event > found in modules classes.jar > (com.google.android.gms:play-services-measurement-api:16.5.0) and > classes.jar (com.google.firebase:firebase-analytics-impl:10.0.1) > Duplicate class com.google.firebase.analytics.FirebaseAnalytics$Param > found in modules classes.jar > (com.google.android.gms:play-services-measurement-api:16.5.0) and > classes.jar (com.google.firebase:firebase-analytics-impl:10.0.1) > Duplicate class > com.google.firebase.analytics.FirebaseAnalytics$UserProperty found in > modules classes.jar > (com.google.android.gms:play-services-measurement-api:16.5.0) and > classes.jar (com.google.firebase:firebase-analytics-impl:10.0.1) > > > Go to the documentation to learn how to Fix dependency resolution errors. how do I fix It?
2019/05/11
[ "https://Stackoverflow.com/questions/56089509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11484860/" ]
For those who face this type of issue in the future Ensure that you are using the specific dependency of play services according to your requirements. In my case, I need a map dependency but I am importing the play service dependency which causes duplicate class issues with another firebase dependency. Use this ``` def playServiceVersion = "17.0.0" implementation "com.google.android.gms:play-services-maps:$playServiceVersion" ``` Instead of ``` def playServiceVersion = "17.0.0" implementation "com.google.android.gms:play-services:$playServiceVersion" ``` For further information check the link below <https://developers.google.com/android/guides/setup>
Reason: This error usually occurs due to depedencies using same functionality. Solution: To revolve such issue is to comment: play-services because play-services-maps has same functions like play-services and also display locations on our android UI system. Please see below for solution. //implementation 'com.google.android.gms:play-services:12.0.1' implementation 'com.google.android.gms:play-services-maps:17.0.0' Also checkout notable transitive dependencies: <https://github.com/firebase/FirebaseUI-Android/releases> I hope its help solve so many developers project issues.
28,754,547
I have the following: ``` import netrc machine = 'ftp.example.com' auth = netrc.netrc().authenticators(machine) ``` I have the following line in my `.netrc` file: ``` machine "### comment" ``` I get the following error: > > netrc.NetrcParseError: bad follower token 'comment"' > > > I can remove the comment, but I need to use this on other accounts where I can not edit the `.netrc` file, so what to do here?
2015/02/26
[ "https://Stackoverflow.com/questions/28754547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10415/" ]
Doesn't your line need to be ``` machine ftp.example.com login user password pw ``` If you start the line with 'machine' you at least need a machine name, before you comment out the rest of the line, otherwise netrc can't parse the line.
I believe it's parsing the line without treating the quotation marks any differently from other non-whitespace characters. So this: ``` machine "### comment" ``` gets turned into the tokens `machine`, `"###`, and `comment"`. After that, it can't find any more tokens, and it barfs. Unfortunately, since there are lots of netrc parsers out there and they might all have different handling of edge cases, you can't really even solve this by writing your own parser unless you can get that parser used by your favorite tools (curl, pip, etc.). As a further aside on comments, apparently the Python `netrc` module will recognize `# machine ...` (with a space) but not `#machine ...` (without a space) as a comment line. The latter results in various errors like `netrc.NetrcParseError: bad toplevel token '...'`, which tools like `pip` seem to hide from you, pretending there are no entries in the file.
6,464,607
I have a demo on the following link: <http://mywebbapp.com/tableSortingDemo.html> When you click on the Status column and start sorting and then click on the pagination arrow to go to page 2 the rows don't alternate color until you click on the Status column again. Is there a script I can write to resolve this?
2011/06/24
[ "https://Stackoverflow.com/questions/6464607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/333757/" ]
Yes, though I suggest using a premade table such as [DataTables](http://www.datatables.net/%20DataTables). Here's a small jQuery plugin that could be used if you can trigger it when you paginate: ``` jQuery.fn.stripe = function() { $(this).find('tr').removeClass('even odd').filter(':odd').addClass('odd').end().find('tr:even').addClass('even'); } $('#table').stripe(); ``` Then be sure to have some CSS that changes the color: ``` tr.odd { background: #fff } tr.even { background: #ddd } ```
It sounds like your logic to specify the background colors for the rows is just running in the wrong place. Without seeing your code, it's impossible to really debug it, though.
71,052,202
I would like to divide a list of positive integers by the length of digits. For example, int\_list = `[1,3,13,888,1004]` -> `[1,3] , [13] , [888] , [1004]` I have implemented below: ```py def seperate_by_digit(int_list): len_set = set() # track how many digits we have int_dict = {} # key : len of digits / val : list of integer for int_ele in int_list: n = len(str(int_ele)) if n not in len_set: int_dict[n] = [int_ele] len_set.add(n) else: sub_int_list = int_dict[n] sub_int_list.append(int_ele) int_dict[n] = sub_int_list return int_dict ``` Is there any better, cleaner way to complete this task?
2022/02/09
[ "https://Stackoverflow.com/questions/71052202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14391435/" ]
I ended up using an approach where I let the Azure pipeline insert the secrets into my appSetting when I am deploying, hence the code will not be interfacing with the keyvault.
On development environment you need to use SecretManager as described [here](https://learn.microsoft.com/en-us/aspnet/core/security/key-vault-configuration?view=aspnetcore-6.0#secret-storage-in-the-development-environment). [Here](https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-6.0&tabs=windows) you can find a deep dive with a working sample.
41,718,919
I have the following function: ``` function void my_randomize_int(int seed, inout int mem, int min, int max); if(max == null) begin `uvm_info("my_randomize_int", "No max constraint, using default value", UVM_LOW) max = 2147483647; end if(min == null) begin `uvm_info("my_randomize_int", "No min constraint, using default value", UVM_LOW) min= -2147483647; end mem = ($urandom(seed) % (max-min+1)) + min; endfunction: my_randomize_int ``` I got the following error: Cannot compare type 'int' to type 'null': It is illegal to compare a handle with a packed type. I have to check if it's null because I want to display a mesage in case there is no value
2017/01/18
[ "https://Stackoverflow.com/questions/41718919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6465067/" ]
Yes, there's [`std::system_error`](http://en.cppreference.com/w/cpp/error/system_error). It's derived from `std::runtime_error`. It's pretty Unix-land-oriented but it does support error codes in general, and I suggest that you use it that way. --- The following code demonstrates how to define one's own error category for application specific error codes: ``` #include <string> #include <system_error> #include <typeinfo> namespace my{ struct Error_code { enum Enum { error_1 = 101, error_2 = 102, error_3 = 103 }; }; class App_error_category : public std::error_category { using Base = std::error_category; public: auto name() const noexcept -> char const* override { return "App error"; } auto default_error_condition( int const code ) const noexcept -> std::error_condition override { (void) code; return {}; } auto equivalent( int const code, std::error_condition const& condition ) const noexcept -> bool override { (void) code; (void) condition; return false; } // The intended functionality of this func is pretty unclear. // It apparently can't do its job (properly) in the general case. auto equivalent( std::error_code const& code, int const condition ) const noexcept -> bool override { return Base::equivalent( code, condition ); } auto message( int const condition ) const -> std::string override { return "An application error occurred, code = " + std::to_string( condition ); } constexpr App_error_category(): Base{} {} }; auto app_error_category() -> App_error_category const& { static App_error_category the_instance; return the_instance; } class App_error : public std::system_error { using Base = std::system_error; public: auto app_error_code() const -> Error_code::Enum { return static_cast<Error_code::Enum>( code().value() ); } App_error( Error_code::Enum const code ) : Base{ code, app_error_category() } {} App_error( Error_code::Enum const code, std::string const& description ) : Base{ code, app_error_category(), description } {} }; } // namespace my void foo() { try { throw my::App_error( my::Error_code::error_1, "can not do the job!" ); } catch( my::App_error const& x ) { switch( x.app_error_code() ) { case my::Error_code::error_1: // I can not contunue, so re throw it throw; case my::Error_code::error_2: // it is not important for me, so I can continue break; case my::Error_code::error_3: //Oh, I need to do something before continue //re_init(); break; } } } #include <iostream> #include <stdlib.h> // EXIT_SUCCESS, EXIT_FAILURE using namespace std; auto main() -> int { try { foo(); return EXIT_SUCCESS; } catch( exception const& x ) { cerr << "!" << x.what() << endl; } return EXIT_FAILURE; } ``` With both Visual C++ 2015 and MingW g++ 6.4.0 this produces the output ``` !can not do the job!: An application error occurred, code = 101 ``` --- In general it's more practical to define specific exception classes than to use error codes. However, for system error codes it's more practical to just pass these codes up with the exception. And for *that* the complexity shown above can be avoided, since the `std::system_category` is then eminently suitable. In short, the complexity here stems from your requirement to not go with the flow, but in a direction somewhat against the current.
Consider using [`std::system_error`](http://en.cppreference.com/w/cpp/error/system_error) out of the box. Note that using simply `throw;` without an argument is a *far* better way of re-throwing your exception (you seem to be using `throw err;`) since the former will throw the exception *by reference* rather than *by value*: the latter can cause object slicing.
3,338,819
My understanding is that taking the minimum of two (or more) functions is like creating a union of the functions which in some cases would result in a non-convex function. I can draw it out with some simple 2d functions but I can't figure out how to show it with equations. Thanks in advance for the help!
2019/08/30
[ "https://math.stackexchange.com/questions/3338819", "https://math.stackexchange.com", "https://math.stackexchange.com/users/699606/" ]
The minimum $h:\Bbb R \to \Bbb R$ of $f(x)=(x-1)^2$ and $g(x)=(x+1)^2$ is not convex at $[-1,1]$. *Proof*: $h(0)>h(-1)$ and $h(0)>h(1)$.
In $[0,1]$, $$f:=x-x^3,\\g:=(1-x)-(1-x)^3,\\h:=\min(f,g)$$ Now the average of $h\left(\dfrac1{\sqrt 3}\right)$ and $h\left(1-\dfrac1{\sqrt 3}\right)$ is $\dfrac{2}{3\sqrt3}$, but $h\left(\dfrac12\right)=\dfrac38$, which is smaller.
3,338,819
My understanding is that taking the minimum of two (or more) functions is like creating a union of the functions which in some cases would result in a non-convex function. I can draw it out with some simple 2d functions but I can't figure out how to show it with equations. Thanks in advance for the help!
2019/08/30
[ "https://math.stackexchange.com/questions/3338819", "https://math.stackexchange.com", "https://math.stackexchange.com/users/699606/" ]
Minimum of $|x|$ and $|1-x|$ is not convex. (In fact it is strictly concave on $(0,1)$). Write $\frac 1 2$ as $\frac 1 2 (0)+\frac 1 2 (1)$. Convexity would mean $\frac 1 2 \leq \frac 1 2 (0)+\frac 1 2 (0)$!
The minimum $h:\Bbb R \to \Bbb R$ of $f(x)=(x-1)^2$ and $g(x)=(x+1)^2$ is not convex at $[-1,1]$. *Proof*: $h(0)>h(-1)$ and $h(0)>h(1)$.
3,338,819
My understanding is that taking the minimum of two (or more) functions is like creating a union of the functions which in some cases would result in a non-convex function. I can draw it out with some simple 2d functions but I can't figure out how to show it with equations. Thanks in advance for the help!
2019/08/30
[ "https://math.stackexchange.com/questions/3338819", "https://math.stackexchange.com", "https://math.stackexchange.com/users/699606/" ]
Minimum of $|x|$ and $|1-x|$ is not convex. (In fact it is strictly concave on $(0,1)$). Write $\frac 1 2$ as $\frac 1 2 (0)+\frac 1 2 (1)$. Convexity would mean $\frac 1 2 \leq \frac 1 2 (0)+\frac 1 2 (0)$!
In $[0,1]$, $$f:=x-x^3,\\g:=(1-x)-(1-x)^3,\\h:=\min(f,g)$$ Now the average of $h\left(\dfrac1{\sqrt 3}\right)$ and $h\left(1-\dfrac1{\sqrt 3}\right)$ is $\dfrac{2}{3\sqrt3}$, but $h\left(\dfrac12\right)=\dfrac38$, which is smaller.
26,093,447
``` private StringReader myReader; private void printToolStripMenuItem_Click(object sender, EventArgs e) { printDialog1.Document = printDocument1; string strText = this.richTextBox1.Text; myReader = new StringReader(strText); if (printDialog1.ShowDialog() == DialogResult.OK) { printDocument1.Print(); } } private void printPrieviewToolStripMenuItem_Click(object sender, EventArgs e) { string strText = this.richTextBox1.Text;//read text for richtextbox myReader = new StringReader(strText); printPreviewDialog1.Document = printDocument1; printPreviewDialog1.ShowDialog(); } private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { string line = null; Font printFont = new System.Drawing.Font("Times New Roman", 8, FontStyle.Regular); SolidBrush myBrush = new SolidBrush(Color.Black); float linesPerPage = 0; float topMargin = 590; float yPosition = 590; int count = 0; float leftMargin = 70; linesPerPage = e.MarginBounds.Height / printFont.GetHeight(e.Graphics); while (count < linesPerPage && ((line = myReader.ReadLine()) != null)) { if (count == 0) { yPosition = 590; topMargin = 590; } else { yPosition = 100; topMargin = 100; } yPosition = topMargin + (count * printFont.GetHeight(e.Graphics)); e.Graphics.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat()); count++; } if (line != null) { e.HasMorePages = true; } else { e.HasMorePages = false; myBrush.Dispose(); } } } } ``` please where is my mistake.i want to print first page is top marigin is 590,and if more pages second page should be print top marigin is 100. above given code is printing is ok but print marigin is not solved help me the corection.
2014/09/29
[ "https://Stackoverflow.com/questions/26093447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4085654/" ]
Please try following link for details of errors <http://technet.microsoft.com/en-us/library/cc645611(v=sql.105).aspx> The error codes are returned by the db server to the sql client. **Update** Try the latest database events and errors here <https://learn.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-events-and-errors>
The rules I use for general classification: * Number = -1 OR Class/Level/Severity = 20: "Connection Error" * Number = -2: "Command Timeout Error" I believe the negative values are strictly from the client library (ie. network connection issues); this implies the "duplicate" numbers like 2 and 53 come back from the server itself for half-connections. Other errors (eg. deadlocks/1205) can be more readily defined by the Number. --- As the other answer contains, here is also a link to various references: * <https://msdn.microsoft.com/en-us/library/cc645611.aspx> * <https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlerror.number.aspx>
39,149,218
I am trying to print a string in all uppercase letters. When I run the print command it prints the type of x and the location. Why does it print the operation instead of the result? ``` x = 'bacon' x = x.upper print x >>> <built-in method upper of str object at 0x02A95F60> ```
2016/08/25
[ "https://Stackoverflow.com/questions/39149218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6625618/" ]
Everything in Python is an object, including functions and methods. `x.upper` is the `upper` attribute of `x`, which happens to be a function object. `x.upper()` is the result of trying to call that attribute as a function, so you are trying to do ``` print x.upper() ``` As an aside, you can try to call any object in Python, not just functions. It will not always work, but the syntax is legitimate. You can do ``` x = 5 x() ``` or even ``` 5() ``` but of course you will get an error (the exact same one in both cases). However, you can actually call objects as functions as long as they define a `__call__` method (as normal functions do). Your example can actually be rewritten as ``` print x.upper.__call__() ```
`upper` (and all other methods) is something like "function ready to use", that way you can do: ``` x = 'bacon' x = x.upper print x() ``` But the most common to see, and the way I think you want is: ``` x = 'bacon' x = x.upper() print x ``` "Ridiculous" example using [lambda](http://www.secnetix.de/olli/Python/lambda_functions.hawk): ``` upper_case = lambda x: x.upper() print(upper_case) # <function <lambda> at 0x7f2558a21938> print(upper_case('bacon')) # BACON ```
114,847
Introduction ------------ You may know and love your normal unit circle. But mathematicans are crazy and thus they have abstracted the concept to any point that satisfies `x*x+y*y=1`. Because Cryptographers1 are also weird, they *love* finite fields and *sometimes* finite rings (it is not like they have much choice though), so let's combine this! The Challenge ------------- ### Input A positive integer larger than one in your favorite encoding. Let's call this number n. ### Output You will output the "picture" (which consists of n times n characters) of the unit circle modulo the input integer as ASCII-Art using "X" (upper-case latin X) and " " (a space). Trailing spaces and newlines are allowed. ### More Details You have to span a coordinate system from bottom-left to top-right. Whenever a point fulfills the circle equation, place an X at the position, otherwise place a space. The condition for a point to be considered part of the circle border is: `mod(x*x+y*y,n)==1`. Here a quick illustration of the coordinate-system: ``` (0,4)(1,4)(2,4)(3,4)(4,4) (0,3)(1,3)(2,3)(3,3)(4,3) (0,2)(1,2)(2,2)(3,2)(4,2) (0,1)(1,1)(2,1)(3,1)(4,1) (0,0)(1,0)(2,0)(3,0)(4,0) ``` If it helps you, you may also invert the direction of any of the axes, but the examples assume this orientation. Who wins? --------- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in byte wins! [Only the default I/O methods are allowed](https://codegolf.meta.stackexchange.com/q/2447/55329) and all standard loopholes are banned. Examples -------- Input: 2 ``` X X ``` Input: 3 ``` X X XX ``` Input: 5 ``` X X X X ``` Input: 7 ``` X X X X X X X X ``` Input: 11 ``` X XX X X X X XX X X X ``` Input: 42 ``` X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X ``` --- 1 I suggest you take a look at my profile if you're wondering here.
2017/04/01
[ "https://codegolf.stackexchange.com/questions/114847", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/55329/" ]
Bash + GNU Utilities, 59 ======================== ```bash x={0..$[$1-1]}d* eval echo $x$x+$1%1-0r^56*32+P|dc|fold -$1 ``` Input `n` given as a command-line parameter. The y-axis is inverted. [Try it online](https://tio.run/nexus/bash#@19hW22gp6cSrWKoaxhbm6LFlVqWmKOQmpyRr6BSoVKhrWKoaqhrUBRnaqZlbKQdUJOSXJOWn5OioKti@P//fxMjAA).
Haskell, 115 bytes ================== ``` n#(a,b)|mod(a*a+b*b)n==1='X'|1>0=' ' m n=map(n#)<$>zipWith(zipWith(,))(replicate n[0..n-1])(replicate n<$>[0..n-1]) ``` The y axis is inverted. [Try it online!](https://tio.run/nexus/haskell#VctBCsJADEDRvacItDBJraXj2vQaCuIiowUDJg5lVtK7j24UXH148Ks3KH2i1Z43lE62qUvkzJHDKaxxGjlA2Bg4m2T0hg7t9NJ81HLHb3siXOb80KuUGfw8DoPv4uUPP9vPq4k6MORFvUALBvv6Bg "Haskell – TIO Nexus") All those parentheses are kind of annoying me... Explanation ----------- ``` n#(a,b)|mod(a*a+b*b)n==1='X'|1>0=' ' n#(a,b) --Operator #, takes a number n and a tuple (a,b) |mod(a*a+b*b)n==1 --Test if the mod equals 1 ='X' --If so, return 'X' |1>0=' ' --Otherwise, return ' ' m n=map(n#)<$>zipWith(zipWith(,))(replicate n[0..n-1])(replicate n<$>[0..n-1]) m n= --Make a new function m with argument n (replicate n[0..n-1]) --Make a list of [[0,1,2,3..n-1],[0,1,2,3..n-1],(n times)] (replicate n<$>[0..n-1]) --Make a list of [[0,0,0(n times)],[1,1,1(n times)]..[n-1,n-1,n-1(n times)] zipWith(zipWith(,)) --Combine them into a list of list of tuples map(n#)<$> --Apply the # operator to every tuple in the list with the argument n ```
114,847
Introduction ------------ You may know and love your normal unit circle. But mathematicans are crazy and thus they have abstracted the concept to any point that satisfies `x*x+y*y=1`. Because Cryptographers1 are also weird, they *love* finite fields and *sometimes* finite rings (it is not like they have much choice though), so let's combine this! The Challenge ------------- ### Input A positive integer larger than one in your favorite encoding. Let's call this number n. ### Output You will output the "picture" (which consists of n times n characters) of the unit circle modulo the input integer as ASCII-Art using "X" (upper-case latin X) and " " (a space). Trailing spaces and newlines are allowed. ### More Details You have to span a coordinate system from bottom-left to top-right. Whenever a point fulfills the circle equation, place an X at the position, otherwise place a space. The condition for a point to be considered part of the circle border is: `mod(x*x+y*y,n)==1`. Here a quick illustration of the coordinate-system: ``` (0,4)(1,4)(2,4)(3,4)(4,4) (0,3)(1,3)(2,3)(3,3)(4,3) (0,2)(1,2)(2,2)(3,2)(4,2) (0,1)(1,1)(2,1)(3,1)(4,1) (0,0)(1,0)(2,0)(3,0)(4,0) ``` If it helps you, you may also invert the direction of any of the axes, but the examples assume this orientation. Who wins? --------- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in byte wins! [Only the default I/O methods are allowed](https://codegolf.meta.stackexchange.com/q/2447/55329) and all standard loopholes are banned. Examples -------- Input: 2 ``` X X ``` Input: 3 ``` X X XX ``` Input: 5 ``` X X X X ``` Input: 7 ``` X X X X X X X X ``` Input: 11 ``` X XX X X X X XX X X X ``` Input: 42 ``` X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X ``` --- 1 I suggest you take a look at my profile if you're wondering here.
2017/04/01
[ "https://codegolf.stackexchange.com/questions/114847", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/55329/" ]
[Python 3](https://docs.python.org/3/), (102 98 95 bytes) ========================================================= ### y-axis inverted ```python n=int(input());r=range(n);p=print for i in r: for j in r:p(end=' 'if(i*i+j*j)%n-1else'X') p() ``` [Try it online!](https://tio.run/nexus/python3#JckxCoAwDADAva/IIk0UB8VJ6T9cBVtJkRiivr8qjscVCSwXsuh9IdFkwRbZIgpNGtTec@kwYGABGx18yD8Uo6zBg@eEXHOT60yVtF3cz@hnTw4UqZShdw8 "Python 3 – TIO Nexus") * saved 4 bytes: omitted variable c in c=' 'if(i*i+j*j)%n-1else'X' * saved 3 bytes: Thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs) (modified print statement)
[GolfScript](http://www.golfscript.com/golfscript/), 34 bytes ============================================================= ``` ~:c,{.*}%:a{:b;a{b+c%1=' x'=}%}%n* ``` [Try it online!](https://tio.run/nexus/golfscript#@19nlaxTradVq2qVWG2VZJ1YnaSdrGpoq65QoW5bq1qrmqf1/7@JEQA "GolfScript – TIO Nexus") I really don't like using variables...
114,847
Introduction ------------ You may know and love your normal unit circle. But mathematicans are crazy and thus they have abstracted the concept to any point that satisfies `x*x+y*y=1`. Because Cryptographers1 are also weird, they *love* finite fields and *sometimes* finite rings (it is not like they have much choice though), so let's combine this! The Challenge ------------- ### Input A positive integer larger than one in your favorite encoding. Let's call this number n. ### Output You will output the "picture" (which consists of n times n characters) of the unit circle modulo the input integer as ASCII-Art using "X" (upper-case latin X) and " " (a space). Trailing spaces and newlines are allowed. ### More Details You have to span a coordinate system from bottom-left to top-right. Whenever a point fulfills the circle equation, place an X at the position, otherwise place a space. The condition for a point to be considered part of the circle border is: `mod(x*x+y*y,n)==1`. Here a quick illustration of the coordinate-system: ``` (0,4)(1,4)(2,4)(3,4)(4,4) (0,3)(1,3)(2,3)(3,3)(4,3) (0,2)(1,2)(2,2)(3,2)(4,2) (0,1)(1,1)(2,1)(3,1)(4,1) (0,0)(1,0)(2,0)(3,0)(4,0) ``` If it helps you, you may also invert the direction of any of the axes, but the examples assume this orientation. Who wins? --------- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in byte wins! [Only the default I/O methods are allowed](https://codegolf.meta.stackexchange.com/q/2447/55329) and all standard loopholes are banned. Examples -------- Input: 2 ``` X X ``` Input: 3 ``` X X XX ``` Input: 5 ``` X X X X ``` Input: 7 ``` X X X X X X X X ``` Input: 11 ``` X XX X X X X XX X X X ``` Input: 42 ``` X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X ``` --- 1 I suggest you take a look at my profile if you're wondering here.
2017/04/01
[ "https://codegolf.stackexchange.com/questions/114847", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/55329/" ]
[Haskell](https://www.haskell.org/), 68 bytes ============================================= ```hs f n|r<-[0..n-1]=unlines[[last$' ':['X'|mod(x*x+y*y)n==1]|y<-r]|x<-r] ``` [Try it online!](https://tio.run/nexus/haskell#@5@mkFdTZKMbbaCnl6drGGtbmpeTmZdaHB2dk1hcoqKuoG4VrR6hXpObn6JRoVWhXalVqZlna2sYW1Npo1sUW1MBIv/nJmbmKdgqFKUmpvjkKdjZ2SoUlJYElxQp6Cmk/TcxAgA "Haskell – TIO Nexus") The y-axis is flipped. Usage: `f 42` returns a newline delimited string. This is a nested list comprehension where both `x` and `y` are drawn from the range `[0..n-1]`. `last$' ':['X'|mod(x*x+y*y)n==1]` is a shorter form of `if mod(x*x+y*y)n==1 then 'X' else ' '`. The list comprehension evaluates to a list of strings which is turned into a single newline separated string by `unlines`.
[Python 3](https://docs.python.org/3/), (102 98 95 bytes) ========================================================= ### y-axis inverted ```python n=int(input());r=range(n);p=print for i in r: for j in r:p(end=' 'if(i*i+j*j)%n-1else'X') p() ``` [Try it online!](https://tio.run/nexus/python3#JckxCoAwDADAva/IIk0UB8VJ6T9cBVtJkRiivr8qjscVCSwXsuh9IdFkwRbZIgpNGtTec@kwYGABGx18yD8Uo6zBg@eEXHOT60yVtF3cz@hnTw4UqZShdw8 "Python 3 – TIO Nexus") * saved 4 bytes: omitted variable c in c=' 'if(i*i+j*j)%n-1else'X' * saved 3 bytes: Thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs) (modified print statement)
114,847
Introduction ------------ You may know and love your normal unit circle. But mathematicans are crazy and thus they have abstracted the concept to any point that satisfies `x*x+y*y=1`. Because Cryptographers1 are also weird, they *love* finite fields and *sometimes* finite rings (it is not like they have much choice though), so let's combine this! The Challenge ------------- ### Input A positive integer larger than one in your favorite encoding. Let's call this number n. ### Output You will output the "picture" (which consists of n times n characters) of the unit circle modulo the input integer as ASCII-Art using "X" (upper-case latin X) and " " (a space). Trailing spaces and newlines are allowed. ### More Details You have to span a coordinate system from bottom-left to top-right. Whenever a point fulfills the circle equation, place an X at the position, otherwise place a space. The condition for a point to be considered part of the circle border is: `mod(x*x+y*y,n)==1`. Here a quick illustration of the coordinate-system: ``` (0,4)(1,4)(2,4)(3,4)(4,4) (0,3)(1,3)(2,3)(3,3)(4,3) (0,2)(1,2)(2,2)(3,2)(4,2) (0,1)(1,1)(2,1)(3,1)(4,1) (0,0)(1,0)(2,0)(3,0)(4,0) ``` If it helps you, you may also invert the direction of any of the axes, but the examples assume this orientation. Who wins? --------- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in byte wins! [Only the default I/O methods are allowed](https://codegolf.meta.stackexchange.com/q/2447/55329) and all standard loopholes are banned. Examples -------- Input: 2 ``` X X ``` Input: 3 ``` X X XX ``` Input: 5 ``` X X X X ``` Input: 7 ``` X X X X X X X X ``` Input: 11 ``` X XX X X X X XX X X X ``` Input: 42 ``` X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X ``` --- 1 I suggest you take a look at my profile if you're wondering here.
2017/04/01
[ "https://codegolf.stackexchange.com/questions/114847", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/55329/" ]
[Python 3](https://docs.python.org/3/), ~~87~~ 83 bytes ======================================================= ```python lambda n:"\n".join("".join(" X"[(y*y+x*x)%n==1]for x in range(n))for y in range(n)) ``` [Try it online!](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqiQZ6UUk6ekl5WfmaehBKMVIpSiNSq1KrUrtCo0VfNsbQ1j0/KLFCoUMvMUihLz0lM18jQ1QSKVKCL/QUKZIKFoIx0FYx0FUx0Fcx0FQ0MdBROjWCsuhYKizLwSjUxNGCsNyIZzNP8DAA "Python 3 – TIO Nexus") The y-axis is inverted
[GNU APL](https://www.gnu.org/software/apl/), 41 chars, 59 bytes ================================================================ Reads an integer and displays the circle. ``` N←⎕◊⌽{(⍵+1)⊃' ' 'X'}¨{1=(N|(+/⍵*2))}¨⍳N N ``` ### Ungolfed ``` N←⎕ ⌽ ⍝ flip the X axis so 0,0 is bottom left { (⍵+1) ⊃ ' ' 'X' ⍝ substitute space for 0, X for 1 } ¨ { 1=(N|(+/⍵*2)) ⍝ mod(x*x+y*y, 1)==1 } ¨ ⍳N N ⍝ generate an NxN grid of coordinates ```
114,847
Introduction ------------ You may know and love your normal unit circle. But mathematicans are crazy and thus they have abstracted the concept to any point that satisfies `x*x+y*y=1`. Because Cryptographers1 are also weird, they *love* finite fields and *sometimes* finite rings (it is not like they have much choice though), so let's combine this! The Challenge ------------- ### Input A positive integer larger than one in your favorite encoding. Let's call this number n. ### Output You will output the "picture" (which consists of n times n characters) of the unit circle modulo the input integer as ASCII-Art using "X" (upper-case latin X) and " " (a space). Trailing spaces and newlines are allowed. ### More Details You have to span a coordinate system from bottom-left to top-right. Whenever a point fulfills the circle equation, place an X at the position, otherwise place a space. The condition for a point to be considered part of the circle border is: `mod(x*x+y*y,n)==1`. Here a quick illustration of the coordinate-system: ``` (0,4)(1,4)(2,4)(3,4)(4,4) (0,3)(1,3)(2,3)(3,3)(4,3) (0,2)(1,2)(2,2)(3,2)(4,2) (0,1)(1,1)(2,1)(3,1)(4,1) (0,0)(1,0)(2,0)(3,0)(4,0) ``` If it helps you, you may also invert the direction of any of the axes, but the examples assume this orientation. Who wins? --------- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in byte wins! [Only the default I/O methods are allowed](https://codegolf.meta.stackexchange.com/q/2447/55329) and all standard loopholes are banned. Examples -------- Input: 2 ``` X X ``` Input: 3 ``` X X XX ``` Input: 5 ``` X X X X ``` Input: 7 ``` X X X X X X X X ``` Input: 11 ``` X XX X X X X XX X X X ``` Input: 42 ``` X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X ``` --- 1 I suggest you take a look at my profile if you're wondering here.
2017/04/01
[ "https://codegolf.stackexchange.com/questions/114847", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/55329/" ]
[Octave](https://www.gnu.org/software/octave/), ~~45~~ 44 bytes =============================================================== ```matlab @(n)[(mod((x=(0:n-1).^2)+x',n)==1)*56+32,''] ``` [Try it online!](https://tio.run/nexus/octave#@@@gkacZrZGbn6KhUWGrYWCVp2uoqRdnpKldoa6Tp2lra6ipZWqmbWyko64e@z8xr1jD0FDzPwA "Octave – TIO Nexus")
[J](http://jsoftware.com/), 20 bytes ==================================== ``` ' x'{~1=[|+/~@:*:@i. ``` [Try it online!](https://tio.run/nexus/j#@59ma6WuUKFeXWdoG12jrV/nYKVl5ZCp9z81OSNfIU3BxIgrtSKzRMHgPwA "J – TIO Nexus")
114,847
Introduction ------------ You may know and love your normal unit circle. But mathematicans are crazy and thus they have abstracted the concept to any point that satisfies `x*x+y*y=1`. Because Cryptographers1 are also weird, they *love* finite fields and *sometimes* finite rings (it is not like they have much choice though), so let's combine this! The Challenge ------------- ### Input A positive integer larger than one in your favorite encoding. Let's call this number n. ### Output You will output the "picture" (which consists of n times n characters) of the unit circle modulo the input integer as ASCII-Art using "X" (upper-case latin X) and " " (a space). Trailing spaces and newlines are allowed. ### More Details You have to span a coordinate system from bottom-left to top-right. Whenever a point fulfills the circle equation, place an X at the position, otherwise place a space. The condition for a point to be considered part of the circle border is: `mod(x*x+y*y,n)==1`. Here a quick illustration of the coordinate-system: ``` (0,4)(1,4)(2,4)(3,4)(4,4) (0,3)(1,3)(2,3)(3,3)(4,3) (0,2)(1,2)(2,2)(3,2)(4,2) (0,1)(1,1)(2,1)(3,1)(4,1) (0,0)(1,0)(2,0)(3,0)(4,0) ``` If it helps you, you may also invert the direction of any of the axes, but the examples assume this orientation. Who wins? --------- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in byte wins! [Only the default I/O methods are allowed](https://codegolf.meta.stackexchange.com/q/2447/55329) and all standard loopholes are banned. Examples -------- Input: 2 ``` X X ``` Input: 3 ``` X X XX ``` Input: 5 ``` X X X X ``` Input: 7 ``` X X X X X X X X ``` Input: 11 ``` X XX X X X X XX X X X ``` Input: 42 ``` X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X ``` --- 1 I suggest you take a look at my profile if you're wondering here.
2017/04/01
[ "https://codegolf.stackexchange.com/questions/114847", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/55329/" ]
[Lithp](https://github.com/andrakis/node-lithp), 125 bytes ---------------------------------------------------------- ``` #N::((join(map(seq(- N 1)0)(scope #Y::((join(map(seq 0(- N 1))(scope #X:: ((?(== 1(@(+(* X X)(* Y Y))N))"X" " "))))""))))"\n") ``` Linebreak for readability. [Try it online!](https://andrakis.github.io/ide2/index.html?code=JSBBbiBlbnRyeSBmb3IgYSBDb2RlZ29sZiBjaGFsbGVuZ2U6CiUgaHR0cDovL2NvZGVnb2xmLnN0YWNrZXhjaGFuZ2UuY29tL3F1ZXN0aW9ucy8xMTQ4NDcvZHJhdy1tZS10aGUtd2VpcmQtdW5pdC1jaXJjbGUKJSBGb3IgYmVzdCByZXN1bHRzLCBleHBhbmQgdGhlIG91dHB1dCB3aW5kb3cgYmVsb3cuCigKICAgIChpbXBvcnQgbGlzdHMpCiAgICAlIFVuZ29sZmVkOgogICAgKGRlZiBmICNOIDo6ICgKICAgICAgICAoam9pbiAobWFwIChzZXEgKC0gTiAxKSAwKSAoc2NvcGUgI1kgOjogKAogICAgICAgICAgICAoam9pbiAobWFwIChzZXEgMCAoLSBOIDEpKSAoc2NvcGUgI1ggOjogKAogICAgICAgICAgICAgICAgKD8gKD09IDEgKEAgKCsgKCogWCBYKSAoKiBZIFkpKSBOKSkgIlgiICIgIikKICAgICAgICAgICAgKSkpICIiKQogICAgICAgICkpKSAiXG4iKQogICAgKSkKICAgICUgR29sZmVkOgogICAgKGRlZiBmICNOOjooKGpvaW4obWFwKHNlcSgtIE4gMSkwKShzY29wZSAjWTo6KChqb2luKG1hcChzZXEgMCgtIE4gMSkpKHNjb3BlICNYOjooKD8oPT0gMShAKCsoKiBYIFgpKCogWSBZKSlOKSkiWCIgIiAiKSkpKSIiKSkpKSJcbiIpKSkKICAgIAogICAgJSBUZXN0czoKICAgIChlYWNoIChzZXEgMiAzMCkgKHNjb3BlICNOIDo6ICgKICAgICAgICAocHJpbnQgIkZvciBOPSIgTiAiOlxuIiAoZiBOKSkKICAgICkpKQogICAgKHByaW50IChmIDQwKSkKKQ==) Not the shortest. I think I need some sort of shorthand module. See the Try it Online link for further explanation, ungolfed version, and some tests. For best results, expand the output window to see more.
[GolfScript](http://www.golfscript.com/golfscript/), 34 bytes ============================================================= ``` ~:c,{.*}%:a{:b;a{b+c%1=' x'=}%}%n* ``` [Try it online!](https://tio.run/nexus/golfscript#@19nlaxTradVq2qVWG2VZJ1YnaSdrGpoq65QoW5bq1qrmqf1/7@JEQA "GolfScript – TIO Nexus") I really don't like using variables...
114,847
Introduction ------------ You may know and love your normal unit circle. But mathematicans are crazy and thus they have abstracted the concept to any point that satisfies `x*x+y*y=1`. Because Cryptographers1 are also weird, they *love* finite fields and *sometimes* finite rings (it is not like they have much choice though), so let's combine this! The Challenge ------------- ### Input A positive integer larger than one in your favorite encoding. Let's call this number n. ### Output You will output the "picture" (which consists of n times n characters) of the unit circle modulo the input integer as ASCII-Art using "X" (upper-case latin X) and " " (a space). Trailing spaces and newlines are allowed. ### More Details You have to span a coordinate system from bottom-left to top-right. Whenever a point fulfills the circle equation, place an X at the position, otherwise place a space. The condition for a point to be considered part of the circle border is: `mod(x*x+y*y,n)==1`. Here a quick illustration of the coordinate-system: ``` (0,4)(1,4)(2,4)(3,4)(4,4) (0,3)(1,3)(2,3)(3,3)(4,3) (0,2)(1,2)(2,2)(3,2)(4,2) (0,1)(1,1)(2,1)(3,1)(4,1) (0,0)(1,0)(2,0)(3,0)(4,0) ``` If it helps you, you may also invert the direction of any of the axes, but the examples assume this orientation. Who wins? --------- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in byte wins! [Only the default I/O methods are allowed](https://codegolf.meta.stackexchange.com/q/2447/55329) and all standard loopholes are banned. Examples -------- Input: 2 ``` X X ``` Input: 3 ``` X X XX ``` Input: 5 ``` X X X X ``` Input: 7 ``` X X X X X X X X ``` Input: 11 ``` X XX X X X X XX X X X ``` Input: 42 ``` X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X ``` --- 1 I suggest you take a look at my profile if you're wondering here.
2017/04/01
[ "https://codegolf.stackexchange.com/questions/114847", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/55329/" ]
[Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 bytes ================================================================= ``` R²+þ`%=1ị⁾X Y ``` The x-axis is inverted. [Try it online!](https://tio.run/nexus/jelly#@x90aJP24X0JqraGD3d3P2rcF6EQ@f//fxMjAA "Jelly – TIO Nexus") ### How it works ``` R²+þ`%=1ị⁾X Y Main link. Argument: n R Range; yield [1, ..., n]. ² Square; yield [1², ..., n²]. +þ` Self table addition; compute x+y for all x and y in [1², ..., n²], grouping by the values of y. % Take all sums modulo n. =1 Compare them with 1, yielding 1 or 0. ị⁾X Index into "X ". Y Separate by linefeeds. ```
[dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 79 bytes ================================================================================ ``` ?dsRsQ[88P]sl[32P]sH[0sM[lM2^lR2^+lQ%d1=l1!=HlM1+dsMlQ>c]dscx10PlR1-dsR0<S]dsSx ``` The `y`-axis is inverted whereas the `x`-axis is not. [Try it online!](https://tio.run/nexus/dc#@2@fUhxUHBhtYREQW5wTbWwEpDyiDYp9o3N8jeJygozitHMCVVMMbXMMFW09cnwNtVOKfXMC7ZJjU4qTKwwNAnKCDHWBRhjYBANFgiv@/zcxAgA "dc – TIO Nexus")
114,847
Introduction ------------ You may know and love your normal unit circle. But mathematicans are crazy and thus they have abstracted the concept to any point that satisfies `x*x+y*y=1`. Because Cryptographers1 are also weird, they *love* finite fields and *sometimes* finite rings (it is not like they have much choice though), so let's combine this! The Challenge ------------- ### Input A positive integer larger than one in your favorite encoding. Let's call this number n. ### Output You will output the "picture" (which consists of n times n characters) of the unit circle modulo the input integer as ASCII-Art using "X" (upper-case latin X) and " " (a space). Trailing spaces and newlines are allowed. ### More Details You have to span a coordinate system from bottom-left to top-right. Whenever a point fulfills the circle equation, place an X at the position, otherwise place a space. The condition for a point to be considered part of the circle border is: `mod(x*x+y*y,n)==1`. Here a quick illustration of the coordinate-system: ``` (0,4)(1,4)(2,4)(3,4)(4,4) (0,3)(1,3)(2,3)(3,3)(4,3) (0,2)(1,2)(2,2)(3,2)(4,2) (0,1)(1,1)(2,1)(3,1)(4,1) (0,0)(1,0)(2,0)(3,0)(4,0) ``` If it helps you, you may also invert the direction of any of the axes, but the examples assume this orientation. Who wins? --------- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in byte wins! [Only the default I/O methods are allowed](https://codegolf.meta.stackexchange.com/q/2447/55329) and all standard loopholes are banned. Examples -------- Input: 2 ``` X X ``` Input: 3 ``` X X XX ``` Input: 5 ``` X X X X ``` Input: 7 ``` X X X X X X X X ``` Input: 11 ``` X XX X X X X XX X X X ``` Input: 42 ``` X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X ``` --- 1 I suggest you take a look at my profile if you're wondering here.
2017/04/01
[ "https://codegolf.stackexchange.com/questions/114847", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/55329/" ]
[Haskell](https://www.haskell.org/), 68 bytes ============================================= ```hs f n|r<-[0..n-1]=unlines[[last$' ':['X'|mod(x*x+y*y)n==1]|y<-r]|x<-r] ``` [Try it online!](https://tio.run/nexus/haskell#@5@mkFdTZKMbbaCnl6drGGtbmpeTmZdaHB2dk1hcoqKuoG4VrR6hXpObn6JRoVWhXalVqZlna2sYW1Npo1sUW1MBIv/nJmbmKdgqFKUmpvjkKdjZ2SoUlJYElxQp6Cmk/TcxAgA "Haskell – TIO Nexus") The y-axis is flipped. Usage: `f 42` returns a newline delimited string. This is a nested list comprehension where both `x` and `y` are drawn from the range `[0..n-1]`. `last$' ':['X'|mod(x*x+y*y)n==1]` is a shorter form of `if mod(x*x+y*y)n==1 then 'X' else ' '`. The list comprehension evaluates to a list of strings which is turned into a single newline separated string by `unlines`.
[Lithp](https://github.com/andrakis/node-lithp), 125 bytes ---------------------------------------------------------- ``` #N::((join(map(seq(- N 1)0)(scope #Y::((join(map(seq 0(- N 1))(scope #X:: ((?(== 1(@(+(* X X)(* Y Y))N))"X" " "))))""))))"\n") ``` Linebreak for readability. [Try it online!](https://andrakis.github.io/ide2/index.html?code=JSBBbiBlbnRyeSBmb3IgYSBDb2RlZ29sZiBjaGFsbGVuZ2U6CiUgaHR0cDovL2NvZGVnb2xmLnN0YWNrZXhjaGFuZ2UuY29tL3F1ZXN0aW9ucy8xMTQ4NDcvZHJhdy1tZS10aGUtd2VpcmQtdW5pdC1jaXJjbGUKJSBGb3IgYmVzdCByZXN1bHRzLCBleHBhbmQgdGhlIG91dHB1dCB3aW5kb3cgYmVsb3cuCigKICAgIChpbXBvcnQgbGlzdHMpCiAgICAlIFVuZ29sZmVkOgogICAgKGRlZiBmICNOIDo6ICgKICAgICAgICAoam9pbiAobWFwIChzZXEgKC0gTiAxKSAwKSAoc2NvcGUgI1kgOjogKAogICAgICAgICAgICAoam9pbiAobWFwIChzZXEgMCAoLSBOIDEpKSAoc2NvcGUgI1ggOjogKAogICAgICAgICAgICAgICAgKD8gKD09IDEgKEAgKCsgKCogWCBYKSAoKiBZIFkpKSBOKSkgIlgiICIgIikKICAgICAgICAgICAgKSkpICIiKQogICAgICAgICkpKSAiXG4iKQogICAgKSkKICAgICUgR29sZmVkOgogICAgKGRlZiBmICNOOjooKGpvaW4obWFwKHNlcSgtIE4gMSkwKShzY29wZSAjWTo6KChqb2luKG1hcChzZXEgMCgtIE4gMSkpKHNjb3BlICNYOjooKD8oPT0gMShAKCsoKiBYIFgpKCogWSBZKSlOKSkiWCIgIiAiKSkpKSIiKSkpKSJcbiIpKSkKICAgIAogICAgJSBUZXN0czoKICAgIChlYWNoIChzZXEgMiAzMCkgKHNjb3BlICNOIDo6ICgKICAgICAgICAocHJpbnQgIkZvciBOPSIgTiAiOlxuIiAoZiBOKSkKICAgICkpKQogICAgKHByaW50IChmIDQwKSkKKQ==) Not the shortest. I think I need some sort of shorthand module. See the Try it Online link for further explanation, ungolfed version, and some tests. For best results, expand the output window to see more.
114,847
Introduction ------------ You may know and love your normal unit circle. But mathematicans are crazy and thus they have abstracted the concept to any point that satisfies `x*x+y*y=1`. Because Cryptographers1 are also weird, they *love* finite fields and *sometimes* finite rings (it is not like they have much choice though), so let's combine this! The Challenge ------------- ### Input A positive integer larger than one in your favorite encoding. Let's call this number n. ### Output You will output the "picture" (which consists of n times n characters) of the unit circle modulo the input integer as ASCII-Art using "X" (upper-case latin X) and " " (a space). Trailing spaces and newlines are allowed. ### More Details You have to span a coordinate system from bottom-left to top-right. Whenever a point fulfills the circle equation, place an X at the position, otherwise place a space. The condition for a point to be considered part of the circle border is: `mod(x*x+y*y,n)==1`. Here a quick illustration of the coordinate-system: ``` (0,4)(1,4)(2,4)(3,4)(4,4) (0,3)(1,3)(2,3)(3,3)(4,3) (0,2)(1,2)(2,2)(3,2)(4,2) (0,1)(1,1)(2,1)(3,1)(4,1) (0,0)(1,0)(2,0)(3,0)(4,0) ``` If it helps you, you may also invert the direction of any of the axes, but the examples assume this orientation. Who wins? --------- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in byte wins! [Only the default I/O methods are allowed](https://codegolf.meta.stackexchange.com/q/2447/55329) and all standard loopholes are banned. Examples -------- Input: 2 ``` X X ``` Input: 3 ``` X X XX ``` Input: 5 ``` X X X X ``` Input: 7 ``` X X X X X X X X ``` Input: 11 ``` X XX X X X X XX X X X ``` Input: 42 ``` X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X ``` --- 1 I suggest you take a look at my profile if you're wondering here.
2017/04/01
[ "https://codegolf.stackexchange.com/questions/114847", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/55329/" ]
Mathematica, 56 48 bytes ------------------------ *Edit: Thanks to Greg Martin and Martin Ender for saving 8 bytes.* ``` Grid@Array[If[Mod[#^2+#2^2,x]==1,X]&,{x=#,#},0]& ``` Original solution: ------------------ ``` Grid@Table[If[Tr[{i-1,j-1}^2]~Mod~#==1,X,],{i,#},{j,#}]& ```
[J](http://jsoftware.com/), 20 bytes ==================================== ``` ' x'{~1=[|+/~@:*:@i. ``` [Try it online!](https://tio.run/nexus/j#@59ma6WuUKFeXWdoG12jrV/nYKVl5ZCp9z81OSNfIU3BxIgrtSKzRMHgPwA "J – TIO Nexus")
114,847
Introduction ------------ You may know and love your normal unit circle. But mathematicans are crazy and thus they have abstracted the concept to any point that satisfies `x*x+y*y=1`. Because Cryptographers1 are also weird, they *love* finite fields and *sometimes* finite rings (it is not like they have much choice though), so let's combine this! The Challenge ------------- ### Input A positive integer larger than one in your favorite encoding. Let's call this number n. ### Output You will output the "picture" (which consists of n times n characters) of the unit circle modulo the input integer as ASCII-Art using "X" (upper-case latin X) and " " (a space). Trailing spaces and newlines are allowed. ### More Details You have to span a coordinate system from bottom-left to top-right. Whenever a point fulfills the circle equation, place an X at the position, otherwise place a space. The condition for a point to be considered part of the circle border is: `mod(x*x+y*y,n)==1`. Here a quick illustration of the coordinate-system: ``` (0,4)(1,4)(2,4)(3,4)(4,4) (0,3)(1,3)(2,3)(3,3)(4,3) (0,2)(1,2)(2,2)(3,2)(4,2) (0,1)(1,1)(2,1)(3,1)(4,1) (0,0)(1,0)(2,0)(3,0)(4,0) ``` If it helps you, you may also invert the direction of any of the axes, but the examples assume this orientation. Who wins? --------- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in byte wins! [Only the default I/O methods are allowed](https://codegolf.meta.stackexchange.com/q/2447/55329) and all standard loopholes are banned. Examples -------- Input: 2 ``` X X ``` Input: 3 ``` X X XX ``` Input: 5 ``` X X X X ``` Input: 7 ``` X X X X X X X X ``` Input: 11 ``` X XX X X X X XX X X X ``` Input: 42 ``` X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X ``` --- 1 I suggest you take a look at my profile if you're wondering here.
2017/04/01
[ "https://codegolf.stackexchange.com/questions/114847", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/55329/" ]
[Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 bytes ================================================================= ``` R²+þ`%=1ị⁾X Y ``` The x-axis is inverted. [Try it online!](https://tio.run/nexus/jelly#@x90aJP24X0JqraGD3d3P2rcF6EQ@f//fxMjAA "Jelly – TIO Nexus") ### How it works ``` R²+þ`%=1ị⁾X Y Main link. Argument: n R Range; yield [1, ..., n]. ² Square; yield [1², ..., n²]. +þ` Self table addition; compute x+y for all x and y in [1², ..., n²], grouping by the values of y. % Take all sums modulo n. =1 Compare them with 1, yielding 1 or 0. ị⁾X Index into "X ". Y Separate by linefeeds. ```
[Python 3](https://docs.python.org/3/), 82 bytes ================================================ ```python f=lambda n,k=0:k<n>f(n,k+1)!=print(''.join(' X'[(k*k+j*j)%n==1]for j in range(n))) ``` [Try it online!](https://tio.run/nexus/python3#DcZBDkAwEADAr6yDdFdFECex3iERhwqVtixp/L/MaZLl01zrZkDKwHUfBhkt/tcNZfxEJy8qVfnbCSqY1IyhCNoXnnJhbhZ7R/DgBKKRY0chomSxayl9 "Python 3 – TIO Nexus")
17,586,113
I am trying to run a very simple program, and I'm stuck on the basics of declaring the nested lists and maps. I'm working on a project which requires me to store polynomials into an ArrayList. Each polynomial is named, so I want a key/value map to pull the name of the polynomial (1, 2, 3 etc.) as the key, and the actual polynomial as the value. NOW the actual polynomial requires key values as well because the nature of this program requires that the exponent be associated with the coefficient. So for example I need an ArrayList of polynomials, say the first one is a simple: polynomial 1: 2x^3 the array list contains the whole thing as a map, and the map contains key: polynomial 1 and value: is a Map... with the 2 and 3 being key/values. The code I have is below but I'm not 100% on how to format such nested logic. ``` public static void main(String[] args) throws IOException{ ArrayList<Map> polynomialArray = new ArrayList<Map>(); Map<String, Map<Integer, Integer>> polynomialIndex = new Map<String, Map<Integer, Integer>>(); String filename = "polynomials.txt"; Scanner file = new Scanner(new File(filename)); for(int i = 0; file.hasNextLine(); i++){ //this will eventually scan polynomials out of a file and do stuff } ``` EDIT: Updated the key/value in Map, still having issues. The code above is giving me the following error: ``` Cannot instantiate the type Map<String,Map<Integer,Integer>> ``` So how then do I go about doing this or am I just going about this all the wrong way?
2013/07/11
[ "https://Stackoverflow.com/questions/17586113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1585868/" ]
You can't instantiate `new Map<String, Map<Integer, Integer>>()` because [`java.util.Map`](http://docs.oracle.com/javase/7/docs/api/java/util/Map.html) is an *interface* (it doesn't have a constructor). You need to use a concrete type like [`java.util.HashMap`](http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html): ``` Map<String, Map<Integer, Integer>> polynomialIndex = new HashMap<String, Map<Integer, Integer>>(); ``` Also, if you're using Java 7 or above, you can use [generic type inference](http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html) to save some typing: ``` Map<String, Map<Integer, Integer>> polynomialIndex = new HashMap<>(); ```
This is incorrect: ``` Map<String, Map<Integer>> polynomialIndex = new Map<String, Map<Integer>>(); ``` Maps need to have two parameters and your nested map `Map<Integer>` only has one. I think you're looking for something like: ``` Map<String, Map<Integer, Integer>> polynomialIndex = new Map<String, Map<Integer, Integer>>(); ``` Or it may be best done separate. ``` Map<String, Map> polynomialIndex = new Map<String, Map>(); Map<Integer, Integer> polynomialNumbers = new Map<Integer, Integer>(); ``` With this you can just put the numbers in the polynomailNumbers Map then use that in polynomialIndex.
7,777
Related: [When is it allowable to change the rules?](https://codegolf.meta.stackexchange.com/q/1346/3808) As noted in the linked meta post above, it's typically particularly frowned upon to significantly change the rules of a challenge after posting it. There's no hard and fast rule on this yet, so the purpose of this meta post is to enact at least some kind of **policy to determine when drastic edits should be rolled back**. Here, we define "rule change" as not any type of edit but **any edit that causes one or more reasonable hypothetical answers to become invalid beyond repair**. Note that the "beyond repair" clause means that this *does not include* minor rule changes such as input/output format. Note that the wording of this definition also (intentionally) does not include edits that give answers *additional* liberties. There are a few "poll-style" answers here to vote / comment on: * [Should rule changes that don't invalidate existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7778/3808) * [Should rule changes that invalidate one or more existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7779/3808) * [Do rule changes in comments count?](https://codegolf.meta.stackexchange.com/a/7780/3808) Adding your own answer is encouraged, though, possibly addressing some of the following questions: * Exactly what it says in the title: If you do think that some rule changes should be acceptable, which ones specifically and in what situations? * If we're going with "rule changes are only allowed if they're minor enough," how do we define a "major" rule change? * If you think the policy should be something other than something that was mentioned here, what is it, and who gets to decide which rule changes are allowed?
2015/12/22
[ "https://codegolf.meta.stackexchange.com/questions/7777", "https://codegolf.meta.stackexchange.com", "https://codegolf.meta.stackexchange.com/users/3808/" ]
Rule changes that don't invalidate existing answers should be allowed (they should not be rolled back). *(Upvote if you agree, downvote if you disagree, and comment for anything else.)*
Rule changes that invalidate existing answers should be allowed (they should not be rolled back). *(Upvote if you agree, downvote if you disagree, and comment for anything else.)*
7,777
Related: [When is it allowable to change the rules?](https://codegolf.meta.stackexchange.com/q/1346/3808) As noted in the linked meta post above, it's typically particularly frowned upon to significantly change the rules of a challenge after posting it. There's no hard and fast rule on this yet, so the purpose of this meta post is to enact at least some kind of **policy to determine when drastic edits should be rolled back**. Here, we define "rule change" as not any type of edit but **any edit that causes one or more reasonable hypothetical answers to become invalid beyond repair**. Note that the "beyond repair" clause means that this *does not include* minor rule changes such as input/output format. Note that the wording of this definition also (intentionally) does not include edits that give answers *additional* liberties. There are a few "poll-style" answers here to vote / comment on: * [Should rule changes that don't invalidate existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7778/3808) * [Should rule changes that invalidate one or more existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7779/3808) * [Do rule changes in comments count?](https://codegolf.meta.stackexchange.com/a/7780/3808) Adding your own answer is encouraged, though, possibly addressing some of the following questions: * Exactly what it says in the title: If you do think that some rule changes should be acceptable, which ones specifically and in what situations? * If we're going with "rule changes are only allowed if they're minor enough," how do we define a "major" rule change? * If you think the policy should be something other than something that was mentioned here, what is it, and who gets to decide which rule changes are allowed?
2015/12/22
[ "https://codegolf.meta.stackexchange.com/questions/7777", "https://codegolf.meta.stackexchange.com", "https://codegolf.meta.stackexchange.com/users/3808/" ]
Rule changes that don't invalidate existing answers should be allowed (they should not be rolled back). *(Upvote if you agree, downvote if you disagree, and comment for anything else.)*
Rule changes in comments are equally valid as those that have been edited into the actual post. *(Upvote if you agree, downvote if you disagree, and comment for anything else.)*
7,777
Related: [When is it allowable to change the rules?](https://codegolf.meta.stackexchange.com/q/1346/3808) As noted in the linked meta post above, it's typically particularly frowned upon to significantly change the rules of a challenge after posting it. There's no hard and fast rule on this yet, so the purpose of this meta post is to enact at least some kind of **policy to determine when drastic edits should be rolled back**. Here, we define "rule change" as not any type of edit but **any edit that causes one or more reasonable hypothetical answers to become invalid beyond repair**. Note that the "beyond repair" clause means that this *does not include* minor rule changes such as input/output format. Note that the wording of this definition also (intentionally) does not include edits that give answers *additional* liberties. There are a few "poll-style" answers here to vote / comment on: * [Should rule changes that don't invalidate existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7778/3808) * [Should rule changes that invalidate one or more existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7779/3808) * [Do rule changes in comments count?](https://codegolf.meta.stackexchange.com/a/7780/3808) Adding your own answer is encouraged, though, possibly addressing some of the following questions: * Exactly what it says in the title: If you do think that some rule changes should be acceptable, which ones specifically and in what situations? * If we're going with "rule changes are only allowed if they're minor enough," how do we define a "major" rule change? * If you think the policy should be something other than something that was mentioned here, what is it, and who gets to decide which rule changes are allowed?
2015/12/22
[ "https://codegolf.meta.stackexchange.com/questions/7777", "https://codegolf.meta.stackexchange.com", "https://codegolf.meta.stackexchange.com/users/3808/" ]
In support of allowing rule changes that invalidate existing answers ==================================================================== **Closing loopholes** Suppose you've posted a [fastest-code](https://codegolf.stackexchange.com/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge about finding factors of integers. Suppose the description of the challenge is "You will be given a positive integer. You must output a proper factor of this integer as quickly as possible." Now, suppose that someone answers with a submission that always returns 1. Technically, this is a valid solution to the challenge as stated. However, it is a trivial solution, and nothing of value is lost by changing the question to say "proper factor greater than 1". This does invalidate the existing solution, and it is a rule change, but it brings the rules in line with the clear intent of the poster and improves the challenge with no real loss. Obviously, there is a fine line between closing loopholes and real changes to the rules, but we should allow closing loopholes, even if answers which exploit them have been posted.
Rule changes that don't invalidate existing answers should be allowed (they should not be rolled back). *(Upvote if you agree, downvote if you disagree, and comment for anything else.)*
7,777
Related: [When is it allowable to change the rules?](https://codegolf.meta.stackexchange.com/q/1346/3808) As noted in the linked meta post above, it's typically particularly frowned upon to significantly change the rules of a challenge after posting it. There's no hard and fast rule on this yet, so the purpose of this meta post is to enact at least some kind of **policy to determine when drastic edits should be rolled back**. Here, we define "rule change" as not any type of edit but **any edit that causes one or more reasonable hypothetical answers to become invalid beyond repair**. Note that the "beyond repair" clause means that this *does not include* minor rule changes such as input/output format. Note that the wording of this definition also (intentionally) does not include edits that give answers *additional* liberties. There are a few "poll-style" answers here to vote / comment on: * [Should rule changes that don't invalidate existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7778/3808) * [Should rule changes that invalidate one or more existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7779/3808) * [Do rule changes in comments count?](https://codegolf.meta.stackexchange.com/a/7780/3808) Adding your own answer is encouraged, though, possibly addressing some of the following questions: * Exactly what it says in the title: If you do think that some rule changes should be acceptable, which ones specifically and in what situations? * If we're going with "rule changes are only allowed if they're minor enough," how do we define a "major" rule change? * If you think the policy should be something other than something that was mentioned here, what is it, and who gets to decide which rule changes are allowed?
2015/12/22
[ "https://codegolf.meta.stackexchange.com/questions/7777", "https://codegolf.meta.stackexchange.com", "https://codegolf.meta.stackexchange.com/users/3808/" ]
Rule changes are allowed ------------------------ They're often a very bad idea, but I don't think we should forbid them, regardless of whether they invalidate answers or not. Most of the time, rule changes are meant to improve the challenge. This can include closing loopholes as isaacg mentioned, but it can also mean just tightening or relaxing the rules slightly if they are found to allow uninteresting solutions which make the interesting ones uncompetitive, or if they are found to disallow interesting solutions. The challenge that sparked this discussion was [this one](https://codegolf.stackexchange.com/q/67158/8478). That's a very good example of a rule change that improves the challenge. In it's original form, brute force was allowed, which would obviously never complete for a square of any interesting size. But efficient solutions exist, and they are a lot more interesting. So adding a time limit after answers were already posted (especially ones which just created random grids until one was valid), definitely improved the question. Early uninteresting answers should not have the power to "lock" a bad challenge in its current state. Yes, invalidated answers are frustrating, and everyone whose answer gets invalidated by a rule change is well within their rights to downvote the challenge (although *I personally find it very weird that PPCG is the only SE where you risk being downvoted for improving your post*), but if that allows the challenge to be a better challenge, then I think it's worth the change. In any case, there shouldn't be a blanket rule against changes, because I think it will lead to more abuse (by early answerers) than it will do good. Challenge authors should still think twice (or three times) if a rule change is worth the trouble. If it invalidates a lot (or the majority) of answers, it's probably not worth it, because many of those invalid answers will remain and it will become a pain to pick out the valid ones. In that case, just learn your lesson for next time. But if it's about disallowing some boring approach that essentially breaks the challenge and has been used once or twice, then go ahead. As for answerers whose answers are invalidated, be a good sportsman and delete (or change) your answer. And before you downvote the challenge for the rule change, consider whether your solution actually added anything valuable to it or whether the challenge isn't actually more interesting if answers like yours aren't valid any more.
Rule changes that don't invalidate existing answers should be allowed (they should not be rolled back). *(Upvote if you agree, downvote if you disagree, and comment for anything else.)*
7,777
Related: [When is it allowable to change the rules?](https://codegolf.meta.stackexchange.com/q/1346/3808) As noted in the linked meta post above, it's typically particularly frowned upon to significantly change the rules of a challenge after posting it. There's no hard and fast rule on this yet, so the purpose of this meta post is to enact at least some kind of **policy to determine when drastic edits should be rolled back**. Here, we define "rule change" as not any type of edit but **any edit that causes one or more reasonable hypothetical answers to become invalid beyond repair**. Note that the "beyond repair" clause means that this *does not include* minor rule changes such as input/output format. Note that the wording of this definition also (intentionally) does not include edits that give answers *additional* liberties. There are a few "poll-style" answers here to vote / comment on: * [Should rule changes that don't invalidate existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7778/3808) * [Should rule changes that invalidate one or more existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7779/3808) * [Do rule changes in comments count?](https://codegolf.meta.stackexchange.com/a/7780/3808) Adding your own answer is encouraged, though, possibly addressing some of the following questions: * Exactly what it says in the title: If you do think that some rule changes should be acceptable, which ones specifically and in what situations? * If we're going with "rule changes are only allowed if they're minor enough," how do we define a "major" rule change? * If you think the policy should be something other than something that was mentioned here, what is it, and who gets to decide which rule changes are allowed?
2015/12/22
[ "https://codegolf.meta.stackexchange.com/questions/7777", "https://codegolf.meta.stackexchange.com", "https://codegolf.meta.stackexchange.com/users/3808/" ]
Rule changes that invalidate existing answers should be allowed (they should not be rolled back). *(Upvote if you agree, downvote if you disagree, and comment for anything else.)*
Rule changes in comments are equally valid as those that have been edited into the actual post. *(Upvote if you agree, downvote if you disagree, and comment for anything else.)*
7,777
Related: [When is it allowable to change the rules?](https://codegolf.meta.stackexchange.com/q/1346/3808) As noted in the linked meta post above, it's typically particularly frowned upon to significantly change the rules of a challenge after posting it. There's no hard and fast rule on this yet, so the purpose of this meta post is to enact at least some kind of **policy to determine when drastic edits should be rolled back**. Here, we define "rule change" as not any type of edit but **any edit that causes one or more reasonable hypothetical answers to become invalid beyond repair**. Note that the "beyond repair" clause means that this *does not include* minor rule changes such as input/output format. Note that the wording of this definition also (intentionally) does not include edits that give answers *additional* liberties. There are a few "poll-style" answers here to vote / comment on: * [Should rule changes that don't invalidate existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7778/3808) * [Should rule changes that invalidate one or more existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7779/3808) * [Do rule changes in comments count?](https://codegolf.meta.stackexchange.com/a/7780/3808) Adding your own answer is encouraged, though, possibly addressing some of the following questions: * Exactly what it says in the title: If you do think that some rule changes should be acceptable, which ones specifically and in what situations? * If we're going with "rule changes are only allowed if they're minor enough," how do we define a "major" rule change? * If you think the policy should be something other than something that was mentioned here, what is it, and who gets to decide which rule changes are allowed?
2015/12/22
[ "https://codegolf.meta.stackexchange.com/questions/7777", "https://codegolf.meta.stackexchange.com", "https://codegolf.meta.stackexchange.com/users/3808/" ]
In support of allowing rule changes that invalidate existing answers ==================================================================== **Closing loopholes** Suppose you've posted a [fastest-code](https://codegolf.stackexchange.com/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge about finding factors of integers. Suppose the description of the challenge is "You will be given a positive integer. You must output a proper factor of this integer as quickly as possible." Now, suppose that someone answers with a submission that always returns 1. Technically, this is a valid solution to the challenge as stated. However, it is a trivial solution, and nothing of value is lost by changing the question to say "proper factor greater than 1". This does invalidate the existing solution, and it is a rule change, but it brings the rules in line with the clear intent of the poster and improves the challenge with no real loss. Obviously, there is a fine line between closing loopholes and real changes to the rules, but we should allow closing loopholes, even if answers which exploit them have been posted.
Rule changes that invalidate existing answers should be allowed (they should not be rolled back). *(Upvote if you agree, downvote if you disagree, and comment for anything else.)*
7,777
Related: [When is it allowable to change the rules?](https://codegolf.meta.stackexchange.com/q/1346/3808) As noted in the linked meta post above, it's typically particularly frowned upon to significantly change the rules of a challenge after posting it. There's no hard and fast rule on this yet, so the purpose of this meta post is to enact at least some kind of **policy to determine when drastic edits should be rolled back**. Here, we define "rule change" as not any type of edit but **any edit that causes one or more reasonable hypothetical answers to become invalid beyond repair**. Note that the "beyond repair" clause means that this *does not include* minor rule changes such as input/output format. Note that the wording of this definition also (intentionally) does not include edits that give answers *additional* liberties. There are a few "poll-style" answers here to vote / comment on: * [Should rule changes that don't invalidate existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7778/3808) * [Should rule changes that invalidate one or more existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7779/3808) * [Do rule changes in comments count?](https://codegolf.meta.stackexchange.com/a/7780/3808) Adding your own answer is encouraged, though, possibly addressing some of the following questions: * Exactly what it says in the title: If you do think that some rule changes should be acceptable, which ones specifically and in what situations? * If we're going with "rule changes are only allowed if they're minor enough," how do we define a "major" rule change? * If you think the policy should be something other than something that was mentioned here, what is it, and who gets to decide which rule changes are allowed?
2015/12/22
[ "https://codegolf.meta.stackexchange.com/questions/7777", "https://codegolf.meta.stackexchange.com", "https://codegolf.meta.stackexchange.com/users/3808/" ]
Rule changes are allowed ------------------------ They're often a very bad idea, but I don't think we should forbid them, regardless of whether they invalidate answers or not. Most of the time, rule changes are meant to improve the challenge. This can include closing loopholes as isaacg mentioned, but it can also mean just tightening or relaxing the rules slightly if they are found to allow uninteresting solutions which make the interesting ones uncompetitive, or if they are found to disallow interesting solutions. The challenge that sparked this discussion was [this one](https://codegolf.stackexchange.com/q/67158/8478). That's a very good example of a rule change that improves the challenge. In it's original form, brute force was allowed, which would obviously never complete for a square of any interesting size. But efficient solutions exist, and they are a lot more interesting. So adding a time limit after answers were already posted (especially ones which just created random grids until one was valid), definitely improved the question. Early uninteresting answers should not have the power to "lock" a bad challenge in its current state. Yes, invalidated answers are frustrating, and everyone whose answer gets invalidated by a rule change is well within their rights to downvote the challenge (although *I personally find it very weird that PPCG is the only SE where you risk being downvoted for improving your post*), but if that allows the challenge to be a better challenge, then I think it's worth the change. In any case, there shouldn't be a blanket rule against changes, because I think it will lead to more abuse (by early answerers) than it will do good. Challenge authors should still think twice (or three times) if a rule change is worth the trouble. If it invalidates a lot (or the majority) of answers, it's probably not worth it, because many of those invalid answers will remain and it will become a pain to pick out the valid ones. In that case, just learn your lesson for next time. But if it's about disallowing some boring approach that essentially breaks the challenge and has been used once or twice, then go ahead. As for answerers whose answers are invalidated, be a good sportsman and delete (or change) your answer. And before you downvote the challenge for the rule change, consider whether your solution actually added anything valuable to it or whether the challenge isn't actually more interesting if answers like yours aren't valid any more.
Rule changes that invalidate existing answers should be allowed (they should not be rolled back). *(Upvote if you agree, downvote if you disagree, and comment for anything else.)*
7,777
Related: [When is it allowable to change the rules?](https://codegolf.meta.stackexchange.com/q/1346/3808) As noted in the linked meta post above, it's typically particularly frowned upon to significantly change the rules of a challenge after posting it. There's no hard and fast rule on this yet, so the purpose of this meta post is to enact at least some kind of **policy to determine when drastic edits should be rolled back**. Here, we define "rule change" as not any type of edit but **any edit that causes one or more reasonable hypothetical answers to become invalid beyond repair**. Note that the "beyond repair" clause means that this *does not include* minor rule changes such as input/output format. Note that the wording of this definition also (intentionally) does not include edits that give answers *additional* liberties. There are a few "poll-style" answers here to vote / comment on: * [Should rule changes that don't invalidate existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7778/3808) * [Should rule changes that invalidate one or more existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7779/3808) * [Do rule changes in comments count?](https://codegolf.meta.stackexchange.com/a/7780/3808) Adding your own answer is encouraged, though, possibly addressing some of the following questions: * Exactly what it says in the title: If you do think that some rule changes should be acceptable, which ones specifically and in what situations? * If we're going with "rule changes are only allowed if they're minor enough," how do we define a "major" rule change? * If you think the policy should be something other than something that was mentioned here, what is it, and who gets to decide which rule changes are allowed?
2015/12/22
[ "https://codegolf.meta.stackexchange.com/questions/7777", "https://codegolf.meta.stackexchange.com", "https://codegolf.meta.stackexchange.com/users/3808/" ]
In support of allowing rule changes that invalidate existing answers ==================================================================== **Closing loopholes** Suppose you've posted a [fastest-code](https://codegolf.stackexchange.com/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge about finding factors of integers. Suppose the description of the challenge is "You will be given a positive integer. You must output a proper factor of this integer as quickly as possible." Now, suppose that someone answers with a submission that always returns 1. Technically, this is a valid solution to the challenge as stated. However, it is a trivial solution, and nothing of value is lost by changing the question to say "proper factor greater than 1". This does invalidate the existing solution, and it is a rule change, but it brings the rules in line with the clear intent of the poster and improves the challenge with no real loss. Obviously, there is a fine line between closing loopholes and real changes to the rules, but we should allow closing loopholes, even if answers which exploit them have been posted.
Rule changes in comments are equally valid as those that have been edited into the actual post. *(Upvote if you agree, downvote if you disagree, and comment for anything else.)*
7,777
Related: [When is it allowable to change the rules?](https://codegolf.meta.stackexchange.com/q/1346/3808) As noted in the linked meta post above, it's typically particularly frowned upon to significantly change the rules of a challenge after posting it. There's no hard and fast rule on this yet, so the purpose of this meta post is to enact at least some kind of **policy to determine when drastic edits should be rolled back**. Here, we define "rule change" as not any type of edit but **any edit that causes one or more reasonable hypothetical answers to become invalid beyond repair**. Note that the "beyond repair" clause means that this *does not include* minor rule changes such as input/output format. Note that the wording of this definition also (intentionally) does not include edits that give answers *additional* liberties. There are a few "poll-style" answers here to vote / comment on: * [Should rule changes that don't invalidate existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7778/3808) * [Should rule changes that invalidate one or more existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7779/3808) * [Do rule changes in comments count?](https://codegolf.meta.stackexchange.com/a/7780/3808) Adding your own answer is encouraged, though, possibly addressing some of the following questions: * Exactly what it says in the title: If you do think that some rule changes should be acceptable, which ones specifically and in what situations? * If we're going with "rule changes are only allowed if they're minor enough," how do we define a "major" rule change? * If you think the policy should be something other than something that was mentioned here, what is it, and who gets to decide which rule changes are allowed?
2015/12/22
[ "https://codegolf.meta.stackexchange.com/questions/7777", "https://codegolf.meta.stackexchange.com", "https://codegolf.meta.stackexchange.com/users/3808/" ]
Rule changes are allowed ------------------------ They're often a very bad idea, but I don't think we should forbid them, regardless of whether they invalidate answers or not. Most of the time, rule changes are meant to improve the challenge. This can include closing loopholes as isaacg mentioned, but it can also mean just tightening or relaxing the rules slightly if they are found to allow uninteresting solutions which make the interesting ones uncompetitive, or if they are found to disallow interesting solutions. The challenge that sparked this discussion was [this one](https://codegolf.stackexchange.com/q/67158/8478). That's a very good example of a rule change that improves the challenge. In it's original form, brute force was allowed, which would obviously never complete for a square of any interesting size. But efficient solutions exist, and they are a lot more interesting. So adding a time limit after answers were already posted (especially ones which just created random grids until one was valid), definitely improved the question. Early uninteresting answers should not have the power to "lock" a bad challenge in its current state. Yes, invalidated answers are frustrating, and everyone whose answer gets invalidated by a rule change is well within their rights to downvote the challenge (although *I personally find it very weird that PPCG is the only SE where you risk being downvoted for improving your post*), but if that allows the challenge to be a better challenge, then I think it's worth the change. In any case, there shouldn't be a blanket rule against changes, because I think it will lead to more abuse (by early answerers) than it will do good. Challenge authors should still think twice (or three times) if a rule change is worth the trouble. If it invalidates a lot (or the majority) of answers, it's probably not worth it, because many of those invalid answers will remain and it will become a pain to pick out the valid ones. In that case, just learn your lesson for next time. But if it's about disallowing some boring approach that essentially breaks the challenge and has been used once or twice, then go ahead. As for answerers whose answers are invalidated, be a good sportsman and delete (or change) your answer. And before you downvote the challenge for the rule change, consider whether your solution actually added anything valuable to it or whether the challenge isn't actually more interesting if answers like yours aren't valid any more.
Rule changes in comments are equally valid as those that have been edited into the actual post. *(Upvote if you agree, downvote if you disagree, and comment for anything else.)*
7,777
Related: [When is it allowable to change the rules?](https://codegolf.meta.stackexchange.com/q/1346/3808) As noted in the linked meta post above, it's typically particularly frowned upon to significantly change the rules of a challenge after posting it. There's no hard and fast rule on this yet, so the purpose of this meta post is to enact at least some kind of **policy to determine when drastic edits should be rolled back**. Here, we define "rule change" as not any type of edit but **any edit that causes one or more reasonable hypothetical answers to become invalid beyond repair**. Note that the "beyond repair" clause means that this *does not include* minor rule changes such as input/output format. Note that the wording of this definition also (intentionally) does not include edits that give answers *additional* liberties. There are a few "poll-style" answers here to vote / comment on: * [Should rule changes that don't invalidate existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7778/3808) * [Should rule changes that invalidate one or more existing answers be allowed?](https://codegolf.meta.stackexchange.com/a/7779/3808) * [Do rule changes in comments count?](https://codegolf.meta.stackexchange.com/a/7780/3808) Adding your own answer is encouraged, though, possibly addressing some of the following questions: * Exactly what it says in the title: If you do think that some rule changes should be acceptable, which ones specifically and in what situations? * If we're going with "rule changes are only allowed if they're minor enough," how do we define a "major" rule change? * If you think the policy should be something other than something that was mentioned here, what is it, and who gets to decide which rule changes are allowed?
2015/12/22
[ "https://codegolf.meta.stackexchange.com/questions/7777", "https://codegolf.meta.stackexchange.com", "https://codegolf.meta.stackexchange.com/users/3808/" ]
Rule changes are allowed ------------------------ They're often a very bad idea, but I don't think we should forbid them, regardless of whether they invalidate answers or not. Most of the time, rule changes are meant to improve the challenge. This can include closing loopholes as isaacg mentioned, but it can also mean just tightening or relaxing the rules slightly if they are found to allow uninteresting solutions which make the interesting ones uncompetitive, or if they are found to disallow interesting solutions. The challenge that sparked this discussion was [this one](https://codegolf.stackexchange.com/q/67158/8478). That's a very good example of a rule change that improves the challenge. In it's original form, brute force was allowed, which would obviously never complete for a square of any interesting size. But efficient solutions exist, and they are a lot more interesting. So adding a time limit after answers were already posted (especially ones which just created random grids until one was valid), definitely improved the question. Early uninteresting answers should not have the power to "lock" a bad challenge in its current state. Yes, invalidated answers are frustrating, and everyone whose answer gets invalidated by a rule change is well within their rights to downvote the challenge (although *I personally find it very weird that PPCG is the only SE where you risk being downvoted for improving your post*), but if that allows the challenge to be a better challenge, then I think it's worth the change. In any case, there shouldn't be a blanket rule against changes, because I think it will lead to more abuse (by early answerers) than it will do good. Challenge authors should still think twice (or three times) if a rule change is worth the trouble. If it invalidates a lot (or the majority) of answers, it's probably not worth it, because many of those invalid answers will remain and it will become a pain to pick out the valid ones. In that case, just learn your lesson for next time. But if it's about disallowing some boring approach that essentially breaks the challenge and has been used once or twice, then go ahead. As for answerers whose answers are invalidated, be a good sportsman and delete (or change) your answer. And before you downvote the challenge for the rule change, consider whether your solution actually added anything valuable to it or whether the challenge isn't actually more interesting if answers like yours aren't valid any more.
In support of allowing rule changes that invalidate existing answers ==================================================================== **Closing loopholes** Suppose you've posted a [fastest-code](https://codegolf.stackexchange.com/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge about finding factors of integers. Suppose the description of the challenge is "You will be given a positive integer. You must output a proper factor of this integer as quickly as possible." Now, suppose that someone answers with a submission that always returns 1. Technically, this is a valid solution to the challenge as stated. However, it is a trivial solution, and nothing of value is lost by changing the question to say "proper factor greater than 1". This does invalidate the existing solution, and it is a rule change, but it brings the rules in line with the clear intent of the poster and improves the challenge with no real loss. Obviously, there is a fine line between closing loopholes and real changes to the rules, but we should allow closing loopholes, even if answers which exploit them have been posted.
2,803,363
I'm interesting for the evaluation of $\int\_{-1}^1 x^{2k} \operatorname{erf}(x)^k \,dx=0$ with $l$ is a real number , I want to get closed form of that integral , i'm coming up to define it as :$\int\_{-1}^1 x^{2k} \operatorname{erf}(x)^k \,dx=0$ if $k$ is odd integer number and else ( equal to $\beta \neq 0$ ) if $k$ is even number ,Now i have two question for asking : **Question (1):** Is really :$\int\_{-1}^{1}x^{2k} \operatorname{erf}(x)^k \, dx=0$ if $k$ is odd integer number and else ( equal to $\beta \neq 0$ ) if $k$ is even number ? **Question (2)**: Can i get a closed form of it in the case of $k$ is even integer over $[-1,1]$ ? **Edit 01**: I have edit the question (2) without changing the meaning according to the given answer such that i want it's closed form in the range $[-1,1]$ if it is possible **Edit 02** I have took Boundaries since it's complicated to get closed form with determinate boundaries
2018/05/31
[ "https://math.stackexchange.com/questions/2803363", "https://math.stackexchange.com", "https://math.stackexchange.com/users/156150/" ]
$$I\_k=\int\_{-1}^1 x^{2k}\, \left[\text{erf}(x)\right]^k \,dx$$ is $0$ if $k$ is odd. So, we need to focus on $$I\_{2k}=\int\_{-1}^1 x^{4k}\, \left[\text{erf}(x)\right]^{2k} \,dx$$ which could be *approximated*, as I wrote in an answer to your previous question, using $$\left[\text{erf}(x)\right]^2\approx 1-e^{-a x^2}\qquad \text{with}\qquad a=(1+\pi )^{2/3} \log ^2(2)$$ making $$I\_{2k}=\int\_{-1}^1 x^{4k}\, \left(1-e^{-a x^2}\right)^{k} \,dx$$ to be developed using the binomial expansion. So, in practice, we face the problem of $$J\_{n,k}=\int\_{-1}^1 x^{4k}\,e^{-n a x^2}\,dx$$ The antiderivative $$\int x^{4k}\,e^{-n a x^2}\,dx=-\frac{1}{2} x^{4 k+1} E\_{\frac{1}{2}-2 k}\left(a n x^2\right)$$ where appears the exponential integral function. Using the bounds, this reduces to $$J\_{n,k}=-E\_{\frac{1}{2}-2 k}(a n)$$ and leads to "reasonable" approximation as shown in the table below $$\left( \begin{array}{ccc} k & \text{approximation} & \text{exact} \\ 1 & 0.22870436048 & 0.22959937502 \\ 2 & 0.08960938943 & 0.08997882179 \\ 3 & 0.04400808083 & 0.04418398568 \\ 4 & 0.02389675159 & 0.02398719298 \\ 5 & 0.01374034121 & 0.01378897319 \\ 6 & 0.00819869354 & 0.00822557475 \\ 7 & 0.00502074798 & 0.00503586007 \\ 8 & 0.00313428854 & 0.00314286515 \\ 9 & 0.00198581489 & 0.00199069974 \\ 10& 0.00127304507 & 0.00127582211 \end{array} \right)$$ **Edit** Another approximation could be obtained using the simplest Padé approximant of the error function $$\text{erf}(x)=\frac{2 x}{\sqrt{\pi } \left(1+\frac{x^2}{3}\right)}$$ which would lead to $$I\_{2k}=\int\_{-1}^1 x^{4k}\, \left[\text{erf}(x)\right]^{2k} \,dx=\frac 2{6k+1}\,\left(\frac{4}{\pi }\right)^k\,\, \_2F\_1\left(2 k,\frac{6k+1}{2}; \frac{6k+3}{2};-\frac{1}{3}\right)$$ slightly less accurate than the previous one. Continuing with Padé approximant $$\text{erf}(x)=\frac{\frac{2 x}{\sqrt{\pi }}-\frac{x^3}{15 \sqrt{\pi }}}{1+\frac{3 x^2}{10}}$$ we should get $$I\_{2k}=\int\_{-1}^1 x^{4k}\, \left[\text{erf}(x)\right]^{2k} \,dx=\frac 2{6k+1}\,\left(\frac{4}{\pi }\right)^k\,\, F\_1\left(\frac{6k+1}{2};-2 k,2 k; \frac{6k+3}{2};\frac{1}{30},-\frac{3}{10}\right)$$ where appears the the Appell hypergeometric function of two variables.
For $k=2$, Maple says the integral is $${\frac { \left( 16\, \left( {\rm erf} \left(l\right) \right) ^{2 }{l}^{5}{\pi}^{3/2}{{\rm e}^{2\,{l}^{2}}}+32\,{\rm erf} \left(l\right) {{\rm e}^{{l}^{2}}}\pi\,{l}^{4}-43\,\pi\,\sqrt {2}{{\rm e}^{2\,{l}^{2} }}{\rm erf} \left(\sqrt {2}l\right)+64\,{\rm erf} \left(l\right){ {\rm e}^{{l}^{2}}}\pi\,{l}^{2}+16\,\sqrt {\pi}{l}^{3}+64\,{\rm erf} \left(l\right){{\rm e}^{{l}^{2}}}\pi+44\,\sqrt {\pi}l \right) {{\rm e} ^{-2\,{l}^{2}}}}{40\;{\pi}^{3/2}}} $$ It doesn't find a closed form for $k=4$, nor does Wolfram Alpha, and I think it's quite unlikely that one exists.
10,677,242
I have a MySQL table that looks something like this: ``` +--------------------------------------+ | id | product_id | qty | +--------------------------------------+ | 1 | 0 | 1 | | 2 | 1 | 3 | | 3 | 0 | 2 | | 4 | 2 | 18 | +--------------------------------------+ ``` I want to get the total number of each product in the table. So for the above table, for instance, here is the result I would like: 0 -> 3 1 -> 3 2 -> 18 I figured the easiest way to do this would be to loop through the MySQL results and add the quantity of each product to an array, at the position in the array that corresponds to the product\_id. I.E: ``` $qtyArray = array(); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $qtyArray[$row[product_id]] += $row[qty]; } ``` I have two questions: 1. Would the above work OK? 2. Is there a better way of doing this? Thank you!
2012/05/20
[ "https://Stackoverflow.com/questions/10677242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1101095/" ]
MySQL does this for you: ``` SELECT product_id, sum(qty) FROM tablename GROUP BY product_id ```
As to the first question. It will work, but Notice "Undefined offset" will be issued Also remember that array index must be a string so ``` $qtyArray[$row['product_id']] += $row['qty']; ```
10,677,242
I have a MySQL table that looks something like this: ``` +--------------------------------------+ | id | product_id | qty | +--------------------------------------+ | 1 | 0 | 1 | | 2 | 1 | 3 | | 3 | 0 | 2 | | 4 | 2 | 18 | +--------------------------------------+ ``` I want to get the total number of each product in the table. So for the above table, for instance, here is the result I would like: 0 -> 3 1 -> 3 2 -> 18 I figured the easiest way to do this would be to loop through the MySQL results and add the quantity of each product to an array, at the position in the array that corresponds to the product\_id. I.E: ``` $qtyArray = array(); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $qtyArray[$row[product_id]] += $row[qty]; } ``` I have two questions: 1. Would the above work OK? 2. Is there a better way of doing this? Thank you!
2012/05/20
[ "https://Stackoverflow.com/questions/10677242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1101095/" ]
MySQL does this for you: ``` SELECT product_id, sum(qty) FROM tablename GROUP BY product_id ```
As mentioned - you're better off using a group query as that's a lot more efficient. However: ``` $qtyArray[$row[product_id]] += $row[qty]; ``` That's going to trigger a notice unless the variable is already set. That's beause it's equivalent to: ``` $qtyArray[$row[product_id]] = $qtyArray[$row[product_id]] + // First time around this won't exist $row[qty]; ``` If (in other circumstances) you need to do something similar - check that the array key exists if there's any doubt.
10,440,792
I'm asking this because I know that the pythonic way to check whether a list is empty or not is the following: ``` my_list = [] if not my_list: print "computer says no" else: # my_list isn't empty print "computer says yes" ``` will print `computer says no`, etc. So this leads me to identify `[]` with `False` truth-values; however, if I try to compare [] and False "directly", I obtain the following: ``` >>> my_list == False False >>> my_list is False False >>> [] == False False ``` etc... What's going on here? I feel like I'm missing something really obvious.
2012/05/03
[ "https://Stackoverflow.com/questions/10440792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/913071/" ]
The `if` statement evaluates everything in a Boolean context, it is like there is an implicit call to the [`bool()`](http://docs.python.org/library/functions.html#bool) built-in function. Here is how you would actually check how things will be evaluated by an `if` statement: ``` >>> bool([]) False >>> bool([]) == False True ``` See the documentation on [Truth Value Testing](http://docs.python.org/library/stdtypes.html#truth-value-testing), empty lists are *considered false*, but this doesn't mean they are equivalent to `False`. [PEP 285](http://www.python.org/dev/peps/pep-0285/) also has some excellent information on why it was implemented this way, see the very last bullet in the *Resolved Issues* section for the part that deals with `x == True` and `x == False` specifically. The most convincing aspect to me is that `==` is generally transitive, so `a == b` and `b == c` implies `a == c`. So if it were the way you expected and `[] == False` were true and `'' == False` were true, one might assume that `[] == ''` should be true (even though it obviously should not be in a language without implicit type conversion).
Empty containers are "falsy," that is, they evaluate to `False` *in a Boolean context*. That doesn't mean they are literally equal to the constant `False`. In other words, the following is `True`: ``` bool([]) == False ``` The truth value of an object is determined by its `__nonzero__()` or its `__len__()` method. (In Python 3, `__nonzero__()` has been renamed to `__bool__()`.) Containers have a `__len__()` method, so they are truthy when they have anything in them and falsy when they are empty. If empty containers were literally equal to `False`, by the way, then any empty container would be equal to any other empty container: for example, `{} == ""` would be `True`. And that just wouldn't make any sense at all! However, just to blow your mind, the following is `True`: ``` False == 0 ``` This is because Booleans are a subclass of integers in Python, and `False` is basically just a zero that gets printed a little differently.
10,440,792
I'm asking this because I know that the pythonic way to check whether a list is empty or not is the following: ``` my_list = [] if not my_list: print "computer says no" else: # my_list isn't empty print "computer says yes" ``` will print `computer says no`, etc. So this leads me to identify `[]` with `False` truth-values; however, if I try to compare [] and False "directly", I obtain the following: ``` >>> my_list == False False >>> my_list is False False >>> [] == False False ``` etc... What's going on here? I feel like I'm missing something really obvious.
2012/05/03
[ "https://Stackoverflow.com/questions/10440792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/913071/" ]
The `if` statement evaluates everything in a Boolean context, it is like there is an implicit call to the [`bool()`](http://docs.python.org/library/functions.html#bool) built-in function. Here is how you would actually check how things will be evaluated by an `if` statement: ``` >>> bool([]) False >>> bool([]) == False True ``` See the documentation on [Truth Value Testing](http://docs.python.org/library/stdtypes.html#truth-value-testing), empty lists are *considered false*, but this doesn't mean they are equivalent to `False`. [PEP 285](http://www.python.org/dev/peps/pep-0285/) also has some excellent information on why it was implemented this way, see the very last bullet in the *Resolved Issues* section for the part that deals with `x == True` and `x == False` specifically. The most convincing aspect to me is that `==` is generally transitive, so `a == b` and `b == c` implies `a == c`. So if it were the way you expected and `[] == False` were true and `'' == False` were true, one might assume that `[] == ''` should be true (even though it obviously should not be in a language without implicit type conversion).
Built-in types in Python have a truth value which allows you to test them for truthfulness. See *[Truth Value Testing](http://docs.python.org/library/stdtypes.html#truth-value-testing)*. This is different than saying `object == False` which is doing an actual value test (equality test). It is using the objects `__eq__()` method to determine if their values are equal.
10,440,792
I'm asking this because I know that the pythonic way to check whether a list is empty or not is the following: ``` my_list = [] if not my_list: print "computer says no" else: # my_list isn't empty print "computer says yes" ``` will print `computer says no`, etc. So this leads me to identify `[]` with `False` truth-values; however, if I try to compare [] and False "directly", I obtain the following: ``` >>> my_list == False False >>> my_list is False False >>> [] == False False ``` etc... What's going on here? I feel like I'm missing something really obvious.
2012/05/03
[ "https://Stackoverflow.com/questions/10440792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/913071/" ]
The `if` statement evaluates everything in a Boolean context, it is like there is an implicit call to the [`bool()`](http://docs.python.org/library/functions.html#bool) built-in function. Here is how you would actually check how things will be evaluated by an `if` statement: ``` >>> bool([]) False >>> bool([]) == False True ``` See the documentation on [Truth Value Testing](http://docs.python.org/library/stdtypes.html#truth-value-testing), empty lists are *considered false*, but this doesn't mean they are equivalent to `False`. [PEP 285](http://www.python.org/dev/peps/pep-0285/) also has some excellent information on why it was implemented this way, see the very last bullet in the *Resolved Issues* section for the part that deals with `x == True` and `x == False` specifically. The most convincing aspect to me is that `==` is generally transitive, so `a == b` and `b == c` implies `a == c`. So if it were the way you expected and `[] == False` were true and `'' == False` were true, one might assume that `[] == ''` should be true (even though it obviously should not be in a language without implicit type conversion).
In your example, the not operator is causing your list to be converted to a boolean. Try this: ``` >>> not [] True >>> not [1] False ``` "is" and "==" don't do that conversion.
10,440,792
I'm asking this because I know that the pythonic way to check whether a list is empty or not is the following: ``` my_list = [] if not my_list: print "computer says no" else: # my_list isn't empty print "computer says yes" ``` will print `computer says no`, etc. So this leads me to identify `[]` with `False` truth-values; however, if I try to compare [] and False "directly", I obtain the following: ``` >>> my_list == False False >>> my_list is False False >>> [] == False False ``` etc... What's going on here? I feel like I'm missing something really obvious.
2012/05/03
[ "https://Stackoverflow.com/questions/10440792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/913071/" ]
Empty containers are "falsy," that is, they evaluate to `False` *in a Boolean context*. That doesn't mean they are literally equal to the constant `False`. In other words, the following is `True`: ``` bool([]) == False ``` The truth value of an object is determined by its `__nonzero__()` or its `__len__()` method. (In Python 3, `__nonzero__()` has been renamed to `__bool__()`.) Containers have a `__len__()` method, so they are truthy when they have anything in them and falsy when they are empty. If empty containers were literally equal to `False`, by the way, then any empty container would be equal to any other empty container: for example, `{} == ""` would be `True`. And that just wouldn't make any sense at all! However, just to blow your mind, the following is `True`: ``` False == 0 ``` This is because Booleans are a subclass of integers in Python, and `False` is basically just a zero that gets printed a little differently.
Built-in types in Python have a truth value which allows you to test them for truthfulness. See *[Truth Value Testing](http://docs.python.org/library/stdtypes.html#truth-value-testing)*. This is different than saying `object == False` which is doing an actual value test (equality test). It is using the objects `__eq__()` method to determine if their values are equal.
10,440,792
I'm asking this because I know that the pythonic way to check whether a list is empty or not is the following: ``` my_list = [] if not my_list: print "computer says no" else: # my_list isn't empty print "computer says yes" ``` will print `computer says no`, etc. So this leads me to identify `[]` with `False` truth-values; however, if I try to compare [] and False "directly", I obtain the following: ``` >>> my_list == False False >>> my_list is False False >>> [] == False False ``` etc... What's going on here? I feel like I'm missing something really obvious.
2012/05/03
[ "https://Stackoverflow.com/questions/10440792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/913071/" ]
Empty containers are "falsy," that is, they evaluate to `False` *in a Boolean context*. That doesn't mean they are literally equal to the constant `False`. In other words, the following is `True`: ``` bool([]) == False ``` The truth value of an object is determined by its `__nonzero__()` or its `__len__()` method. (In Python 3, `__nonzero__()` has been renamed to `__bool__()`.) Containers have a `__len__()` method, so they are truthy when they have anything in them and falsy when they are empty. If empty containers were literally equal to `False`, by the way, then any empty container would be equal to any other empty container: for example, `{} == ""` would be `True`. And that just wouldn't make any sense at all! However, just to blow your mind, the following is `True`: ``` False == 0 ``` This is because Booleans are a subclass of integers in Python, and `False` is basically just a zero that gets printed a little differently.
In your example, the not operator is causing your list to be converted to a boolean. Try this: ``` >>> not [] True >>> not [1] False ``` "is" and "==" don't do that conversion.
10,440,792
I'm asking this because I know that the pythonic way to check whether a list is empty or not is the following: ``` my_list = [] if not my_list: print "computer says no" else: # my_list isn't empty print "computer says yes" ``` will print `computer says no`, etc. So this leads me to identify `[]` with `False` truth-values; however, if I try to compare [] and False "directly", I obtain the following: ``` >>> my_list == False False >>> my_list is False False >>> [] == False False ``` etc... What's going on here? I feel like I'm missing something really obvious.
2012/05/03
[ "https://Stackoverflow.com/questions/10440792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/913071/" ]
Built-in types in Python have a truth value which allows you to test them for truthfulness. See *[Truth Value Testing](http://docs.python.org/library/stdtypes.html#truth-value-testing)*. This is different than saying `object == False` which is doing an actual value test (equality test). It is using the objects `__eq__()` method to determine if their values are equal.
In your example, the not operator is causing your list to be converted to a boolean. Try this: ``` >>> not [] True >>> not [1] False ``` "is" and "==" don't do that conversion.
30,866,844
I´m trying to simulate a multi layer doughnut chart by initializing Chart.js multiple times over same canvas. There is only one chart visible at the time. The other will be visible when you hover over its position… Does somebody know how to make both visible at the same time? Here is my code: ``` <!doctype html> <html> <head> <title>Doughnut Chart</title> <script src="../Chart.js"></script> <style> body{ padding: 0; margin: 0; } #canvas-holder-1{ position: fixed; top: 50%; left: 50%; margin-top: -250px; margin-left: -250px; } </style> </head> <body> <div id="canvas-holder-1"> <canvas id="chart-area" width="500" height="500"/> </div> <script> var doughnutData = [ { value: 20, color:"#F7464A", highlight: "#FF5A5E", label: "Red", }, { value: 50, color: "#46BFBD", highlight: "#5AD3D1", label: "Green" }, { value: 30, color: "#FDB45C", highlight: "#FFC870", label: "Yellow" }, { value: 40, color: "#949FB1", highlight: "#A8B3C5", label: "Grey" }, { value: 120, color: "#4D5360", highlight: "#616774", label: "Dark Grey" } ]; var doughnutData2 = [ { value: 10, color:"#F7464A", highlight: "#FF5A5E", label: "Red", }, { value: 100, color: "#46BFBD", highlight: "#5AD3D1", label: "Green" }, { value: 20, color: "#FDB45C", highlight: "#FFC870", label: "Yellow" }, { value: 60, color: "#949FB1", highlight: "#A8B3C5", label: "Grey" }, { value: 120, color: "#4D5360", highlight: "#616774", label: "Dark Grey" } ]; window.onload = function(){ var ctx = document.getElementById("chart-area").getContext("2d"); window.myDoughnut = new Chart(ctx).Doughnut(doughnutData, { responsive : false, animateScale: false, animateRotate:false, animationEasing : "easeOutSine", animationSteps : 80, percentageInnerCutout : 90, }); myDoughnut.outerRadius= 200; window.myDoughnut2 = new Chart(ctx).Doughnut(doughnutData2, { responsive : false, animateScale: false, animateRotate:false, animationEasing : "easeOutSine", animationSteps : 80, percentageInnerCutout : 90 }); }; </script> </body> </html> ``` Thanks, Jochen
2015/06/16
[ "https://Stackoverflow.com/questions/30866844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5014911/" ]
To show the messages you got from validation beneath the corresponding form field, you need to use the following code if the send button is tapped: ``` var formValues = form.getValues(), fields = form.query("field"); // remove the style class from all fields for (var i = 0; i < fields.length; i++) { fields[i].removeCls('invalidField'); // TODO: Remove old error messages from fields } // dump form fields into new model instance var model = Ext.create('App.model.Contact', formValues); // validate form fields var errors = model.validate(); if (!errors.isValid()) { var msgStr = ""; // loop through validation errors and generate a message to the user errors.each(function (errorObj) { var s = Ext.String.format('field[name={0}]', errorObj.getField()); form.down(s).addCls('invalidField'); msgStr += errorObj.getMessage() + "<br/>"; // Set value of errorObj.getMessage() as error message to field }); Ext.Msg.alert("Error!", msgStr); } ``` And your message will look like the attached screen shot ![Error message](https://i.stack.imgur.com/KMxoF.jpg)
you have to take an item below form like that ``` items: [{ xtype: 'textareafield', itemId: 'errorMessage' }] ``` and get item set text on button tap ``` if (!errors.isValid()) { // loop through validation errors and generate a message to the user errors.each(function (errorObj) { var s = Ext.String.format('field[name={0}]', errorObj.getField()); form.down(s).addCls('invalidField'); // Set value of errorObj.getMessage() as error message to field Ext.getCmp('errorMessage').setText(errorObj.getMessage()); }); } ```
30,866,844
I´m trying to simulate a multi layer doughnut chart by initializing Chart.js multiple times over same canvas. There is only one chart visible at the time. The other will be visible when you hover over its position… Does somebody know how to make both visible at the same time? Here is my code: ``` <!doctype html> <html> <head> <title>Doughnut Chart</title> <script src="../Chart.js"></script> <style> body{ padding: 0; margin: 0; } #canvas-holder-1{ position: fixed; top: 50%; left: 50%; margin-top: -250px; margin-left: -250px; } </style> </head> <body> <div id="canvas-holder-1"> <canvas id="chart-area" width="500" height="500"/> </div> <script> var doughnutData = [ { value: 20, color:"#F7464A", highlight: "#FF5A5E", label: "Red", }, { value: 50, color: "#46BFBD", highlight: "#5AD3D1", label: "Green" }, { value: 30, color: "#FDB45C", highlight: "#FFC870", label: "Yellow" }, { value: 40, color: "#949FB1", highlight: "#A8B3C5", label: "Grey" }, { value: 120, color: "#4D5360", highlight: "#616774", label: "Dark Grey" } ]; var doughnutData2 = [ { value: 10, color:"#F7464A", highlight: "#FF5A5E", label: "Red", }, { value: 100, color: "#46BFBD", highlight: "#5AD3D1", label: "Green" }, { value: 20, color: "#FDB45C", highlight: "#FFC870", label: "Yellow" }, { value: 60, color: "#949FB1", highlight: "#A8B3C5", label: "Grey" }, { value: 120, color: "#4D5360", highlight: "#616774", label: "Dark Grey" } ]; window.onload = function(){ var ctx = document.getElementById("chart-area").getContext("2d"); window.myDoughnut = new Chart(ctx).Doughnut(doughnutData, { responsive : false, animateScale: false, animateRotate:false, animationEasing : "easeOutSine", animationSteps : 80, percentageInnerCutout : 90, }); myDoughnut.outerRadius= 200; window.myDoughnut2 = new Chart(ctx).Doughnut(doughnutData2, { responsive : false, animateScale: false, animateRotate:false, animationEasing : "easeOutSine", animationSteps : 80, percentageInnerCutout : 90 }); }; </script> </body> </html> ``` Thanks, Jochen
2015/06/16
[ "https://Stackoverflow.com/questions/30866844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5014911/" ]
To show the messages you got from validation beneath the corresponding form field, you need to use the following code if the send button is tapped: ``` var formValues = form.getValues(), fields = form.query("field"); // remove the style class from all fields for (var i = 0; i < fields.length; i++) { fields[i].removeCls('invalidField'); // TODO: Remove old error messages from fields } // dump form fields into new model instance var model = Ext.create('App.model.Contact', formValues); // validate form fields var errors = model.validate(); if (!errors.isValid()) { var msgStr = ""; // loop through validation errors and generate a message to the user errors.each(function (errorObj) { var s = Ext.String.format('field[name={0}]', errorObj.getField()); form.down(s).addCls('invalidField'); msgStr += errorObj.getMessage() + "<br/>"; // Set value of errorObj.getMessage() as error message to field }); Ext.Msg.alert("Error!", msgStr); } ``` And your message will look like the attached screen shot ![Error message](https://i.stack.imgur.com/KMxoF.jpg)
``` var formValues = form.getValues(), fields = form.query("field"); // remove the style class from all fields for (var i = 0; i < fields.length; i++) { fields[i].removeCls('invalidField'); // TODO: Remove old error messages from fields } // dump form fields into new model instance var model = Ext.create('App.model.Contact', formValues); // validate form fields var errors = model.validate(); if (!errors.isValid()) { // loop through validation errors and generate a message to the user errors.each(function (errorObj) { var s = Ext.String.format('field[name={0}]', errorObj.getField()); form.down(s).addCls('invalidField'); form.down(s).setHtml(errorObj.getMessage()); // Set value of errorObj.getMessage() as error message to field }); } ``` You can use the setHtml method of the text field to show and hide the error message dynamically but it will just render the message you will need to handle the CSS and multiple error message cases from there [Please refer documentation for more details here](https://docs.sencha.com/touch/2.4/2.4.0-apidocs/#!/api/Ext.field.Text-method-setHtml)
59,213,370
**pay.service.ts** ``` @ViewChild('cardElementForm', { static: false }) cardElementForm: ElementRef; stripe = Stripe(environment.stripe.pubKey); async createStripeForm() { const stripeElements = this.stripe.elements(); const cardElement = stripeElements.create('card'); cardElement.mount(this.cardElementForm.nativeElement); } ``` Edit: added more code. This is my service that im importing into my page.ts **page.html** ``` <form #saveCard="ngForm" class="saveCardForm"> <ion-item> <div id="cardElementForm" #cardElementForm></div> <ion-text *ngIf="error">{{ error }}</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.createStripeForm()">Create form</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.saveCard()">Send data</ion-text> </ion-item> </form> ``` **page.ts** ``` import { Pay } from '../services/pay.service'; ``` I get error: ``` TypeError: this.cardElementForm is undefined ``` Wheres the problem? Im stuck at this.
2019/12/06
[ "https://Stackoverflow.com/questions/59213370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11918246/" ]
I had this error today, for me it was that I had a syntax-level error in my `.ts` files, so they couldn't really compile. In above situation, I think, the tests should not start (and instead show compile error). But for whatever reason, somehow the tests start, and `Jasmine` fails with "`No specs found`" log.
Once I moved the .spec file into the the /spec dir it found the tests.
59,213,370
**pay.service.ts** ``` @ViewChild('cardElementForm', { static: false }) cardElementForm: ElementRef; stripe = Stripe(environment.stripe.pubKey); async createStripeForm() { const stripeElements = this.stripe.elements(); const cardElement = stripeElements.create('card'); cardElement.mount(this.cardElementForm.nativeElement); } ``` Edit: added more code. This is my service that im importing into my page.ts **page.html** ``` <form #saveCard="ngForm" class="saveCardForm"> <ion-item> <div id="cardElementForm" #cardElementForm></div> <ion-text *ngIf="error">{{ error }}</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.createStripeForm()">Create form</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.saveCard()">Send data</ion-text> </ion-item> </form> ``` **page.ts** ``` import { Pay } from '../services/pay.service'; ``` I get error: ``` TypeError: this.cardElementForm is undefined ``` Wheres the problem? Im stuck at this.
2019/12/06
[ "https://Stackoverflow.com/questions/59213370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11918246/" ]
I had this error today, for me it was that I had a syntax-level error in my `.ts` files, so they couldn't really compile. In above situation, I think, the tests should not start (and instead show compile error). But for whatever reason, somehow the tests start, and `Jasmine` fails with "`No specs found`" log.
In my case I saw some errors in terminal when I run ng test but when browser open it shown no specs found. ERROR IN PROJECT [![enter image description here](https://i.stack.imgur.com/Eqti9.png)](https://i.stack.imgur.com/Eqti9.png) this was the error. After fixed the above error it showed all the specs with the result of executed test cases
59,213,370
**pay.service.ts** ``` @ViewChild('cardElementForm', { static: false }) cardElementForm: ElementRef; stripe = Stripe(environment.stripe.pubKey); async createStripeForm() { const stripeElements = this.stripe.elements(); const cardElement = stripeElements.create('card'); cardElement.mount(this.cardElementForm.nativeElement); } ``` Edit: added more code. This is my service that im importing into my page.ts **page.html** ``` <form #saveCard="ngForm" class="saveCardForm"> <ion-item> <div id="cardElementForm" #cardElementForm></div> <ion-text *ngIf="error">{{ error }}</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.createStripeForm()">Create form</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.saveCard()">Send data</ion-text> </ion-item> </form> ``` **page.ts** ``` import { Pay } from '../services/pay.service'; ``` I get error: ``` TypeError: this.cardElementForm is undefined ``` Wheres the problem? Im stuck at this.
2019/12/06
[ "https://Stackoverflow.com/questions/59213370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11918246/" ]
In my case I saw some errors in terminal when I run ng test but when browser open it shown no specs found. ERROR IN PROJECT [![enter image description here](https://i.stack.imgur.com/Eqti9.png)](https://i.stack.imgur.com/Eqti9.png) this was the error. After fixed the above error it showed all the specs with the result of executed test cases
I had the same issue but in my case I upgraded from angular 9 to angular 10 and tests stopped running, I was getting a lot of: ``` src/app/xxxxx/basic-info/basic-info.component.spec.ts:391:9 - error TS2532: Object is possibly 'undefined'. 391 this.whatToDelete = ["mumbo", "jumbo"]; ``` So in the 'describe' I changed the arrow function to a regular function because an arrow function does not have it's own 'this' \* > > Unlike regular functions, arrow functions do not have their own this . > The value of this inside an arrow function remains the same throughout > the lifecycle of the function and is always bound to the value of this > in the closest non-arrow parent function. > > > * Hope this can help one of you and save you some time
59,213,370
**pay.service.ts** ``` @ViewChild('cardElementForm', { static: false }) cardElementForm: ElementRef; stripe = Stripe(environment.stripe.pubKey); async createStripeForm() { const stripeElements = this.stripe.elements(); const cardElement = stripeElements.create('card'); cardElement.mount(this.cardElementForm.nativeElement); } ``` Edit: added more code. This is my service that im importing into my page.ts **page.html** ``` <form #saveCard="ngForm" class="saveCardForm"> <ion-item> <div id="cardElementForm" #cardElementForm></div> <ion-text *ngIf="error">{{ error }}</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.createStripeForm()">Create form</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.saveCard()">Send data</ion-text> </ion-item> </form> ``` **page.ts** ``` import { Pay } from '../services/pay.service'; ``` I get error: ``` TypeError: this.cardElementForm is undefined ``` Wheres the problem? Im stuck at this.
2019/12/06
[ "https://Stackoverflow.com/questions/59213370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11918246/" ]
I had this error today, for me it was that I had a syntax-level error in my `.ts` files, so they couldn't really compile. In above situation, I think, the tests should not start (and instead show compile error). But for whatever reason, somehow the tests start, and `Jasmine` fails with "`No specs found`" log.
Solved it. Once i moved the .spec files into the /src folder, Jasmine detected them without any problems.
59,213,370
**pay.service.ts** ``` @ViewChild('cardElementForm', { static: false }) cardElementForm: ElementRef; stripe = Stripe(environment.stripe.pubKey); async createStripeForm() { const stripeElements = this.stripe.elements(); const cardElement = stripeElements.create('card'); cardElement.mount(this.cardElementForm.nativeElement); } ``` Edit: added more code. This is my service that im importing into my page.ts **page.html** ``` <form #saveCard="ngForm" class="saveCardForm"> <ion-item> <div id="cardElementForm" #cardElementForm></div> <ion-text *ngIf="error">{{ error }}</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.createStripeForm()">Create form</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.saveCard()">Send data</ion-text> </ion-item> </form> ``` **page.ts** ``` import { Pay } from '../services/pay.service'; ``` I get error: ``` TypeError: this.cardElementForm is undefined ``` Wheres the problem? Im stuck at this.
2019/12/06
[ "https://Stackoverflow.com/questions/59213370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11918246/" ]
In my case I saw some errors in terminal when I run ng test but when browser open it shown no specs found. ERROR IN PROJECT [![enter image description here](https://i.stack.imgur.com/Eqti9.png)](https://i.stack.imgur.com/Eqti9.png) this was the error. After fixed the above error it showed all the specs with the result of executed test cases
I had a similar issue and apparently it was due to an invalid import. This was the specific import: `import 'rxjs/add/observable/throw'` I just removed the import and everything worked fine. ng test seemed to execute just fine, so it was a little confusing.
59,213,370
**pay.service.ts** ``` @ViewChild('cardElementForm', { static: false }) cardElementForm: ElementRef; stripe = Stripe(environment.stripe.pubKey); async createStripeForm() { const stripeElements = this.stripe.elements(); const cardElement = stripeElements.create('card'); cardElement.mount(this.cardElementForm.nativeElement); } ``` Edit: added more code. This is my service that im importing into my page.ts **page.html** ``` <form #saveCard="ngForm" class="saveCardForm"> <ion-item> <div id="cardElementForm" #cardElementForm></div> <ion-text *ngIf="error">{{ error }}</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.createStripeForm()">Create form</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.saveCard()">Send data</ion-text> </ion-item> </form> ``` **page.ts** ``` import { Pay } from '../services/pay.service'; ``` I get error: ``` TypeError: this.cardElementForm is undefined ``` Wheres the problem? Im stuck at this.
2019/12/06
[ "https://Stackoverflow.com/questions/59213370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11918246/" ]
Solved it. Once i moved the .spec files into the /src folder, Jasmine detected them without any problems.
I had a similar issue and apparently it was due to an invalid import. This was the specific import: `import 'rxjs/add/observable/throw'` I just removed the import and everything worked fine. ng test seemed to execute just fine, so it was a little confusing.
59,213,370
**pay.service.ts** ``` @ViewChild('cardElementForm', { static: false }) cardElementForm: ElementRef; stripe = Stripe(environment.stripe.pubKey); async createStripeForm() { const stripeElements = this.stripe.elements(); const cardElement = stripeElements.create('card'); cardElement.mount(this.cardElementForm.nativeElement); } ``` Edit: added more code. This is my service that im importing into my page.ts **page.html** ``` <form #saveCard="ngForm" class="saveCardForm"> <ion-item> <div id="cardElementForm" #cardElementForm></div> <ion-text *ngIf="error">{{ error }}</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.createStripeForm()">Create form</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.saveCard()">Send data</ion-text> </ion-item> </form> ``` **page.ts** ``` import { Pay } from '../services/pay.service'; ``` I get error: ``` TypeError: this.cardElementForm is undefined ``` Wheres the problem? Im stuck at this.
2019/12/06
[ "https://Stackoverflow.com/questions/59213370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11918246/" ]
Solved it. Once i moved the .spec files into the /src folder, Jasmine detected them without any problems.
I had the same issue but in my case I upgraded from angular 9 to angular 10 and tests stopped running, I was getting a lot of: ``` src/app/xxxxx/basic-info/basic-info.component.spec.ts:391:9 - error TS2532: Object is possibly 'undefined'. 391 this.whatToDelete = ["mumbo", "jumbo"]; ``` So in the 'describe' I changed the arrow function to a regular function because an arrow function does not have it's own 'this' \* > > Unlike regular functions, arrow functions do not have their own this . > The value of this inside an arrow function remains the same throughout > the lifecycle of the function and is always bound to the value of this > in the closest non-arrow parent function. > > > * Hope this can help one of you and save you some time
59,213,370
**pay.service.ts** ``` @ViewChild('cardElementForm', { static: false }) cardElementForm: ElementRef; stripe = Stripe(environment.stripe.pubKey); async createStripeForm() { const stripeElements = this.stripe.elements(); const cardElement = stripeElements.create('card'); cardElement.mount(this.cardElementForm.nativeElement); } ``` Edit: added more code. This is my service that im importing into my page.ts **page.html** ``` <form #saveCard="ngForm" class="saveCardForm"> <ion-item> <div id="cardElementForm" #cardElementForm></div> <ion-text *ngIf="error">{{ error }}</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.createStripeForm()">Create form</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.saveCard()">Send data</ion-text> </ion-item> </form> ``` **page.ts** ``` import { Pay } from '../services/pay.service'; ``` I get error: ``` TypeError: this.cardElementForm is undefined ``` Wheres the problem? Im stuck at this.
2019/12/06
[ "https://Stackoverflow.com/questions/59213370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11918246/" ]
Solved it. Once i moved the .spec files into the /src folder, Jasmine detected them without any problems.
Once I moved the .spec file into the the /spec dir it found the tests.
59,213,370
**pay.service.ts** ``` @ViewChild('cardElementForm', { static: false }) cardElementForm: ElementRef; stripe = Stripe(environment.stripe.pubKey); async createStripeForm() { const stripeElements = this.stripe.elements(); const cardElement = stripeElements.create('card'); cardElement.mount(this.cardElementForm.nativeElement); } ``` Edit: added more code. This is my service that im importing into my page.ts **page.html** ``` <form #saveCard="ngForm" class="saveCardForm"> <ion-item> <div id="cardElementForm" #cardElementForm></div> <ion-text *ngIf="error">{{ error }}</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.createStripeForm()">Create form</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.saveCard()">Send data</ion-text> </ion-item> </form> ``` **page.ts** ``` import { Pay } from '../services/pay.service'; ``` I get error: ``` TypeError: this.cardElementForm is undefined ``` Wheres the problem? Im stuck at this.
2019/12/06
[ "https://Stackoverflow.com/questions/59213370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11918246/" ]
I had this error today, for me it was that I had a syntax-level error in my `.ts` files, so they couldn't really compile. In above situation, I think, the tests should not start (and instead show compile error). But for whatever reason, somehow the tests start, and `Jasmine` fails with "`No specs found`" log.
I had the same issue but in my case I upgraded from angular 9 to angular 10 and tests stopped running, I was getting a lot of: ``` src/app/xxxxx/basic-info/basic-info.component.spec.ts:391:9 - error TS2532: Object is possibly 'undefined'. 391 this.whatToDelete = ["mumbo", "jumbo"]; ``` So in the 'describe' I changed the arrow function to a regular function because an arrow function does not have it's own 'this' \* > > Unlike regular functions, arrow functions do not have their own this . > The value of this inside an arrow function remains the same throughout > the lifecycle of the function and is always bound to the value of this > in the closest non-arrow parent function. > > > * Hope this can help one of you and save you some time
59,213,370
**pay.service.ts** ``` @ViewChild('cardElementForm', { static: false }) cardElementForm: ElementRef; stripe = Stripe(environment.stripe.pubKey); async createStripeForm() { const stripeElements = this.stripe.elements(); const cardElement = stripeElements.create('card'); cardElement.mount(this.cardElementForm.nativeElement); } ``` Edit: added more code. This is my service that im importing into my page.ts **page.html** ``` <form #saveCard="ngForm" class="saveCardForm"> <ion-item> <div id="cardElementForm" #cardElementForm></div> <ion-text *ngIf="error">{{ error }}</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.createStripeForm()">Create form</ion-text> </ion-item> <ion-item> <ion-text (click)="this.payments.saveCard()">Send data</ion-text> </ion-item> </form> ``` **page.ts** ``` import { Pay } from '../services/pay.service'; ``` I get error: ``` TypeError: this.cardElementForm is undefined ``` Wheres the problem? Im stuck at this.
2019/12/06
[ "https://Stackoverflow.com/questions/59213370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11918246/" ]
In my case I saw some errors in terminal when I run ng test but when browser open it shown no specs found. ERROR IN PROJECT [![enter image description here](https://i.stack.imgur.com/Eqti9.png)](https://i.stack.imgur.com/Eqti9.png) this was the error. After fixed the above error it showed all the specs with the result of executed test cases
Once I moved the .spec file into the the /spec dir it found the tests.
763,642
Is there an app that can adjust gamma/brightness/contrast for ubuntu 16.04? `xgamma` doesn't have any effect. Thank you **Edits** ``` *-display:0 description: VGA compatible controller product: Mobile 4 Series Chipset Integrated Graphics Controller vendor: Intel Corporation physical id: 2 bus info: pci@0000:00:02.0 version: 09 width: 64 bits clock: 33MHz capabilities: msi pm vga_controller bus_master cap_list rom configuration: driver=i915 latency=0 resources: irq:27 memory:d0000000-d03fffff memory:c0000000-cfffffff ioport:50f0(size=8) *-display:1 UNCLAIMED description: Display controller product: Mobile 4 Series Chipset Integrated Graphics Controller vendor: Intel Corporation physical id: 2.1 bus info: pci@0000:00:02.1 version: 09 width: 64 bits clock: 33MHz capabilities: pm bus_master cap_list configuration: latency=0 resources: memory:d3400000-d34fffff ```
2016/04/27
[ "https://askubuntu.com/questions/763642", "https://askubuntu.com", "https://askubuntu.com/users/226761/" ]
**Note this is not a app but a script can be made if the process works on your pc** Open your terminal and enter this command. `xrandr -q | grep " connected"` My output is: **DVI-I-0 connected primary 1280x1024+0+0 (normal left inverted right x axis y axis) 376mm x 301mm** Copy the value that comes before "connected". In my case as you can see its "DVI-I-0" Yours might me something else. Now try this command replacing "DVI-I-0" with the value you got from the previous command. `xrandr --output DVI-I-0 --gamma 0.5:0.5:0.5` `xrandr --output your_value --gamma 0.5:0.5:0.5` The last three decimal values separated by colon sets the gamma value. The values have a range from 1.0:1.0:1.0 to 0.0:0.0:0.0 Default is 1.0:1.0:1.0 **Note:: I use xrandr to set brightness on my display. It will sometimes reset to the default value, sometimes during a program launch. So I use a script with a desktop shortcut for convenience.**
As shown in other answer: ``` xrandr --output your_display_name --gamma 0.5:0.5:0.5 ``` To automatically apply *xrandr* options on each login, commands can be done in a simple Python script **added to "Startup Applications"** in Ubuntu. ~/xrandr\_display\_setup.py: ```py #!/usr/bin/env python3 import subprocess as sp # R:G:B, float nums 0 to 1 gamma = '0.85:0.85:0.85' def output(cmd): return sp.check_output(cmd, shell=True).decode('utf-8').strip() def set_gamma(display): sp.run('xrandr --output {0} --gamma {1}'.format(display, gamma).split()) # `line` e.g. "HDMI-2 connected primary 1920x1080+0+0 (normal..." line = output('xrandr -q | grep " connected"') if line: display = line.split()[0] set_gamma(display) exit(0) ```
6,444,632
I have an Excel table saved as a CSV that looks something like (when it's in Excel) this just longer: ``` Monday Tuesday Wednesday Thursday Friday marsbar 9 8 0 6 5 reeses 0 0 0 9 0 twix 2 3 0 5 6 snickers 9 8 0 6 5 ``` (The format isnt perfect, but you get the gist--candy bars/day). I want to write a program for python in which I could input a list of candy bar names in the program ``` >>> ['twix', 'reeses'] ``` and it would give me the days of the week on which those candy bars were eaten and how many candy bars in the list were eaten on that day. The result would look something like this: ``` Monday 2 Tuesday 3 Wednesday 0 Thursday 14 Friday 6 ``` could someone help me write such a program?
2011/06/22
[ "https://Stackoverflow.com/questions/6444632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/808545/" ]
Your best bet is to use the `csv` package built into python. It will let you loop over the rows, giving you a list each time, like so: ``` import csv candy_reader = csv.reader(open('candy.csv', 'rb')) for row in candy_reader: if row[0] in candy_to_find: monday_total += row[1] # etc. ``` I didn't initialize several variables, but I think this should give you the basic idea.
We can *help you* write such a program, yes. We will not write the program for you (that's not what StackOverflow is about). Python comes with a [CSV module](http://www.python.org/doc//current/library/csv.html), which will read in an Excel-saved CSV file. You can store your data in a [dictionary](http://www.python.org/doc//current/library/csv.html#csv.DictReader), which will make it easier to retrieve. Good luck!
6,444,632
I have an Excel table saved as a CSV that looks something like (when it's in Excel) this just longer: ``` Monday Tuesday Wednesday Thursday Friday marsbar 9 8 0 6 5 reeses 0 0 0 9 0 twix 2 3 0 5 6 snickers 9 8 0 6 5 ``` (The format isnt perfect, but you get the gist--candy bars/day). I want to write a program for python in which I could input a list of candy bar names in the program ``` >>> ['twix', 'reeses'] ``` and it would give me the days of the week on which those candy bars were eaten and how many candy bars in the list were eaten on that day. The result would look something like this: ``` Monday 2 Tuesday 3 Wednesday 0 Thursday 14 Friday 6 ``` could someone help me write such a program?
2011/06/22
[ "https://Stackoverflow.com/questions/6444632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/808545/" ]
We can *help you* write such a program, yes. We will not write the program for you (that's not what StackOverflow is about). Python comes with a [CSV module](http://www.python.org/doc//current/library/csv.html), which will read in an Excel-saved CSV file. You can store your data in a [dictionary](http://www.python.org/doc//current/library/csv.html#csv.DictReader), which will make it easier to retrieve. Good luck!
In addition to the other answers, you may also want to take a look at the xlrd module, as it can deal with the excel spreadsheets directly if you'd rather not deal with CSV business. The module allows you to read entire (or ranges) of rows/columns at a time as well as grabbing individual cells and you can iterate through everything to search for what you want and then return whatever related 'values' you want in the same row/column from where you found your search criteria.
6,444,632
I have an Excel table saved as a CSV that looks something like (when it's in Excel) this just longer: ``` Monday Tuesday Wednesday Thursday Friday marsbar 9 8 0 6 5 reeses 0 0 0 9 0 twix 2 3 0 5 6 snickers 9 8 0 6 5 ``` (The format isnt perfect, but you get the gist--candy bars/day). I want to write a program for python in which I could input a list of candy bar names in the program ``` >>> ['twix', 'reeses'] ``` and it would give me the days of the week on which those candy bars were eaten and how many candy bars in the list were eaten on that day. The result would look something like this: ``` Monday 2 Tuesday 3 Wednesday 0 Thursday 14 Friday 6 ``` could someone help me write such a program?
2011/06/22
[ "https://Stackoverflow.com/questions/6444632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/808545/" ]
We can *help you* write such a program, yes. We will not write the program for you (that's not what StackOverflow is about). Python comes with a [CSV module](http://www.python.org/doc//current/library/csv.html), which will read in an Excel-saved CSV file. You can store your data in a [dictionary](http://www.python.org/doc//current/library/csv.html#csv.DictReader), which will make it easier to retrieve. Good luck!
Some useful bits: If you have a list of lists like ``` [['marsbar', 0, 1, 2, 3, 4], ['twix', 3, 4, 5, 6, 7]] ``` (which you should be able to get by using the `csv` module) You will probably want to convert it to a dictionary, where the first item of each list is used for the key, and the rest make up the value. You can do this with something like ``` dict((x[0], x[1]) for x in list_of_lists) ``` You can look up multiple keys with a list comprehension as well: ``` [the_dict[key] for key in key_list] ``` That gives you a list of lists, where you want to sum the first elements of each list, the second elements, etc. To do that, we 'zip' the lists to make a list of lists with all the first elements, all the second elements etc., and then sum the inner lists. ``` [sum(x) for x in zip(*the_requested_candybars)] ``` The `zip()` function takes multiple arguments; the `*` here turns the list of lists into several list arguments. We can `zip` again to match up the week names with the sums.
6,444,632
I have an Excel table saved as a CSV that looks something like (when it's in Excel) this just longer: ``` Monday Tuesday Wednesday Thursday Friday marsbar 9 8 0 6 5 reeses 0 0 0 9 0 twix 2 3 0 5 6 snickers 9 8 0 6 5 ``` (The format isnt perfect, but you get the gist--candy bars/day). I want to write a program for python in which I could input a list of candy bar names in the program ``` >>> ['twix', 'reeses'] ``` and it would give me the days of the week on which those candy bars were eaten and how many candy bars in the list were eaten on that day. The result would look something like this: ``` Monday 2 Tuesday 3 Wednesday 0 Thursday 14 Friday 6 ``` could someone help me write such a program?
2011/06/22
[ "https://Stackoverflow.com/questions/6444632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/808545/" ]
Your best bet is to use the `csv` package built into python. It will let you loop over the rows, giving you a list each time, like so: ``` import csv candy_reader = csv.reader(open('candy.csv', 'rb')) for row in candy_reader: if row[0] in candy_to_find: monday_total += row[1] # etc. ``` I didn't initialize several variables, but I think this should give you the basic idea.
Maybe with the [csv module](http://docs.python.org/library/csv.html) I suppose the delimiter is the tab character (`\t`) ``` import csv reader = csv.reader(open('csv_file.csv', 'rb'), delimiter='\t') for row in reader: print row >>>['Monday','Tuesday', 'Wednesday', 'Thursday', 'Friday'] ['marsbar', '9', '8','0', '6', '5'] ['reeses', '0', '0', '0', '9', '0'] ['twix', '2', '3', '0', '5', '6'] ['snickers', '9', '8', '0', '6', '5'] ```
6,444,632
I have an Excel table saved as a CSV that looks something like (when it's in Excel) this just longer: ``` Monday Tuesday Wednesday Thursday Friday marsbar 9 8 0 6 5 reeses 0 0 0 9 0 twix 2 3 0 5 6 snickers 9 8 0 6 5 ``` (The format isnt perfect, but you get the gist--candy bars/day). I want to write a program for python in which I could input a list of candy bar names in the program ``` >>> ['twix', 'reeses'] ``` and it would give me the days of the week on which those candy bars were eaten and how many candy bars in the list were eaten on that day. The result would look something like this: ``` Monday 2 Tuesday 3 Wednesday 0 Thursday 14 Friday 6 ``` could someone help me write such a program?
2011/06/22
[ "https://Stackoverflow.com/questions/6444632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/808545/" ]
Maybe with the [csv module](http://docs.python.org/library/csv.html) I suppose the delimiter is the tab character (`\t`) ``` import csv reader = csv.reader(open('csv_file.csv', 'rb'), delimiter='\t') for row in reader: print row >>>['Monday','Tuesday', 'Wednesday', 'Thursday', 'Friday'] ['marsbar', '9', '8','0', '6', '5'] ['reeses', '0', '0', '0', '9', '0'] ['twix', '2', '3', '0', '5', '6'] ['snickers', '9', '8', '0', '6', '5'] ```
In addition to the other answers, you may also want to take a look at the xlrd module, as it can deal with the excel spreadsheets directly if you'd rather not deal with CSV business. The module allows you to read entire (or ranges) of rows/columns at a time as well as grabbing individual cells and you can iterate through everything to search for what you want and then return whatever related 'values' you want in the same row/column from where you found your search criteria.
6,444,632
I have an Excel table saved as a CSV that looks something like (when it's in Excel) this just longer: ``` Monday Tuesday Wednesday Thursday Friday marsbar 9 8 0 6 5 reeses 0 0 0 9 0 twix 2 3 0 5 6 snickers 9 8 0 6 5 ``` (The format isnt perfect, but you get the gist--candy bars/day). I want to write a program for python in which I could input a list of candy bar names in the program ``` >>> ['twix', 'reeses'] ``` and it would give me the days of the week on which those candy bars were eaten and how many candy bars in the list were eaten on that day. The result would look something like this: ``` Monday 2 Tuesday 3 Wednesday 0 Thursday 14 Friday 6 ``` could someone help me write such a program?
2011/06/22
[ "https://Stackoverflow.com/questions/6444632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/808545/" ]
Maybe with the [csv module](http://docs.python.org/library/csv.html) I suppose the delimiter is the tab character (`\t`) ``` import csv reader = csv.reader(open('csv_file.csv', 'rb'), delimiter='\t') for row in reader: print row >>>['Monday','Tuesday', 'Wednesday', 'Thursday', 'Friday'] ['marsbar', '9', '8','0', '6', '5'] ['reeses', '0', '0', '0', '9', '0'] ['twix', '2', '3', '0', '5', '6'] ['snickers', '9', '8', '0', '6', '5'] ```
Some useful bits: If you have a list of lists like ``` [['marsbar', 0, 1, 2, 3, 4], ['twix', 3, 4, 5, 6, 7]] ``` (which you should be able to get by using the `csv` module) You will probably want to convert it to a dictionary, where the first item of each list is used for the key, and the rest make up the value. You can do this with something like ``` dict((x[0], x[1]) for x in list_of_lists) ``` You can look up multiple keys with a list comprehension as well: ``` [the_dict[key] for key in key_list] ``` That gives you a list of lists, where you want to sum the first elements of each list, the second elements, etc. To do that, we 'zip' the lists to make a list of lists with all the first elements, all the second elements etc., and then sum the inner lists. ``` [sum(x) for x in zip(*the_requested_candybars)] ``` The `zip()` function takes multiple arguments; the `*` here turns the list of lists into several list arguments. We can `zip` again to match up the week names with the sums.
6,444,632
I have an Excel table saved as a CSV that looks something like (when it's in Excel) this just longer: ``` Monday Tuesday Wednesday Thursday Friday marsbar 9 8 0 6 5 reeses 0 0 0 9 0 twix 2 3 0 5 6 snickers 9 8 0 6 5 ``` (The format isnt perfect, but you get the gist--candy bars/day). I want to write a program for python in which I could input a list of candy bar names in the program ``` >>> ['twix', 'reeses'] ``` and it would give me the days of the week on which those candy bars were eaten and how many candy bars in the list were eaten on that day. The result would look something like this: ``` Monday 2 Tuesday 3 Wednesday 0 Thursday 14 Friday 6 ``` could someone help me write such a program?
2011/06/22
[ "https://Stackoverflow.com/questions/6444632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/808545/" ]
Your best bet is to use the `csv` package built into python. It will let you loop over the rows, giving you a list each time, like so: ``` import csv candy_reader = csv.reader(open('candy.csv', 'rb')) for row in candy_reader: if row[0] in candy_to_find: monday_total += row[1] # etc. ``` I didn't initialize several variables, but I think this should give you the basic idea.
In addition to the other answers, you may also want to take a look at the xlrd module, as it can deal with the excel spreadsheets directly if you'd rather not deal with CSV business. The module allows you to read entire (or ranges) of rows/columns at a time as well as grabbing individual cells and you can iterate through everything to search for what you want and then return whatever related 'values' you want in the same row/column from where you found your search criteria.
6,444,632
I have an Excel table saved as a CSV that looks something like (when it's in Excel) this just longer: ``` Monday Tuesday Wednesday Thursday Friday marsbar 9 8 0 6 5 reeses 0 0 0 9 0 twix 2 3 0 5 6 snickers 9 8 0 6 5 ``` (The format isnt perfect, but you get the gist--candy bars/day). I want to write a program for python in which I could input a list of candy bar names in the program ``` >>> ['twix', 'reeses'] ``` and it would give me the days of the week on which those candy bars were eaten and how many candy bars in the list were eaten on that day. The result would look something like this: ``` Monday 2 Tuesday 3 Wednesday 0 Thursday 14 Friday 6 ``` could someone help me write such a program?
2011/06/22
[ "https://Stackoverflow.com/questions/6444632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/808545/" ]
Your best bet is to use the `csv` package built into python. It will let you loop over the rows, giving you a list each time, like so: ``` import csv candy_reader = csv.reader(open('candy.csv', 'rb')) for row in candy_reader: if row[0] in candy_to_find: monday_total += row[1] # etc. ``` I didn't initialize several variables, but I think this should give you the basic idea.
Some useful bits: If you have a list of lists like ``` [['marsbar', 0, 1, 2, 3, 4], ['twix', 3, 4, 5, 6, 7]] ``` (which you should be able to get by using the `csv` module) You will probably want to convert it to a dictionary, where the first item of each list is used for the key, and the rest make up the value. You can do this with something like ``` dict((x[0], x[1]) for x in list_of_lists) ``` You can look up multiple keys with a list comprehension as well: ``` [the_dict[key] for key in key_list] ``` That gives you a list of lists, where you want to sum the first elements of each list, the second elements, etc. To do that, we 'zip' the lists to make a list of lists with all the first elements, all the second elements etc., and then sum the inner lists. ``` [sum(x) for x in zip(*the_requested_candybars)] ``` The `zip()` function takes multiple arguments; the `*` here turns the list of lists into several list arguments. We can `zip` again to match up the week names with the sums.
6,444,632
I have an Excel table saved as a CSV that looks something like (when it's in Excel) this just longer: ``` Monday Tuesday Wednesday Thursday Friday marsbar 9 8 0 6 5 reeses 0 0 0 9 0 twix 2 3 0 5 6 snickers 9 8 0 6 5 ``` (The format isnt perfect, but you get the gist--candy bars/day). I want to write a program for python in which I could input a list of candy bar names in the program ``` >>> ['twix', 'reeses'] ``` and it would give me the days of the week on which those candy bars were eaten and how many candy bars in the list were eaten on that day. The result would look something like this: ``` Monday 2 Tuesday 3 Wednesday 0 Thursday 14 Friday 6 ``` could someone help me write such a program?
2011/06/22
[ "https://Stackoverflow.com/questions/6444632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/808545/" ]
In addition to the other answers, you may also want to take a look at the xlrd module, as it can deal with the excel spreadsheets directly if you'd rather not deal with CSV business. The module allows you to read entire (or ranges) of rows/columns at a time as well as grabbing individual cells and you can iterate through everything to search for what you want and then return whatever related 'values' you want in the same row/column from where you found your search criteria.
Some useful bits: If you have a list of lists like ``` [['marsbar', 0, 1, 2, 3, 4], ['twix', 3, 4, 5, 6, 7]] ``` (which you should be able to get by using the `csv` module) You will probably want to convert it to a dictionary, where the first item of each list is used for the key, and the rest make up the value. You can do this with something like ``` dict((x[0], x[1]) for x in list_of_lists) ``` You can look up multiple keys with a list comprehension as well: ``` [the_dict[key] for key in key_list] ``` That gives you a list of lists, where you want to sum the first elements of each list, the second elements, etc. To do that, we 'zip' the lists to make a list of lists with all the first elements, all the second elements etc., and then sum the inner lists. ``` [sum(x) for x in zip(*the_requested_candybars)] ``` The `zip()` function takes multiple arguments; the `*` here turns the list of lists into several list arguments. We can `zip` again to match up the week names with the sums.
45,343,570
This is my current data in database. ``` ======================================== id | IC |date |time | 1 | test |2017-07-27 |14:19:26 | 2 | test |2017-07-27 |14:20:26 | 3 | second |2017-07-28 |06:58:55 | ======================================== ``` I want to get the maxdate and maxtime for each IC. I tried: ``` SELECT id,pass_no,time_in,ic,date_in FROM `check_in` WHERE date_in = (SELECT MAX(date_in) FROM check_in) AND time_in = (SELECT MAX(time_in) FROM check_in) GROUP BY IC ``` But it only return the last row data for me. The result I wanted is like ``` ======================================== id | IC |date |time | 2 | test |2017-07-27 |14:20:26 | 3 | second |2017-07-28 |06:58:55 | ======================================== ```
2017/07/27
[ "https://Stackoverflow.com/questions/45343570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7935771/" ]
This will return the max date & time per ic: ``` select ic, max(date), max(time) from check_in group by ic ```
This should work ``` select max(time),date,id from (select max(date) as date,time,id from check-in group by time,id ) group by date,id; ```
45,343,570
This is my current data in database. ``` ======================================== id | IC |date |time | 1 | test |2017-07-27 |14:19:26 | 2 | test |2017-07-27 |14:20:26 | 3 | second |2017-07-28 |06:58:55 | ======================================== ``` I want to get the maxdate and maxtime for each IC. I tried: ``` SELECT id,pass_no,time_in,ic,date_in FROM `check_in` WHERE date_in = (SELECT MAX(date_in) FROM check_in) AND time_in = (SELECT MAX(time_in) FROM check_in) GROUP BY IC ``` But it only return the last row data for me. The result I wanted is like ``` ======================================== id | IC |date |time | 2 | test |2017-07-27 |14:20:26 | 3 | second |2017-07-28 |06:58:55 | ======================================== ```
2017/07/27
[ "https://Stackoverflow.com/questions/45343570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7935771/" ]
This will return the max date & time per ic: ``` select ic, max(date), max(time) from check_in group by ic ```
You can use a tuple and group by ic ``` SELECT id,pass_no,time_in,ic,date_in FROM `check_in` WHERE (date_in, time_in, ic) in ( SELECT MAX(date_in), max(time_id), ic FROM check_in GROUP BY id) ```
45,343,570
This is my current data in database. ``` ======================================== id | IC |date |time | 1 | test |2017-07-27 |14:19:26 | 2 | test |2017-07-27 |14:20:26 | 3 | second |2017-07-28 |06:58:55 | ======================================== ``` I want to get the maxdate and maxtime for each IC. I tried: ``` SELECT id,pass_no,time_in,ic,date_in FROM `check_in` WHERE date_in = (SELECT MAX(date_in) FROM check_in) AND time_in = (SELECT MAX(time_in) FROM check_in) GROUP BY IC ``` But it only return the last row data for me. The result I wanted is like ``` ======================================== id | IC |date |time | 2 | test |2017-07-27 |14:20:26 | 3 | second |2017-07-28 |06:58:55 | ======================================== ```
2017/07/27
[ "https://Stackoverflow.com/questions/45343570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7935771/" ]
This will return the max date & time per ic: ``` select ic, max(date), max(time) from check_in group by ic ```
Did you try with "OR" condition insteads "AND"?
45,343,570
This is my current data in database. ``` ======================================== id | IC |date |time | 1 | test |2017-07-27 |14:19:26 | 2 | test |2017-07-27 |14:20:26 | 3 | second |2017-07-28 |06:58:55 | ======================================== ``` I want to get the maxdate and maxtime for each IC. I tried: ``` SELECT id,pass_no,time_in,ic,date_in FROM `check_in` WHERE date_in = (SELECT MAX(date_in) FROM check_in) AND time_in = (SELECT MAX(time_in) FROM check_in) GROUP BY IC ``` But it only return the last row data for me. The result I wanted is like ``` ======================================== id | IC |date |time | 2 | test |2017-07-27 |14:20:26 | 3 | second |2017-07-28 |06:58:55 | ======================================== ```
2017/07/27
[ "https://Stackoverflow.com/questions/45343570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7935771/" ]
You can use a tuple and group by ic ``` SELECT id,pass_no,time_in,ic,date_in FROM `check_in` WHERE (date_in, time_in, ic) in ( SELECT MAX(date_in), max(time_id), ic FROM check_in GROUP BY id) ```
This should work ``` select max(time),date,id from (select max(date) as date,time,id from check-in group by time,id ) group by date,id; ```
45,343,570
This is my current data in database. ``` ======================================== id | IC |date |time | 1 | test |2017-07-27 |14:19:26 | 2 | test |2017-07-27 |14:20:26 | 3 | second |2017-07-28 |06:58:55 | ======================================== ``` I want to get the maxdate and maxtime for each IC. I tried: ``` SELECT id,pass_no,time_in,ic,date_in FROM `check_in` WHERE date_in = (SELECT MAX(date_in) FROM check_in) AND time_in = (SELECT MAX(time_in) FROM check_in) GROUP BY IC ``` But it only return the last row data for me. The result I wanted is like ``` ======================================== id | IC |date |time | 2 | test |2017-07-27 |14:20:26 | 3 | second |2017-07-28 |06:58:55 | ======================================== ```
2017/07/27
[ "https://Stackoverflow.com/questions/45343570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7935771/" ]
You can use a tuple and group by ic ``` SELECT id,pass_no,time_in,ic,date_in FROM `check_in` WHERE (date_in, time_in, ic) in ( SELECT MAX(date_in), max(time_id), ic FROM check_in GROUP BY id) ```
Did you try with "OR" condition insteads "AND"?
1,986,872
I'm porting a Delphi 5 app to D2010, and I've got a bit of a problem. On one form is a TImage component with an OnMouseMove event that's supposed to update a label whenever the mouse is moved over the image. This worked just fine in the original app, but now the OnMouseMove event fires constantly whenever the mouse is over the image, whether it's moving or not, which causes the label to flicker horribly. Does anyone know what's causing this and how to fix it?
2009/12/31
[ "https://Stackoverflow.com/questions/1986872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32914/" ]
*My psychic debugging sense tells me that you are on Windows, the label is a tooltip window and you are updating on every mousemove.* In all seriousness, I've seen this exact thing with tooltip window when we switched to Vista. It seems that more recent versions of the Windows tooltip window somehow generate WM\_MOUSEMOVE messages when you update them. The only fix I could find was to only update the label when the text actually changes. So, If you aren't on windows, Ignore me. But if you are on Windows, try updating the label text only when it actually changes.
Mason, I can't reproduce this is a new D2010 (Update 4 & 5) VCL Forms application on Windows XP SP2. Here's what I did: * File|New|VCL Forms Application * Dropped a TImage and TLabel on the form * Picked a random image out of the default images folder (GreenBar.bmp) for the TImage.Picture * Double-clicked the TImage.OnMouseMove event in the Object Inspector, and added the following code: ``` procedure TForm1.Image1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin Label1.Caption := Format('X: %d Y: %d', [X, Y]); end; ``` * Ran the application (F9). The label showed "Label1" (the default caption, of course) until I first moved the mouse over the image. It then updated correctly to show the X and Y coordinates. As soon as I moved the mouse pointer out of the image, the label stopped updating. It appears to be something in your specific code, or something specific to the version of Windows you're using, and not Delphi 2010 itself.