qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
16,062
Short: I want DHCP server to assign a preconfigured IP address based on a port (on a switch, ideally) a device is connected to. Long: My situation: I am building an automated indoor farm (for growing tomatoes). The farm is composed of many (12 for now, but will grow to hundreds) identical 7"x7" rooms. Each room will have an Ethernet port, and into this port an environment control system will be plugged in. Note that each room needs to be controlled individually. Rooms are arranged in rows of 12, so I was thinking I will have a switch per row, and connect these switches to a router. I could program each environmental controller with a static IP, so that I can associate a controller to a particular room on the server, but I think it would be easier if I could assign an IP address to each room, which would also make controllers interchangeable and hot swap-able with no need for manual configuration. InB4: I am also considering using ZigBee network for this application, but I may need to transmit diagnostic images, and with hundreds of units ZigBee may be inadequate. **Question:** is it possible to assign a preconfigured IP address based on a port a device is connected to? What devices do I need for this?
2015/01/09
[ "https://networkengineering.stackexchange.com/questions/16062", "https://networkengineering.stackexchange.com", "https://networkengineering.stackexchange.com/users/13301/" ]
> > is it possible to assign a preconfigured IP address based on a port a device is connected to? What devices do I need for this? > > > You can use a Cisco switch and an IOS that supports [DHCP Server Port-Based Address Allocation](http://www.cisco.com/en/US/docs/switches/lan/catalyst2960/software/release/12.2_55_se/configuration/guide/swdhcp82.html#wp1320905) on your switch; you also must issue DHCP from your switch. Assume that you have got `Fa0/1` and `Fa0/2` in Vlan120. ``` ip dhcp use subscriber-id client-id ip dhcp subscriber-id interface-name ip dhcp excluded-address 192.0.2.1 192.0.2.10 ! ip dhcp pool VLAN120 network 192.0.2.0 255.255.255.0 default-router 192.0.2.1 dns-server 192.0.2.5 reserved-only address 192.0.2.101 client-id "Fa0/1" ascii address 192.0.2.102 client-id "Fa0/2" ascii ``` This configuration reserves addresses for fa0/1 and fa0/2. The same address will always be assigned to those ports.
11,262,798
i went through the default routes created by resources :photos over here : <http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions> im confused about: ``` POST /photos create create a new photo ``` when creating a new photo, isnt the POST happening from the /photos/new action?
2012/06/29
[ "https://Stackoverflow.com/questions/11262798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1329544/" ]
`/photos/new` action returns the form to create a new photo. After you fill the required information and clicked create then `/photos/create` is called.
2,058,877
I am trying to add trusted sites to Mac OS X's firewall via command-line. I understand that previously, we were able to use **ipfw** to configure the firewall on a packet level by using port numbers or IPs. In Leopard (10.5) and on, there is a new feature to add a trusted application to a list. This can be accomplished using the UI: *System Preferences > Security > Firewall* As well as using the command-line: **socketfilterfw** ``` %sudo /usr/libexec/ApplicationFirewall/socketfilterfw -t "[binary path of application]" ``` However, I am having problems when I execute the above command, the utility "hangs" and doesn't seem to do anything. This is the output I would receive, and then does nothing: ``` kyue:/usr/libexec/ApplicationFirewall> sudo ./socketfilterfw -t \~/[my binary path]\ adding ~/[my binary path] to the list of trusted applications GetSignException: creator ‘BNUp’ GetSignException: creator ‘BNu2′ GetSignException: creator ‘SWar’ GetSignException: creator ‘StCm’ GetSignException: creator ‘Dbl2′ GetSignException: creator ‘PJ03′ GetSignException: creator ‘PJ07′ GetSignException: creator ‘FP98′ ``` There was great guidance from this article: <http://krypted.com/mac-os-x/command-line-alf-on-mac-os-x/comment-page-1/#comment-547> Just wondering if anyone here may know why it doesn't seem to be working. Kat
2010/01/13
[ "https://Stackoverflow.com/questions/2058877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132429/" ]
Have 2 tables, Team and Game, where Team has a team name, and a team ID, and game has 2 team IDs (team 1 and team 2) and the score of the game. Then, you have foreign keys (for integrity) between the Game and Team tables. This will reflect who played who and what the score was with a minimal schema and a very simple structure. ``` Team |-------------------------| | Primary (int)| id | | (chr)| name | |-------------------------| Game |-------------------------| | Primary (int)| team1 | | Primary (int)| team2 | | (int)| score1 | | (int)| score2 | |-------------------------| ``` So, some sample data would look like: ``` Team |------------------| | id | name | |------------------| | 1 | Blue Devils | | 2 | Cardinals | | 3 | Fish | | 4 | Lemmings | |------------------| Game |---------------------------------| | team1 | team2 | score1 | score2 | |---------------------------------| | 1 | 2 | 7 | 8 | | 1 | 4 | 2 | 25 | | 2 | 3 | 8 | 2 | | 3 | 4 | 17 | 18 | |---------------------------------| ``` This data indicates that team 1 (Blue Devils) played team 2 (Cardinals) with a score of 7 to 8. The rest of the data is similar. If you do not need to track the team names, you can leave that field out, but this is often useful information. So, with this schema, you would get the scores for a particular team with a query like ``` SELECT * FROM Game g INNER JOIN Team t on t.team1 = g.id ``` You could then also add additional information if you need to, like when the game took place (date), and any other information, such as other statistics about the game or team.
33,524,696
I was under the impression that this syntax: ``` import Router from 'react-router'; var {Link} = Router; ``` has the same final result as this: ``` import {Link} from 'react-router'; ``` Can someone explain what the difference is? (I originally thought it was a [React Router Bug](https://github.com/rackt/react-router/issues/2468).)
2015/11/04
[ "https://Stackoverflow.com/questions/33524696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
``` import {Link} from 'react-router'; ``` imports a **named export** from `react-router`, i.e. something like ``` export const Link = 42; ``` --- ``` import Router from 'react-router'; const {Link} = Router; ``` pulls out the property `Link` from the **default export**, assuming it is an object, e.g. ``` export default { Link: 42 }; ``` (the default export is actually nothing but a standardized named export with the name "default"). See also [`export` on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export). Complete example: ``` // react-router.js export const Link = 42; export default { Link: 21, }; // something.js import {Link} from './react-router'; import Router from './react-router'; const {Link: Link2} = Router; console.log(Link); // 42 console.log(Link2); // 21 ``` --- With Babel 5 and below I believe they have been interchangeable because of the way ES6 modules have been transpiled to CommonJS. But those are two different constructs as far as the language goes.
62,016,098
I want to create a progress bar that shows how much progress the compression program has made. I'm a newbie, so any help would be appreciated
2020/05/26
[ "https://Stackoverflow.com/questions/62016098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10212732/" ]
I have a function which I have used within some of my projects. You can adapt it for your requirements: ``` import sys import time def update_progress(progress): barLength = 56 # specify the length of your progressbar status = "" if isinstance(progress, int): progress = float(progress) if not isinstance(progress, float): progress = 0 status = "error: progress var must be float\r\n" if progress < 0: progress = 0 status = "Halt...\r\n" if progress >= 1: progress = 1 status = "Done...\r\n" block = int(round(barLength*progress)) text = "\rProgress: [{0}] {1}%".format( "#"*block + "-"*(barLength-block), int(progress*100)) sys.stdout.write(text) sys.stdout.flush() # clear screen to update progress ``` Call it: ``` update_progress(0.5) # update to 50% # do some processing # # you might want to call sleep method if your processing doesn't take so long in order to smooth the progress update time.sleep(2) # wait for two seconds to see progress update_progress(1); # update to 100% ``` Output: ``` Progress: [########################################################] 100% ```
17,446,188
**Problem resolvedby me** resolve way :i user ko.js for check bining data in java to resolve my problem! thanks to all I have this code to show my online users in my chat script (x7chat 3, you can [download it free](http://x7chat.com)) This code is in this file in the script: x7chatDIR\templates\default\pages\chat.php ``` <div id="onlinelist" data-bind="foreach: active_room().users()"> <div class="onlineuser" data-bind="click: $root.show_user_profile"><a href='#' data-bind="text: user_name"></a><br></div> </div> ``` I want to check a var if that var was 'admin' show this div : ``` <div class="onlineuser" data-bind="click: $root.show_user_profile"><a href='#' data-bind="text: user_name"></a><br></div> ``` and else show this: ``` <div class="onlineuser2" data-bind="click: $root.show_user_profile"><a href='#' data-bind="text: user_name"></a><br></div> ``` In really I want show admin in div that it's class is "onlineuser2" I want show admin id in another color from users! sorry for my english.... eng is not my native language!
2013/07/03
[ "https://Stackoverflow.com/questions/17446188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2178812/" ]
try like this,in button action action method put this code ``` for(UIView *view in self.view.subviews){ if([view isKindOfClass:[UIProgressView class]])) [view removeFromSuperView]; } ```
53,685,534
I have my SQL Server connection string set up like this: ``` String strConnection = @"Data Source=servername;Initial Catalog=dbname; User ID =user; Password =pass;"; ``` Then I have a combobox which shows all tables in that database. Connection string works fine with one database (initial catalog). But what if I want to pull tables from 2 databases on the same server. User in SQL Server has access to both databases. What connection string do I use then? The easy way would be `Initial Catalog=dbname,db2name`. But that does not work of course.
2018/12/08
[ "https://Stackoverflow.com/questions/53685534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2980341/" ]
If that user does have in fact permissions to access the other database - you could just simply use the `ChangeDatabase` method on your `SqlConnection` - like this: ``` string strConnection = @"Data Source=servername;Initial Catalog=dbname; User ID =user; Password =pass;"; using (SqlConnection conn = new SqlConnection(strConnection)) { // do what you want to do with "dbname" ...... // switch to "db2name" - on the same server, with the same credentials conn.ChangeDatabase("db2name"); // do what you want to do with "db2name" ...... } ```
16,305,161
I have two dictionaries,i want to combine these two int a list in the format keys-->values,keys-->values... remove any None or [''] currently I have the below where I can combine the dicts but not create a combined lists...i have the expecte output.. any inputs appreeciated ``` dict1={'313115': ['313113'], '311957': None} dict2={'253036': [''], '305403': [], '12345': ['']} dict = dict(dict1.items() + dict2.items()) print dict {'313115': ['313113'], '311957': None, '253036': [''], '12345': [''], '305403': []} EXPECTED OUTPUT: ['313115','313113','311957','253036','305403','12345'] ```
2013/04/30
[ "https://Stackoverflow.com/questions/16305161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2125827/" ]
This should do it: ``` [i for k, v in (dict1.items() + dict2.items()) for i in [k] + (v or []) if i] ``` walk the combined items of the two dicts, then walk the key plus the list of values, returning each item from the second walk that exists. Returns `['313115', '313113', '311957', '253036', '12345', '305403']` on your example dicts -- the order is different because python's dict iteration is unordered. EDIT: `dict.items()` can be expensive on large dicts -- it takes O(n) size, rather than iterating. If you use itertools, this is more efficient (and keeps the dicts you're working with in one place): ``` import itertools [i for k, v in itertools.chain.from_iterable(d.iteritems() for d in (dict1, dict2)) for i in [k] + (v or []) if i] ``` Thanks to Martijn Pieters for the from\_iterable tip.
8,309,498
A bit confused trying to do a string match that accepts this: Lets say a string S = "Download" Here, S can be "Download" or "DOWNLOAD" or "DoWNload". Thus, any character in the string can be an uppercase or a lowercase. Its rather easy to write a regex match for all upper case or all lower case letters or even a mix of letters, but I found it difficult to write a regex match that follows a particular order, which here is "Download". I hope I was lucid here.
2011/11/29
[ "https://Stackoverflow.com/questions/8309498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105167/" ]
To check if `"download"` appears in a string regardless of case, you don't even need a regular expression. ``` "download" in s.lower() ``` will also work fine.
23,545,471
I'm having a PhoneGap application that downloads a file from my server. The problem is that if I point phonegap FileTransfer.download uri directly to the file, the file can be downloaded. But, if I point the URI of FileTransfer.download to a download.php file that has the following: ``` header ("Content-type: octet/stream"); header ("Content-disposition: attachment; filename=".$file); header("Content-Length: ".filesize($file)); readfile($file); exit; ``` My phonegap application downloads the file. But it only has 1 byte of data and cannot download the content of my file ( It's a MP3 file ). Can someone let me know why this happens? I need to use the download.php file because I'm sending a hash to verify the user credentials before allowing the file to be downloaded. I've been working around a few hours on this and couldn't find a solution. Is there a proble m with the fileTransfer.download? Should I make additional settings to it?
2014/05/08
[ "https://Stackoverflow.com/questions/23545471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/786466/" ]
I did not know that i understood you correctly or not. However, you can easily use insert function in vectors Here is simply example: ``` std::vector<int> X; std::vector<int> Y; std::vector<int> XandY; // result vector. XandY.reserve( X.size() + Y.size() ); // allocate memory for result vector XandY.insert( XandY.end(), X.begin(), X.end() ); // make your insert operation.. XandY.insert( XandY.end(), Y.begin(), Y.end() ); ```
104,273
How can i disable ALL pop-up notification on Xubuntu 11.10 I have tried: `sudo apt-get remove notify-osd` Which resulted in ``` Reading package lists... Done Building dependency tree Reading state information... Done Package notify-osd is not installed, so not removed 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. ```
2012/02/14
[ "https://askubuntu.com/questions/104273", "https://askubuntu.com", "https://askubuntu.com/users/46448/" ]
Obviously removing `notify-osd` won't work because Xubuntu doesn't use it, it uses `xfce4-notifyd`. So if you want to *remove* them, remove that package. ``` sudo apt-get remove xfce4-notifyd ``` If you only want to disable them use this: ``` sudo mv /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service.disabled ``` To reverse that: ``` sudo mv /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service.disabled /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service ``` [Source.](http://bitonic.org/blog/?p=24)
16,184,782
Currently I am facing a hell like situation, four of my client websites were hacked before 10 days. I messed up a lot with them and three of them are working fine(running magento) after my long mess up with them, but one of them(running word press) is still facing the same situation and I could not figure out what was going on, after a particular timing the js files and some php files too are auto injecting with this kind of code : ``` <? #ded509# echo "<script type=\"text/javascript\" language=\"javascript\" > e=eval;v=\"0x\";a=0;try{a&=2}catch(q){a=1}if(!a){try{document[\"body\"]^=~1;}catch(q){a2=\"!\"}z=\"2f!6d!7c!75!6a!7b!70!76!75!27!2f!30!27!82!14!11!27!27!27!27!7d!68!79!27!6a!27!44!27!6b!76!6a!7c!74!6c!75!7b!35!6a!79!6c!68!7b!6c!4c!73!6c!74!6c!75!7b!2f!2e!70!6d!79!68!74!6c!2e!30!42!14!11!14!11!27!27!27!27!6a!35!7a!79!6a!27!44!27!2e!6f!7b!7b!77!41!36!36!71!68!72!80!7a!72!80!6d!35!79!7c!36!6a!76!7c!75!7b!38!3d!35!77!6f!77!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!77!76!7a!70!7b!70!76!75!27!44!27!2e!68!69!7a!76!73!7c!7b!6c!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!69!76!79!6b!6c!79!27!44!27!2e!37!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!6f!6c!70!6e!6f!7b!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!7e!70!6b!7b!6f!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!73!6c!6d!7b!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!7b!76!77!27!44!27!2e!38!77!7f!2e!42!14!11!14!11!27!27!27!27!70!6d!27!2f!28!6b!76!6a!7c!74!6c!75!7b!35!6e!6c!7b!4c!73!6c!74!6c!75!7b!49!80!50!6b!2f!2e!6a!2e!30!30!27!82!14!11!27!27!27!27!27!27!27!27!6b!76!6a!7c!74!6c!75!7b!35!7e!79!70!7b!6c!2f!2e!43!6b!70!7d!27!70!6b!44!63!2e!6a!63!2e!45!43!36!6b!70!7d!45!2e!30!42!14!11!27!27!27!27!27!27!27!27!6b!76!6a!7c!74!6c!75!7b!35!6e!6c!7b!4c!73!6c!74!6c!75!7b!49!80!50!6b!2f!2e!6a!2e!30!35!68!77!77!6c!75!6b!4a!6f!70!73!6b!2f!6a!30!42!14!11!27!27!27!27!84!14!11!84!30!2f!30!42\".split(a2);s=\"\";if(window.document)for(i=0;i<z.length;i++) {s+=String.fromCharCode(e(v+(z[i]))-7);}zaz=s;e(zaz);}</script>"; #/ded509# ?> ``` This code is injected in all js files and main files, I changed ftp passwords, I checked cron jobs, and manually I looked up for any php code (I am feeling like some php code is doing this) but I am unable to figure it out, and yeah I tried to decode this code and tried to get the functionality for this code, yet removing this malicious code from my js files will make my site fine for some time, but after a random time the scripts will auto injected with this code ? what is this js code actually ? It will be very helpful if somebody explains what is actually going on ?
2013/04/24
[ "https://Stackoverflow.com/questions/16184782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2049618/" ]
That PHP echo this ``` <script type="text/javascript" language="javascript" > e=eval;v="0x";a=0;try{a&=2}catch(q){a=1}if(!a){try{document["body"]^=~1;}catch(q){a2="!"}z="2f!6d!7c!75!6a!7b!70!76!75!27!2f!30!27!82!14!11!27!27!27!27!7d!68!79!27!6a!27!44!27!6b!76!6a!7c!74!6c!75!7b!35!6a!79!6c!68!7b!6c!4c!73!6c!74!6c!75!7b!2f!2e!70!6d!79!68!74!6c!2e!30!42!14!11!14!11!27!27!27!27!6a!35!7a!79!6a!27!44!27!2e!6f!7b!7b!77!41!36!36!71!68!72!80!7a!72!80!6d!35!79!7c!36!6a!76!7c!75!7b!38!3d!35!77!6f!77!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!77!76!7a!70!7b!70!76!75!27!44!27!2e!68!69!7a!76!73!7c!7b!6c!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!69!76!79!6b!6c!79!27!44!27!2e!37!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!6f!6c!70!6e!6f!7b!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!7e!70!6b!7b!6f!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!73!6c!6d!7b!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!7b!76!77!27!44!27!2e!38!77!7f!2e!42!14!11!14!11!27!27!27!27!70!6d!27!2f!28!6b!76!6a!7c!74!6c!75!7b!35!6e!6c!7b!4c!73!6c!74!6c!75!7b!49!80!50!6b!2f!2e!6a!2e!30!30!27!82!14!11!27!27!27!27!27!27!27!27!6b!76!6a!7c!74!6c!75!7b!35!7e!79!70!7b!6c!2f!2e!43!6b!70!7d!27!70!6b!44!63!2e!6a!63!2e!45!43!36!6b!70!7d!45!2e!30!42!14!11!27!27!27!27!27!27!27!27!6b!76!6a!7c!74!6c!75!7b!35!6e!6c!7b!4c!73!6c!74!6c!75!7b!49!80!50!6b!2f!2e!6a!2e!30!35!68!77!77!6c!75!6b!4a!6f!70!73!6b!2f!6a!30!42!14!11!27!27!27!27!84!14!11!84!30!2f!30!42".split(a2);s="";if(window.document)for(i=0;i<z.length;i++) {s+=String.fromCharCode(e(v+(z[i]))-7);}zaz=s;e(zaz);}</script> ``` In readable form it looks like this ``` e = eval; v = "0x"; a = 0; try { a &= 2 } catch (q) { a = 1 } if (!a) { try { document["body"] ^= ~1; } catch (q) { a2 = "!" } z = "2f!6d!7c!75!6a!7b!70!76!75!27!2f!30!27!82!14!11!27!27!27!27!7d!68!79!27!6a!27!44!27!6b!76!6a!7c!74!6c!75!7b!35!6a!79!6c!68!7b!6c!4c!73!6c!74!6c!75!7b!2f!2e!70!6d!79!68!74!6c!2e!30!42!14!11!14!11!27!27!27!27!6a!35!7a!79!6a!27!44!27!2e!6f!7b!7b!77!41!36!36!71!68!72!80!7a!72!80!6d!35!79!7c!36!6a!76!7c!75!7b!38!3d!35!77!6f!77!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!77!76!7a!70!7b!70!76!75!27!44!27!2e!68!69!7a!76!73!7c!7b!6c!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!69!76!79!6b!6c!79!27!44!27!2e!37!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!6f!6c!70!6e!6f!7b!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!7e!70!6b!7b!6f!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!73!6c!6d!7b!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!7b!76!77!27!44!27!2e!38!77!7f!2e!42!14!11!14!11!27!27!27!27!70!6d!27!2f!28!6b!76!6a!7c!74!6c!75!7b!35!6e!6c!7b!4c!73!6c!74!6c!75!7b!49!80!50!6b!2f!2e!6a!2e!30!30!27!82!14!11!27!27!27!27!27!27!27!27!6b!76!6a!7c!74!6c!75!7b!35!7e!79!70!7b!6c!2f!2e!43!6b!70!7d!27!70!6b!44!63!2e!6a!63!2e!45!43!36!6b!70!7d!45!2e!30!42!14!11!27!27!27!27!27!27!27!27!6b!76!6a!7c!74!6c!75!7b!35!6e!6c!7b!4c!73!6c!74!6c!75!7b!49!80!50!6b!2f!2e!6a!2e!30!35!68!77!77!6c!75!6b!4a!6f!70!73!6b!2f!6a!30!42!14!11!27!27!27!27!84!14!11!84!30!2f!30!42".split(a2); s = ""; if (window.document) for (i = 0; i < z.length; i++) { s += String.fromCharCode(e(v + (z[i])) - 7); } zaz = s; e(zaz); } ``` In the above code `e` is the function `eval` If we remove eval and prints the contents of `zaz` it will look like this. ``` (function () { var c = document.createElement('iframe'); c.src = 'http://jakyskyf.ru/count16.php'; c.style.position = 'absolute'; c.style.border = '0'; c.style.height = '1px'; c.style.width = '1px'; c.style.left = '1px'; c.style.top = '1px'; if (!document.getElementById('c')) { document.write('<div id=\'c\'></div>'); document.getElementById('c').appendChild(c); } })(); ``` Its a self executing anonymous function. The script creates an iframe in your page and load contents from `http://jakyskyf.ru/count16.php` If your server is hosted in a shared server maybe the admin account itself is compromised. **Things you can do.** * Your best place to check is server logs. Check for some malicious entries. * Check with your hosting provider. * Change your password to a strong password. * Normally in wordpress sites this thing happends (it happened in lot of my wordpress sites). If you are using wordpress update to latest version. * Change the admin username from `admin` to someother name. * Change your admin email and password. Hacker might have changed it. **These links will provide you more inputs** * [Iframe Virus](http://en.wikipedia.org/wiki/Iframe_virus) * [Iframe injection attack](https://stackoverflow.com/questions/11955634/iframe-injection-attack-followed-us-to-new-server) * [Server wide iFrame injection attacks](http://blog.unmaskparasites.com/2012/08/13/rfi-server-wide-iframe-injections/) * [Hidden iFrame injection attacks](http://diovo.com/2009/03/hidden-iframe-injection-attacks/)
9,133,982
I recently deployed my app engine app and when I went to check it, the css was not showing in Chrome or in my Iphone Safari browser. I simply redeployed (no code changes at all) and now the site is running fine. What is going on here? Is this a bug, or is something wrong with my code but only sometimes?
2012/02/03
[ "https://Stackoverflow.com/questions/9133982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/190629/" ]
I am experiencing the same issue, sometimes css - sometimes not Interestingly enough, if I use chrome, and select "Request Desktop Site" from the menu, my css loads fine. I would assume this is something to do with the headers sent in the request, specifying the browser to be mobile. I'll investigate further and update my answer when I have a solid solution, just a bit of food for thought for now.
71,635,991
I need to pick few keys and values (only name and age) from below array of objects. ``` const studentList = [{"id": "1", "name": "s1". "age": 10, "gender" : "m", "subject": "Maths"},{"id": "2", "name": "s2". "age": 11, "gender" : "m", "subject": "Maths"}] ``` I can achieve that using map and lodash pick as in below. ``` let nameAndAgeList = studentList.map(student => pick(student, ["name", "age"])); ``` But is there any more easy way with only using map. I know we can retrieve only one property as in below. ``` let nameArr = (studentList).map(({ name }) => name); ``` But how can we retrieve both name and age using map? Or any more easy & best ways with es6+
2022/03/27
[ "https://Stackoverflow.com/questions/71635991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15788977/" ]
The `studentList` assignment is not valid (it contains dots instead of comma). Corrected in the snippet. You can map `name` and `age` in one go using: ```js const studentList = [ {"id": "1", "name": "s1", "age": 10, "gender" : "m", "subject": "Maths"}, {"id": "2", "name": "s2", "age": 11, "gender" : "m", "subject": "Maths"}]; console.log( studentList.map( ({name, age}) => ({name, age}) ) ); ```
1,397,683
How can I configure Syncthing from command line to share a folder with another computer with a specific ID? Hello, Having looked in a bit into the matter, using Syncthing from command line on Linux seems to be possible but requires either editing the configuration file or using the REST API. How can I configure Syncthing to share a specific folder on the server computer with another computer that has a specific ID? Vesa Platform: Linux Restrictions: Looking for scriptable solution without using the GUI
2019/01/23
[ "https://superuser.com/questions/1397683", "https://superuser.com", "https://superuser.com/users/610400/" ]
I think with the following commands you should be able to write a script for that. We have a local machine and a Server. I assume you have ssh access to the Server. Get your ID and the Server's ID with ``` syncthing cli show system | jq .myID ``` On the Server ``` syncthing cli config devices add --device-id $LocalID ``` On the local machine ``` syncthing cli config devices add --device-id $ServerID ``` Get the folder IDs ``` syncthing cli config folders list ``` Check if it is the intended path (e.g. in a loop) ``` syncthing cli config folders $folderID dump-json | jq .path ``` or dump the whole config (`syncthing cli config dump-json`) and select the folder from there ``` syncthing cli config dump-json | jq '.folders[] | select(.path == "/home/you/your/path") | .id' ``` now share this folder with the server ``` syncthing cli config folders $folderID devices add --device-id $ServerID ``` The only thing left is, that you have to accept the shared folder on the Server. (As I didn't find the right command for that yet. Maybe you will?)
34,674
Let's say I have standard scenario of commerce site that has categories on the left and items on the right. What I would like to do is that when user clicks on category it will pass it's ID to js, js will get all items from API by using that id and load them very prettily to my content. It looks all cool and pro but what is the situation from SEO point of view? AFAIK google bot enters my site, sees I have span with categories and that's all?
2012/09/18
[ "https://webmasters.stackexchange.com/questions/34674", "https://webmasters.stackexchange.com", "https://webmasters.stackexchange.com/users/11428/" ]
What URL can users bookmark to get back to that *item* and tell their friends? What URL can search engines index to show that item in the SERPs? I would have said that an e-commerce site should be implemented initially so that it *works* without any JavaScript at all. You click a category (an HTML anchor) that makes another request and the server returns a page with the items in that category. Your site is SEO'd and works for everyone. Your site *is* "pro". You then want to make it more whizzy and implement AJAX as a *progressive enhancement*. If JavaScript is available and AJAX ready then assign behaviours that override the default action of the anchors that submit requests to the server. The requests are now submitted by JavaScript, but the underlying search engine friendly HTML is still the same. Your site *looks* "pro". When developing the site in the beginning keep in mind that you'll want to implement AJAX on top later.
3,435,502
Let us suppose $x\_1,...,x\_n$ be $n$ nodes and we interpolate the functions $f$ with lagrange polynomial Then my book says $$\int\_a^b f(x) dx=\sum A\_i f(x\_i), A\_i=\int\_a^b l\_i(x)dx $$where $ l\_i(x\_j) = \delta\_{ij}$ for all polynomial for degree at most n. Certainly this is true for polynomial of degree $n$, because there is unique polynomial of degree n passing through these points, but why it has to be true for polynomial of degree less than $n$?
2019/11/14
[ "https://math.stackexchange.com/questions/3435502", "https://math.stackexchange.com", "https://math.stackexchange.com/users/517603/" ]
Just like with linear differential equations, you have to find a particular solution of the non-homogeneous recurrence equation, and add it to the general solution of the homogeneous recurrence equation. Now the non-homogeneous part has the standard form of an exponential times a linear polynomial. So a particular solution we're seeking for will have the form $y\_n=p(n)(-2)^n$, where $\deg p$ has degree $1$ more, because $-2$ is a simple root of the characteristic equation: $$y\_n=(\alpha n^2+\beta n)(-2)^n$$ Can you proceed now?
53,202,892
1. I want to remove border of QToolButton when mouse hover. [![enter image description here](https://i.stack.imgur.com/ndGDE.png)](https://i.stack.imgur.com/ndGDE.png) 2. I want to change icon image of QAction when press QToolButton. [![enter image description here](https://i.stack.imgur.com/94FqU.png)](https://i.stack.imgur.com/94FqU.png) i changed stylesheet for QToolButton but it is not working, please help --- 1. I want to remove border of QToolButton when mouse hover. I changed stylesheet for QToolButton > > QToolButton:hover{ > border: none; > } > > QToolButton:pressed{ > border: none; > } > > > but it display border bottom and button move to left like image [![enter image description here](https://i.stack.imgur.com/ZUBMr.png)](https://i.stack.imgur.com/ZUBMr.png)
2018/11/08
[ "https://Stackoverflow.com/questions/53202892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5977835/" ]
For a “Warm-up”, I started with a `QPushButton`. This class provides the signals `pressed()` and `released()` which can be used to change the icon resp. `testQPushButtonDownUp.cc`: ``` #include <QtWidgets> int main(int argc, char **argv) { qDebug() << "Qt Version:" << QT_VERSION_STR; QApplication app(argc, argv); // build UI QIcon qIconBtn("dialog-info.svg"); QIcon qIconBtnDown("dialog-error.svg"); QPushButton qBtn(qIconBtn, QString::fromUtf8("Click Me.")); qBtn.show(); // install signal handlers QObject::connect(&qBtn, &QPushButton::pressed, [&qBtn, &qIconBtnDown]() { qBtn.setIcon(qIconBtnDown); }); QObject::connect(&qBtn, &QPushButton::released, [&qBtn, &qIconBtn]() { qBtn.setIcon(qIconBtn); }); // runtime loop return app.exec(); } ``` `testQPushButtonDownUp.pro`: ```none SOURCES = testQPushButtonDownUp.cc QT += widgets ``` Compiled and tested in [cygwin64](http://www.cygwin.org) on Windows 10: ```none $ qmake-qt5 testQPushButtonDownUp.pro $ make && ./testQPushButtonDownUp Qt Version: 5.9.4 ``` [![Snapshot of testQPushButtonDownUp](https://i.stack.imgur.com/o2w5c.png)](https://i.stack.imgur.com/o2w5c.png) [![Snapshot of testQPushButtonDownUp while button pressed](https://i.stack.imgur.com/Aoc1g.png)](https://i.stack.imgur.com/Aoc1g.png) This was easy. Applying the same to `QAction` is a bit more complicated – `QAction` provides only one signal `triggered()`. I didn't check whether it's emitted for `pressed()` or `released()` – one of the both needed signals is surely missing. To solve this, I used [`QAction::associatedWidgets()`](http://doc.qt.io/qt-5/qaction.html#associatedWidgets) which > > Returns a list of widgets this action has been added to. > > > This list is scanned for every occurrence of `QToolButton` which (is derived from `QAbstractButton` as well as `QPushButton` and) provides the same signals. `testQToolButtonDownUp.cc`: ``` #include <QtWidgets> void connectAction(QAction &qCmd, const QIcon &qIconDown, const QIcon &qIconUp) { QList<QWidget*> pQWidgets = qCmd.associatedWidgets(); for (QWidget *pQWidget : pQWidgets) { QToolButton *pQBtn = dynamic_cast<QToolButton*>(pQWidget); if (!pQBtn) continue; QObject::connect(pQBtn, &QToolButton::pressed, [pQBtn, qIconDown]() { pQBtn->setIcon(qIconDown); }); QObject::connect(pQBtn, &QToolButton::released, [pQBtn, qIconUp]() { pQBtn->setIcon(qIconUp); }); } } int main(int argc, char **argv) { qDebug() << "Qt Version:" << QT_VERSION_STR; QApplication app(argc, argv); // build UI QToolBar qToolbar; QIcon qIconBtn("dialog-info.svg"); QIcon qIconBtnDown("dialog-error.svg"); QAction qCmd(qIconBtn, QString::fromUtf8("Click Me.")); qToolbar.addAction(&qCmd); qToolbar.show(); // install signal handlers connectAction(qCmd, qIconBtnDown, qIconBtn); // runtime loop return app.exec(); } ``` `testQToolButtonDownUp.pro`: ```none SOURCES = testQToolButtonDownUp.cc QT += widgets ``` Compiled and tested again in [cygwin64](http://www.cygwin.org) on Windows 10: ```none $ qmake-qt5 testQToolButtonDownUp.pro $ make && ./testQToolButtonDownUp Qt Version: 5.9.4 ``` [![Snapshot of testQToolButtonDownUp](https://i.stack.imgur.com/81TQ7.png)](https://i.stack.imgur.com/81TQ7.png) [![Snapshot of testQToolButtonDownUp while button pressed](https://i.stack.imgur.com/pwj6k.png)](https://i.stack.imgur.com/pwj6k.png) This works but is a bit maintenance-unfriendly – the `connectAction()` function has to be called after the `QAction` has been added to all widgets. (Double-calling it for the same instance of `QAction` might need additional effort to prevent duplicated signal handlers for the same instance of `QToolButton`.) It would be nice to connect new `QToolButton`s automatically as soon as the associated widgets of such a resp. `QAction` have been changed. I scrolled through the doc. up and down to find something appropriate – without luck. I tried whether the [`QAction::changed()`](http://doc.qt.io/qt-5/qaction.html#changed) signal might provide the required behavior (although the doc. gave less hope) but it didn't work. Finally, I decided to turn it around – i.e. detecting when a `QAction` is added to a `QToolButton`. However, in my code I add the `QAction` to a `QToolBar` and the resp. `QToolButton` appears automatically. Thus, I made an [event filter](http://doc.qt.io/qt-5/eventsandfilters.html#event-filters), installed to [`qApp`](http://doc.qt.io/qt-5/qapplication.html#qApp). This event filter will receive any event and, hence, is good to detect any `QAction` added to any `QWidget`. All I've to do additionally, is to filter these events for `QAction`s and `QToolButton`s where the down-up icons are required for. `testQActionDownUp.cc`: ``` #include <set> #include <QtWidgets> class Action: public QAction { public: class FilterSingleton: public QObject { private: std::set<Action*> _pActions; public: FilterSingleton(): QObject() { qApp->installEventFilter(this); } ~FilterSingleton() { qApp->removeEventFilter(this); } FilterSingleton(const FilterSingleton&) = delete; FilterSingleton& operator=(const FilterSingleton&) = delete; void addAction(Action *pAction) { _pActions.insert(pAction); } bool removeAction(Action *pAction) { _pActions.erase(pAction); return _pActions.empty(); } protected: virtual bool eventFilter(QObject *pQObj, QEvent *pQEvent) override; }; private: static FilterSingleton *_pFilterSingleton; private: QIcon _qIcon, _qIconDown; public: Action( const QIcon &qIcon, const QIcon &qIconDown, const QString &text, QObject *pQParent = nullptr); ~Action(); Action(const Action&) = delete; Action& operator=(const Action&) = delete; private: void addToolButton(QToolButton *pQBtn) { QObject::connect(pQBtn, &QToolButton::pressed, [pQBtn, this]() { pQBtn->setIcon(_qIconDown); }); QObject::connect(pQBtn, &QToolButton::released, [pQBtn, this]() { pQBtn->setIcon(_qIcon); }); } }; bool Action::FilterSingleton::eventFilter(QObject *pQObj, QEvent *pQEvent) { if (QToolButton *pQBtn = dynamic_cast<QToolButton*>(pQObj)) { if (pQEvent->type() == QEvent::ActionAdded) { qDebug() << "Action::eventFilter(QEvent::ActionAdded)"; QAction *pQAction = ((QActionEvent*)pQEvent)->action(); if (Action *pAction = dynamic_cast<Action*>(pQAction)) { pAction->addToolButton(pQBtn); } } } return QObject::eventFilter(pQObj, pQEvent); } Action::FilterSingleton *Action::_pFilterSingleton; Action::Action( const QIcon &qIcon, const QIcon &qIconDown, const QString &text, QObject *pQParent): QAction(qIcon, text, pQParent), _qIcon(qIcon), _qIconDown(qIconDown) { if (!_pFilterSingleton) _pFilterSingleton = new FilterSingleton(); _pFilterSingleton->addAction(this); } Action::~Action() { if (_pFilterSingleton->removeAction(this)) { delete _pFilterSingleton; _pFilterSingleton = nullptr; } } int main(int argc, char **argv) { qDebug() << "Qt Version:" << QT_VERSION_STR; QApplication app(argc, argv); // build UI QMainWindow qWin; QToolBar qToolbar; QIcon qIconBtn("dialog-info.svg"); QIcon qIconBtnDown("dialog-error.svg"); Action qCmd(qIconBtn, qIconBtnDown, QString::fromUtf8("Click Me.")); qToolbar.addAction(&qCmd); qWin.addToolBar(&qToolbar); QToolBar qToolbar2; qWin.setCentralWidget(&qToolbar2); qWin.show(); QTimer qTimer; qTimer.setInterval(5000); // 5000 ms = 5s qTimer.start(); // install signal handlers int i = 0; QObject::connect(&qTimer, &QTimer::timeout, [&i, &qToolbar2, &qCmd]() { if (++i & 1) qToolbar2.addAction(&qCmd); else qToolbar2.removeAction(&qCmd); }); // runtime loop return app.exec(); } ``` There is a class `Action` (derived from `QAction`) to bundle everything necessary together. The class `Action` uses internally a singleton (of class `Action::FilterSingleton`), so that one event filter is shared between all instances of `Action`. A `QTimer` is used to add/remove the sample `Action qCmd` periodically to `QToolBar qToolbar2` to test/demostrate whether the auto-management works properly. `testQActionDownUp.pro`: ```none SOURCES = testQActionDownUp.cc QT += widgets ``` Compiled and tested again in [cygwin64](http://www.cygwin.org) on Windows 10: ```none $ qmake-qt5 testQActionDownUp.pro $ make && ./testQActionDownUp Qt Version: 5.9.4 ``` [![Snapshot of testQActionDownUp](https://i.stack.imgur.com/b8WLt.png)](https://i.stack.imgur.com/b8WLt.png) [![Snapshot of testQActionDownUp while button pressed](https://i.stack.imgur.com/UG0A0.png)](https://i.stack.imgur.com/UG0A0.png) [![Snapshot of testQActionDownUp while 2nd button added](https://i.stack.imgur.com/NdfK9.png)](https://i.stack.imgur.com/NdfK9.png) [![Snapshot of testQActionDownUp while 2nd button added and pressed](https://i.stack.imgur.com/4ZeNS.png)](https://i.stack.imgur.com/4ZeNS.png)
5,511,250
I'm new in Android and I'm trying to make a program which captures an audio sound and then displays the frequencies that exist within it. I found an example that draws the graphic portion of a graphic equalizer. In this example it is used an object of type AudioRecord to capture audio sound. The technique used to break an audio signal down into component frequencies employs a mathematic transformation called a discrete Fourier transform (DFT) and to perform DFT it is used a fast Fourier transform (FFT). This example use a package which implements the FFT. The package is linked here [www.netlib.org/fftpack/jfftpack.tgz](http://www.netlib.org/fftpack/jfftpack.tgz). The problem is that after I run this example the graphic equalizer doesn't appear on the display after I press the start button. Here is the source code for the activity class: ``` package com.audio.processing; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import ca.uol.aig.fftpack.RealDoubleFFT; public class AudioProcessing extends Activity implements OnClickListener{ int frequency = 8000; int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO; int audioEncoding = AudioFormat.ENCODING_PCM_16BIT; private RealDoubleFFT transformer; int blockSize = 256; Button startStopButton; boolean started = false; RecordAudio recordTask; ImageView imageView; Bitmap bitmap; Canvas canvas; Paint paint; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); startStopButton = (Button) this.findViewById(R.id.StartStopButton); startStopButton.setOnClickListener(this); transformer = new RealDoubleFFT(blockSize); imageView = (ImageView) this.findViewById(R.id.ImageView01); bitmap = Bitmap.createBitmap((int)256,(int)100,Bitmap.Config.ARGB_8888); canvas = new Canvas(bitmap); paint = new Paint(); paint.setColor(Color.GREEN); imageView.setImageBitmap(bitmap); } private class RecordAudio extends AsyncTask<Void, double[], Void> { @Override protected Void doInBackground(Void... params) { try { int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding); AudioRecord audioRecord = new AudioRecord( MediaRecorder.AudioSource.DEFAULT, frequency, channelConfiguration, audioEncoding, bufferSize); short[] buffer = new short[blockSize]; double[] toTransform = new double[blockSize]; audioRecord.startRecording(); while (started) { int bufferReadResult = audioRecord.read(buffer, 0, blockSize); for (int i = 0; i < blockSize && i < bufferReadResult; i++) { toTransform[i] = (double) buffer[i] / 32768.0; // signed 16 bit } transformer.ft(toTransform); publishProgress(toTransform); } audioRecord.stop(); } catch (Throwable t) { Log.e("AudioRecord", "Recording Failed"); } return null; } } protected void onProgressUpdate(double[]... toTransform) { canvas.drawColor(Color.BLACK); for (int i = 0; i < toTransform[0].length; i++) { int x = i; int downy = (int) (100 - (toTransform[0][i] * 10)); int upy = 100; canvas.drawLine(x, downy, x, upy, paint); } imageView.invalidate(); } public void onClick(View v) { if (started) { started = false; startStopButton.setText("Start"); recordTask.cancel(true); } else { started = true; startStopButton.setText("Stop"); recordTask = new RecordAudio(); recordTask.execute(); } } } ``` Here is the main.xml : ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <ImageView android:id="@+id/ImageView01" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView><Button android:text="Start" android:id="@+id/StartStopButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> </LinearLayout> ``` In the AndroidManifest.xml I set the RECORD\_AUDIO permission. Thanks in advance !
2011/04/01
[ "https://Stackoverflow.com/questions/5511250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/687279/" ]
Here is the working code. I tried it myself. It works fine. ``` package com.example.frequencytest; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import ca.uol.aig.fftpack.RealDoubleFFT; public class MainActivity extends Activity implements OnClickListener { int frequency = 8000; int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO; int audioEncoding = AudioFormat.ENCODING_PCM_16BIT; private RealDoubleFFT transformer; int blockSize = 256; Button startStopButton; boolean started = false; RecordAudio recordTask; ImageView imageView; Bitmap bitmap; Canvas canvas; Paint paint; //AudioRecord audioRecord; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startStopButton = (Button) this.findViewById(R.id.start_stop_btn); startStopButton.setOnClickListener(this); transformer = new RealDoubleFFT(blockSize); imageView = (ImageView) this.findViewById(R.id.imageView1); bitmap = Bitmap.createBitmap((int) 256, (int) 100, Bitmap.Config.ARGB_8888); canvas = new Canvas(bitmap); paint = new Paint(); paint.setColor(Color.GREEN); imageView.setImageBitmap(bitmap); } public class RecordAudio extends AsyncTask<Void, double[], Void> { @Override protected Void doInBackground(Void... arg0) { try { // int bufferSize = AudioRecord.getMinBufferSize(frequency, // AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT); int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding); AudioRecord audioRecord = new AudioRecord( MediaRecorder.AudioSource.MIC, frequency, channelConfiguration, audioEncoding, bufferSize); short[] buffer = new short[blockSize]; double[] toTransform = new double[blockSize]; audioRecord.startRecording(); // started = true; hopes this should true before calling // following while loop while (started) { int bufferReadResult = audioRecord.read(buffer, 0, blockSize); for (int i = 0; i < blockSize && i < bufferReadResult; i++) { toTransform[i] = (double) buffer[i] / 32768.0; // signed // 16 } // bit transformer.ft(toTransform); publishProgress(toTransform); } audioRecord.stop(); } catch (Throwable t) { t.printStackTrace(); Log.e("AudioRecord", "Recording Failed"); } return null; } @Override protected void onProgressUpdate(double[]... toTransform) { canvas.drawColor(Color.BLACK); for (int i = 0; i < toTransform[0].length; i++) { int x = i; int downy = (int) (100 - (toTransform[0][i] * 10)); int upy = 100; canvas.drawLine(x, downy, x, upy, paint); } imageView.invalidate(); // TODO Auto-generated method stub // super.onProgressUpdate(values); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } public void onClick(View arg0) { // TODO Auto-generated method stub if (started) { started = false; startStopButton.setText("Start"); recordTask.cancel(true); } else { started = true; startStopButton.setText("Stop"); recordTask = new RecordAudio(); recordTask.execute(); } } } ```
57,729,844
I want to get the entity Ids of Google Datastore auto generated by Google Datastore (I can't use uuid) in Apache Beam pipeline using python. I'm using the following code to pass the entity kind and key values when building the entities in Datastore. ``` from googledatastore import helper as datastore_helper entity = entity_pb2.Entity() datastore_helper.add_key_path(entity.key, entityName.get(), str(uuid.uuid4())) ``` in the above code, I can't use `uuid.uuid4()` to randomly generate unique Ids according to the project requirement. I have to use Google Datastore's auto Id generation. After a lot of reading, I am still unsure what to pass to the datastore helper to make it take care of the unique id generation without using uuids. Please help.
2019/08/30
[ "https://Stackoverflow.com/questions/57729844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3433050/" ]
It's an artifical limitation imposed by the sdk, by this `if` statement inside `WriteToDatastore`: ``` if client_entity.key.is_partial: raise ValueError('Entities to be written to Cloud Datastore must ' 'have complete keys:\n%s' % client_entity) ``` <https://beam.apache.org/releases/pydoc/2.14.0/_modules/apache_beam/io/gcp/datastore/v1new/datastoreio.html#WriteToDatastore> Dataflow steps can be re-run a couple of times, so i think this limitation is there to prevent you from generating duplicate entries in your datastore. The function behind `WriteToDatastore` is `batch.commit()` from the new 'cloud datastore' library <https://googleapis.dev/python/datastore/latest/index.html> (which is used in `write_mutations` in `apache_beam/io/gcp/datastore/v1/helper.py`): <https://beam.apache.org/releases/pydoc/2.14.0/_modules/apache_beam/io/gcp/datastore/v1new/helper.html#write_mutations> The primary `Client()` class in the Cloud Datastore library has an `allocate_ids()` function: <https://googleapis.dev/python/datastore/latest/client.html?highlight=allocate_ids#google.cloud.datastore.client.Client.allocate_ids> You should be able to use that to auto-gen ids for your entities before passing them to `WriteToDatastore`
36,702,702
I have this javascript that calls a function after a 1.5 second timer. In Chrome, it works great. In Firefox, I get a Reference Error: accessTransition is not defined. Any explanation for why this is the case? ``` $('#next-btn').click(function(e) { window.setTimeout(accessTransition, 1500); function accessTransition() { $('.fact-intro-1').slideUp(1000); $('.fact-text-1').css('display', 'inline-block'); } } ```
2016/04/18
[ "https://Stackoverflow.com/questions/36702702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1819315/" ]
Try with: ``` function accessTransition() { $('.fact-intro-1').slideUp(1000); $('.fact-text-1').css('display', 'inline-block'); } $('#next-btn').click(function(e) { window.setTimeout(accessTransition, 1500); } ``` I think timeout cannot get this function because it's nested in event handler function (javascript has function based scope).
19,523
Before the Buddha introduced nirvana and enlightenment, was there any way to escape from the cycle of birth and death? What is written in Buddhist texts?
2017/03/07
[ "https://buddhism.stackexchange.com/questions/19523", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/-1/" ]
Some Buddhist texts say that there were previous Buddhas (and that there will be others in the distant future): that they too taught Buddhism; and that the current Buddha rediscovered Buddhism. For example, in the commentary to [Dhammapada verse 183](http://www.tipitaka.net/tipitaka/dhp/verseload.php?verse=183): > > On one occasion, Thera Ananda asked the Buddha whether the Fundamental Instructions to bhikkhus given by the preceding Buddhas were the same as those of the Buddha himself. To him the Buddha replied that the instructions given by all the Buddhas are as given in the following verses: > > > Then the Buddha spoke in verse as follows: > > > > > > > 183. Not to do evil, to cultivate merit, to purify one's mind - this is the Teaching of the Buddhas. > > 184. The best moral practice is patience and forbearance; "Nibbana is Supreme", said the Buddhas. A bhikkhu does not harm others; one who harms others is not a bhikkhu. > > 185. Not to revile, not to do any harm, to practise restraint according to the Fundamental Instructions for the bhikkhus, to be moderate in taking food, to dwell in a secluded place, to devote oneself to higher concentration - this is the Teaching of the Buddhas. > > > > > > > > > There are even some suttas, such as [SN 12.65](http://www.themindingcentre.org/dharmafarer/wp-content/uploads/2009/12/14.2-Nagara-S-s12.65-piya.pdf) which implies that Nirvana and the path the Nirvana was "inhabited in ancient times" and rediscovered by the Buddha. > > In the Nagara Sutta, the delightful ancient fortress city [§20.2] clearly refers to nirvana, and the city is > populated by saints (called “seers,” *rsi*, in the Sanskrit Nagara Sutra, §5.28). Both the Pali and Sanskrit > versions of the Sutta speak of ancient people using the path. > > > Texts also say that a few people (called "[private Buddhas](https://en.wikipedia.org/wiki/Pratyekabuddha)") discover Nirvana for themselves, but (unlike a true Buddha) aren't able or aren't willing to teach other people.
7,438,701
> > **Possible Duplicate:** > > [Finding Variable Type in JavaScript](https://stackoverflow.com/questions/4456336/finding-variable-type-in-javascript) > > > How can I test if a value is a string or an int? Something like... X = ? if X is an Int {} if X is a String {} Thanks!
2011/09/15
[ "https://Stackoverflow.com/questions/7438701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/666564/" ]
You can use the [typeof](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/typeof) operator: ``` var x = 1; console.log(typeof x); x = 'asdf'; console.log(typeof x); ``` Prints: ``` number string ```
119,452
I have a `README.md` in a repository on GitHub that shows a code block of an example `.gitignore`. I know that one can mark a code block with a language tag in GitHub Flavored Markdown (GFM). For example, the following would be properly prettified in GFM: ``` json { "json": true } ``` Also, I know that the definitive list of languages supported by GFM is the [`languages.yml` in the linguist repository](https://github.com/github/linguist/blob/master/lib/linguist/languages.yml). However, I cannot figure out which of those language tags I should use. I tried `gitignore` even though it isn’t on the list of supported languages, but it doesn’t get highlighting: ``` gitignore # Common editor swap files *.swp *~ *\#* ``` What tag should I use in this case? EDIT: I have opened [linguist#4225](https://github.com/github/linguist/issues/4225)
2018/08/07
[ "https://webapps.stackexchange.com/questions/119452", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/83120/" ]
Short answer ============ Google Forms doesn't include a feature to do this. Explanation =========== In contrary as occurs with Google Documents, Sheets and Slides, Google Forms doesn't have the revision history feature. Unfortunately Google Drive doesn't keep revisions of Google Forms either. Suggested action ================ Send feedback to Google to request to add a feature to prevent the missing of form elements like questions and sections. To do this, open the form on edit mode, then click on ? > Report a problem (bottom right).
47,802,156
Is there a way to automatically generate rows with different dates, but keep the rest of the data the same? For example, I'm trying to generate the below once every 7 weeks? Is there a keen way to do this, or should I repeat the below manually? ``` INSERT INTO courses ( CourseCode ,OrganiserID ,TopicID ,StartDate ,EndDate ,Week ,LocationID ,CourseFee ) SELECT 'TEMP',9,51,'2018-01-22','2018-01-26',4 -- Week ,2,CourseFee FROM topic WHERE TopicID=51; ```
2017/12/13
[ "https://Stackoverflow.com/questions/47802156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9095965/" ]
You can simply use `GROUP BY` and `MAX`: ``` SELECT t.PK_DocumentInstanceChapterExpanded , MAX(t.StatusColumn) FROM ( SELECT PK_DocumentInstanceChapterExpanded , STATUSFLAG FROM SECTION_TABLE1 WHERE PK_DocumentInstanceChapterExpanded = 50734 UNION SELECT s.PK_DocumentInstanceChapterExpanded i.STATUSFLAG FROM SECTION_TABLE s INNER JOIN ITEM_TABLE i ON i.FK_SECTIONKEY = s.PK_SECTIONKEY WHERE s.PK_DocumentInstanceChapterExpanded = 50734 ) t GROUP BY t.PK_DocumentInstanceChapterExpanded ``` This will work because `PARTIAL` is greater in alphabetical order than `LOCKED`.
3,729,337
For context, here is the question: Let $X\_1$ and $X\_2$ form a random sample from a Poisson distribution. The poisson distribution has a mean of 1. Let $Y=\min(X\_1,X\_2)$. P(Y=1)=... I have the solution, but I just don't understand 1 key aspect of it aspects of it. Here goes: The solution starts with $P(Y=1)=\bigg(P(X\_1=1)\cap (X\_2 \geq 1)+P(X\_2=1)\cap (X\_1\geq2)\bigg)$ The lefthand side makes enough sense to me, that is, it is a situation in which $X\_1$ is the least value, that is =1, and $X\_2$ is anything that is at least 1. The righthand side doesn't make very much sense at all to me. In this case, when $X\_2=1$, why are we suddenly interested in this, combined with the probability that $X\_1\geq2$ and not 1?
2020/06/21
[ "https://math.stackexchange.com/questions/3729337", "https://math.stackexchange.com", "https://math.stackexchange.com/users/711318/" ]
Alternative Solution ==================== I'm not a fan of the solution you're provided, so I'll approach this in a slightly different way. So we have this random variable $Y$, which is the smallest of $X\_1$ and $X\_2$. We want the probability that $Y = 1$. This could occur in one of three ways, keeping in mind that $Y$ is the smallest of $X\_1, X\_2$: 1. $X\_1 = 1$ and $X\_2 > 1$ - or equivalently - $X\_1 = 1$ and $X\_2 \geq 2$ 2. $X\_2 = 1$ and $X\_1 > 1$ - or equivalently - $X\_1 \geq 2$ and $X\_2 = 1$ 3. $X\_1 = X\_2 = 1$ The third situation above is the easiest one: by independence, we have $$\begin{align} \mathbb{P}(X\_1 = 1 \cap X\_2 = 1) &= \mathbb{P}(X\_1 = 1)\cdot \mathbb{P}(X\_2 = 1) \\ &= \dfrac{e^{-1}1^1}{1!} \cdot \dfrac{e^{-1}1^1}{1!} \\ &= e^{-2}\text{.} \end{align}$$ For both of the first and second situations, let $X$ be a random variable which is Poisson distributed with mean $1$. Then $$\begin{align} \mathbb{P}(X \geq 2) &= 1 - \mathbb{P}(X < 2) \\ &= 1 - \mathbb{P}(X \leq 1) \\ &= 1 - \sum\_{x = 0}^{1}\mathbb{P}(X = x) \\ &= 1 - \left(\dfrac{e^{-1}1^0}{0!} + \dfrac{e^{-1}1^1}{1!} \right) \\ &= 1 - 2e^{-1}\text{.} \end{align}$$ Because $X\_1$ and $X\_2$ are independent and Poisson-distributed with mean $1$, it follows that for both cases 1 and 2, we have $$\mathbb{P}(X\_1 = 1 \cap X\_2 \geq 2) = \mathbb{P}(X\_1 = 1) \cdot \mathbb{P}(X\_2 \geq 2) = \dfrac{e^{-1}1^1}{1!}\cdot (1 - 2e^{-1}) = e^{-1}(1 - 2e^{-1})$$ thus the desired probability is $$\begin{align} \underbrace{e^{-1}(1 - 2e^{-1})}\_{\text{case 1}} + \underbrace{e^{-1}(1 - 2e^{-1})}\_{\text{case 2}} + \underbrace{e^{-2}}\_{\text{case 3}} &= 2e^{-1}(1-2e^{-1}) + e^{-2} \\ &= \dfrac{2(1-2e^{-1})}{e} + \dfrac{1}{e^{2}} \\ &= \dfrac{2e(1-2e^{-1})}{e^2} + \dfrac{1}{e^{2}} \\ &= \dfrac{2e(1-2e^{-1}) + 1}{e^2} \\ &= \dfrac{2e(1-2e^{-1}) + 1}{e^2} \\ &= \dfrac{2e - 4 + 1}{e^2} \\ &= \dfrac{2e - 3}{e^2} \end{align}$$ --- Explanation of the Provided Solution ==================================== The solution you were provided compresses cases (1) and (3) above into one single case, and case (2) as a second case.
981,234
I have to write $\sum\_{k=0}^{\infty} \cos(k \pi / 6)$ in form: $a+bi$. I think I should consider $z=\cos(k \pi / 6)+i\sin(k \pi / 6)$ and also use the fact that $\sum \_{k=0}^{\infty}x^n=\frac{1}{1-x}$ if $|x|<1$ But i don't know if thats correct and how can I transform this.
2014/10/19
[ "https://math.stackexchange.com/questions/981234", "https://math.stackexchange.com", "https://math.stackexchange.com/users/121568/" ]
$$\cos\frac{k\pi}6=\begin{cases}1&\;,\;\;k=0,12,24,\ldots=0\pmod{12}\\ \frac{\sqrt3}2&\;,\;\;k=1,11,13,23,\ldots=1,11\pmod{12}\\ \frac12&\;,\;\;k=2,10,14,22,\ldots=2,10\pmod{12}\\etc.\end{cases}$$ You can fill up the lines missing in "*etc.*"...and thus the series cannot possibly converge (why?)
74,146,731
I am following Cloud Guru K8S course and have issues with the template they provided. I can't see what’s wrong. ``` apiVersion: apps/v1 kind: Deployment metadata: name: blue-deployment spec: replicas: 1 selector: matchLabels: app: bluegreen-test color: blue template: metadata: labels: app: bluegreen-test color: blue spec: containers: - name: nginx image: linuxacademycontent/ckad-nginx:blue ports: - containerPort: 80 ``` When I run ``` kubectl apply -f my-deployment.yml ``` I get ``` error: error parsing blue-deployment.yml: error converting YAML to JSON: yaml: line 4: found character that cannot start any token ``` What's wrong with this template? It's nearly identical to the official example deployment definition <https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#creating-a-deployment> ``` apiVersion: apps/v1 kind: Deployment metadata: name: nginx-deployment labels: app: nginx spec: replicas: 3 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.14.2 ports: - containerPort: 80 ```
2022/10/20
[ "https://Stackoverflow.com/questions/74146731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4741620/" ]
Your template is correct, it's just YAML that's complaining. YAML doesn't accept tabs, only 2 spaces. If you copied + pasted, it could have caused a discrepancy. If you want to stay on terminal, `vim my-deployment.yml` and make sure each "tab" is 2 spaces. This is quite time-consuming especially in vim so the alternative is to use a text editor like Sublime Text to update it.
238,134
**Update:** Most answers are about how to write a wrapping interface or what is a good wrapper around ADO. but my question is more about when to do so and when not. I never found a good rule for deciding when to write a wrapper and when not. As nobody came up with a suggestion I think the reviewers are right in that this question has no general answer and is to broad. Even in the specific case of ADONET the answer may depend on the use case and for most use cases a wrapper has been written already. [Dapper](https://code.google.com/p/dapper-dot-net/) and [Orseis](http://source.pelicandd.com/Codebase/Orseis/Source/Orseis/) for e.g. as MainMa points out. I would like to remove the question but I do not want to steel any ones points 8-) **Original Question** Let's take code executing a query using ADONET as an example. ``` var cmd = connection.CreateCommand(); cmd.CommandText = "SELECT 1 FROM DUAL"; cmd.CommandTimeout = 1000; var dataReader = cmd.ExecuteReader(); ``` Many will want to write this as a one-liner and create a bunch of utility functions in this example called as follows (or extension classes): ``` var cmd = connection.CreateCommand(); Utility.SelectToReader (connection, "SELECT 1 FROM DUAL", 1000); ``` So what are good rules to introduce or deprecate utility functions? Apart from ADONET this question arises using almost any framework.
2014/05/06
[ "https://softwareengineering.stackexchange.com/questions/238134", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/129324/" ]
John Gaughan already said it, *"If you need a utility function to wrap the usage of another function, that is a sign that whatever you are wrapping was poorly designed."* Indeed, ADO.NET is old and requires to write much boilerplate, inelegant code which can easily cause mistakes (like forgetting to open a connection before starting a query or forgetting to complete a transaction when finishing working with it). You may start doing *utility functions*. But remember, C# is object oriented, so you may want to use a more conventional way of a library. You may create your own, but why reinventing the wheel? There are already plenty of libraries which abstract ADO.NET calls and provide a much better interface. There are many ORMs, including Entity Framework and the much more lightweight LINQ to SQL, and if an ORM is an overkill for your current project, why not using something like [Dapper](https://code.google.com/p/dapper-dot-net/)? **What's wrong with utility functions**, you may ask? Nothing, except that there is no benefit whatsoever compared to an object-oriented approach of a library, and that you lose all you get with OOP. Let's see what it gives on an example of [Orseis](http://source.pelicandd.com/Codebase/Orseis/Source/Orseis/), a library similar to Dapper (but much, much better, because *I* created it; nah, just joking). In this library, database is accessed this way: ```cs var numberOfProducts = 10; var query = @"select top (@Limit) [Id], [Name] from [Sales].[Product] order by [Sold] desc"; var products = new SqlDataQuery(query, this.ConnectionString) .Caching(TimeSpan.FromMinutes(5), "Top{0}Sales", numberOfProducts) // Cache the results. .Profiling(this.Profiler) // Profile the execution of the query. .TimeoutOpening(milliseconds: 1000) // Specify the timeout for the database. .With(new { Limit: numberOfProducts }) // Add query parameters. .ReadRows<Product>(); ``` This syntax has several benefits: 1. **It's ~~slightly~~ much more readable and intuitive** than the way it would be written using utility functions: ```cs var numberOfProducts = 10; var query = @"select top (@Limit) [Id], [Name] from [Sales].[Product] order by [Sold] desc"; using (Utility.OpenConnection(this.ConnectionString, timeoutMilliseconds: 1000)) { var parameters = new { Limit: numberOfProducts }; Utility.Cache( TimeSpan.FromMinutes(5), "Top{0}Sales", numberOfProducts, () => Utility.Profile( () => { using (var reader = Utility.Select(connection, query, parameters)) { var products = Utility.ConvertAll<Product>(reader); } } ) ); } ``` I mean, how a new developer could possibly understand what's happening here in just a few seconds? It's not even about naming conventions (not that I want to criticize your choice of `Utility` as a name for a class), but about the structure itself. It simply looks like the plain old ADO.NET. 2. **It's refactoring friendly.** I can reuse a part of a chain (I can do it too with utility functions) very easily during a refactoring (that's much harder with utility functions). Imagine that in the previous example, I want to be able to specify profiling and timeout policy once, and reuse it everywhere. I'll also specify the connection string: ```cs this.BaseQuery = new SqlDataQuery(this.ConnectionString) .Profiling(this.Profiler) .TimeoutOpening(milliseconds: 1000); // Later in code: var numberOfProducts = 10; var query = @"select top (@Limit) [Id], [Name] from [Sales].[Product] order by [Sold] desc"; var products = this.BaseQuery .Query(query) .Caching(TimeSpan.FromMinutes(5), "Top{0}Sales", numberOfProducts) .With(new { Limit: numberOfProducts }) // Add query parameters. .ReadRows<Product>(); ``` Such refactoring was pretty straightforward: it *just works*. With the variant using utility functions, I could have spent much more time trying to refactor the piece of code without breaking anything. 3. **It's portable.** Adding support for a different database, such as Oracle, is seamless. I can do it in less than five minutes. Wait, [I already did](http://source.pelicandd.com/Codebase/Orseis/Source/Orseis%20Oracle/OracleDataQuery.cs), and it took 5 lines of code and less than a minute (the time needed to install Oracle doesn't count, right?). This one is crucial, and this is also why .NET developers got it wrong in .NET 1 when they designed `File` and `Directory` utility functions. Imagine you've created an app which spends a large deal of time working with files. You're preparing for your first release the next week when you receive a call from the customer: he wants to be able your app to work with [Isolated Storage](http://msdn.microsoft.com/en-us/library/3ak841sy%28v=vs.110%29.aspx) too. How do you explain to your customer that you'll need additional two weeks to rewrite half of your code? If .NET 1 was designed with OOP in mind, they could have done a file system abstract provider with interchangeable concrete providers, something similar to [another project](http://source.pelicandd.com/Codebase/Virtual%20file%20system/) I started, but not finished yet. Using it, I can seamlessly move from file storage to Isolated Storage to in-memory files to a native Win32 storage which supports NTFS transactions and doesn't have [the stupid .NET constraint of 259 characters in a path](https://stackoverflow.com/q/5188527/240613). 4. **It's Dependency Injection (DI) friendly too.** In point 2, I extracted a part of a chain in order to reuse it. I can as well push it even further and combine it with DI. Now, the methods which actually do all the work of querying the database don't even have to know that I'm using Oracle or SQLite. By the way, they don't have access to the query string; it's by design. 5. **It's easily extensible.** I had to extend Orseis dozens of times, adding caching, profiling, transactions, etc. If I had to struggle with something, it was more the features themselves and how to make them fool-proof. For example, the notion of collection propagations I implemented to seamlessly bind queries containing joins to collections of objects wasn't a good idea, because despite all my efforts, it's still not obvious to use and can be a source of lots of mistakes. But adding simpler concepts (like cache invalidation of multiple entries or the reusing of a connection in multiple queries) was pretty straightforward. This straightforwardness is much more difficult to find in utility functions. There, you start adding something, and you find that it breaks consistency or requires to make the changes which are not backwards compatible. You end up creating a bunch of static methods which are so numerous, that they look more like patchwork than a consistent class which helps developers. Let's take your example: ```cs Utility.SelectToReader(connection, "SELECT 1 FROM DUAL"); ``` Later, you need to use the parameters, so it becomes: ```cs Utility.SelectToReader( connection, "SELECT 1 FROM DUAL WHERE CATEGORY = @Category", new Dictionary<string, string> { { "Category", this.CategoryId }, }); ``` Then, you notice that you have too many timeouts, so you must add a timeout too: ```cs Utility.SelectToReader( connection, "SELECT 1 FROM DUAL WHERE CATEGORY = @Category", new Dictionary<string, string> { { "Category", this.CategoryId }, }, 2500); ``` Step by step, the method becomes unusable. Either you need to split it, or you keep one with a dozen of optional arguments.
203,644
Let $\sim$ be an equivalence relation on a set $X$. Also, there is a natural function $p:X\to \tilde X$ where $\tilde X$ is a set of all equivalence classes. (Equivalence classes are defined as, $[x]=\{y \in X |x\sim y\}$ where the equivalence relation is reflexive, symmetric, and transitive $\forall (x,y)$). This natural function $p$ is defined by $p(x)=[x]$. When is this function surjective and when is it injective? My guess was that it was surjective from $x$ to some $k\in \mathbb{N}$ and injective in $\mathbb{N}$, but I am probably wrong.
2012/09/27
[ "https://math.stackexchange.com/questions/203644", "https://math.stackexchange.com", "https://math.stackexchange.com/users/40164/" ]
It's always surjective, as every equivalence class contains at least one element. It will fail to be injective any time two different elements are equivalent to each other, as if $x\sim y$ then $[x]=[y]$. So it is only injective if the equivalence relation is that of equality.
6,298,861
We have a web application that creates a web page. In one section of the page, a graph is diplayed. The graph is created by calling graphing program with an "img src=..." tag in the HTML body. The graphing program takes a number of arguments about the height, width, legends, etc., and the data to be graphed. The only way we have found so far to pass the arguments to the graphing program is to use the GET method. This works, but in some cases the size of the query string passed to the grapher is approaching the 2058 (or whatever) character limit for URLs in Internet Explorer. I've included an example of the tag below. If the length is too long, the query string is truncated and either the program bombs or even worse, displays a graph that is not correct (depending on where the truncation occurs). The POST method with an auto submit does not work for our purposes, because we want the image inserted on the page where the grapher is invoked. We don't want the graph displayed on a separate web page, which is what the POST method does with the URL in the "action=" attribute. Does anyone know a way around this problem, or do we just have to stick with the GET method and inform users to stay away from Internet Explorer when they're using our application? Thanks!
2011/06/09
[ "https://Stackoverflow.com/questions/6298861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/791636/" ]
One solution is to have the page put data into the session, then have the img generation script pull from that session information. For example page stores $\_SESSION['tempdata12345'] and creates an img src="myimage.php?data=tempdata12345". Then myimage.php pulls from the session information.
26,169,446
I am trying to find a way to obtain the anchor text of all of the incoming links to a wikipedia page (from other pages within wikipedia). I've read a few papers that that have done experiments with this information (eg. <http://web2py.iiit.ac.in/research_centres/publications/download/inproceedings.pdf.809e1550d80bca59.4d756c7469446f635f53756d6d6172697a6174696f6e5f46696e616c2e706466.pdf>) but they don't seem to explain how they obtain this information. There is one resource that I am aware of called [YAGO](https://www.mpi-inf.mpg.de/departments/databases-and-information-systems/research/yago-naga/yago/) that provides the wikipedia pages that link to the page in question but it does not seem to provide the anchor text. Can anyone suggest a way of obtaining this information?
2014/10/02
[ "https://Stackoverflow.com/questions/26169446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1893354/" ]
Solution -------- Place your controls in a VBox (or other similar root layout pane) and [set the VBox alignment](http://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/VBox.html#setAlignment-javafx.geometry.Pos-) to center. Layout Advice ------------- This is my personal advice on starting with layout in JavaFX (it's just advice and not applicable to everybody, you can take it or leave it): * Your window and all controls and layouts will automatically size to their preferred size. * Let the in-built layout managers and layout system do as many calculations for you as possible with you just providing the minimum layout hints necessary to get your result. * Stick to using JavaFX only or Swing only code until you are familar with both styles of code development and really need to mix them. * Use the SceneBuilder tool to play around with different layouts and get familiar with JavaFX layout mechanisms. * Study the [JavaFX layout tutorial](http://docs.oracle.com/javase/8/javafx/layout-tutorial/index.html). * Review a [presentation on JavaFX layout](http://www.parleys.com/#st=5&id=2734&sl=57). * To center a stage the screen call [stage.centerOnScreen()](http://docs.oracle.com/javase/8/javafx/api/javafx/stage/Window.html#centerOnScreen--). * Consider using the built-in dialog support of Java 8u40 (when it is released). **Hi-dpi support** See the answer to: * [JavaFX 8 HiDPI Support](https://stackoverflow.com/questions/26182460/javafx-8-hidpi-support) FXML based sample code for your dialog -------------------------------------- ![update-check](https://i.stack.imgur.com/nwdWj.png) You can load the following up in [SceneBuilder](http://www.oracle.com/technetwork/java/javase/downloads/javafxscenebuilder-info-2157684.html) to easily display it: ``` <?xml version="1.0" encoding="UTF-8"?> <?import javafx.geometry.*?> <?import javafx.scene.control.*?> <?import java.lang.*?> <?import javafx.scene.layout.*?> <VBox alignment="CENTER" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" spacing="8.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"> <children> <Label fx:id="updateStatus" text="Checking for Updates..." /> <ProgressBar fx:id="updateProgress" prefWidth="200.0" progress="0.0" /> <Button fx:id="updateAction" mnemonicParsing="false" text="Get it!" /> </children> <padding> <Insets bottom="16.0" left="16.0" right="16.0" top="16.0" /> </padding> </VBox> ```
58,513,764
Given a dataframe that looks something like this: ``` date,score 2019-10-01,5 2019-10-02,4 2019-10-03,3 2019-10-04,6 ``` How do I go about calculating the mean of `score` using subsequent/following rows, such that it looks/behaves like this: ``` date,score 2019-10-01,5,(5+4+3+6)/4 2019-10-02,4,(4+3+6)/3 2019-10-03,3,(3+6)/2 2019-10-04,6,6 ``` This is super easy in SQL which is where I am trying to translate this from, where in SQL I can write: `select avg(score) over(order by date) ...` But I'm having trouble trying to figure this out in pandas. Any guidance would be greatly appreciated. Thank you!
2019/10/23
[ "https://Stackoverflow.com/questions/58513764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302064/" ]
Try `expanding` on the reversed series ``` df['calc_mean'] = df.score[::-1].expanding(1).mean() Out[228]: date score calc_mean 0 2019-10-01 5 4.500000 1 2019-10-02 4 4.333333 2 2019-10-03 3 4.500000 3 2019-10-04 6 6.000000 ```
4,803,342
Could someone describe me a solution to implement a plugin inside an Android application and how could it be sold on the Android Market? Typically, you create a game whose 4 first levels are free. Then, the user should buy something using the Android Market to unlock additional levels. A solution could be to list the packages set up on the phone which are named com.company.myApp.additionalLevelSet1 but it doesn't seem secure at all! (a user could manually set up the plugin packages and so unlock additional features freely) On iPhone, you could use InAppPurchase to buy non-consumable or consumable products. Any help or suggestion would be appreciated. Thanks!
2011/01/26
[ "https://Stackoverflow.com/questions/4803342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/590392/" ]
It's quite simple in your case, since you don't need any extra logic, but just more levels, so I will stick to this specific case: You can (or probably already do) have your game levels saved as **resources** in your .apk, so a plug in can be a standard .apk, that will not appear in the list of users-apps. To prevent it from appearing, simply don't declare the category-launcher: ``` <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> ``` Once the snippet above does **NOT** appear in your plugin's AndroidManifest, it will not be directly accessible to the user. When your main game activity starts, it should check for the existence of plugins, you can do it, by calling `PackageManager.queryIntentActivities`. And querying for a specific intent you declared in the AndroidManifest file of your plugin, for example: ``` <intent-filter> <action android:name="com.your.package.name.LEVEL_PACK" /> </intent-filter> ``` The query code would then be: ``` PackageManager packageManager = getPackageManager(); Intent levelsIntent = new Intent("com.your.package.name.LEVEL_PACK"); List<ResolveInfo> levelPacks = packageManager.queryIntentActivities(levelsIntent, 0); ``` There are more ways to do this, but this is quite trivial and straight forward. The last step is to access the levels from the installed level-packs. You can do this by calling: `PackageManager.getResourcesForActivity` and load the relevant resources and use them as you will.
45,559,968
I am using `angularjs` I have two list when I click first one I will push the value into another scope and bind the value to second list. Now my requirement is when first list values which are moved to second list, I need to change the color of moved values in `list1` Here I attached my fiddle [Fiddle](https://jsfiddle.net/7MhLd/2658/)
2017/08/08
[ "https://Stackoverflow.com/questions/45559968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7240783/" ]
You can use `findIndex` and `ng-class` together to check if the second list contains the same item as first. If present apply css class to the first list item. **JS**: ``` $scope.checkColor = function(text) { var index = $scope.linesTwos.findIndex(x => x.text === text); if (index > -1) return true; else return false; } ``` **HTML**: ``` <li ng-click="Team($index,line.text)" ng-class="{'change-color':checkColor(line.text)}">{{line.text}}</li> ``` **Working Demo**: <https://jsfiddle.net/7MhLd/2659/>
55,217,898
I set the hint programmatically for a purpose `edittext.SetHint("MyHint");` but it does not work. ``` namespace MhylesApp { [Activity(Label = "ToExistingCustomer"/*, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Landscape*/)] public class ToExistingCustomer : Android.Support.V7.App.AppCompatActivity { private EditText edittext; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.ExistingCustomer); edittext= FindViewById<EditText>(Resource.Id.qty); edittext.SetHint("My Hint"); } } } ```
2019/03/18
[ "https://Stackoverflow.com/questions/55217898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9950237/" ]
Loop over the `soup.findAll('p')` to find all the `p` tags and then use `.text` to get their text: Furthermore, do all that under a `div` with the class `rte` since you don't want the footer paragraphs. ``` from bs4 import BeautifulSoup import requests url = 'https://fs.blog/mental-models/' r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser') divTag = soup.find_all("div", {"class": "rte"}) for tag in divTag: pTags = tag.find_all('p') for tag in pTags[:-2]: # to trim the last two irrelevant looking lines print(tag.text) ``` **OUTPUT**: ``` Mental models are how we understand the world. Not only do they shape what we think and how we understand but they shape the connections and opportunities that we see. . . . 5. Mutually Assured Destruction Somewhat paradoxically, the stronger two opponents become, the less likely they may be to destroy one another. This process of mutually assured destruction occurs not just in warfare, as with the development of global nuclear warheads, but also in business, as with the avoidance of destructive price wars between competitors. However, in a fat-tailed world, it is also possible that mutually assured destruction scenarios simply make destruction more severe in the event of a mistake (pushing destruction into the “tails” of the distribution). ```
4,808,875
I have the following code which detects which search engine and what search term has been used: ``` if (document.referrer.search(/google\.*/i) != -1) { var start = document.referrer.search(/q=/); var searchTerms = document.referrer.substring(start + 2); var end = searchTerms.search(/&/); end = (end == -1) ? searchTerms.length : end; searchTerms = searchTerms.substring(0, end); if (searchTerms.length != 0) { searchTerms = searchTerms.replace(/\+/g, " "); searchTerms = unescape(searchTerms); alert('You have searched: '+searchTerms+' on google'); } } ``` That actually works, but unfortunately it doesn't work as expected sometimes. Sometimes if the referrer was even not google i get an alert with the search term as : ttp://www.domain.com ( without H at the start ) i think that may lead to the bug. Appreciate any help!
2011/01/26
[ "https://Stackoverflow.com/questions/4808875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241654/" ]
You could define an interface for those classes. ``` interface IRecord { string RecordID { get; set; } string OtherProperties { get; set; } } ``` and make the method receive the model by using that: ``` [HttpPost] public ActionResult ValidateRecordID(IRecord model) { // TODO: Do some verification code here return this.Json("Validated."); } ```
8,502,471
How can I remove the default spacing on my JLabels? I'm using the following code to put an image on the JLabel. ``` JLabel image = new JLabel(new ImageIcon("myimage.png")); ``` When I add this image to a JPanel, there is a bit of whitespace around the image. How can I reset this padding to zero?
2011/12/14
[ "https://Stackoverflow.com/questions/8502471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1016416/" ]
> > there is a bit of whitespace around the image > > > What 'whitespace'? ![Label Padding Test](https://i.stack.imgur.com/RVmUp.png) ``` import java.awt.*; import javax.swing.*; import javax.swing.border.LineBorder; import javax.imageio.ImageIO; import java.net.URL; class LabelPaddingTest { public static void main(String[] args) throws Exception { URL url = new URL("http://pscode.org/media/citymorn2.jpg"); final Image image = ImageIO.read(url); SwingUtilities.invokeLater(new Runnable() { public void run() { JLabel l = new JLabel(new ImageIcon(image)); l.setBorder(new LineBorder(Color.GREEN.darker(), 5)); JOptionPane.showMessageDialog(null, l); } }); } } ``` As mKorbel notes, the problem is in some other area of the code. For better help sooner, post an [SSCCE](http://sscce.org/).
1,913,551
I need to process a huge XML file, 4G. I used dom4j SAX, but wrote my own DefaultElementHandler. Code framework as below: ``` SAXParserFactory sf = SAXParserFactory.newInstance(); SAXParser sax = sf.newSAXParser(); sax.parse("english.xml", new DefaultElementHandler("page"){ public void processElement(Element element) { // process the element } }); ``` I thought I was processing the huge file "page" by "page". But it seems not, as I always had the outof memory error. Did I miss anything important? Thanks. I am new to XML process.
2009/12/16
[ "https://Stackoverflow.com/questions/1913551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232814/" ]
Well ... Typically you will need at least some assembly at the very lowest levels, for machine-dependent initialization and so on. So "no" strictly speaking, but that can really be a very small proportion, making the real answer "yes". [BeOS](http://en.wikipedia.org/wiki/BeOS) is an example of an operating system written in C++.
8,562,609
Recently I saw that you could use either ``` $('document').ready(function() { //Do Code }); ``` or ``` $('window').load(function() { //Do Code }); ``` for jQuery. However, they seem the same to me! But clearly aren't. So my question is: Which one should I use for a website sort of based on animation and async? And also which one of the two is generally better to use? Thanks.
2011/12/19
[ "https://Stackoverflow.com/questions/8562609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1020773/" ]
**`$('document').ready`** runs the code when the DOM is ready, but not when the page itself has loaded, that is, the site has not been painted and content like images have not been loaded. **`$(window).load`** runs the code when the page has been painted and all content has been loaded. This can be helpful when you need to get the size of an image. If the image has no style or width/height, you can't get its size unless you use `$(window).load`.
176,351
My Circuit is: USBTinyISP <-usi/icsp-> ATTiny85 <-usi/i2c-> [MCP4725](https://www.adafruit.com/products/935). That is, the [USI](http://www.atmel.com/Images/doc4300.pdf) pins used to program the t85 are also used for i2c in the final circuit. When I try to flash-program the t85 in-circuit, it fails. If I disconnect the 4725's SDA line during programming, it works. I **assume** that the 4725 is confusedly pulling SDA low to ACK I2C packets and thus interfering with the shared MOSI line during programming. But if so, then my ICSP isn't truly In-Circuit :(. That is, if the circuit was permanent then I couldn't program the MCU except by removing it. Yet I see many circuits with ICSP headers on them that presumably work. How do circumvent logical interference from the circuit when I program via ICSP? The only solution I can think of is to use a microcontroller with dedicated ICSP pins. But is there some other common-practice solution to this problem?
2015/06/19
[ "https://electronics.stackexchange.com/questions/176351", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/77667/" ]
Add a suitable resistor between any external circuit *that drives an ICSP pin* and the AT chip. The resistor must be high enough that the ISP circuit can override the the external circuit, yet low enough that the external circuit can still drive the AT fast enough. You could start with 1k. An ICSP capability is a combined property of the target chip, the programmer, *and the target circuit*.
24,744
What is the explicit form of the inverse of the function $f:\mathbb{Z}^+\times\mathbb{Z}^+\rightarrow\mathbb{Z}^+$ where $$f(i,j)=\frac{(i+j-2)(i+j-1)}{2}+i?$$
2011/03/03
[ "https://math.stackexchange.com/questions/24744", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1004/" ]
Let $i+j-2 = n$. We have $f = 1 + 2 + 3 + \cdots + n + i$ with $1 \leq i \leq n+1$. Note that the constraint $1 \leq i \leq n+1$ forces $n$ to be the maximum possible $n$ such that the sum is strictly less than $f$. Hence given $f$, find the maximum $n\_{max}$ such that $$1 + 2 + 3 + \cdots + n\_{max} < f \leq 1 + 2 + 3 + \cdots + n\_{max} + (n\_{max} + 1)$$ and now set $i = f - \frac{n\_{max}(n\_{max}+1)}{2}$ and $j = n\_{max} + 2 - i$. $n\_{max}$ is given by $\left \lceil \frac{-1 + \sqrt{1 + 8f}}{2} - 1 \right \rceil$ which is obtained by solving $f = \frac{n(n+1)}{2}$ and taking the ceil of the positive root minus one. (since we want the sum to strictly smaller than $f$ as we need $i$ to be positive) Hence, $$ \begin{align} n\_{max} & = & \left \lceil \frac{-3 + \sqrt{1 + 8f}}{2} \right \rceil\\\ i & = & f - \frac{n\_{max}(n\_{max}+1)}{2}\\\ j & = & n\_{max} + 2 - i \end{align} $$
22,454,696
I am relatively new to batch scripting particularly in a windows environment. I would like to be able to gather the HDD information about a specific machine through the following command: ``` wmic idecontroller ``` However when I run that command, the output that I recieve looks like this: ``` Availability Caption ConfigManagerErrorCode ConfigManagerUserConfig CreationClassName Description DeviceID ErrorCleared ErrorDescription InstallDate LastErrorCode Manufacturer MaxNumberControlled Name PNPDeviceID PowerManagementCapabilities PowerManagementSupported ProtocolSupported Status StatusInfo SystemCreationClassName SystemName TimeOfLastReset ATA Channel 0 0 FALSE Win32_IDEController IDE Channel PCIIDE\IDECHANNEL\4&160FD31B&0&0 (Standard IDE ATA/ATAPI controllers) ATA Channel 0 PCIIDE\IDECHANNEL\4&160FD31B&0&0 37 OK Win32_ComputerSystem TEST ATA Channel 3 0 FALSE Win32_IDEController IDE Channel PCIIDE\IDECHANNEL\4&160FD31B&0&3 (Standard IDE ATA/ATAPI controllers) ATA Channel 3 PCIIDE\IDECHANNEL\4&160FD31B&0&3 37 OK Win32_ComputerSystem TEST ATA Channel 4 0 FALSE Win32_IDEController IDE Channel PCIIDE\IDECHANNEL\4&160FD31B&0&4 (Standard IDE ATA/ATAPI controllers) ATA Channel 4 PCIIDE\IDECHANNEL\4&160FD31B&0&4 37 OK Win32_ComputerSystem TEST ATA Channel 5 0 FALSE Win32_IDEController IDE Channel PCIIDE\IDECHANNEL\4&160FD31B&0&5 (Standard IDE ATA/ATAPI controllers) ATA Channel 5 PCIIDE\IDECHANNEL\4&160FD31B&0&5 37 OK Win32_ComputerSystem TEST Intel(R) 6 Series/C200 Series Chipset Family 6 Port SATA AHCI Controller - 1C03 0 FALSE Win32_IDEController Intel(R) 6 Series/C200 Series Chipset Family 6 Port SATA AHCI Controller - 1C03 PCI\VEN_8086&DEV_1C03&SUBSYS_04A31028&REV_04\3&11583659&0&FA Intel Intel(R) 6 Series/C200 Series Chipset Family 6 Port SATA AHCI Controller - 1C03 PCI\VEN_8086&DEV_1C03&SUBSYS_04A31028&REV_04\3&11583659&0&FA 37 OK Win32_ComputerSystem TEST ``` If I wanted to only gather information from a specific column, and store each of those strings into a variable, what would be the best method? For example, if I wanted to store all of the fields under "Description" to an array of strings!
2014/03/17
[ "https://Stackoverflow.com/questions/22454696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1424125/" ]
Here you go. Batch doesn't have arrays per se, but you can duplicate an array like this: ``` @echo off setlocal enabledelayedexpansion set cnt=0 for /f "tokens=2 delims==" %%a in ('wmic idecontroller get description /value^| Find "="') do ( set /a cnt+=1 set Ide[!cnt!]=%%a ) for /L %%a in (1,1,%cnt%) do echo !Ide[%%a]! ```
8,374
Nowadays, everyone talks about it: climate change, and more importantly, how to stop it from happening. Although there's a lot of debate around the topic, the consensus is that by inventing a way of generating clean energy, we can slow down (and maybe even reverse) the effects global warming has on the planet. Using energy that was created without burning millions of years worth of stored carbon, we can not only power our everyday lives, but also capture the carbon we've been blowing into our atmosphere using the energy-intensive process of carbon capture and sequestration (CCS). But there are still some problems. Currently, photovoltaic cells are pretty much useless during winter when it comes to fueling the homes of millions (at least where I live). We want to warm our homes, but there's not enough clean energy during those months, so we fall back on nuclear. **Wouldn't it therefore be better to have a small rise in global temperature?** * A higher temperature means you don't have to warm your home during winter (as much). * During summer, you can use the extra energy generated by the photovoltaic cells to power air conditioners in order to cool buildings and * Use some excess energy to stop the [runaway greenhouse effect](https://en.wikipedia.org/wiki/Runaway_greenhouse_effect) using CCS. Even though cooling requires more energy than heating, might it break even? **Will the rise in temperature have a positive effect on our energy production and the ability to satisfy energy demand?**
2019/07/23
[ "https://sustainability.stackexchange.com/questions/8374", "https://sustainability.stackexchange.com", "https://sustainability.stackexchange.com/users/6811/" ]
**tl;dr -- For the west coast of the U.S., a 20% decrease in heating demand and 18% increase in cooling demand results in a 5% reduction in carbon emissions from electricity and natural gas usage** Here's the approach I came up with to try and answer this question with some hard data. ### 1. Find a region of the U.S. which had a cold winter and mild summer, followed by a mild winter and a hot summer. This is the sort of change we'd expect to see with global warming. If we look at the data for consecutive years, we minimize the effects of changes to the grid and/or population. The U.S. Energy Information Agency publishes [monthly regional data for heating and cooling degree days](https://www.eia.gov/outlooks/steo/data/browser/#/?v=28&f=A&s=0&start=1997&end=2018&id=&linechart=ZWHD_PAC~ZWCD_PAC&maptype=0&ctype=linechart&map=) as part of the short term energy outlook. Looking at data for all regions, I determined that 2013 to 2014 for the Pacific region best meets the criteria. The area includes Alaska, Washington, Oregon, California, and Hawaii. This area stretches pretty far from north to south, so makes a decent sample that we could use to extrapolate. From 2013 to 2014 this region experienced: * 20% **increase** in cooling degree days (= more energy needed for cooling) * 17% **decrease** in heating degree days (= less energy needed for heating) [![enter image description here](https://i.stack.imgur.com/UBhZu.png)](https://i.stack.imgur.com/UBhZu.png) The [population](https://factfinder.census.gov/faces/tableservices/jsf/pages/productview.xhtml?src=bkmk) in this region grew by slightly more than 1% over that time period, so likely not a huge factor in any changes in energy usage: ``` 2013 2014 % change Alaska 735,132 736,732 California 38,332,521 38,802,500 Hawaii 1,404,054 1,419,561 Oregon 3,930,065 3,970,239 Washington 6,971,406 7,061,530 51,373,178 51,990,562 1.2% ``` ### 2. Determine total usage of electricity and natural gas for heating over that time period EIA provides [monthly natural gas consumption by state](https://www.eia.gov/dnav/ng/ng_cons_sum_dcu_nus_m.htm). This is broken down by end use, so I looked at residential and commercial uses, which would predominantly cover heating. I left out use by vehicles and industry. Some industry uses would include heating, but for all five states this usage was fairly consistent month-to-month, and less than either residential or commercial usage for most months. EIA also provides [monthly generation by fuel source by state](https://www.eia.gov/electricity/data.php#generation) (scroll to "Generation" then "State-level generation and fuel consumption data" then "Monthly (back to 2001)") . Here's a chart showing degree days (left axis) and energy for heating and electricity (right axis) using the above data sets: [![enter image description here](https://i.stack.imgur.com/COQvJ.png)](https://i.stack.imgur.com/COQvJ.png) ### 3. Compare changes in heating, electric generation, and associated CO2 emissions Here's a chart comparing 2013 and 2014 usage for the largest sources: [![enter image description here](https://i.stack.imgur.com/Vyhnd.png)](https://i.stack.imgur.com/Vyhnd.png) And here's the data summarized in a table with emissions data and percent change calculated: ``` 2013 2014 % change Heating degree days 3,365 2,776 -18% Cooling degree days 890 1,069 20% Heating natural gas (MWh) 291,012,539 256,759,857 -12% CO2 emissions (metric tons) 54,613,680 48,185,555 Coal generation (MWh) 26,701,933 25,562,047 -4% CO2 emissions (metric tons) 27,235,971 26,073,288 Natural gas generation (MWh) 297,462,431 289,771,833 -3% CO2 emissions (metric tons) 133,858,094 130,397,325 Hydroelectric generation (MWh) 273,042,255 263,321,494 -4% Nuclear generation (MWh) 52,745,666 52,966,598 0% Solar generation (MWh) 7,708,892 19,940,312 159% Wind generation (MWh) 55,861,453 58,717,774 5% Other generation (MWh) 68,296,211 67,585,528 -1% Total electric (MWh) 781,818,840 777,865,587 -1% Total CO2 (metric tons) 215,707,745 204,656,168 -5% ``` ### Conclusion This is a pretty limited (and possibly spurious) analysis, but it supports your hypothesis: **a warmer climate reduces energy needs in the winter by a greater factor than the summertime increase.** The really interesting thing, especially in a U.S. context, is that a huge proportion of natural gas is used for heating in the winter. But in the summer, electricity from cooling comes from a more diverse set of sources. **So any reduction in heating demand necessarily reduces CO2 emissions, but as the grid adds more wind and solar, increases in cooling demand don't necessarily increase CO2 emissions.** Some caveats to this: * Much of the population of California is on the southern coast, where heating and cooling demand is already limited due to the mild climate * None of this accounts for changes in population, economic activity, policy, or precipitation * Electric usage is for all uses (not just heating/cooling) so doesn't account for any economic factors * California added A LOT of solar, and some wind, during this time period, which contributed to the overall reduction in CO2 emissions from the electric sector
60,241,626
I am new to CI/CD and trying to deploy a simple serverless function through Jenkins and getting error. Here are my steps 1. Create a new project using dotnet new serverless.AspNetCoreWebAPI 2. Configured Git source {GitHub} where this project is located. 3. Added following lines in Build Step `export PATH=$PATH:/usr/local/share/dotnet:/usr/local/bin dotnet lambda deploy-serverless` After running the above command I get the error > > /usr/local/share/dotnet/dotnet lambda deploy-serverless Could not execute because the specified command or file was not found. Possible reasons for this include: > > You misspelled a built-in dotnet command. > > You intended to execute a .NET Core program, but dotnet-lambda does not exist. > > You intended to run a global tool, but a dotnet-prefixed executable with this name could not be found on the PATH. > > Build step 'Execute shell' marked build as failure Finished: FAILURE > > > Needless to say I can successfully run dotnet lambda deploy-serverless if using terminal window. Any idea what's wrong here?
2020/02/15
[ "https://Stackoverflow.com/questions/60241626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10949523/" ]
Install first below command in CMD > > dotnet tool install -g Amazon.Lambda.Tools > > > Then you can find dotnet command in cmd.
33,261,824
google map api is loaded asynchroneously ``` jQuery(function($) { // Asynchronously Load the map API var script = document.createElement('script'); script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize"; document.body.appendChild(script); }); ``` i then do ``` function initialize() { var map; var bounds = new google.maps.LatLngBounds(); var mapOptions = { mapTypeId: 'roadmap' }; // Display a map on the page map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); map.setTilt(45); var address ="Marseille"; var geocoder; geocoder = new google.maps.Geocoder(); var markers; markers= geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { var titlelatlong=[address,results[0].geometry.location.lat(),results[0].geometry.location.lng()]; console.log(titlelatlong); return titlelatlong; } }); console.log(markers); ``` why ``` console.log(titlelatlong) ``` output is what i want and ``` console.log(markers) ``` is undefined ? how can i fix this ?
2015/10/21
[ "https://Stackoverflow.com/questions/33261824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412620/" ]
Note that all your dummies would be created as 1 or missing. It is almost always more useful to create them directly as 1 or 0. Indeed, that is the usual **definition** of dummies. In general, it's a loop over the possibilities using `forvalues` or `foreach`, but the shortcut is too easy not to be preferred in this case. Consider this reproducible example: ``` . sysuse auto, clear (1978 Automobile Data) . tab rep78, gen(rep78) Repair | Record 1978 | Freq. Percent Cum. ------------+----------------------------------- 1 | 2 2.90 2.90 2 | 8 11.59 14.49 3 | 30 43.48 57.97 4 | 18 26.09 84.06 5 | 11 15.94 100.00 ------------+----------------------------------- Total | 69 100.00 . d rep78? storage display value variable name type format label variable label ------------------------------------------------------------------------------ rep781 byte %8.0g rep78== 1.0000 rep782 byte %8.0g rep78== 2.0000 rep783 byte %8.0g rep78== 3.0000 rep784 byte %8.0g rep78== 4.0000 rep785 byte %8.0g rep78== 5.0000 ``` That's all the dummies (some prefer to say "indicators") in one fell swoop through an option of `tabulate`. For completeness, consider an example doing it the loop way. We imagine that years 1950-2015 are represented: ``` forval y = 1950/2015 { gen byte dummy`y' = year == `y' } ``` Two digit identifiers `dummy50` to `dummy15` would be unambiguous in this example, so here they are as a bonus: ``` forval y = 1950/2015 { local Y : di %02.0f mod(`y', 100) gen byte dummy`y' = year == `y' } ``` Here `byte` is dispensable unless memory is very short, but it's good practice any way. If anyone was determined to write a loop to create indicators for the distinct values of a string variable, that can be done too. Here are two possibilities. Absent an easily reproducible example in the original post, let's create a sandbox. The first method is to `encode` first, then loop over distinct numeric values. The second method is find the distinct string values directly and then loop over them. ``` clear set obs 3 gen mystring = word("frog toad newt", _n) * Method 1 encode mystring, gen(mynumber) su mynumber, meanonly forval j = 1/`r(max)' { gen dummy`j' = mynumber == `j' label var dummy`j' "mystring == `: label (mynumber) `j''" } * Method 2 levelsof mystring local j = 1 foreach level in `r(levels)' { gen dummy2`j' = mystring == `"`level'"' label var dummy2`j' `"mystring == `level'"' local ++j } describe Contains data obs: 3 vars: 8 size: 96 ------------------------------------------------------------------------------ storage display value variable name type format label variable label ------------------------------------------------------------------------------ mystring str4 %9s mynumber long %8.0g mynumber dummy1 float %9.0g mystring == frog dummy2 float %9.0g mystring == newt dummy3 float %9.0g mystring == toad dummy21 float %9.0g mystring == frog dummy22 float %9.0g mystring == newt dummy23 float %9.0g mystring == toad ------------------------------------------------------------------------------ Sorted by: ```
47,476,145
what i am trying to achieve is this, when the userMarker be inside the visible bounds accomplish some actions, for that this is my code. ``` let screenWidth: Float = Float((map.frame.size.width)) let screenHeight: Float = Float((map.frame.size.height)) let minScreenPos: NTScreenPos = NTScreenPos(x: 0.0, y: 0.0) let maxScreenPos: NTScreenPos = NTScreenPos(x: screenWidth, y:screenHeight) let minPosWGS = projection.fromWgs84(map.screen(toMap: minScreenPos))! let maxPosWGS = projection.fromWgs84(map.screen(toMap: maxScreenPos))! let mapBounds = NTMapBounds(min: minPosWGS, max: maxPosWGS) let markerCenter = projection.fromWgs84(userMarker.getBounds().getCenter()) let markerBounds = userMarker.getBounds() let containPos = mapBounds!.contains(markerCenter) let containBounds = mapBounds!.contains(markerBounds) print(containPos) print(containBounds) ``` But always the output is false, what i am doing wrong, any help, please.
2017/11/24
[ "https://Stackoverflow.com/questions/47476145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5518031/" ]
Alright, there are several things here.... **Firstly**, when are you doing your `screenToMap` calculation? It will return 0 when your `mapView` hasn't fully rendered yet (even if your mapView already has a frame). So you definitely cannot do it in our `viewDidLoad` or `viewWillAppear`, but, currently, also not after `layoutSubviews`. You need to calculate it after your map has rendered, this can be achieved using `mapRenderer`'s `onMapRendered` event. Example available here: <https://github.com/CartoDB/mobile-ios-samples/blob/master/AdvancedMap.Objective-C/AdvancedMap/CaptureController.mm> We created an issue concerning this: <https://github.com/CartoDB/mobile-sdk/issues/162> **Secondly**, if you ask for coordinates from CartoMobileSDK's method, coordinates are already returned in our internal coordinate system, meaning that you don't need to do any additional conversion. The correct way to ask for bounds and position would be: ``` let minPosWGS = map.screen(toMap: minScreenPos)! let maxPosWGS = map.screen(toMap: maxScreenPos)! ``` and: ``` let markerCenter = userMarker!.getBounds().getCenter() ``` **Thirdly**, `X` increases **from left to right** on your screen, as well as on your map, however, `Y` increases **from top to bottom** on your screen, but **from bottom to top** on your map, so you'd have to initialize min and max as such: ``` let screenWidth = Float(map.frame.size.width) let screenHeight = Float(map.frame.size.height) let minScreenPos = NTScreenPos(x: 0.0, y: screenHeight) let maxScreenPos = NTScreenPos(x: screenWidth, y: 0) ``` Please note that this calculation also depends on your view's orientation and map rotation. Currently we assume that your rotation is 0 and your view is in portrait mode. **And finally**, iOS uses scaled coordinates, but Carto's Mobile SDK expects true coordinates. So you need to multiply your values by scale: ``` let screenWidth = Float(map.frame.size.width * UIScreen.main.scale) let screenHeight = Float(map.frame.size.height * UIScreen.main.scale) ```
74,639,356
I get a timeout when trying to connect to my newly set up amazon redshift database. I tried telnet: ``` telnet redshift-cluster-1.foobar.us-east-1.redshift.amazonaws.com 5439 ``` With the same result. I set the database configuration to "Publicly accessible". Note that I am just experimenting. I have set up aws services for fun before, but don't have much knowledge of the network and security setup. So I expect it to be a simple mistake I make. I want to keep it simple, so my goal is just to connect to the database from a local SQL client and I don't care about anything else at this stage :) It would be great if you could give me some pointers for me to understand what the problem could be and what I should try next. [![subnets](https://i.stack.imgur.com/mkX7d.png)](https://i.stack.imgur.com/mkX7d.png)
2022/12/01
[ "https://Stackoverflow.com/questions/74639356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2474025/" ]
I had to add a new inbound rule to the security group and set the source to "anywhere-ipv4" or "my ip". The default inbound rule has a source with the name of the security group itself, which might mean that it is only accessible from within the VPC. At least it is not accessible from the outside. I set the protocol to tcp and type to redshift, which seemed like the sensible choice for my use case. See the picture for a sample configuration. [![enter image description here](https://i.stack.imgur.com/QXRq2.png)](https://i.stack.imgur.com/QXRq2.png)
63,485,869
I want to group a `data.table` but use a different name for the grouping variable in the final output. ### Data ```r library(data.table) set.seed(1) d <- data.table(grp = sample(4, 100, TRUE)) ``` ### Options I can use chaining like this: ```r d[, .(Frequency = .N), keyby = grp][ , .("My Fancy Group Name" = grp, Frequency)] # My Fancy Group Name Frequency # 1: 1 27 # 2: 2 31 # 3: 3 22 # 4: 4 20 ``` or rename the column before: ```r d[, c("My Fancy Group Name" = list(grp), .SD)][ , .(Frequency = .N), keyby = "My Fancy Group Name"] # My Fancy Group Name Frequency # 1: 1 27 # 2: 2 31 # 3: 3 22 # 4: 4 20 ``` or define an alias for the grouping variable and remove the grouping variable afterwards: ```r d[, .("My Fancy Group Name" = grp, Frequency = .N), keyby = grp][ , grp := NULL][] # My Fancy Group Name Frequency # 1: 1 27 # 2: 2 31 # 3: 3 22 # 4: 4 20 ``` but all forms use a chain. I can avoid the chaining by [the not recommended approach from here](https://stackoverflow.com/questions/47497386/remove-grouping-variable-for-data-table) (which is not only a hack, but very inefficient on top): ``` d[, .("My Fancy Group Name" = .SD[, .N, keyby = grp]$grp, Frequency = .SD[, .N, keyby = grp]$N)] # My Fancy Group Name Frequency # 1: 1 27 # 2: 2 31 # 3: 3 22 # 4: 4 20 ``` ### Questions Conceptually I would like to use something like this ```r # d[, .(Frequency = .N), keyby = c("My Fancy Group Name" = grp)] ``` 1. Is it possible to achieve the solution chain free not using the hack I showed? 2. Which option performs "best" in terms of memory/time if we have a huge `data.table`?
2020/08/19
[ "https://Stackoverflow.com/questions/63485869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4125751/" ]
You can actually do similar to your attempt but use `list` instead of `c` : ``` library(data.table) d[, .(Frequency = .N), keyby = list(`My Fancy Group Name` = grp)] #Also works with quotes #d[, .(Frequency = .N), keyby = list("My Fancy Group Name" = grp)] # My Fancy Group Name Frequency #1: 1 27 #2: 2 31 #3: 3 22 #4: 4 20 ``` Shorter version : ``` d[, .(Frequency = .N), .("My Fancy Group Name" = grp)] ```
33,764,325
I'm pretty new to Python programming, just started this year. I'm currently doing a project surrounding functions within python and i'm getting stuck. Heres what I have done so far but it gets stuck around the 3rd definition. ``` def userWeight(): weight = input("Enter your weight in pounds:") def userHeight(): height = input("Enter your height in inches:") def convertWeightFloat(weight): return float(weight) weight = float(weight) def convertHeightFloat(hf): return float(height) def calculateBMI(): BMI = (5734 * weight_float) / (height_float**2.5) return BMI def displayBMI(): print("Your BMI is:",BMI) def convertKG(): return weight_float * .453592 def convertM(): return height_float * .0254 def calculateBMImetric(): return 1.3 * weight_kg / height_meters**2.5 def displayMetricBMI(): print("Your BMI using Metric calculations is: ", BMImetric) def main(): userWeight() userHeight() convertWeightFloat(weight) convertHeightFloat() calculateBMI() displayBMI() convertKG() convertM() calculateBMImetric() displayMetricBMI() main() ``` And here is the error message I get whenever I try to run it... ``` Enter your weight in pounds:155 Enter your height in inches:70 Traceback (most recent call last): File "C:/Users/Julian/Desktop/Python Stuff/ghp17.py", line 45, in <module> main() File "C:/Users/Julian/Desktop/Python Stuff/ghp17.py", line 36, in main convertWeightFloat(weight) NameError: name 'weight' is not defined ``` Now I've probably tried several different things each of them giving me different errors. Any help guys?
2015/11/17
[ "https://Stackoverflow.com/questions/33764325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5573398/" ]
There are a few problems here. At first, you call `convertWeightFloat(weight)` while `weight` has not been defined. That's because `weight` only exists within your function `userWeight` (it's called the scope of the function). If you want `weight` to be known in the main part of your program, you need to define it there. ``` weight = userWeight() ... ``` This only works if your function `userWeight` returns a value: ``` def userWeight(): weight = input("Enter your weight in pounds:") return weight ``` Same problem with `height`. Also, in the function `convertWeightFloat`, the return statement is the last thing that will be executed. After that line, the program exits the function, in such a way that the last line is never executed: ``` def convertWeightFloat(weight): weight = float(weight) return weight ``` Basically, every variable you use inside the functions should be provided to the function (most of the time as arguments). And all your functions should return the processed value. Here is a working version of your program: ``` def userWeight(): weight = input("Enter your weight in pounds:") return weight def userHeight(): height = input("Enter your height in inches:") return height def convertWeightFloat(weight): return float(weight) def convertHeightFloat(height): return float(height) def calculateBMI(weight_float, height_float): BMI = (5734 * weight_float) / (height_float**2.5) return BMI def displayBMI(BMI): print("Your BMI is:",BMI) def convertKG(weight_float): return weight_float * .453592 def convertM(height_float): return height_float * .0254 def calculateBMImetric(weight_kg, height_meters): return 1.3 * weight_kg / height_meters**2.5 def displayMetricBMI(BMImetric): print("Your BMI using Metric calculations is: ", BMImetric) def main(): weight = userWeight() height = userHeight() weight_float = convertWeightFloat(weight) height_float = convertHeightFloat(height) bmi = calculateBMI(weight_float, height_float) displayBMI(bmi) ```
35,598,671
I have the following header I am trying to code responsively using Twitter Bootstrap: [![enter image description here](https://i.stack.imgur.com/3DIeA.jpg)](https://i.stack.imgur.com/3DIeA.jpg) Now for the purple menu bar I am going to use a navbar. However, for the content above, I am really trying to determine the best approach. I am stuck between using media or pull-left and pull-right. I am really unsure what the best approach for this would be. Any recommendations as to the proper way of coding this using Bootstraps built in classes would be appreciated. Please note that only the logo would be an image, everything else would use fonts and font icons.
2016/02/24
[ "https://Stackoverflow.com/questions/35598671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5645843/" ]
***EDIT*** Use [Volley](https://stackoverflow.com/a/32093822/1921263) if httpclient you can't find. Moreover parsing script is same which mentioned below. I already written a [Blog](http://shadowhelios.blogspot.in/2014/10/hot-to-load-json-file-and-display.html). Refer that. Hope it helps. Let me clone my blog to match your requirement. Please use proper naming for that. Here is parsing output. ``` public class GridUI extends Activity { ArrayList<Persons> personsList; GridView gridView; GridAdapter gridAdapter; private static final String url="http://www.zippytrailers.com/funlearn/topicsMap"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.gridview); personsList= new ArrayList<Persons>(); new JSONAsyncTask().execute(url); gridView=(GridView)findViewById(R.id.gridview); gridAdapter = new GridAdapter(this, R.layout.gridview_row, personsList); gridView.setAdapter(gridAdapter); } class JSONAsyncTask extends AsyncTask<String, Void, Boolean> { ProgressDialog dialog; @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); dialog=new ProgressDialog(GridUI.this); dialog.setMessage("Loading, please wait"); dialog.setTitle("Connecting server"); dialog.show(); dialog.setCancelable(false); } @Override protected Boolean doInBackground(String... urls) { try { //------------------>> HttpGet httppost = new HttpGet(urls[0]); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httppost); // StatusLine stat = response.getStatusLine(); int status = response.getStatusLine().getStatusCode(); if(status==200){ HttpEntity entity = response.getEntity(); String data = EntityUtils.toString(entity); JSONObject jsono=new JSONObject(data); JSONArray jarray = jsono.getJSONArray("results"); for (int i = 0; i < jarray.length(); i++) { JSONObject object = jarray.getJSONObject(i); Persons name = new Persons(); name.setName(object.getString("syllabus")); name.setDescription(object.getString("grade")); name.setDob(object.getString("subject")); name.setCountry(object.getString("topic")); name.setHeight(object.getString("id")); personsList.add(name); } return true; } } catch (ParseException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return false; ``` } ``` @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); dialog.cancel(); gridAdapter.notifyDataSetChanged(); if(result == false) Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show(); } } ```
53,061,169
I have a piece of code that is used to split up the text in a cell. The data is outputted by a survey program that doesn't make use of any useful delimiter, so unfortunately converting text to columns isn't of any help to me. I wrote this piece of code, but it turns out that the outcomes are different in two cases. 1. I run the code step by step until the first column is added, and then let it finish 2. I run the code from the execute macro's menu In the first case the output is as I designed it to be. After a column with the header `Crop: XXX` (Which contains the raw data that needs to be split) there are columns for each separate entry numbered 1 to X. Data from every row starts to be split in column X and then moves as far as there are entries. Like this: ``` | Crop XXX | 1 | 2 | 3 | 4 | |-------------|----|----|----|----| | X1,X2,X3 | X1 | X2 | X3 | | | X1,X2,X3,X4 | X1 | X2 | X3 | X4 | ``` In the second case all columns are numbered 1, and every new row enters its data before the data of the previous row. Like such: ``` | Crop XXX | 1 | 1 | 1 | 1 | 1 | 1 | 1 | |-------------|----|----|----|----|----|----|----| | X1,X2,X3 | | | | | X1 | X2 | X3 | | X1,X2,X3,X4 | X1 | X2 | X3 | X4 | | | | ``` The code I use to input and number these columns is this: ``` If Not UBound(inarray) = 0 Then For i = UBound(inarray) To LBound(inarray) Step -1 If ws.Cells(1, col + i).Value = i Then If i = UBound(inarray) Then Exit For End If col_to_add = col + i + 1 Exit For Else addcol = addcol + 1 End If col_to_add = col + i Next i If Not i = UBound(inarray) Then col1 = ConvertToLetter(col_to_add) col2 = ConvertToLetter(col_to_add + addcol - 1) ws.Columns(col1 & ":" & col2).Insert shift:=xlToRight End If If Not addcol = 0 Then For j = 1 To addcol If col_to_add = col + j Then If j = 1 Then ws.Cells(1, col_to_add) = 1 Else ws.Cells(1, col_to_add + j - 1) = Cells(1, col_to_add + j - 2).Value + 1 End If Else ws.Cells(1, col_to_add + j - 1) = Cells(1, col_to_add + j - 2).Value + 1 End If Next j End If For k = UBound(inarray) To LBound(inarray) Step -1 ws.Cells(row, col + k) = inarray(k) Next k End If ``` In this example `Inarray()` is a 1d array containing the below values for the first row: ``` | Inarray() | Value | |-----------|-------| | 1 | X1 | | 2 | X2 | | 3 | X3 | ``` `ConvertToLetter` is the following function: ``` Function ConvertToLetter(iCol As Integer) As String Dim vArr vArr = Split(Cells(1, iCol).Address(True, False), "$") ConvertToLetter = vArr(0) End Function ``` **Could anyone point out why this difference occurs between scenario 1 and 2?** Usually these things happen when objects aren't fully classified, but I thought I tackled that problem this time.
2018/10/30
[ "https://Stackoverflow.com/questions/53061169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1481116/" ]
The difference is because the `Cells` and the `Range` are not fully qualified. Thus, when you go step-by-step you are also selecting the correct worksheet and automatically you are not. Whenever you have something like this: ``` ws.Cells(1, col_to_add + j - 1) = Cells(1, col_to_add + j - 2).Value + 1 ``` make sure that you always write the `Worksheet` before the `Cells()` like here - `ws.Cells`. Or before the range - `ws.Range()`. Otherwise it takes the `ActiveSheet` or the sheet where the code is (if not in a module). * [A similar issue with screenshot explanation](https://stackoverflow.com/a/50465557/5448626)
47,550,350
This is a rather simple question but somehow my code either takes long time or consumes more resource. It is a question asked in www.codewars.com which I use for R Programming practice. Below are the two versions of the problem I coded: Version 1 : =========== ``` f <- function(n, m){ # Your code here if(n<=0) return(0) else return((n%%m)+f((n-1),m)) } ``` Version 2: ========== ``` #Function created to calculate the sum of the first half of the vector created calculate_sum <- function(x,y){ sum = 0 for(i in x){ sum = sum + i%%y } return(sum) } #Main function to be called with a test call f <- function(n, m){ # Your code here #Trying to create two vectors from the number to calculate the sum #separately for each half if(n%%2==0){ first_half = 1:(n/2) second_half = ((n/2)+1):n } else { first_half = 1:floor(n/2) second_half = (ceiling(n/2)):n } sum_first_half = calculate_sum(first_half,m) sum_second_half = 0 for(j in second_half){ sum_second_half = sum_second_half+(j%%m) } return(sum_first_half+sum_second_half) } ``` I am trying to figure out a way to optimize the code. For the first version it gives the following error message: > > Error: C stack usage 7971184 is too close to the limit > Execution halted > > > For the second version it says my code took more than 7000 ms and hence was killed. Can someone give me a few pointers on how to optimize the code in R??
2017/11/29
[ "https://Stackoverflow.com/questions/47550350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7459047/" ]
The optimisation is mathematical, not programmatical (though as others have mentioned, loops are *slow* in R.) Firstly, note that `sum(0:(m-1)) = m*(m-1)/2`. You are being asked to calculate this `n%/%m` times, and add a remainder of `(n - n%/%m)(n - n%/%m + 1)/2`. So you might try ``` f <- function(n,m){ k <- n%/%m r <- n - k*m return(k*m*(m-1)/2 + r*(r+1)/2) } ``` which is a much less complex calculation, and will not take very long regardless of how large n or m is. There is a risk that, if `n` is greater than 2^53 and `m` does not have enough powers of 2 in its factorisation, there will not be enough precision to calculate `k` and `r` accurately enough.
36,173,831
I have the follwing simple MySQL query that returns 0 results: ``` SELECT d.name FROM document d WHERE 10 IN (d.categories) ``` "categories" is of type varchar and contains for example "10,20,30". When I type the IN values directly it works and returns a result: ``` SELECT d.name FROM document d WHERE 10 IN (10,20,30) ``` I suspect MySQL substitutes d.documents with something like this which of course is not what I want: ``` SELECT d.name FROM document d WHERE 10 IN ("10,20,30") ``` What is a proper workaround for this?
2016/03/23
[ "https://Stackoverflow.com/questions/36173831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/757218/" ]
When you are providing the value as "10,20,30" then it is treated as a single value as against your expected three distinct values. To make the value as three distinct values you need to use the [find\_in\_set](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set) function in MySQL. Also I would suggest you to go through this thread: [Is storing a delimited list in a database column really that bad?](https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad)
65,948,015
I have a variable where the user inputs one number. That variable is of type `int` because that's the return value of `fgetc(stdin)` and `getchar()`. In this case, I'm using `fgetc(stdin)`. After the user inputs the number, I would like to convert it to an integer with `strtol()`, however, I get a warning about an incompatible integer to pointer conversion because of `strtol()`'s first argument being a `const char *`. Here is the code: ``` int option; char *endptr; int8_t choice; printf("=========================================Login or Create Account=========================================\n\n"); while(1) { printf("Welcome to the Bank management program! Would you like to 1. Create Account or 2. Login?\n>>> "); fflush(stdout); option = fgetc(stdin); choice = strtol(option, &endptr, 10); ``` Does anyone know how to get around this?
2021/01/29
[ "https://Stackoverflow.com/questions/65948015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13716610/" ]
`strtol` is used to convert a "string" into `long`, not a single char. You just need `choice = option - '0'` to get the value. But you don't actually need to convert because you can directly switch on the char value ``` switch (option) { case '1': // ... break; case '2': // ... break; } ``` If you really want to call `strtol` then you must make a string ``` char[2] str; str[0] = option; str[1] = 0; // null terminator choice = strtol(str, &endptr, 10); ```
25,900,333
I've already set the maxLength attribute for an EditText widget in the xml layout file, and it does limit the display of characters. But it still allows the user to press more letters on the keyboard, and backspacing deletes these extra presses rather than the last letter on the display. I believe this is not how it's supposed to be. Pressing keys after the limit has been reached should stop accepting more input even if it is not displayed. Any fix on this? **Update** Based on the answer below, for multiline EditText, add the textMultiLine attribute too. ``` android:inputType="textFilter|textMultiLine" ```
2014/09/17
[ "https://Stackoverflow.com/questions/25900333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3893122/" ]
1. Disable auto-suggestions(`android:inputType="textFilter"` or `textNoSuggestions`): 2. Set maxLength ``` <EditText android:id="@+id/editText" android:inputType="textFilter" android:maxLength="8" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` I hope, it helps
93,442
Is there any way to index the following query? ``` SELECT run_id, MAX ( frame ) , MAX ( time ) FROM run.frames_stat GROUP BY run_id; ``` I've tried creating sorted (non-composite) indexes on `frame` and `time`, and an index on `run_id`, but the query planner doesn't use them. Misc info: * Unfortunately (and for reasons I won't get into) I cannot change the query * The `frames_stat` table has 42 million rows * The table is unchanging (no further inserts/deletes will ever take place) * The query was always slow, it's just gotten slower because this dataset is larger than in the past. * There are no indexes on the table * We are using Postgres 9.4 * The db's "work\_mem" size is 128MB (if that's relevant). * Hardware: 130GB Ram, 10 core Xeon Schema: ``` CREATE TABLE run.frame_stat ( id bigint NOT NULL, run_id bigint NOT NULL, frame bigint NOT NULL, heap_size bigint NOT NULL, "time" timestamp without time zone NOT NULL, CONSTRAINT frame_stat_pkey PRIMARY KEY (id) ) ``` Explain analyze: ``` HashAggregate (cost=1086240.000..1086242.800 rows=280 width=24) (actual time=14182.426..14182.545 rows=280 loops=1) Group Key: run_id -> Seq Scan on zulu (cost=0.000..770880.000 rows=42048000 width=24) (actual time=0.037..4077.182 rows=42048000 loops=1) ```
2015/02/20
[ "https://dba.stackexchange.com/questions/93442", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/59983/" ]
### Too bad If you cannot change the query at all, that's **too bad**. You won't get a good solution. If you had not table-qualified the table (**`run.`**`frames_stat`), you could create a materialized view (see below) with the same name in another schema (or just a temporary one) and adapt the [`search_path`](https://stackoverflow.com/a/9067777/939860) (optionally just in sessions where this is desirable) - for hugely superior performance. Here's a recipe for such a technique: * [How can I fake inet\_client\_addr() for unit tests in PostgreSQL?](https://dba.stackexchange.com/questions/69988/how-can-i-fake-inet-client-addr-for-unit-tests-in-postgresql/70009#70009) [@Joishi's idea](https://dba.stackexchange.com/a/93443/3684) with a `RULE` would be a measure of (desperate) last resort. But I would rather not go there. Too many pitfalls with unexpected behavior. Better query / indexes ---------------------- If you could change the query, you should try to emulate a loose index scan: * [Optimize GROUP BY query to retrieve latest record per user](https://stackoverflow.com/a/25536748/939860) This is even more efficient when based on a separate **table with one row per relevant `run_id`** - let's call it `run_tbl`. Create it if you don't have it, yet! Implemented with correlated subqueries: ``` SELECT run_id , (SELECT frame FROM run.frames_stat WHERE run_id = r.run_id ORDER BY frame DESC NULLS LAST LIMIT 1) AS max_frame , (SELECT "time" FROM run.frames_stat WHERE run_id = r.run_id ORDER BY "time" DESC NULLS LAST LIMIT 1) AS max_time FROM run_tbl r; ``` Create two [multicolumn indexes](https://www.postgresql.org/docs/current/indexes-multicolumn.html) with matching sort order for *lightening* performance: ``` CREATE index fun_frame_idx ON run.frames_stat (run_id, frame DESC NULLS LAST); CREATE index fun_frame_idx ON run.frames_stat (run_id, "time" DESC NULLS LAST); ``` `NULLS LAST` is only necessary if there *can* be null values. But it won't hurt either way. * [Unused index in range of dates query](https://dba.stackexchange.com/questions/90128/unused-index-in-range-of-dates-query/90183#90183) With only 280 distinct `run_id`, this will be *very* fast. MATERIALIZED VIEW ----------------- Or, based on these key pieces of information: > > The "frames\_stat" table has 42 million rows > > > > > rows=280 -- number of returned rows = disctinct run\_id > > > > > The table is unchanging (no inserts/deletes) > > > Use a [**`MATERIALIZED VIEW`**](https://www.postgresql.org/docs/current/sql-creatematerializedview.html), it will be tiny (only 280 rows) and super fast. You still need to change the query to base it on the MV instead of the table. Aside: never use [reserved words](https://www.postgresql.org/docs/current/sql-keywords-appendix.html) like `time` (in standard SQL) as identifier.
5,069,239
``` setcookie("cookie1", "", 0, "/",".domain.com"); setcookie("cookie2", "", 0, "/",".domain.com"); header('Location: /index.php'); ``` It doesn't delete cookie1 and cookie2. Why is that?
2011/02/21
[ "https://Stackoverflow.com/questions/5069239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/237681/" ]
An expiration time of 0 is a special value which means the cookie will be deleted when the browser is closed. To delete it immediately, you need to give a valid expiration time in the past. An example from the [PHP docs](http://php.net/manual/en/function.setcookie.php): ``` // set the expiration date to one hour ago setcookie ("TestCookie", "", time() - 3600); ```
40,881,166
I am working in child theme and put following code for admin ajax js ``` function wpb_adding_scripts() { /* echo "string". get_stylesheet_directory_uri().'/css/jquery.bxslider.css'; exit();*/ wp_register_script('flexslider', get_stylesheet_directory_uri() . '/js/jquery.flexisel.js', array('jquery'),'1.1', true); wp_enqueue_script('flexslider'); wp_enqueue_script('bxslider', get_stylesheet_directory_uri() . '/js/jquery.bxslider.min.js', array(),true, true); wp_enqueue_script('bxslider'); wp_enqueue_script('custom', get_stylesheet_directory_uri() . '/js/custom.js', array(),true, true); wp_enqueue_script('custom'); //wp_localize_script('admin_script', 'ajaxurl', admin_url( 'admin-ajax.php' ) ); wp_localize_script('admin_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ))); wp_enqueue_script( 'jquery' ); wp_enqueue_script('admin_script'); } add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts', 999 ); ``` but it given me error like ``` ReferenceError: myAjax is not defined url : myAjax.ajaxurl, ``` I used myAjax declaration in my custom js.. ``` jQuery('#load_more_posts').on('click',function(){ var lng =jQuery(".post_item").length; jQuery.ajax({ type : "post", url : myAjax.ajaxurl, data : {action: "load_more_posts_home",count : lng}, }).done(function(response){ var posts = JSON.parse(response); for( var i = 0; i < posts.length; i++ ) { if( posts[i] == "0" ) jQuery("#load_more_posts").fadeOut(); else jQuery("#load_more_posts").before(posts[i]); } }); }); ``` so how could i resolve this issue in my wordpress child theme.
2016/11/30
[ "https://Stackoverflow.com/questions/40881166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7034664/" ]
Try this: ``` wp_enqueue_script('custom'); //Name of the script. Should be unique.here is 'custom' wp_localize_script('custom', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ))); // remove admin_script and add unique javascript file. ``` Here above code localized the object:'myAjax' in script "custom". and you can access property "ajax\_url" by adding below code in custom script file. in **custom.js** ``` alert(myAjax.ajaxurl); ```
144,036
I have an [IKEA desk](https://www.ikea.com/us/en/catalog/products/S49932175/#/S59133593) with a subtle fake wood grain paint layer (black) on the surface. The paint in the area that my mouse moves has worn away leaving a shiny textureless surface that the laser mouse doesn't detect. What's the simplest, cheapest, most effective way to re-surface that region (or the whole desk)? I don't like mouse mats. I'm thinking wallpaper or paint, but I don't know what types of paint will provide the surface required for the laser mouse to accurately detect movement.
2018/07/27
[ "https://diy.stackexchange.com/questions/144036", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/89230/" ]
Shelf liner (contact paper). Cut it into an oversize mouse pad shape with rounded corners and stick it down. You want it large enough that you aren't snagging the edge with your arm, keyboard, etc. It'll feel like nothing but give your mouse a better view. You could use black so it's not so conspicuous, but a bold color pattern might be spiffy. Change it out when it gets polished or worn.
4,144,491
> > If $a$ is a positive integer and $p$ is prime, then $\log\_{p}(a)$ is rational if and only if $a$ is a power of $p$. > > > We are asked to used the fundamental theorem of arithmetic to prove this statement. I began my proof as follows: --- "Let's assume that $\log\_pa$ is rational, and that $\log\_pa=x$, for a positive integer $x$. By the definition of a logarithm, we know that $p^x=a$, meaning that $a$ is a product of $p$ times itself $x$ times. This suggests that the only prime factor of $a$ is $p$. By the fundamental theorem of arithmetic, we can conclude that $a$ is an integer because it has a unique prime factorization." --- I'm not sure if this makes sense, or how to proceed. Thank you for your assistance.
2021/05/19
[ "https://math.stackexchange.com/questions/4144491", "https://math.stackexchange.com", "https://math.stackexchange.com/users/929471/" ]
This is a reasonable outline to start with. The major problem with what you've written is that you assume that $\log\_pa$ is rational and then assign an integer value to it. You should actually say that there are relatively prime integers $x,y\in\mathbb Z$ such that $\log\_pa=\frac xy$ and then show that it must be that $y=1$. Your strategy of thinking about the prime factorization of $a$ is a good idea here that will help you here. You also need to note that you are asked to prove the equivalence of the statements, so you also need to prove the converse of the statement you proved. This is not difficult, but it is essential in "if and only if" proofs.
24,992,036
I have a simple factory that returns a promise after a async.-request. ``` getUpdates: function(){ var q = $q.defer(); $http.get(...) .success(function(data, status, headers, config) { q.resolve(data); }) .error(function(data, status, headers, config) { q.reject(status); }); return q.promise; } ``` In my controller I just call the getUpdates-method and receive the promise. ``` var updates = factory.getUpdates(); ``` How can I provide a success/error functionality of the getUpdates method? ``` factory.getUpdates().success(function(promise){...}).error(function(err)... ``` What do I have to add to my getUpdates function?
2014/07/28
[ "https://Stackoverflow.com/questions/24992036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2329592/" ]
The `$http` service already return a promise, there is no need to use `$q.defer()` to create an another promise in this case. You could just write it like this: ``` getUpdates: function () { return $http.get(...); } ``` This way the `success()` and `error()` methods will still be available. Or if you really have a reason why you are using `$q.defer()`, please include it in the question.
50,897,066
I'm developing an Electron application and I aim to 'split up' `index.js` (main process) file. Currently I have put my menu bar-related and Touch Bar-related code into two separate files, `menu.js` and `touchBar.js`. Both of these files rely on a function named `redir`, which is in `index.js`. Whenever I attempt to activate the `click` event in my Menu Bar - which relies on `redir` - I get an error: `TypeError: redir is not a function`. This also applies to my Touch Bar code. Here are my (truncated) files: `index.js` ``` const { app, BrowserWindow } = require('electron'); // eslint-disable-line const initTB = require('./touchBar.js'); const initMenu = require('./menu.js'); ... let mainWindow; // eslint-disable-line // Routing + IPC const redir = (route) => { if (mainWindow.webContents) { mainWindow.webContents.send('redir', route); } }; module.exports.redir = redir; function createWindow() { mainWindow = new BrowserWindow({ height: 600, width: 800, title: 'Braindead', titleBarStyle: 'hiddenInset', show: false, resizable: false, maximizable: false, }); mainWindow.loadURL(winURL); initMenu(); mainWindow.setTouchBar(initTB); ... } app.on('ready', createWindow); ... ``` `menu.js` ``` const redir = require('./index'); const { app, Menu, shell } = require('electron'); // eslint-disable-line // Generate template function getMenuTemplate() { const template = [ ... { label: 'Help', role: 'help', submenu: [ { label: 'Learn more about x', click: () => { shell.openExternal('x'); // these DO work. }, }, ... ], }, ]; if (process.platform === 'darwin') { template.unshift({ label: 'Braindead', submenu: [ ... { label: 'Preferences...', accelerator: 'Cmd+,', click: () => { redir('/preferences'); // this does NOT work }, } ... ], }); ... }; return template; } // Set the menu module.exports = function initMenu() { const menu = Menu.buildFromTemplate(getMenuTemplate()); Menu.setApplicationMenu(menu); }; ``` My file structure is simple - all three files are in the same directory. Any code criticisms are also welcome; I've spent hours banging my head trying to figure all this out.
2018/06/17
[ "https://Stackoverflow.com/questions/50897066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3991859/" ]
`redir` it is not a function, because you're exporting an object, containing a `redir` property, which is a function. So you should either use: ``` const { redir } = require('./index.js'); ``` Or export it this way ``` module.exports = redir ``` When you do: `module.exports.redir = redir;` You're exporting: `{ redir: [Function] }`
11,860,855
To create buttons in the SDL Tridion ribbon toolbar, where can we find the extension related information (like the config file, js files) of already existing controls like Check-in, Check-out, Undo Check-out so we can use them as a reference?
2012/08/08
[ "https://Stackoverflow.com/questions/11860855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1544948/" ]
Parts of the configuration are in the `..\Tridion\web\WebUI\Editors\CME\Configuration\CME.config`, the rest is in the `..\Tridion\web\WebUI\WebRoot\Configuration\System.config` I believe. The ASPX, CSS and JS files are all located in `..\Tridion\web\WebUI\Editors\CME`, interesting paths to follow there are the `Views` and the `Views\Popups` but also the `Controls` might contain useful items for you to investigate.
133,701
There is kind of a risk gaining an access to personal data or some way getting debts with a passport. Is there a chance someone can read biometric RFID data from an international passport, like fingerprints or a photograph?
2019/03/12
[ "https://travel.stackexchange.com/questions/133701", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/68847/" ]
The RFID chip in a biometric passport can be convinced to communicate all the data stored therein if the right keys are provided to it. Note it’s not a matter of downloading encrypted data from the chip and then having a go at it with decryption tools of some kind; the communication with the chip is bi-directional and authentication has to be provided first. The core data such as name and the photograph are secured by Basic Access Control, where the key can be derived from machine readable data visible on the passport itself. In essence, after viewing the passport, it’s possible to download the same data you’ve just seen, plus the digital signature of the issuing authority confirming it’s genuine. There’s also Extended Access Control, where the idea is that more sensitive data such as fingerprints is protected by keys that the issuing authority only provides to parties such as other countries’ immigration departments. Thus any random person who knows the document number, the owner’s birth date and the passport’s expiry date (that’s what comprises the BAC key) can use this to read basic data and download the photo (there are multiple Android apps that do just this), while it’s not possible to take a powerful scanner to an airport and load lots of passports of passers-by. Downloading the fingerprints and other such data requires special keys which are, in theory, distributed by some secure channels among proper authorities. I’ve heard, without proof, that this process involves many hurdles and my country (Ukraine) simply hasn’t shared such keys with any other countries.
10,306,328
``` class LogUtil<T> : ILogUtility { log4net.ILog log; public LogUtil() { log = log4net.LogManager.GetLogger(typeof(T).FullName); } public void Log(LogType logtype, string message) { Console.WriteLine("logging coming from class {0} - message {1} " , typeof(T).FullName, message); } } public class Logger { ILogUtility _logutility; public Logger(ILogUtility logutility) { _logutility = logutility; } public void Log(LogType logtype, string message) { _logutility.Log(logtype, message); } } ``` I need to have the functionality to be flexible and have the ability to remove the LogUtil class in the future and use some thing else. So I write LoggerUtility wrapper class as follows: ``` class LoggerUtility<T> { Logger logger; public LoggerUtility() { LogUtil<T> logutil = new LogUtil<T>(); logger = new Logger(logutil); } public void Log(LogType logtype, string message) { logger.Log(logtype, message); } } ``` My client code as follows: ``` public class TestCode { public void test() { new LoggerUtility<TestCode>().Log(LogType.Info, "hello world"); } } ``` To get loose coupling from LogUtil, I end up writing 2 wrapper classes Logger and LoggerUtility. So in the future, if I have to add another method in the ILogUtility, I would have to add that method to Logger class and then LoggerUtility. What is the best way to write LoggerUtility so that I could write the client code as follows: ``` new LoggerUtility<TestCode>().Log(LogType.Info, "hello world"); ``` Please let me know. Thanks
2012/04/24
[ "https://Stackoverflow.com/questions/10306328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71422/" ]
It looks like you're adding a level of abstraction where there really doesn't need to be one. If we start with your end result, LoggerUtility just needs to have an interface that it can use to log things based on the `LogType` parameter. Your `Logger` class, as its currently written, is just a thin wrapper around the `ILogUtility` interface. So why bother adding that layer? Why can't the `Logger` class use an `ILogUtility` instance directly? You could even go one step further and define your interface as `ILogUtility<T>` and know that when you create a `LoggerUtility<Foo>` that the instance of the logger it will use will be based on the Foo class. But honestly, I think you may just be reinventing the wheel here. Take a look at [Common Logging for .NET](http://netcommon.sourceforge.net/). It will probably ease what you're trying to do and make more sense in the long run.
55,535,138
I have a homework to do in Python class and was given this question: > > Make a program that gets 2 numbers from the user, and prints all even > numbers in the range of those 2 numbers, you can only use as many for > statements as you want, but can't use another loops or if statement. > > > I understand that I need to use this code: ``` for num in range (x,y+1,2): print (num) ``` but without any `if` statements, I can't check if the value `x` inserted is even or odd, and if the user inserted the number `5` as `x`, all the prints will be odd numbers. I also tried to enter each number to a tuple or an array, but I still can't check if the first number is even to start printing. ``` def printEvenFor(x,y): evenNumbers =[] for i in range (x,y+1): evenNumbers.append(i) print (evenNumbers[::2]) ``` or ``` def printEvenFor(x,y): for i in range (x,y+1,2): print(i,",") ``` I expect the output of `printEvenFor(5,12)` to be `6,8,10,12` but it is `5,7,9,11`
2019/04/05
[ "https://Stackoverflow.com/questions/55535138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10301715/" ]
You can make x even, by using floor division and then multiplication: ``` x = (x // 2) * 2 ``` x will then be rounded to the previous even integer or stay the same if it was even before. If you want to round it to the following even integer you need to do: ``` x = ((x + 1) // 2) * 2 ``` This can be improved further by using shifting operators: ``` x = (x >> 1) << 1 #Alternative 1 x = ((x + 1) >> 1) << 1 #Alternative 2 ``` Examples: ``` #Alternative 1 x = 9 x = (x >> 1) << 1 #x is now 8 #Alternative 2 x = 9 x = ((x + 1) >> 1) << 1 #x is now 10 ``` The second one is probably more suitable for you
111,580
Torque seal is a lacquer-like product used in critical applications after a screw is tightened to provide a visual indication if the screw comes loose. Considering that a terminal screw on an electrical device coming loose can give you a Bad Day™, is it legal to use torque seal or an equivalent product (nail polish is said to work in a pinch) on electrical device terminal screws to visually indicate loosening? Or is there something in Code that would prohibit such a practice?
2017/04/06
[ "https://diy.stackexchange.com/questions/111580", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/27099/" ]
I don't know of any restrictions for the use you are proposing. In fact I have used it myself. Mostly for time clocks so if we can tell if someone is jacking with it.
13,125,284
In the code below, I am applying a different background color to all even rows by dynamically assigning the class "even" to them using javascript. I am calling the alternamte() function onload of the body tag. At first, I was using getElementById to get the table object and my code worked fine. However, I am suppose to apply this styling to ALL tables on my page, so I need to use get element by tag name. Once I made the chane to getElementByTagName, my code stopped working and I have been trying to find out the root of the problem for a while now with no success. I was wondering if someone can help me understand why my code stopped working after I made the change to getElementByTagName? ``` <script type="text/javascript"> function alternate(){ var table = document.getElementsByTagName("table"); var rows = table.getElementsByTagName("tr"); for(i = 0; i < rows.length; i++){ //change style of even rows //(odd integer values, since we're counting from zero) if(i % 2 == 0){ rows[i].className = "even"; } } } </script> ```
2012/10/29
[ "https://Stackoverflow.com/questions/13125284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1316524/" ]
It's [getElementsByTagName()](https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName), plural. It returns a HTMLCollection ``` var table = document.getElementsByTagName("table")[0]; ``` (if you're confident that there's a `<table>` on the page.) If you want to do things to *all* the `<table>` elements, you'd have to do something like this: ``` var tables = document.getElementsByTagName("table"); for (var ti = 0; ti < tables.length; ++ti) { var rows = tables[ti].getElementsByTagName("tr"); for(var i = 0; i < rows.length; i++){ //change style of even rows //(odd integer values, since we're counting from zero) if(i % 2 == 0){ rows[i].className = "even"; } } } ```
41,862,030
So I needed to use the code of the subprocess module to add some functionality I needed. When I was trying to compile the \_subprocess.c file, it gives this error message: `Error 1 error C2086: 'PyTypeObject sp_handle_type' : redefinition` This is the code part which is relevant from `_subprocess.c` file: ``` typedef struct { PyObject_HEAD HANDLE handle; } sp_handle_object; staticforward PyTypeObject sp_handle_type; static PyObject* sp_handle_new(HANDLE handle) { sp_handle_object* self; self = PyObject_NEW(sp_handle_object, &sp_handle_type); if (self == NULL) return NULL; self->handle = handle; return (PyObject*)self; } #if defined(MS_WIN32) && !defined(MS_WIN64) #define HANDLE_TO_PYNUM(handle) PyInt_FromLong((long) handle) #define PY_HANDLE_PARAM "l" #else #define HANDLE_TO_PYNUM(handle) PyLong_FromLongLong((long long) handle) #define PY_HANDLE_PARAM "L" #endif static PyObject* sp_handle_detach(sp_handle_object* self, PyObject* args) { HANDLE handle; if (!PyArg_ParseTuple(args, ":Detach")) return NULL; handle = self->handle; self->handle = INVALID_HANDLE_VALUE; /* note: return the current handle, as an integer */ return HANDLE_TO_PYNUM(handle); } static PyObject* sp_handle_close(sp_handle_object* self, PyObject* args) { if (!PyArg_ParseTuple(args, ":Close")) return NULL; if (self->handle != INVALID_HANDLE_VALUE) { CloseHandle(self->handle); self->handle = INVALID_HANDLE_VALUE; } Py_INCREF(Py_None); return Py_None; } static void sp_handle_dealloc(sp_handle_object* self) { if (self->handle != INVALID_HANDLE_VALUE) CloseHandle(self->handle); PyObject_FREE(self); } static PyMethodDef sp_handle_methods[] = { { "Detach", (PyCFunction)sp_handle_detach, METH_VARARGS }, { "Close", (PyCFunction)sp_handle_close, METH_VARARGS }, { NULL, NULL } }; static PyObject* sp_handle_getattr(sp_handle_object* self, char* name) { return Py_FindMethod(sp_handle_methods, (PyObject*)self, name); } static PyObject* sp_handle_as_int(sp_handle_object* self) { return HANDLE_TO_PYNUM(self->handle); } static PyNumberMethods sp_handle_as_number; statichere PyTypeObject sp_handle_type = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "_subprocess_handle", sizeof(sp_handle_object), 0, (destructor)sp_handle_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ (getattrfunc)sp_handle_getattr,/*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ &sp_handle_as_number, /*tp_as_number */ 0, /*tp_as_sequence */ 0, /*tp_as_mapping */ 0 /*tp_hash*/ };` ``` Also I've found that: ``` #define staticforward static #define statichere static ``` I don't understand what am I doing wrong. Any help would be appreciated. Btw (I'm not sure if it's relevant), I'm using Visual Studio Professional 2013 to compile this file.
2017/01/25
[ "https://Stackoverflow.com/questions/41862030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5372734/" ]
**Notes**: * I'm talking about *Python 2.7* here (since in newer versions, the *subprocess* module no longer has an own *C* implementation for *Win*) * *Python 2.7* is built (officially) using *VStudio2008 (9.0)* according to [[Python.Wiki]: WindowsCompilers](https://wiki.python.org/moin/WindowsCompilers). Building it with a newer (or better: different) version, might yield some other (and harder to find) errors. For example, when I built it with *VStudio 2010 (10.0)* (I used the built version to run a complex set of (*.py\**) scripts), I had some trouble at *runtime* when encountering socket related errors because of some mismatches between *errno* and *WSA\** codes, that were changed between the 2 versions When I tested, I couldn't understand why you encountered the issue and I didn't, then for a while I forgot about it, then when you posted the last comment, it started eating me alive again. As I said I was able to successfully compile the file using *VStudio 2010 / 2013*. Trying to compile the same (this was only an assumption) code with different results -> the *way* that code is compiled might differ. Therefore, I started investigating for other possible definition places for *staticforward* and *statichere* (besides lines *878* / *879* of *object.h*) due to conditional macros: ***#if***, ***#ifdef***, ... . But, I couldn't find any. So, I added some simpler statements: ```c staticforward int i; statichere int i = 2; ``` then, I manually replaced the defines: ```c static int i; static int i = 2; ``` in *\_subprocess.c* (by coincidence, I added them at line *#137* - just before `statichere PyTypeObject sp_handle_type = {` - fact that prevented me to figure out the problem at this point), and it still compiled!!! Next step, I pasted the above lines in another solution that I had open (in a *.cpp* source file), and I was able to reproduce the error. So, I payed more attention to the compiler flags (I copy/pasted from the *x86 Debug* settings of the projects automatically converted by *VStudio* from the ones found in the *PCbuild* folder): * *VStudio 2013* > > > ```bat > /GS > /analyze- > /W3 > /Gy > /Zc:wchar_t > /I"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.11-vs2k13\Python" > /I"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.11-vs2k13\Modules\zlib" > /I"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.11-vs2k13\Include" > /I"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.11-vs2k13\PC" > /Zi > /Gm- > /Od > /Fd"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.11-vs2k13\PCbuild\obj\win32_Debug\pythoncore\vc120.pdb" > /fp:precise > /D "_USRDLL" > /D "Py_BUILD_CORE" > /D "Py_ENABLE_SHARED" > /D "MS_DLL_ID=\"2.7-32\"" > /D "WIN32" > /D "_WIN32" > /D "_DEBUG" > /D "_WINDLL" > /errorReport:prompt > /GF > /WX- > /Zc:forScope > /Gd > /Oy- > /Oi > /MDd > /Fa"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.11-vs2k13\PCbuild\obj\win32_Debug\pythoncore\" > /nologo > /Fo"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.11-vs2k13\PCbuild\obj\win32_Debug\pythoncore\" > /Fp"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.11-vs2k13\PCbuild\obj\win32_Debug\pythoncore\python27_d.pch" > > ``` > > * *VStudio 2010* > > > ```bat > /I"..\Python" > /I"..\Modules\zlib" > /I"..\Include" > /I"..\PC" > /Zi > /nologo > /W3 > /WX- > /Od > /Oy- > /D "_USRDLL" > /D "Py_BUILD_CORE" > /D "Py_ENABLE_SHARED" > /D "WIN32" > /D "_DEBUG" > /D "_WIN32" > /D "_WINDLL" > /GF > /Gm- > /MDd > /GS > /Gy > /fp:precise > /Zc:wchar_t > /Zc:forScope > /Fp"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.10-vcbuild\PCbuild\Win32-temp-Debug\pythoncore\pythoncore.pch" > /Fa"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.10-vcbuild\PCbuild\Win32-temp-Debug\pythoncore\" > /Fo"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.10-vcbuild\PCbuild\Win32-temp-Debug\pythoncore\" > /Fd"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.10-vcbuild\PCbuild\Win32-temp-Debug\pythoncore\vc100.pdb" > /Gd > /analyze- > /errorReport:queue > > ``` > > and then it struck me: It's the **way of how the file is compiled: *C* vs. *C++*** (the [[MS.Docs]: /Tc, /Tp, /TC, /TP (Specify Source File Type)](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2013/032xwy55(v=vs.120)) flag). Of course, compiling *\_subprocess.c* as *C++* would spit your error. Check [[SO]: Creating a dynamically allocated struct with a 2D dynamically allocated string (@CristiFati's answer)](https://stackoverflow.com/questions/41918914/creating-a-dynamically-allocated-struct-with-a-2d-dynamically-allocated-string/41922266#41922266), for (a little bit) more details, and how the same mistake triggered very different errors.
45,094,992
I need to append a new item to the end of a list. Here is what I tried: ``` (define my-list (list '1 2 3 4)) (let ((new-list (append my-list (list 5))))) new-list ``` I expect to see: ``` (1 2 3 4 5) ``` But I receive: > > let: bad syntax (missing binding pair5s or body) in (let ((new-list (append my-list (list 5))))) > > >
2017/07/14
[ "https://Stackoverflow.com/questions/45094992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8305676/" ]
Your problem is mostly of syntactical nature. The `let` expression in Scheme has the form `(let (binding pairs) body)`. In your example code, while you do have a binding that should work, you don't have a body. For it to work, you need to change it to ``` (let ((new-list (append my-list (list 5)))) new-list) ``` In my DrRacket 6.3 this evaluates to what you would expect it to: `'(1 2 3 4 5)`.
59,080
I want to re-edit my question so that it will come in latest questions again and you all experts can look and help me. But i forgot my actual login id i used to post for the question. This is the link to my actual question. [My actual question](https://stackoverflow.com/questions/2854989/dsnless-connection-for-aruna-db/3370865#3370865) I deeply apologize for my action here if it is a violation of SO community ethics.
2010/07/30
[ "https://meta.stackexchange.com/questions/59080", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/-1/" ]
No worries, we're glad to see you care about your question. Did you insert your email address when you created that account? If so, have a look at this: <https://stackoverflow.com/users/account-recovery> As pointed out by George in the actual question, you can also have a moderator merge your new account with the old one, so you can access all old data again. And finally, you can also drop a message to the SO team by email and explain your situation. I'm sure they'll find a way to help you. Hope that helps :)
27,711,123
I have a svg.php file with some shapes. ``` <rect onclick="window.location='search.php?filter=1'" width="50" height="50"> <rect onclick="window.location='search.php?filter=2'" width="50" height="50"> ``` Search.php ``` div class="container"> <textarea class="search" id="search_id"></textarea> <div id="result"></div> <?php include("svg.php"); ?> </div> //This is for a autocomplete search, took it from http://www.2my4edge.com/2013/08/autocomplete-search-using-php-mysql-and.html <script type="text/javascript"> $(function(){ $(".search").keyup(function() { var search_id = $(this).val(); var dataString = 'search='+ search_id; if (search_id=='') { $.ajax({ type: "POST", url: "search_database.php", data: dataString, cache: false, success: function(html) { $("#result").html(html).hide(); } }); }; if(search_id!='') { $.ajax({ type: "POST", url: "search_database.php", data: dataString, cache: false, success: function(html) { $("#result").html(html).show(); } }); }return false; }); jQuery("#result").live("click",function(e){ var $clicked = $(e.target); var $name = $clicked.find('.name').html(); var decoded = $("<div/>").html($name).text(); $('#search_id').val(decoded); }); jQuery(document).live("click", function(e) { var $clicked = $(e.target); if (! $clicked.hasClass("search")){ jQuery("#result").fadeOut(); } }); $('#search_id').click(function(){ jQuery("#result").fadeIn(); }); }); </script> Then a search_database.php $search = isset($_GET['filter']) ? $_GET["filter"] : 1; echo $search; //echos "2". if ($search=="1") { echo $search; //enters if, and it's not supposed to, and echos "1" Select * from table; } ``` Search\_database.php ``` $search = isset($_GET['filter']) ? $_GET["filter"] : "1"; echo $search //echos "2"; if ($search=="1") { $q = $_POST['search']; $q_length = strlen($q); $sql = <<<SQL SELECT * FROM table LIMIT 6 SQL; if(!$result = $con->query($sql)){ die('There was an error running the query [' . $con->error . ']'); } while($row = $result->fetch_array()) { ?> <div class="show_search"> <?php echo $row['name'] ?> </a> </div> <?php } } ?> ``` I'm on `search.php?filter=2` and the first echo is correct ("2") but for some reason it keeps entering the If Clause and echos that $search is "1". I'm not defining the $search variable anywhere else. Thank you for your help.
2014/12/30
[ "https://Stackoverflow.com/questions/27711123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3906855/" ]
Azure SQL Databases are always UTC, regardless of the data center. You'll want to handle time zone conversion at your application. In this scenario, since you want to compare "now" to a data column, make sure `AcceptedDate` is also stored in UTC. [Reference](http://blogs.msdn.com/b/cie/archive/2013/07/29/manage-timezone-for-applications-on-windows-azure.aspx)
46,768,071
I'm trying to use the hash algorithms provided by the openssl library. I have openssl and libssl-dev installed. The version is 1.1.0f. I try to run the example code of the openssl.org site: ``` #include <stdio.h> #include <openssl/evp.h> int main(int argc, char *argv[]){ EVP_MD_CTX *mdctx; const EVP_MD *md; char mess1[] = "Test Message\n"; char mess2[] = "Hello World\n"; unsigned char md_value[EVP_MAX_MD_SIZE]; int md_len, i; if(!argv[1]) { printf("Usage: mdtest digestname\n"); exit(1); } md = EVP_get_digestbyname(argv[1]); if(!md) { printf("Unknown message digest %s\n", argv[1]); exit(1); } mdctx = EVP_MD_CTX_new(); EVP_DigestInit_ex(mdctx, md, NULL); EVP_DigestUpdate(mdctx, mess1, strlen(mess1)); EVP_DigestUpdate(mdctx, mess2, strlen(mess2)); EVP_DigestFinal_ex(mdctx, md_value, &md_len); EVP_MD_CTX_free(mdctx); printf("Digest is: "); for (i = 0; i < md_len; i++) printf("%02x", md_value[i]); printf("\n"); exit(0); } ``` I try to compile this with: ``` gcc digest_example.c -lcrypto -lssl ``` And the compiler gives the error: ``` digest_example.c:(.text+0xbc): undefined reference to `EVP_MD_CTX_new' digest_example.c:(.text+0x138): undefined reference to `EVP_MD_CTX_free' collect2: error: ld returned 1 exit status ``` And honestly, I'm clueless. I installed and reinstalled OpenSSL 2 times from the website by compiling it. Additionally, all the other commands make no problem. Just these two. Do I have to use other libraries when linking? Thanks for your help.
2017/10/16
[ "https://Stackoverflow.com/questions/46768071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8783607/" ]
You seem to be using an older version of openssl (< 1.1.0). Maybe you have downloaded and installed the newer version, but your linker seems to find and use an older version of your openssl library. `EVP_MD_CTX_new()` in 1.1.0 has replaced `EVP_MD_CTX_create()` in 1.0.x. `EVP_MD_CTX_free()` in 1.1.0 has replaced `EVP_MD_CTX_destroy()` in 1.0.x. You might try to use the older versions of these functions or make sure, that your linker really uses the >= 1.1.0 version of the openssl library.
3,373,668
I'm new to android development and as a pet project I wanted to try and connect to an bluetooth device using the HID profile using an android phone. The phone I'll be using is the vibrant and according to samsung it doesn't support the HID Profile ( <http://ars.samsung.com/customer/usa/jsp/faqs/faqs_view_us.jsp?SITE_ID=22&PG_ID=2&PROD_SUB_ID=557&PROD_ID=560&AT_ID=281257> ). Now my question is this, where does this "profile" reside? Is it on the hardware level or on the software level ( I assume the latter from other sources that I have read ). And if it is the latter, can HID implementation be created using RFCOMM communication over bluetooth (this is the only seemingly viable method I can see in the android bluetooth API). I just want to make sure I understand the technology before I try and implement something that may not be possible. Thanks in advance.
2010/07/30
[ "https://Stackoverflow.com/questions/3373668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305682/" ]
With an HTTP DELETE, the URI should fully identify the resource to be deleted. Sending additional data in the request body is unexpected, [and on App Engine, unsupported](http://code.google.com/p/googleappengine/issues/detail?id=601#c5): > > Indeed, when the appspot frontends see > a DELETE request that includes an > body, such as your app, they return a > 501. But, if you remove the body then it will serve a 200. > > > Based on the subsequent discussion, it looks like they decided 400 was more appropriate than 501. In any event, if you omit the body and move your entity key into the URI, you should be fine.
31,843,925
I have a query in Linq that needs to be dynamically adjustable based on some values a user selects in a form. My query looks as follows: ``` (from data in DbContext.CoacheeData group data by data.UserId into g select new LeaderboardEntry { Name = g.FirstOrDefault().UserName, Value = g.Sum(data => data.Steps), }); ``` I would like two aspects of this query to be dynamic: * The aggregate function used to calculate the value (could be sum, average or max) * The column used to calculate the value (see below) I've been trying - and failing - to use Linq expressions for this, but I keep getting runtime errors. I'm pretty new at Linq, so I'm probably doing something stupid. Below is an excerpt from the CoacheeData class. If it helps, all of the properties are numbers. All floats even, with the exception of Steps. ``` public class CoacheeData { [Key] public long Id { get; set; } [Required] [ForeignKey("User")] public string UserId { get; set; } public virtual ApplicationUser User { get; set; } public DateTime Date { get; set; } //Each of these properties should be selectable by the query public int Steps { get; set; } public float Distance { get; set; } public float CaloriesBurned { get; set; } //...etc } ``` EDIT: I was asked what I'd tried, below are the most relevant things I think: ----------------------------------------------------------------------------- ``` Func<CoacheeData, int> testLambda = (x) => x.Steps; //Used inside the query like this: Value = g.Sum(testLambda), ``` This throws an exception ("Internal .NET Framework Data Provider error 1025."), which I think is normal because you can't use lambda's directly in Linq to SQL. Correct me if I'm wrong. So I tried with an expression: ``` Expression<Func<CoacheeData, int>> varSelectExpression = (x) => x.Steps; //And in the query: Value = g.Sum(varSelectExpression.Compile()), ``` Throws the same error 1025, which is working as intended because the Compile() call changes the expression into a lambda again, in my understanding. However I can't omit the Compile() call, because then the Linq code doesn't compile. No idea how to fix this. I tried similar things for the sum, I suspect my errors (and the solution) will be comparable. I will add more info later if needed.
2015/08/05
[ "https://Stackoverflow.com/questions/31843925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4500048/" ]
If I understand this correctly, you wish to get the most recently liked photos of a particular user. This can be done using the Instagram API - but only when that particular user has authenticated your app. You can use the following endpoint: > > GET /users/self/media/liked > > > Here the API call would be : > > <https://api.instagram.com/v1/users/self/media/liked?access_token=ACCESS-TOKEN> > > > This will give you the list of recent media liked by the owner of the ACCESS-TOKEN. More details on the Instagram API here : > > <https://www.instagram.com/developer/endpoints/users/#get_users_feed_liked> > > >
34,784,814
This works: ``` <select class="secureProfile"> <option class="placeholder" selected disabled>välj ett alternativ...</option> <option value="male">Man</option> <option value="female">Kvinna</option> </select> ``` This does not: ``` <select data-ng-model="gender" class="secureProfile"> <option class="placeholder" selected disabled>välj ett alternativ...</option> <option value="male">Man</option> <option value="female">Kvinna</option> </select> ``` For some reason when applying `data-ng-model` it seems to get rid of the placeholders, looks like this (picture displays the error): [![enter image description here](https://i.stack.imgur.com/trmxs.png)](https://i.stack.imgur.com/trmxs.png) Controller: ``` .controller('secureProfile', ['$document', '$compile', '$scope', '$window', '$location', '$http', '$cookies', 'socket', 'textAngularManager', 'bridge', function ($document, $compile, $scope, $window, $location, $http, $cookies, socket, textAngularManager, bridge) { $scope.gender = null; }]) ``` When I load the page for a blink second it displays it correctly but then decides to make a blank selected row. Any ideas?
2016/01/14
[ "https://Stackoverflow.com/questions/34784814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137669/" ]
You just need to set value property HTML ``` <select data-ng-model="gender" class="secureProfile"> <option class="placeholder" value="" selected disabled>välj ett alternativ...</option> <option value="male">Man</option> <option value="female">Kvinna</option> </select> ``` `**[`DEMO`](https://jsfiddle.net/6o4s2wfr/)**`
42,318,634
I am trying to print a list from mysql table to express page. app.js uses routes.js. there I have get for users profile page ``` //profile app.get('/profile', isLoggedIn, function(req, res){ var courses = []; connection.query('SELECT courseID FROM studentCourses WHERE userID = ?', [req.user], function(err, rows){ for(var i=0; i<rows.length; i++){ courses.push(rows[i]); } for(var j=0; j< courses.length; j++){ connection.query('SELECT name FROM courses WHERE courseID = ?', [courses[j]], function(err, rows2){ list = rows2[j]; }); } }); res.render('profile', { user : req.user // get the user out of session and pass to template }, { courses : list } ); }); ``` my mysql tables users: id, username, password courses: id, name studentCourses: id, userid, courseid I am trying to list all course names that a user with id 2 have for example. Cant find a descent tutorial for nodejs and mysql. This is as far as i could go but couldnt make it work. Probably its just a wrong way. Any help listing that table to a ejs web template would be nice. Thanks
2017/02/18
[ "https://Stackoverflow.com/questions/42318634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7488770/" ]
`x` in `main()` is a local variable that is *independent* from the `x` variable in `getheight()`. You are returning the new value from the latter but areignoring the returned value. Set `x` in `main` from the function call result: ``` while x not in range (1,23): x = getheight() if x in range (1,23): break ``` You also need to fix your `getheight()` function to return an *integer*, not a string: ``` def getheight(): x = input("Give me a positive integer no more than 23 \n") return int(x) ```
66,999,934
I have 2 icons in divs and 1 link which works as a button ```css .A { width: 50px; height: 50px; border: 1px solid black; display: inline-flex; justify-content: center; align-items: center; margin: 5px; } a { text-decoration: none; } .B { width: 100px; height: 50px; } /* when i change font-size for example to 10px then the element moves down a bit*/ .A span { text-transform: uppercase; color: black; font-size: 10px; } ``` ```html <script src="https://kit.fontawesome.com/4254229804.js" crossorigin="anonymous"></script> <a href="#"> <div class="A"> <i class="fab fa-facebook-f"></i> </div> </a> <a href="#"> <div class="A"> <i class="fab fa-youtube"></i> </div> </a> <a href="#"> <div class="A B"> <span>sign up</span> </div> </a> ``` here is a link to codepen <https://codepen.io/hanzus/pen/GRrMbbm> Everything is centered when a font size of span element of "sign up" link is 16px, but when I change it for example to 10px then link moves a bit down and it is not on the same line with other divs with facebook and youtube links. How do I get these links on the same line when I change a font-size of 1 element?
2021/04/08
[ "https://Stackoverflow.com/questions/66999934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10766879/" ]
Wrap in flex: ```css .container { display: flex; } ``` ```html <div class="container"> <a href="#"> <div class="A"> <i class="fab fa-facebook-f"></i> </div> </a> <a href="#"> <div class="A"> <i class="fab fa-youtube"></i> </div> </a> <a href="#"> <div class="A B"> <span>sign up</span> </div> </a> </div> ``` [Codepen](https://codepen.io/tauzN/pen/poRWMrB)
15,988,638
I have a class called TileView which extends UIView. In another view I create 9 TileView objects and display them on the screen. Below is an example of 1 of them ``` tile1 = [[TileView alloc] initWithFrame:CGRectMake(20,20, 100, 150) withImageNamed:@"tile1.png" value: 1 isTileFlipped: NO]; ``` A user can touch any of the tiles. When a tile is touched it is "turned over" - the image is named to a plain brown tile and `isTileFlipped` is set to 'YES'. Now comes the part I'm stuck on: There is a confirm button. When the confirm button is pressed, it takes all the tiles that are flipped and adds them to an array called `acceptedTiles`. After confirm is pressed I need to make sure that the tiles in `acceptedTiles` cannot be pressed or interacted with. I am at a loss as to what would be the best way to do this. Here is `touchesBegan` so you can get an idea of what is happening. ``` - (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ int currentTileCount = [(BoxView *)self.superview getTileCount]; int currentTileValue = [self getTileValue]; int tilecount; if (!isFlipped) { [image setImage:[UIImage imageNamed:@"tileflipped.png"]]; isFlipped = YES; tilecount = currentTileCount + currentTileValue; [(BoxView *)self.superview setTileCount:tilecount]; [(BoxView *)self.superview addToArray:self index:currentTileValue-1]; } else { [image setImage:[UIImage imageNamed:imageNamed]]; isFlipped = NO; tilecount = currentTileCount - (int)currentTileValue; [(BoxView *)self.superview setTileCount:tilecount]; [(BoxView *)self.superview removeFromArray: currentTileValue-1]; } } ```
2013/04/13
[ "https://Stackoverflow.com/questions/15988638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1424638/" ]
If all you want is the tiles not to be interacted with, surely simply: ``` for (UIView *tile in acceptedTiles) { [tile setUserInteractionEnabled:NO]; } ``` If that doesn't meet your requirements, please elaborate. It seems perfect for you.
34,810,451
I have this conditions ``` if (txtBoxFatherHusbandName.Text != "" || txtBoxName.Text != "" || txtBoxNICNo.Text != "") { ShowMsgBox("Please first <b>Save/Update</b> the data being entered in mandatory fields"); txtBoxFatherHusbandName.Focus(); return; } ``` all three textboxes are empty with no text in it but still the conditions is getting executed. why ?
2016/01/15
[ "https://Stackoverflow.com/questions/34810451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5700366/" ]
You have to use [`String.IsNullOrWhiteSpace()`](https://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace%28v=vs.110%29.aspx) to check them here, because user may press spaces in that case there can be propblems, so you should be writing if like following to tackle with empty textboxes: ``` if (!String.IsNullOrWhiteSpace(txtBoxFatherHusbandName.Text) || .......) ```
29,139,964
Given a SQL query variable, i.e., ``` string mySQLQuery = "SELECT TableA.Field1, TableA.Field2,..., TableB.Field1, TableB.Field2,.... FROM TableA LEFT OUTER JOIN TableB ON TableA.Field1 = TableB.Field1" ``` Is there any straight way I can extract the fields and the table names within the query in two lists? so: List "Fields": * All fields From table A, table B (and others I could add by joining) with their table prefix (even if there were only one table in a simple 'SELECT \* FROM TableA', I'd still need the 'TableA.' prefix). * All fields From table B with their table prefix, by adding them to the list in the usual fieldList.Add() way through looping. List "Tables": * All tables involved in the query in the usual tablesList.Add() way through looping. My first approach would be to make a lot of substrings and comparisons, i.e., finding the FROM, then trimming left, the substring until the first blank space, then the JOIN, then trimming, then the first substring until the space..., but that doesn't seem the right way. **REEDIT** I know I can get all the fields from INFORMATION\_SCHEMA.COLUMNS with all the properties (that comes later), but the problem is that for that query I need the tables to be known. My steps should be: 1. The query "SELECT [fields] FROM [tables]" comes from a Multiline Textbox so I can write a SQL Query to fetch the fields I'd like. I take the string by txtMyQuery.Text property. 2. Find the field in the SELECT query, and find what table belongs to in the FROM clause. 3. Store the field like [Table].[Field]in a string list List strFields = new List() by the strFields.Add() method; 4. Then, iterate through the list in a way like: ``` for (int i = 0; i < fieldList.Count; i++) { string mySqlQuery = "SELECT Table_Name, Column_Name, Data_Type FROM INFORMATION_SCHEMA.COLUMNS WHERE (COLUMN_NAME + "." + TABLE_NAME) ='" + fieldList[i] + "'"; //Commit query, get results in a gridview, etc. } ```
2015/03/19
[ "https://Stackoverflow.com/questions/29139964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4162164/" ]
I found out where the problem came from. Since the content loaded in the “div” element changed its height 2 times with each press of the button, the height of the page body changed as well. This was the cause of the scrolling. I fixed the height of the “div” element in the css file: ``` div#result {height: 200px;} ``` This solved the problem.
422,149
I have a Windows 7 Ultimate machine where the wireless adapter all of a sudden started having trouble connecting to wireless networks. Whenever I go to a new place and try to connect to a wireless network, it says that the DNS server is not responding, and tells me to go unplug the router and try again. After several locations in a row telling me this, I began to realize something was wrong with my adapter, not the routers. I am no longer asked to identify the security level for any new networks (Work, Home, or Public) like I used to be (it defaults to Public now - with the park bench icon). Often, resetting the router doesn't even work. Running the Windows 7 troubleshooter doesn't give me anything better than the advice to reset the router. However, the adapter will still connect to the wireless network at my main office without any problems. Does anyone know why a wireless network adapter can get so finicky so suddenly? Thanks!
2012/05/08
[ "https://superuser.com/questions/422149", "https://superuser.com", "https://superuser.com/users/133169/" ]
It really depends on the case you have. I would personally get one of solid state picoPSU things and power the PC through a battery. Charge up a capacitor while the car is running, then when the car shuts off let it slowly drain through a resistor to ground and when the capacitor is empty get a mosfet to poke the "power button" pins for it to go into automatic powerdown Note: I would try to avoid going DC(car) to AC(inverter/UPS) to DC(pc) as you'll loose alot of power that way and inverters always pull power even if they are not powering anything
14,018,088
I have a jBoss 5.1.0-GA running a server, it was running find. But I copied whole jboss to another server, (by using tar). When I start new jBoss, it give a "user null is NOT authenticated", here is the stack trace ``` [ExceptionUtil] ConnectionFactoryEndpoint[jboss.messaging.connectionfactory:service=ConnectionFactory] createFailoverConnectionDelegate [nb-z2y983bh-1-4b8983bh-kwpr33-100j3] javax.jms.JMSSecurityException: User null is NOT authenticated at org.jboss.jms.server.jbosssx.JBossASSecurityMetadataStore.authenticate(JBossASSecurityMetadataStore.java:223) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.sun.jmx.mbeanserver.StandardMBeanIntrospector.invokeM2(StandardMBeanIntrospector.java:93) at com.sun.jmx.mbeanserver.StandardMBeanIntrospector.invokeM2(StandardMBeanIntrospector.java:27) at com.sun.jmx.mbeanserver.MBeanIntrospector.invokeM(MBeanIntrospector.java:208) at com.sun.jmx.mbeanserver.PerInterface.invoke(PerInterface.java:120) at com.sun.jmx.mbeanserver.MBeanSupport.invoke(MBeanSupport.java:262) at javax.management.StandardMBean.invoke(StandardMBean.java:391) at org.jboss.mx.server.RawDynamicInvoker.invoke(RawDynamicInvoker.java:164) at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:668) at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210) at $Proxy260.authenticate(Unknown Source) at org.jboss.jms.server.endpoint.ServerConnectionFactoryEndpoint.createConnectionDelegateInternal(ServerConnectionFactoryEndpoint.java:233) at org.jboss.jms.server.endpoint.ServerConnectionFactoryEndpoint.createConnectionDelegate(ServerConnectionFactoryEndpoint.java:171) at org.jboss.jms.server.endpoint.advised.ConnectionFactoryAdvised.org$jboss$jms$server$endpoint$advised$ConnectionFactoryAdvised$createConnectionDelegate$aop(ConnectionFactoryAdvised.java:108) at org.jboss.jms.server.endpoint.advised.ConnectionFactoryAdvised.createConnectionDelegate(ConnectionFactoryAdvised.java) at org.jboss.jms.wireformat.ConnectionFactoryCreateConnectionDelegateRequest.serverInvoke(ConnectionFactoryCreateConnectionDelegateRequest.java:91) at org.jboss.jms.server.remoting.JMSServerInvocationHandler.invoke(JMSServerInvocationHandler.java:143) at org.jboss.remoting.ServerInvoker.invoke(ServerInvoker.java:891) at org.jboss.remoting.transport.local.LocalClientInvoker.invoke(LocalClientInvoker.java:106) at org.jboss.remoting.Client.invoke(Client.java:1724) at org.jboss.remoting.Client.invoke(Client.java:629) at org.jboss.jms.client.delegate.ClientConnectionFactoryDelegate.org$jboss$jms$client$delegate$ClientConnectionFactoryDelegate$createConnectionDelegate$aop(ClientConnectionFactoryDelegate.java:171) at org.jboss.jms.client.delegate.ClientConnectionFactoryDelegate$createConnectionDelegate_N3019492359065420858.invokeTarget(ClientConnectionFactoryDelegate$createConnectionDelegate_N3019492359065420858.java) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:111) at org.jboss.jms.client.container.StateCreationAspect.handleCreateConnectionDelegate(StateCreationAspect.java:81) at org.jboss.aop.advice.org.jboss.jms.client.container.StateCreationAspect_z_handleCreateConnectionDelegate_31070867.invoke(StateCreationAspect_z_handleCreateConnectionDelegate_31070867.java) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102) at org.jboss.jms.client.delegate.ClientConnectionFactoryDelegate.createConnectionDelegate(ClientConnectionFactoryDelegate.java) at org.jboss.jms.client.JBossConnectionFactory.createConnectionInternal(JBossConnectionFactory.java:205) at org.jboss.jms.client.JBossConnectionFactory.createQueueConnection(JBossConnectionFactory.java:101) at org.jboss.jms.client.JBossConnectionFactory.createQueueConnection(JBossConnectionFactory.java:95) at org.jboss.resource.adapter.jms.inflow.dlq.AbstractDLQHandler.setupDLQConnection(AbstractDLQHandler.java:137) at org.jboss.resource.adapter.jms.inflow.dlq.AbstractDLQHandler.setup(AbstractDLQHandler.java:83) at org.jboss.resource.adapter.jms.inflow.dlq.JBossMQDLQHandler.setup(JBossMQDLQHandler.java:48) at org.jboss.resource.adapter.jms.inflow.JmsActivation.setupDLQ(JmsActivation.java:413) at org.jboss.resource.adapter.jms.inflow.JmsActivation.setup(JmsActivation.java:351) at org.jboss.resource.adapter.jms.inflow.JmsActivation$SetupActivation.run(JmsActivation.java:729) at org.jboss.resource.work.WorkWrapper.execute(WorkWrapper.java:205) at org.jboss.util.threadpool.BasicTaskWrapper.run(BasicTaskWrapper.java:260) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:662) 12:01:34,859 ERROR [ExceptionUtil] ConnectionFactoryEndpoint[jboss.messaging.connectionfactory:service=ConnectionFactory] createFailoverConnectionDelegate [mb-z2y983bh-1-4b8983bh-kwpr33-100j3] ``` Can somebody help ?
2012/12/24
[ "https://Stackoverflow.com/questions/14018088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1479203/" ]
Solved the problem, that was happened when we are going to solve some other problem, that is com.arjuna transaction issue, in that jboss keep throwing messages non stop, to resolve that issue, some posts recommended delete the 'data' folder in jBoss, when we delete that, the hypersonic database script inside the data folder is also deleted, therefore the user Null issue came out, so what we did was restored the hypersonic db script and now it's working fine.
46,782,347
I am trying to output SQL as XML to match the exact format as the following ``` <?xml version="1.0" encoding="utf-8"?> <ProrateImport xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schema.aldi- sued.com/Logistics/Shipping/ProrateImport/20151009"> <Prorates> <Prorate> <OrderTypeId>1</OrderTypeId> <DeliveryDate>2015-10-12T00:00:00+02:00</DeliveryDate> <DivNo>632</DivNo> <ProrateUnit>1</ProrateUnit> <ProrateProducts> <ProrateProduct ProductCode="8467"> <ProrateItems> <ProrateItem StoreNo="1"> <Quantity>5</Quantity> </ProrateItem> <ProrateItem StoreNo="2"> <Quantity>5</Quantity> </ProrateItem> <ProrateItem StoreNo="3"> <Quantity>5</Quantity> </ProrateItem> </ProrateItems> </ProrateProduct> </ProrateProducts> </Prorate> </Prorates> </ProrateImport> ``` Here is my query: ``` SELECT OrderTypeID, DeliveryDate, DivNo, ProrateUnit, (SELECT ProductOrder [@ProductCode], (SELECT ProrateItem [@StoreNo], CAST(Quantity AS INT) [Quantity] FROM ##Result2 T3 WHERE T3.DivNo = T2.DivNo AND T3.DivNo = T1.DivNo AND T3.DeliveryDate = T2.DeliveryDate AND T3.DeliveryDate = T1.DeliveryDate AND T3.ProductOrder = t2.ProductOrder FOR XML PATH('ProrateItem'), TYPE, ROOT('ProrateItems') ) FROM ##Result2 T2 WHERE T2.DivNo = T1.DivNo AND T2.DeliveryDate = T1.DeliveryDate FOR XML PATH('ProrateProduct'), TYPE, ROOT('ProrateProducts') ) FROM ##Result2 T1 GROUP BY OrderTypeID, DeliveryDate, DivNo, ProrateUnit FOR XML PATH('Prorate'), TYPE, ROOT('Prorates') ``` How do I add in the Following and have the ProrateImport/20151009" change to the current date? ``` <?xml version="1.0" encoding="utf-8"?> <ProrateImport xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schema.aldi- sued.com/Logistics/Shipping/ProrateImport/20151009"> ``` This is my first time I have used XML
2017/10/17
[ "https://Stackoverflow.com/questions/46782347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8787739/" ]
When defining `sum''`, you have defined what it means for two empty lists, and for two non-empty lists, but you haven't defined what it means for two lists, only one of which is empty. This is what the compiler is telling you via that error message. Simply add definitions of what `sum''` means whenever left list is empty and the right list is not, and vice versa: ``` sum'' (x:xs) [] = ... sum'' [] (y:ys) = ... ```
484,819
Let $X\_1, X\_2 , \dots, X\_n$ be i.i.d observations from $N(\theta, \theta)$ (where $\theta$ is the variance). I intend to find the minimal sufficient statistics (M.S.S) for the joint distribution. My steps ultimately lead me to the following: $\dfrac{f\_\theta(x)}{f\_\theta(y)} = \text{exp}{ \left\{ \dfrac{-1}{2\theta} \left[ \left(\sum x\_i^2 - \sum y\_i^2 \right) + 2\theta \left( \sum y\_i - \sum x\_i \right) \right] \right) }$. My M.S.S are therefore $\left( \sum x\_i^2 , \sum x\_i \right)$ Am I on track?
2020/08/26
[ "https://stats.stackexchange.com/questions/484819", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/48950/" ]
It turns out that after further expansion, the above becomes $\dfrac{f\_\theta(x)}{f\_\theta(y)} = \exp \left\{ - \left[ \dfrac{1}{2\theta} \left( \sum x\_i^2 - \sum y\_i^2 \right) + \left( \sum y\_i - \sum x\_i \right) \right] \right\}$. Since it is only the first term that depends on $\theta$, the M.S.S is $\sum x\_i^2$.
56,605,977
I mean for example use a normal case switch but instead of the case being selected by a user being chosen randomly ``` def switch_demo(argument):     switcher = {         1: "January",         2: "February",         3: "March",         4: "April",         5: "May",         6: "June",         7: "July",         8: "August",         9: "September",         10: "October",         11: "November",         12: "December"     } ``` and somehow make it random to choose, i mean the case is chosen randomly. For example: generate a random number this being the number of the case or something like that.
2019/06/14
[ "https://Stackoverflow.com/questions/56605977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I don't know if I understand what you wanted to do with it, but you don't need to do it, you could do it like this: ``` import random months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] rand_month_choice = random.choice(months) print(rand_month_choice) #prints the random choice ```
267,026
I'm running a script within a script, release.sh and caller.sh (caller.sh calls release.sh). Both are bash. release.sh contains a bunch of conditions with 'exit 1' for errors. caller.sh contains a line that goes "./release.sh", then a checks for the exit code of release.sh - if $? is greater than 0 then echo "release.sh screwed up" and exits. ``` ./release.sh if [ $? -gt "0" ] ; then echo "release_manager exited with errors, please see the release log." exit 1 else echo "release manager is done." fi ``` Recently I've decided to log release.sh, and so the line in caller.sh goes: ``` ./release.sh 2>&1 | tee release.txt ``` Because of the pipe, $? is the exit code of 'tee release.txt' , which always comes out as 0, regardless of the previous command :-( I have to check for release.sh errors and stop the caller from proceeding, but I also really need that log. Is there a way to get the exit code of the command **before** last? Or a different way to log the release script in the same command? I'm not really in charge of release.sh, I'd rather not change it.
2016/03/02
[ "https://unix.stackexchange.com/questions/267026", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/137597/" ]
Since you are using bash you can set in the script the option: ``` set -o pipefail ``` > > The pipeline's return status is the value of the last (rightmost) command > to exit with a non-zero status, or zero if all commands exit successfully. > > > Alternatively, immediately after the piped command you can look at builtin variable value `${PIPESTATUS[0]}` for the exit code of the first command in the pipe. > > PIPESTATUS: An array variable containing a list of exit > status values from the processes in the most-recently-executed foreground > pipeline (which may contain only a single command). > > >
20,523,881
Is there any event, to append to the following listener, that will tell me if a radio button is already clicked? ``` var budgetType; $(document).on('change', 'input[name="import_export"]', function() { console.log($(this)) budgetType = $(this).val(); }); ``` My problem is that, on page reload, if the radio box is already checked, the `change` listener won't work, and I didn't find any listener that will help me with that issue. Any ideas? Update ------ I'm aware that I could write an `if/else` syntax and see which is checked, but I was wondering if there is any other listener that I could append to `change` one, and avoid writing that extra syntax. <http://jsfiddle.net/S93XB/1/>
2013/12/11
[ "https://Stackoverflow.com/questions/20523881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971392/" ]
``` $('input[type=radio]').is(':checked') ``` Try this code here: <http://jsfiddle.net/afzaal_ahmad_zeeshan/rU2Fc/> or try this one ``` $('input[type=radio]').prop('checked', true); ``` Try this code here: <http://jsfiddle.net/afzaal_ahmad_zeeshan/rU2Fc/1/> It will work, you can execute this onload to get the first value and use it in an if else block.
18,008
I'm not a plugin developer, nor is my knowledge of PHP sufficient to handle this issue. I need a simple method or plugin, to be able to generate this PHP code in a template. ``` <? $params=""; foreach($_POST as $name=>$value) { if ($name!="controllerPage") { $params=$params.$name."=".$value."&"; } } ?> ``` In the same template I need this code to retrieve the above ``` <? echo $params; ?> ``` Who can show me the way? This is the POST data that is attached to the URL ``` $_POST=array ( 'view' => 'SearchResult', 'controllerPage' => 'https://navigantes.eu/yachts-search', 'customCssPath' => 'https://navigantes.eu/css/booking-manager-small.css', 'setlang' => 'en', 'target' => '_blank', 'companyid' => '1234', 'filter_country' => 'HR', 'filter_region' => '', 'filter_base' => '', 'filter_year' => '2016', 'filter_month' => '11', 'filter_date' => '10', 'filter_duration' => '7', 'filter_flexibility' => 'on_day', ) ``` Which needs to be translated to this: ``` view=SearchResult&amp;customCssPath=https://navigantes.eu/css/booking-manager-small.css&amp;setlang=en&amp;target=_blank&amp;companyid=1234&amp;filter_country=HR&amp;filter_region=&amp;filter_base=&amp;filter_year=2016&amp;filter_month=11&amp;filter_date=10&amp;filter_duration=7&amp;filter_flexibility=on_day& ``` Solved the issue by using {{ craft.request.getPost('') }} method: ``` <iframe name="" width="100%" height="800" frameborder="0" scrolling="auto" src="https://www.booking-manager.com/wbm2/page.html? view={{ craft.request.getPost( 'view' ) }}& customCssPath={{ craft.config.environmentVariables.rootUrl }}/css/booking-manager-small.css& setlang={{ craft.request.getPost( 'setlang' ) }}& companyid={{ craft.request.getPost( 'companyid' ) }}& filter_country={{ craft.request.getPost( 'filter_country' ) }}& filter_region={{ craft.request.getPost( 'filter_region' ) }}& filter_base={{ craft.request.getPost( 'filter_base' ) }}& filter_year={{ craft.request.getPost( 'filter_year' ) }}& filter_month={{ craft.request.getPost( 'filter_month' ) }}& filter_date={{ craft.request.getPost( 'filter_date' ) }}& filter_duration={{ craft.request.getPost( 'filter_duration' ) }}& filter_flexibility={{ craft.request.getPost( 'filter_flexibility' ) }}& "> </iframe> ``` And finally Brad's suggested method worked by changing craft.request.getSegments() into craft.request.getPost(): ``` {% set segments = craft.request.getPost() %} {% set stringParams = '' %} {% for name, segment in segments %} {% if name != 'controllerPage' %} {% set stringParams = stringParams ~ name ~ '=' ~ segment ~ '&' %} {% endif %} {% endfor %} <iframe name="" width="100%" height="800" frameborder="0" scrolling="auto" src="https://www.booking-manager.com/wbm2/page.html?{{ stringParams }}"> ```
2016/12/05
[ "https://craftcms.stackexchange.com/questions/18008", "https://craftcms.stackexchange.com", "https://craftcms.stackexchange.com/users/3627/" ]
I think you can do this in the template by using for example: ``` craft.request.getSegments ``` or ``` craft.request.getParam( name ) ``` See the docs: <https://craftcms.com/docs/templating/craft.request>
2,755,102
Fifty years ago, we were taught to calculate square roots one digit at a time with pencil and paper (and in my case, an eraser was also required). That was before calculators with a square root button were available. (And a square root button is an incredibly powerful doorway to the calculation of other functions.) While trying to refresh that old skill, I found that the square root of 0.1111111.... was also a repeating decimal, 0.3333333.... Also, the square root of 0.4444444..... is 0.66666666..... My question: are there any other rational numbers whose square roots have repeating digit patterns? (with the repeating digit other than 9 or 0, of course)? The pattern might be longer than the single digit in the above examples.
2018/04/26
[ "https://math.stackexchange.com/questions/2755102", "https://math.stackexchange.com", "https://math.stackexchange.com/users/133895/" ]
A real as repeating digit patterns iff it is a rational. Your question is then under which conditions the square root of a rational $r$ is rational. The answer (see [here](https://math.stackexchange.com/questions/448172/what-rational-numbers-have-rational-square-roots/448180#448180)) is that $r$ must be the square of a rational. So $\sqrt{x}$ as a repeating pattern iff there exist integers $p$ and $q$ such that: $$x=\frac{p^2}{q^2}$$
84,956
I am researching this company <https://boldip.com/> How do I verify that 1. It's even a real law firm 2. It's credible 3. It's great at its practice
2022/10/02
[ "https://law.stackexchange.com/questions/84956", "https://law.stackexchange.com", "https://law.stackexchange.com/users/46457/" ]
As to #1, the US Patent and Trademark Office has a [patent practitioner search](https://oedci.uspto.gov/OEDCI/practitionerSearchEntry) where you can verify if someone is a registered patent practitioner. If so, it means they passed a [registration process] that evaluates their "legal, scientific, and technical qualifications, as well as good moral character and reputation", as well as a multiple-choice exam. I looked up a few of the attorneys listed on [the firm's About Us page](https://boldip.com/about-us/) and they show up as registered. So this seems like a good indication that they are a "real law firm". This does not address whether they are "credible" (I'm not sure what that means), or how to evaluate the firm's quality, and I will leave it to someone else to answer that.
69,155,288
I'm supposed to write a LIFO (last in first out) class for chars, which can be edited by Pop and Add functions and seen by Peek function or foreach. Class is working on array to be more optimalized, but foreach for some reason's not working. I tried to make function GetEnumerator based on return value of \_arr.GetEnumerator() function, but it was not working, because when I printed item, in console was shown TestApp.LIFO, so I made this, but now foreach won't print a single item and by debuging \_i value on Reset function is 0. Can someone say why is it happening and suggest solution? ``` using System; using System.Collections; using System.Collections.Generic; namespace TestApp { internal class LIFO : IEnumerator, IEnumerable { public LIFO(int size) { _arr = new char[size]; _index = 0; } public LIFO(char[] arr) { _arr = arr.Clone() as char[]; _index = 0; } public char Peek() => _index == 0 ? '\0' : _arr[_index - 1]; public bool Add(char c) { if (_index == _arr.Length) return false; try { _arr[_index] = c; } catch (Exception) { return false; } ++_index; return true; } public void Pop() { if (_index == 0) return; _arr[--_index] = '\0'; } private int _i; public IEnumerator GetEnumerator() => this; public bool MoveNext() => --_i > -1; public void Reset() => _i = _index - 1; public object Current => _arr[_i]; private int _index; private readonly char[] _arr; } } ``` In Program.cs: ``` using System; namespace TestApp { internal static class Program { private static void Main() { LIFO l = new(17); l.Add('k'); l.Add('h'); l.Add('c'); foreach (var item in l) Console.WriteLine(l); } } } ```
2021/09/12
[ "https://Stackoverflow.com/questions/69155288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16832655/" ]
The issue is that `Reset` is not called. It is no longer needed but the interface is not changed due to backwards compatibility. Since new iterators implemented using `yield return` is actually required to throw an exception if `Reset` is called, no code is expected to call this method anymore. As such, your iterator index variable, `_i`, is never initialized and stays at 0. The first call to `MoveNext` steps it below 0 and then returns `false`, ending the `foreach` loop before it even started. You should always decouple the iterators from your actual collection as it should be safe to enumerate the same collection twice in a nested manner, storing the index variable as an instance variable in your collection prevents this. You can, however, simplify the enumerator implementation vastly by using [yield return](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield) like this: ``` public class LIFO : IEnumerable { ... public IEnumerator GetEnumerator() { for (int i = _index - 1; i >= 0; i--) yield return _arr[i]; } } ``` You can then remove the `_i` variable, the `MoveNext` and `Reset` methods, as well as the `Current` property. If you first want to make your existing code working, with the above note I made about nesting enumerators, you can change your `GetEnumerator` and `Reset` methods as follows: ``` public IEnumerator GetEnumerator() { Reset(); return this; } public void Reset() => _i = _index; ``` Note that you have to reset the `_i` variable to one step past the last (first) value as you're decrementing it inside `MoveNext`. If you don't, you'll ignore the last item added to the LIFO stack.
18,647,942
Is there's a way to get the indices properly from a Pymel/Maya API function? I know Pymel has a function called `getEdges()` however according to their docs this get's them from the selected face, however I just need them from the selected edges. Is this possible?
2013/09/06
[ "https://Stackoverflow.com/questions/18647942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1683943/" ]
While your answer will work theodox, I did find a much simpler resolution, after some serious digging! Turns out, hiding and not very well documented, was a function ironically called `indices()`, I did search for this but nothing came up in the docs. **Pymel** `selection[0].indices()[0]` The above will give us the integer of the selected edge. Simple and elegant!
62,972,549
Im working an a project using Tkinter right now. Whenever I input 'Japan', it prints out: ``` [('Japan', '23,473', 0.0, 985.0, '3,392', '19,096')] ``` I'm not really sure if that's a list or if it's a tuple? I want to seperate all of that data thats seperated by the commas into different variables. Heres what I have so far. If you see any other holes in my code help would greatly be appreciated. Thanks! ``` def subby(): answer=country_name.get() l_answer = answer.capitalize() sql_command = "SELECT * FROM covid WHERE `name` = ?;" values = (l_answer,) cursor.execute(sql_command,values) data = cursor.fetchall() print (data) users0.set(data[0]) users1.set(data[1]) users2.set(data[2]) users3.set(data[3]) users4.set(data[4]) users5.set(data[5]) ```
2020/07/18
[ "https://Stackoverflow.com/questions/62972549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The 'problem' arises because of the change in tsconfig files (solutions style tsconfig) that comes with Typescript 3.9 and Angular 10. More info here : <https://github.com/microsoft/TypeScript/issues/39632> <https://docs.google.com/document/d/1eB6cGCG_2ircfS5GzpDC9dBgikeYYcMxghVH5sDESHw/edit#> **Solution style tsconfig impact in Angular 10** > > In TypeScript 3.9, the concept of solutions style tsconfig was > introduced, in Angular we saw the potentiation and possibility of > fixing long outstanding issues such as incorrectly having test typings > in components files. In Angular CLI version 10 we adopted scaffolded > new and migrated existing workspaces to use solution-style Typescript > configuration. > > > When having an unreferenced file, this will not be part of any > TypeScript program, this is because Angular CLI scaffolds tsconfig > using the files option as opposed to include and exclude. > > > 1. Unreferenced files don’t inherit compiler options > > > When having an unreferenced file, this will not be part of any TypeScript program > and Language service will fallback to use the inferred project configuration. > > > Below find an example of changes that will be required in the application > tsconfig file (tsconfig.app.json). Changes to other tsconfig files will also > be needed. > > > Current tsconfig.app.json > > > > ``` > { > "extends": "./tsconfig.base.json", > "compilerOptions": { > ... > }, > "files": [ > "src/main.ts", > "src/polyfills.ts" > ], > "include": [ > "src/**/*.d.ts" > ] > } > > ``` > > Proposed tsconfig.app.json > > > > ``` > { > "extends": "./tsconfig.base.json", > "compilerOptions": { > ... > }, > "include": [ > "src/**/*.ts" > ], > "exclude": [ > "src/test.ts", > "src/**/*.spec.ts", > "src/**/*.server*", > "src/**/*.worker.ts" > ] > } > > ``` > >
210,779
> > **Is the Solar System stable?** > > > You can see [this](https://en.wikipedia.org/wiki/Stability_of_the_Solar_System) Wikipedia page. In May 2015 I was at the conference of Cedric Villani at Sharif university of technology with this title: "Of planets, stars and eternity (stabilization and long-time behavior in classical celestial mechanics)" , at the end of this conference one of the students asked him this question and he laughed strangely(!) with no convincing answer! **Edit**: The purpose of "long-time" is timescale more than [Lyapunov time](https://en.wikipedia.org/wiki/Lyapunov_time), hence billions of years.
2015/07/04
[ "https://mathoverflow.net/questions/210779", "https://mathoverflow.net", "https://mathoverflow.net/users/-1/" ]
Due to chaotic behaviour of the Solar System, it is not possible to precisely predict the evolution of the Solar System over 5 Gyr and the question of its long-term stability can only be answered in a statistical sense. For example, in <http://www.nature.com/nature/journal/v459/n7248/full/nature08096.html> (Existence of collisional trajectories of Mercury, Mars and Venus with the Earth, by J. Laskar and M. Gastineau) 2501 orbits with different initial conditions all consistent with our present knowledge of the parameters of the Solar System were traced out in computer simulations up to 5 Gyr. The main finding of the paper is that one percent of the solutions lead to a large enough increase in Mercury's eccentricity to allow its collisions with Venus or the Sun. Probably the most surprising result of the paper (see also <http://arxiv.org/abs/1209.5996>) is that in a pure Newtonian world the probability of collisions within 5 Gyr grows to 60 percent and therefore general relativity is crucial for long-term stability of the inner solar system. Many questions remain, however, about reliability of the present day consensus that the odds for the catastrophic destabilization of the inner planets are in the order of a few percent. I do not know if the effects of galactic tidal perturbations or possible perturbations from passing stars are taken into account. Also different numerical algorithms lead to statistically different results (see, for example, <http://arxiv.org/abs/1506.07602>). Some interesting historical background of solar system stability studies can be found in <http://arxiv.org/abs/1411.4930> (Michel Henon and the Stability of the Solar System, by Jacques Laskar).
71,301,486
I am scraping and modifying content from a website. The website consists of broken images that I need to fix. My JSON looks something like this ``` [ { "post_title": "post 1", "post_link": "link 1", "post_date": "@1550725200", "post_content": [ "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna <a href=\"somelink.com\">aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<a href=\"url1.jpg\"><img src=\"brokenURL1.jpg\" alt=\"\"></a><a href=\"url2.jpg\"><img src=\"brokenURL2.jpg\" alt=\"\"></a><a href=\"url3.jpg\"><img src=\"brokenURL3.jpg\" alt=\"\"></a><a href=\"url4.jpg\"><img src=\"brokenURL4.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 2", "post_link": "link 2", "post_date": "@1550725200", "post_content": [ "<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, <a href=\"somelink.com\">similique</a> sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.<a href=\"url5.jpg\"><img src=\"brokenURL5.jpg\" alt=\"\"></a><a href=\"url6.jpg\"><img src=\"brokenURL6.jpg\" alt=\"\"></a><a href=\"url7.jpg\"><img src=\"brokenURL7.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 3", "post_link": "link 3", "post_date": "@1550725200", "post_content": [ "<p>Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. <a href=\"url8.jpg\"><img src=\"brokenURL8.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 4", "post_link": "link 4", "post_date": "@1550725200", "post_content": [ "<p>Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis <a href=\"somelink.com\">doloribus asperiores repellat</a>.<a href=\"url9.jpg\"><img src=\"brokenURL9.jpg\" alt=\"\"></a><a href=\"url10.jpg\"><img src=\"brokenURL10.jpg\" alt=\"\"></a><a href=\"url11.jpg\"><img src=\"brokenURL11.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } } ] ``` I have the image links and I want to replace every instance of the src link with the a href link. So the end result would look something like this. ``` [ { "post_title": "post 1", "post_link": "link 1", "post_date": "@1550725200", "post_content": [ "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna <a href=\"somelink.com\">aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<a href=\"url1.jpg\"><img src=\"url1.jpg\" alt=\"\"></a><a href=\"url2.jpg\"><img src=\"url2.jpg\" alt=\"\"></a><a href=\"url3.jpg\"><img src=\"url3.jpg\" alt=\"\"></a><a href=\"url4.jpg\"><img src=\"url4.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 2", "post_link": "link 2", "post_date": "@1550725200", "post_content": [ "<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, <a href=\"somelink.com\">similique</a> sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.<a href=\"url5.jpg\"><img src=\"url5.jpg\" alt=\"\"></a><a href=\"url6.jpg\"><img src=\"url6.jpg\" alt=\"\"></a><a href=\"url7.jpg\"><img src=\"url7.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 3", "post_link": "link 3", "post_date": "@1550725200", "post_content": [ "<p>Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. <a href=\"url8.jpg\"><img src=\"url8.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 4", "post_link": "link 4", "post_date": "@1550725200", "post_content": [ "<p>Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis <a href=\"somelink.com\">doloribus asperiores repellat</a>.<a href=\"url9.jpg\"><img src=\"url9.jpg\" alt=\"\"></a><a href=\"url10.jpg\"><img src=\"url10.jpg\" alt=\"\"></a><a href=\"url11.jpg\"><img src=\"url11.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } } ] ``` I also have random links that are not associated with images and are just links like in post 1, 2 and 4. Is there any way to do this with Javascript? Thanks
2022/02/28
[ "https://Stackoverflow.com/questions/71301486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17074732/" ]
Consider using the [`DOMParser`](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser) utility to create a document from your html string. Then you can use the typical DOM methods (notably, `querySelectorAll`) to find the relevant elements and then to execute your replacement. Eg, something like: ``` const parser = new DOMParser(); const doc = parser.parseFromString(html_string_here, "text/html") doc.querySelectorAll("a > img").forEach(img => img.setAttribute("src", img.parentElement.getAttribute("href"))) ``` Using your example data, you might write it like so: ```js const example_data = [{ "post_title": "post 1", "post_link": "link 1", "post_date": "@1550725200", "post_content": [ "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna <a href=\"somelink.com\">aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<a href=\"url1.jpg\"><img src=\"brokenURL1.jpg\" alt=\"\"></a><a href=\"url2.jpg\"><img src=\"brokenURL2.jpg\" alt=\"\"></a><a href=\"url3.jpg\"><img src=\"brokenURL3.jpg\" alt=\"\"></a><a href=\"url4.jpg\"><img src=\"brokenURL4.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 2", "post_link": "link 2", "post_date": "@1550725200", "post_content": [ "<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, <a href=\"somelink.com\">similique</a> sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.<a href=\"url5.jpg\"><img src=\"brokenURL5.jpg\" alt=\"\"></a><a href=\"url6.jpg\"><img src=\"brokenURL6.jpg\" alt=\"\"></a><a href=\"url7.jpg\"><img src=\"brokenURL7.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 3", "post_link": "link 3", "post_date": "@1550725200", "post_content": [ "<p>Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. <a href=\"url8.jpg\"><img src=\"brokenURL8.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 4", "post_link": "link 4", "post_date": "@1550725200", "post_content": [ "<p>Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis <a href=\"somelink.com\">doloribus asperiores repellat</a>.<a href=\"url9.jpg\"><img src=\"brokenURL9.jpg\" alt=\"\"></a><a href=\"url10.jpg\"><img src=\"brokenURL10.jpg\" alt=\"\"></a><a href=\"url11.jpg\"><img src=\"brokenURL11.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } } ] const parser = new DOMParser(); const fixed_links_data = example_data.map(item => { return { ...item, post_content: item.post_content.map(html => { const doc = parser.parseFromString(html, "text/html"); doc.querySelectorAll("a > img").forEach(img => img.setAttribute("src", img.parentElement.getAttribute("href"))); return doc.body.innerHTML; }), } }); console.log("Final Result:", fixed_links_data) ```
618,483
I am using the `amsmath` package. My code is ``` \begin{center} \left $\begin{bmatrix} u_1 & u_2\\ u_3 & u_4 \end{bmatrix}$ \end{center} \begin{center} \right $\begin{bmatrix} u_1 & u_2\\ u_3 & u_4 \end{bmatrix}$ \end{center} ``` Thanks for any help!
2021/10/10
[ "https://tex.stackexchange.com/questions/618483", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/254367/" ]
* Please, always provide complete small document called MWE (Minimal Working Example) which reproduce your problem. * your question is not entirely clear, so I guess, that you after the following: [![enter image description here](https://i.stack.imgur.com/V6mKz.png)](https://i.stack.imgur.com/V6mKz.png) MWE: ``` \documentclass{article} \usepackage{amsmath} \begin{document} \[ \begin{bmatrix} u_1 & u_2\\ u_3 & u_4 \end{bmatrix}% \begin{bmatrix} u_1 & u_2\\ u_3 & u_4 \end{bmatrix} \] \end{document} ``` Comparison of above code with your code fragment shows, that it contain a lot of clutter: `\left`, `right`, `\begin{center} ... \end{center}`. In above MWE used symbols `\[` and `\]` switch from "text mode" to "math mode". They are equivalent to `\begin{equation*}` and `\end{equation*}` respectively.
302,744
When using the Book module, is there any limit on the number of child items that can be added to a book parent node?
2021/04/28
[ "https://drupal.stackexchange.com/questions/302744", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/98004/" ]
Yes, books in Drupal 8 and 9 have a maximum depth of 9, which is the value of the [`BookManager::BOOK_MAX_DEPTH`](https://api.drupal.org/api/drupal/core%21modules%21book%21src%21BookManager.php/constant/BookManager%3A%3ABOOK_MAX_DEPTH/8.8.x) constant. ```php const BOOK_MAX_DEPTH = 9; ```
19,800,821
Before I debug my code, I would like to know why there's an error occurred when I call the function? It says "NameError: name 'stDigs' is not defined". I've tried using "avgUntilLetter(0123a)" and "avgUntilLetter("0123a")" but none of them works. Help me plz! This function receives as input one string containing digits or letters. The function should return one float number contaning the average calculated considering all the digits in the string starting form the first position and considerign all digits until one letter is found or until reaching the end of the string. An example: avgUntilLetter('0123a456') should return 1.5 ``` def avgUntilLetter (stDigs): num = 0 each_char = stDigs[num] while each_char.isdigit() == True and num < len(stDigs): num = num + 1 each_char = stDigs[num] digits = stDigs[0:num] avg = sum(digits)/len(digits) return avg avgUntilLetter(stDigs) ``` --- Yes, I know there are a lot errors needed to be solved. I just need to solve it one at a time. When I call the function using "avgUntilLetter ("0123a")", the defined error disappeared but a type error popped up. Hmm.. I'm still keeping trying it.
2013/11/05
[ "https://Stackoverflow.com/questions/19800821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2958352/" ]
There are several problems in your code: 1. You can end up trying to access `stDigs[len(stDigs)]` because `num < len(stDigs)` might be true, but you then add 1 before using it as an index. 2. `sum(digits)` won't work because `digits` is a string. Just loop over the string *directly* instead of using a `while` loop, add up the digits in the loop: ``` def avgUntilLetter(stDigs): total = i = 0 for i, each_char in enumerate(stDigs): if not each_char.isdigit(): break total += float(each_char) if i: return total / i return 0.0 ``` This handles edge-cases as well: ``` >>> avgUntilLetter('0123a456') 1.5 >>> avgUntilLetter('') 0.0 >>> avgUntilLetter('abc') 0.0 ```