id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_codereview.59828 | I'm working on a project of mine, and I've had to write out a fair bit of jQuery. This is a generator and a calculator for some League of Legends related content.I was wondering if you could see any possible compact-ness changes that could be made.Here is my code. Hopefully I can trust you to take a look at it without taking it.note: The table is 12x24 broken down into 3x6var max_points = 30var spent_points = 0var total_off = 0var total_def = 0var total_utl = 0$('document').ready(function() { $('table.masteries tr.p0 td:nth-child(1)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p0 td:nth-child(2)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p0 td:nth-child(3)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p0 td:nth-child(4)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p0 td:nth-child(5)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p0 td:nth-child(6)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p0 td:nth-child(7)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p0 td:nth-child(8)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p0 td:nth-child(9)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p0 td:nth-child(10)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p0 td:nth-child(11)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p0 td:nth-child(12)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p0 td').on('click', function(){ if(spent_points < max_points) { if(!this.i){ this.i = 0; } s = $(this).find('p').text() current_max = parseInt(s.substr(s.length - 1)) if ( $(this).is($(':nth-child(1)')) || $(this).is($(':nth-child(2)')) || $(this).is($(':nth-child(3)')) || $(this).is($(':nth-child(4)')) ) { if(this.i < current_max) { this.i = this.i+1 total_off = total_off + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.offensive').text(total_off); $('span.spent').text(spent_points); } console.log(this.i); } else if ( $(this).is($(':nth-child(5)')) || $(this).is($(':nth-child(6)')) || $(this).is($(':nth-child(7)')) || $(this).is($(':nth-child(8)')) ) { if(this.i < current_max) { this.i = this.i+1 total_def = total_def + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.defensive').text(total_def); $('span.spent').text(spent_points); } console.log(this.i); } else if ( $(this).is($(':nth-child(9)')) || $(this).is($(':nth-child(10)')) || $(this).is($(':nth-child(11)')) || $(this).is($(':nth-child(12)')) ) { if(this.i < current_max) { this.i = this.i+1 total_utl = total_utl + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.utility').text(total_utl); $('span.spent').text(spent_points); } console.log(this.i); } if(total_off >= 4) { $('table.masteries tr.p4 td:nth-child(1)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p4 td:nth-child(2)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p4 td:nth-child(3)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p4 td:nth-child(4)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); } if(total_def >= 4) { $('table.masteries tr.p4 td:nth-child(5)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p4 td:nth-child(6)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p4 td:nth-child(8)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); } if(total_utl >= 4) { $('table.masteries tr.p4 td:nth-child(10)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p4 td:nth-child(11)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p4 td:nth-child(12)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); } }}); $('table.masteries tr.p4 td').on('click', function(){ if(spent_points < max_points) { if(!this.i){ this.i = 0; } s = $(this).find('p').text() current_max = parseInt(s.substr(s.length - 1)) if ( $(this).is($(':nth-child(1)')) || $(this).is($(':nth-child(2)')) || $(this).is($(':nth-child(3)')) || $(this).is($(':nth-child(4)')) ) { if(this.i < current_max) { this.i = this.i+1 total_off = total_off + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.offensive').text(total_off); $('span.spent').text(spent_points); } console.log(this.i); } else if ( $(this).is($(':nth-child(5)')) || $(this).is($(':nth-child(6)')) || $(this).is($(':nth-child(7)')) || $(this).is($(':nth-child(8)')) ) { if(this.i < current_max) { this.i = this.i+1 total_def = total_def + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.defensive').text(total_def); $('span.spent').text(spent_points); } console.log(this.i); } else if ( $(this).is($(':nth-child(9)')) || $(this).is($(':nth-child(10)')) || $(this).is($(':nth-child(11)')) || $(this).is($(':nth-child(12)')) ) { if(this.i < current_max) { this.i = this.i+1 total_utl = total_utl + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.utility').text(total_utl); $('span.spent').text(spent_points); } console.log(this.i); } if(total_off >= 8) { $('table.masteries tr.p8 td:nth-child(1)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p8 td:nth-child(2)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p8 td:nth-child(3)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p8 td:nth-child(4)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); } if(total_def >= 8) { $('table.masteries tr.p8 td:nth-child(5)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p8 td:nth-child(6)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p8 td:nth-child(7)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p8 td:nth-child(8)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); } if(total_utl >= 8) { $('table.masteries tr.p8 td:nth-child(9)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p8 td:nth-child(10)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p8 td:nth-child(11)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p8 td:nth-child(12)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); } }}); $('table.masteries tr.p8 td').on('click', function(){ if(spent_points < max_points) { if(!this.i){ this.i = 0; } s = $(this).find('p').text() current_max = parseInt(s.substr(s.length - 1)) if ( $(this).is($(':nth-child(1)')) || $(this).is($(':nth-child(2)')) || $(this).is($(':nth-child(3)')) || $(this).is($(':nth-child(4)')) ) { if(this.i < current_max) { this.i = this.i+1 total_off = total_off + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.offensive').text(total_off); $('span.spent').text(spent_points); } console.log(this.i); } else if ( $(this).is($(':nth-child(5)')) || $(this).is($(':nth-child(6)')) || $(this).is($(':nth-child(7)')) || $(this).is($(':nth-child(8)')) ) { if(this.i < current_max) { this.i = this.i+1 total_def = total_def + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.defensive').text(total_def); $('span.spent').text(spent_points); } console.log(this.i); } else if ( $(this).is($(':nth-child(9)')) || $(this).is($(':nth-child(10)')) || $(this).is($(':nth-child(11)')) || $(this).is($(':nth-child(12)')) ) { if(this.i < current_max) { this.i = this.i+1 total_utl = total_utl + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.utility').text(total_utl); $('span.spent').text(spent_points); } console.log(this.i); } if(total_off >= 12) { $('table.masteries tr.p12 td:nth-child(1)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p12 td:nth-child(2)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p12 td:nth-child(3)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p12 td:nth-child(4)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); } if(total_def >= 12) { $('table.masteries tr.p12 td:nth-child(5)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p12 td:nth-child(6)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p12 td:nth-child(7)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p12 td:nth-child(8)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); } if(total_utl >= 12) { $('table.masteries tr.p12 td:nth-child(9)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p12 td:nth-child(10)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p12 td:nth-child(11)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p12 td:nth-child(12)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); } }}); $('table.masteries tr.p12 td').on('click', function(){ if(spent_points < max_points) { if(!this.i){ this.i = 0; } s = $(this).find('p').text() current_max = parseInt(s.substr(s.length - 1)) if ( $(this).is($(':nth-child(1)')) || $(this).is($(':nth-child(2)')) || $(this).is($(':nth-child(3)')) || $(this).is($(':nth-child(4)')) ) { if(this.i < current_max) { this.i = this.i+1 total_off = total_off + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.offensive').text(total_off); $('span.spent').text(spent_points); } console.log(this.i); } else if ( $(this).is($(':nth-child(5)')) || $(this).is($(':nth-child(6)')) || $(this).is($(':nth-child(7)')) || $(this).is($(':nth-child(8)')) ) { if(this.i < current_max) { this.i = this.i+1 total_def = total_def + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.defensive').text(total_def); $('span.spent').text(spent_points); } console.log(this.i); } else if ( $(this).is($(':nth-child(9)')) || $(this).is($(':nth-child(10)')) || $(this).is($(':nth-child(11)')) || $(this).is($(':nth-child(12)')) ) { if(this.i < current_max) { this.i = this.i+1 total_utl = total_utl + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.utility').text(total_utl); $('span.spent').text(spent_points); } console.log(this.i); } if(total_off >= 16) { $('table.masteries tr.p16 td:nth-child(1)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p16 td:nth-child(2)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p16 td:nth-child(4)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); } if(total_def >= 16) { $('table.masteries tr.p16 td:nth-child(5)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p16 td:nth-child(6)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p16 td:nth-child(7)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); } if(total_utl >= 16) { $('table.masteries tr.p16 td:nth-child(10)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); $('table.masteries tr.p16 td:nth-child(11)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); } }}); $('table.masteries tr.p16 td').on('click', function(){ if(spent_points < max_points) { if(!this.i){ this.i = 0; } s = $(this).find('p').text() current_max = parseInt(s.substr(s.length - 1)) if ( $(this).is($(':nth-child(1)')) || $(this).is($(':nth-child(2)')) || $(this).is($(':nth-child(4)')) ) { if(this.i < current_max) { this.i = this.i+1 total_off = total_off + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.offensive').text(total_off); $('span.spent').text(spent_points); } console.log(this.i); } else if ( $(this).is($(':nth-child(5)')) || $(this).is($(':nth-child(6)')) || $(this).is($(':nth-child(7)')) ) { if(this.i < current_max) { this.i = this.i+1 total_def = total_def + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.defensive').text(total_def); $('span.spent').text(spent_points); } console.log(this.i); } else if ( $(this).is($(':nth-child(10)')) || $(this).is($(':nth-child(11)')) ) { if(this.i < current_max) { this.i = this.i+1 total_utl = total_utl + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.utility').text(total_utl); $('span.spent').text(spent_points); } console.log(this.i); } if(total_off >= 20) { $('table.masteries tr.p20 td:nth-child(2)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); } if(total_def >= 20) { $('table.masteries tr.p20 td:nth-child(6)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); } if(total_utl >= 20) { $('table.masteries tr.p20 td:nth-child(10)') .attr(style,background-image:url('./assets/masteries/mastery0.png')); } }}); $('table.masteries tr.p20 td').on('click', function(){ if(spent_points < max_points) { if(!this.i){ this.i = 0; } s = $(this).find('p').text() current_max = parseInt(s.substr(s.length - 1)) if ($(this).is($(':nth-child(2)'))) { if(this.i < current_max) { this.i = this.i+1 total_off = total_off + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.offensive').text(total_off); $('span.spent').text(spent_points); } console.log(this.i); } else if ($(this).is($(':nth-child(6)'))) { if(this.i < current_max) { this.i = this.i+1 total_def = total_def + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.defensive').text(total_def); $('span.spent').text(spent_points); } console.log(this.i); } else if ($(this).is($(':nth-child(10)'))) { if(this.i < current_max) { this.i = this.i+1 total_utl = total_utl + 1 spent_points = spent_points + 1 $(this).find('span').text(this.i); $('span.utility').text(total_utl); $('span.spent').text(spent_points); } console.log(this.i); } }}); }); | Generator and calculator for League of Legends content | javascript;jquery | A primer for people unfamiliar with League of LegendsThis should have been included in OP, but it wasn't. I'll describe the Mastery system here.League of Legends has a customisable component known as a a collective Mastery Tree. This shares aspects with skill trees or talent trees from other games; it's a hierarchical arrangement of Masteries. Masteries come in three flavours, or trees: Offense, Defense, and Utility, represented by total_off, total_def, and total_utl in OP's code. Players can spend up to 30 total points, and different masteries have different limits on how many points may be spent on them. For example, the Phasewalker mastery has a cap of one point, while a player can spend up to 4 points in the Fury mastery. In addition to being split up by category, masteries are also separated by depth. Each tree is arranged in six rows. In order to be able to spend points in lower rows, a certain number of points must have been spent in earlier rows in the same tree.An example of what OP is trying to create can be found here.You've mixed together the trees. This is silly. There's no point in putting Offense masteries together with Utility masteries. Create three separate tables: one for Offense, one for Defense, and one for Utility. By doing so, you'll save yourself from all the pointless if ($(this).is($(:nth-child(1))) || ... checking.Javascript uses camelCase. I'd rename your variables to maxPoints, etc.CSS should not be set with attr(). Setting CSS with attr is just about the worst way to do it, unless you know what you're doing. This will overwrite all other style changes. Instead, use .css(background-image, url:(...)).There's no point in modifying each td individually. table.masteries tr.p0 has exactly 12 children, so you can just use $(table.masteries tr.p0 td). (If for some reason you needed to only select those twelve, then you could use $(... td:nth-child(n + 1):not(:nth-child(n + 13))), but I'm certain that's not the case here.)Here's my rewrite of lines 8 through 31:$(table.masteries tr.p0 td).css(background-image, url('assets/masteries/mastery0.png'));Don't create properties in DOM objects to save data. Instead of using this.i, try something like $(this).data(i). Better yet, make a meaningful name, like $(this).data(pointsSpent).Avoid polluting global scope. Declare local variables with var s before using them.Store jQuery objects instead of continuously creating them. Constructing jQuery objects is not free. Instead, save it with a local variable using var $this = $(this) for later use.Use semicolons consistently. Either use them or omit them. Don't use them in some places and omit them in others.Don't assume console is available. It won't be in IE unless DevTools is open, so avoid using it unless you put var console = console || { log: function(){}, ... }; somewhere in your code.Personally, I think giving rows classes according to their index is pointless; you could just use a :nth-child() selector instead.You aren't using .is() right. Use a selector without constructing a jQuery object: $(this).is(:nth-child(1)).Your way of finding the max points to spend on a mastery is a nightmare to maintain. Rather than scanning some child <p> element, just specify the data on the cell: <td data-maxPoints=4>Fury</td>, or similar.Instead of spent_points = spent_points + 1, you could be doing spent_points++.You are repeating a lot of code that could otherwise be put into a common function.Rather than hard-coding the number of required points, store them in an array or calculate them:var pointsRequiredByRow = [0, 4, 8, 12, 16, 20];// or just notice that points required = row * 4, where row is zero-basedYou have a ton to fix. I've listed some things for you to get started on, but a comprehensive review would be way too long. I suggest making some changes and then asking a follow-up question with your revised code. |
_webapps.47402 | Isn't there anywhere an option to disable this behavior?Even gmail doesn't activate your status (when you are idle) as soon as you just click on gmail tab!It's a very bad behavior that trello shows everyone that you are online even when just you want to view the page!Wish there was a solution for this terrible behavior of Trello. | Trello shows me online when I just click on its tab (not bringing the mouse in) | trello | I really don't see the issue here. If you open the tab, it should be assumed that you are active on it, even if it was for a second. If you don't want people to know you are on then don't open the tab yet. |
_webmaster.97071 | I have an 'internal' website at my company that i'd like to allow outside access to via a reverse proxy with an Apache Server.The wrinkle here is that I only want particular Mobile Users accessing this reverse proxy.I've created a very generic mobile app that will ALWAYS pass a cookie like MOBILEUSER=TRUE.Is it possible to write a mod_rewrite rule to check for the existence of that cookie and ONLY allow requests with that cookie and value through?thanks for any help!! | Using mod_rewrite to check for existence of a cookie | mod rewrite;reverse proxy | null |
_cs.57911 | I was reading hashing from CLRS. In it author says:Let $\mathscr{H}$ be a finite collection of hash functions that map a given universe $U$ of keys into the range ${0,1,...,m-1}$. Such a collection is said to be universal if for each pair of distinct keys $k,l\in U$, the number of hash functions $h\in\mathscr{H}$ for which $h(k)= h(l)$ is at most $|\mathscr{H}|/m$. So basically in universal set of hash functions, the number of hash functions a finite collection of hash functions is said to be universal if number of hash functions $h$ for which $h(k)=h(l)$ is at most $\frac{\text{number of hash functions}}{\text{size of hash table}}=\frac{|\mathscr{H}|}{m}$However next the author says:In other words, with a hash function randomly chosen from $\mathscr{H}$, the chance of a collision between distinct keys $k$ and $l$ is no more than the chance $1/m$ of a collision if $h(k)$ and $h(l)$ were randomly and independently chosen from the set $\{0,1,...,m-1\}$.I didnt get the last part $h(k)$ and $h(l)$ were randomly and independently chosen from the set $\{0,1,...,m-1\}$. How $|\mathscr{H}|=$[$h(k)$ and $h(l)$ were randomly and independently chosen from the set $\{0,1,...,m-1\}$] | Constraint on Universal set of hash functions | hash;hash tables;hashing | null |
_webapps.43849 | I have three gmail groups A, B and C, each with say ten members. Now I want create another bigger gmail group, say, BIG containing all the members of A, B, and C.I tried simply clicking on the plus button and writing the names A, B and C. It did not work. Please tell me whether it is possible to add a gmail group to another gmail group in some way, or I should not bother?Do we have only the exhaustive way of individually adding all those thirty plus names to BIG? | Can I Create a Bigger Gmail Group from Several (Smaller) Gmail Groups? | gmail;google contacts | You cannot add a Google Contacts group to another group directly. Groups do not nest (kind of like how Gmail labels do not nest if you have not activated nesting in Labs). However, we don't need to add users to BIG one-by-one either. You have a couple options, actually.The Easy WayThe most direct, and probably easiest for most circumstances, is to batch add users from A to BIG, then from B to BIG, then from C to BIG (etc.). I assume you already have A, B, and C, so now create BIG. Now go to A. Click the Select All checkbox to select every contact in Group A. Then, click the Groups menu (the drop-down menu with a three-person icon) and click the open checkbox next to the BIG group. This will add everyone from A to BIG.Removing contacts from lists can be done on a one-by-one or group-by-group basis (or any combination thereof).Something More ElaborateUPDATE: Google no longer permits nested groups. No workaround at this time. My original notes still included here for reference purposes, and in the hopes that we find a workaround. Made my answer a wiki to facilitate other solutions!Hang on! you say. (I don't know, what do you usually say? It's a one-sided conversation right now, I get to put words in your mouth. Here come some more:) This easy way works for simple lists, but what if things get complicated? What if Jane Test is leaving Group B. Normally, this would mean that I remove her from BIG also. But I have lots of contacts and groups; Maybe Jane should still be in BIG because she is a member of Group C also. Or, what if I forget about this issue and don't check Jane's contact card for other groups when editing it, and then take her out of BIG mistakenly?Now I think you're being picky, but there is a solution for this too. Instead of using Google Contacts for these more complex contact/group and group/group relationships, create some private Google Groups for A, B, C, and BIG. Unlike Contacts groups, Groups groups (is that a thing?) can include other Groups groups. (See: http://support.google.com/a/bin/answer.py?hl=en&answer=167100) Look, we're just going to call those Groups now. You can email everyone in a Google Group by setting their member preferences (for that Group) to receive all posts by email, and then by emailing a post to the group. Every member of the group gets the email.That way, if Jane is in Groups B and C; and Groups A, B, and C are members of Group BIG; then when you remove Jane from Group B she will retain her membership in Group BIG in virtue of her membership in Group C. So, you don't have to check and you are less likely to mistakenly remove Jane from BIG. |
_webapps.25525 | I would like to embed a Google spreadsheet directly into my email, so that it reflects the document changes. How do I do that? | How to reference Google spreadsheet inside your mail message? | gmail;google spreadsheets | null |
_vi.9648 | File BATMAN:-2-3-4-6-8-10-11-13-14-16-17-18-19-20-21-25-29-30-33-35-36-37-43-44-45-47-48-49-50-51-52-54-55-56-57-58-59-60-61-62-63-64-65-66-68-69-70-71-73-74-75-76-81-82-83-85-86-87-88-89-90-91-92-94-95-96-97-98-99-101-102-103-104-108-110-111-112-113-114-115-116-117-128-129-130-131-132-133-134-135-136-137-147-148-149-150-151-154-155-156-157-158-159-160-161-162-163-164-165-166-167-168-171-173-174-175-177-180-184-185-186-187-188-189-190-191File ROBIN:-2-3-4-6-7-8-11-16-17-18-20-21-29-30-33-34-35-36-37-44-48-49-51-52-55-56-57-58-61-65-66-67-69-70-71-74-75-76-80-81-82-83-86-90-91-92-95-97-98-100-101-103-104-119-120-121-122-123-124-125-127-129-131-132-133-134-136-138-139-140-141-142-143-144-150-156-157-158-161-163-164-165-166-167-172-173-175-179-184-186-189-191File LOCUTOR:-4-147I work in a translation company , and need to count the time that the actor speaks, and insert the count into the current file.In my vimrc file I created this function:fun! Abb() exe :s/-//gnendfuncHow do I insert the number of word count manually. Thanks for your help | Vim Word count and insert into current text | vimscript;count | Assuming for each actor, you only have a single line with the many hyphens and your cursor is on a line with the many hyphens, you can do it like this:call append('.', Count: .len(split(getline('.'),'-')))Of course you can now wrap it into a function, find the next line with hyphens in it, if the cursor is not on it or add some error management. That is left as an excercise to the reader :) |
_cogsci.3150 | Background Information of my questions:At the age of eight I was diagnosed with Dyslexia, I am now 47. I went from not being able to read and barely able to write to a college reading level in 9 months. I was in a program run by a Mrs. Cooper in Pennsylvania. I have taken several different IQ tests during my lifetime and found the results vary widely. I have noted that in the last ten years or so Dyslexia seems to be an almost antiquated diagnosis and am very curious about the definition of dyslexia in current science and the correlation, if any, between Dyslexia and intelligence.Questions:Is there any specific IQ test that is directed at measuring the IQ's of people with dyslexia? What is the correlation between having dyslexia and IQ? | Dyslexia and IQ | learning;measurement;intelligence;reading;iq | null |
_cogsci.1617 | Recently, Joseph Henrich of UBC has been promoting his cultural brain hypothesis. The goal is to explain a selection pressure behind the development of the human brain and general intelligence. The basic premise is that our brains evolved to be better and better at accurately replicating cultural information (or memes) between generations. A secondary part of his hypothesis is that there was a tight co-evolution between culture and the genes that shape us.This seems contrary to the more orthodox thinking of that genes shaped the base of humans largely without large-scale culture (when we were small hunter-gatherer tribes and thus culture was minimal), and then recently (on an evolutionary time scale) large-scale culture 'turned on' and there has not been a sufficient time for this to produce large genetic differences. In simplest terms, the co-evolution was minimal and instead we should think of the key players being gene evolution followed by cultural evolution (on different timescales).To confuse things further, some scientists (like Satoshi Kanazawa of LSE) view most of what we associated with the 'perks' of human brain (such as general intelligence) as mal-adaptive on the individual level. Thus there seems to be a large distinction between the 3 general threads, which raises the question:What is the key evidence for the cultural brain hypothesis and gene-culture co-evolution?The only evidence I know of potential recent co-evolution of culture and genes is Dediu & Ladd's (2007) suggestion that the split between tonal and atonal languages is related to a recent (~6k years ago) mutation in the ASPM gene. Is there other evidence of recent co-evolution between genes and large-scale culture?Related questionsDo atonal languages have a tonal ancestor?Is religiousness a genetically heritable feature? | Cultural brain hypothesis and gene-culture co-evolution | intelligence;evolution;philosophy of mind | null |
_unix.257650 | How to count how many files belong to each user/group combination? I need to do this for each user/group combination that exists, in each of the directory trees /etc, /usr, and /var. | How to count how many files belong to each user/group combination? | files;scripting;users;group | null |
_unix.48970 | I'd like to test auto-vote protection on my site (not published yet).I've found Expect program, but I can't get it working with telnet http. | How to create auto vote script using `expect`? | expect | I'd use the curl command line tool to do this. I'm presuming that you have a form submission, in which a field vote can choose A, B, or C, for example:curl -F vote=A http://example.com/submitvote/or, if there were a name field to go with it, for example:curl -F vote=C -F name=my name http://example.com/submitvote/ |
_webapps.28034 | Possible Duplicate:Search for multiple unrelated words in Google Search I've noticed recently that Google force-feeds me certain results even if I explicitly demand that a particular keyword be included. For example, searching for:None of the returned results include the word awful, though I was under the impression that + forces the word to appear in the results. Has this feature been deprecated by Google? If not, is there a way to perform a search that must include certain keywords?(P.S. I sincerely apologize to fans of this comedian. I just had no examples handy that did not include him.) | How to force Google to use a keyword? | google search | The plus sign no longer works in Google searches.Use quotes to search for an exact word. |
_codereview.106679 | I have a list of patients, Patient class has Prescriptions property, which is a list of Prescription objects. Prescription has 3 important attributes, Medicament,Amount and Type(which is basically a key for joining).I need to join a list of Prescription types, as a prescription type has an attribute Influence which servers as multiplier for the amount.var prescriptions = (from prs in (from p in patients from pr in p.Prescriptions join type in DatabaseService.PrescriptionTypes on pr.Type equals type.Value select new { Med = pr.Medicament,Amount = pr.Amount * (int)type.Influence }) group prs by prs.Med into prgs select new { Medicament = prgs.Key,Amount = prgs.Sum(prg => prg.Amount) }).ToList();Basically what I do (from inner to outer queries)Join prescriptions with prescription types, get Medicament and the multiplied AmountGroup the records by the MedicamentRun one more select to get the overall sum from all patientsIs there any simpler way?EDIT:So I realised couple things and simplified the query quite a bit, I think it's much more readable now. The things I missed the first time were:SelectMany that lets me get rid of the outter select, since prescriptions are all I care aboutBeing able to create new objects within group statement, hence one more select can be avoidedThe new code looks like var prescriptions = from p in patients.SelectMany(p => p.Prescriptions) join type in DatabaseService.PrescriptionTypes on p.Type equals type.Value group new { Amount = p.Amount * (int)type.Influence } by p.Medicament into prs select new { Medicament = prs.Key,Amount = prs.Sum(pr => pr.Amount) };With that I'm pretty happy and I doubt you can simplify it anymore. | Sum data that needs to be joined and grouped by | c#;linq | null |
_unix.280697 | I'm debugging a strange issue with a logging SaaS solution. We appear to be duplicating logs sent to the SaaS. Logs are sent via an rsyslog forwarder over TLS. I'm trying to see if I can reproduce the issue by running a remote rsyslog server and forwarding a since instance's logs to that server to monitor. Let's call the server where logs originate guineapig and the remote rsyslog server watcher. watcher is configured to listen on UDP port 514 using configuration like this:$ModLoad imudp.so$UDPServerRun 514$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat# log everything to the /var/log/remotesyslog file*.* /var/log/remotesyslog guineapig is configured to forward everything to watcher using its IP address:$ModLoad imuxsock$ModLoad imjournal$ModLoad imudp.so$UDPServerRun 514$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat$IncludeConfig /etc/rsyslog.d/*.conf$IMJournalStateFile imjournal.stateauthpriv.* /var/log/securemail.* -/var/log/maillogcron.* /var/log/cron*.emerg *uucp,news.crit /var/log/spoolerlocal7.* /var/log/boot.logInside /etc/rsyslog.d/22-remote-rsyslog.conf on guineapig:# forward everything over UDP to watcher*.* @@10.0.1.1:514Unfortunately, when I then restart the SystemD rsyslog service and attempt to trigger a log message on guineapig, I don't see it appear in the file on watcher:user@guineapig ~$ logger please work# doesn't workHowever, if I directly tell logger where to go, the log line shows up:user@guineapig ~$ logger -n 10.0.1.1 please work for real# worksI'm having a very difficult time trudging through rsyslog's documentation, but for some reason my logs aren't getting forwarded properly to watcher. Is there an obvious issue in my configuration on guineapig? Both systems are on CentOS 7. | rsyslog not forwarding messages to remote rsyslog server | centos;rsyslog | null |
_unix.4649 | Possible Duplicate:NIS and autofs error I have one server and one client machine.In Server, I have configured NIS, and /home/guest/nis1 is shared through NFS. Both NFS and NIS are configured in same server.In client, I have configured autofs to export home directory of NIS user. When I try to login in client from nis1 username then I got the following error message.Could not chdir to home directory /home/guest/nis1: Permission denied-bash: /home/guest/nis1/.bash_profile: Permission denied-bash-3.1$How Can i troubleshot?? | Problem with NIS | administration;nis | null |
_scicomp.23177 | I am looking for an algorithm to search a substring in a string. I know there are a number of wellknown Algorithms like Knuth-Morris-Pratt, for instance, and I suppose most preimplemented functions use one of those. However, I remember a lecture, long ago, where the lecturer said that the usefullness of such an algorithm depends partly on the size of the alphabet. KMP and BMH obviously work fine on an ordinary 26-letter alphabet. But what do I do if I have a much smaller alphabet (say, DNA: 4 letters or simply a binary)?Are there an particular algorithms that work well on very small alphabets? I googled and supposed I should easily find something as searching through DNA is rather common, but to no avail. Any help?Please do not downvote, this is my first question in this subcommunity, I do not know yet what is considered too basic here and what is ok. | String search algorithm on small alphabet | algorithms | null |
_softwareengineering.109187 | Recently I found that Netscape used quite simple algorithm to generate random number for Message Authentication Code to establish an HTTPS connection (Nestscpe used time, process identification number, and parent-process identification number). So now I wonder what source of seed do modern browsers use to guarantee true randomness? | Random number for HTTPS MAC | browser;encryption;random;https | null |
_webmaster.48828 | I am currently developing my record label's website and I'm sure I need a page on there about what information I will collect.The website has no log ins or any interaction from the user apart from clicking page to page. I still need a privacy policy page on here though don't I as I will log statistics using various tools? | What do I need to write for a privacy policy page on my website? | terms of use;privacy policy;problem | null |
_unix.170694 | I'm trying to map the shown with sudo fdisk -l and what is written in the MBR. However they seem to differ.What fdisk shows: Device Boot Start End Blocks Id System/dev/sda1 * 2048 490612735 245305344 83 Linux/dev/sda2 490614782 976771071 243078145 5 Extended/dev/sda5 968929280 976771071 3920896 82 Linux swap / Solaris/dev/sda6 490614784 968929279 239157248 83 LinuxWhat partition table in the MBR says:00001be: 8020 2100 83fe ffff 0008 0000 0020 3e1d . !.......... >.00001ce: 00fe ffff 05fe ffff fe2f 3e1d 0228 fa1c ........./>..(..00001de: 0000 0000 0000 0000 0000 0000 0000 0000 ................00001ee: 0000 0000 0000 0000 0000 0000 0000 0000 ................The steps for getting the MBR were:sudo dd if=/dev/sda of=~/mbr.file bs=512 count=1 Getting the first 512 bytes.xxd -s 446 -l 64 mbr.file Print just the partition tables. | MBR not corresponding to fdisk -l? | partition;fdisk;mbr | null |
_unix.48711 | When I run the command:awk '/from/ {print $7} /to/ { print $7}' erroMuitoDoido.txtThe file is:May 19 04:44:43 server postfix/smtpd[32595]: CDAB515013: client=servidor.dominio.com.br[10.10.10.44]May 19 04:44:43 server postfix/cleanup[18651]: CDAB515013: message-id=<[email protected]>May 19 04:44:43 server postfix/qmgr[16684]: CDAB515013: [email protected], size=19590, nrcpt=1 (queue active)May 19 04:44:50 server postfix/pipe[32596]: CDAB515013: [email protected], relay=dovecot, delay=6.2, delays=0.02/6/0/0.14, dsn=2.0.0, status=sent (delivered via dovecot service)May 19 04:44:50 server postfix/qmgr[16684]: CDAB515013: removedThe output is:[email protected],[email protected],[email protected],The problem is that the line [email protected], occurs twice! How can I fix this?AWK version: GNU Awk 4.0.0OS: Debian 6, OpenSuse 12.1, CentOS 6.2 | Why does awk execute both actions? | awk | null |
_unix.361813 | Im having an issue where rsyslog and other services will freeze when rsyslog can no longer write logs. Once I restart rsyslog, everything comes back up and works. I believe this is because the loq que has filled up and can no longer be written to. The main service affected is jabber. Im trying to find a way to tell rsyslog to destroy the logs in memory if it gets full and can no longer write. So far im unable to get this down. Any ideas? | Setting rsyslog to emtpy que when it is unable to write | rsyslog;rsyslogd | null |
_unix.42660 | I want to know whether it is possible to gunzip multiple files and rename them with one command/script.I have a bunch of files in the format:test.20120708191601.DAT.3599502593.gztest.20120708201601.DAT.99932140.gztest.20120708204600.DAT.1184686967.gztest.20120708212100.DAT.824089664.gztest.20120708215100.DAT.1286044098.gztest.20120708222100.DAT.1414234861.gzI need to gunzip them and remove everything after the .DAT, to be in the format:test.20120708191601.DATtest.20120708201601.DATtest.20120708204600.DATtest.20120708212100.DATtest.20120708215100.DATtest.20120708222100.DAT | Gunzip multiple files and rename them | rename;gzip | Try this:for file in *.gz; do gunzip -c $file > ${file/.DAT*/.DAT}doneThe approach uses gunzip's option to output the uncompressed stream to standard output (-c), so we can redirect it to another file, without a second renaming call. The renaming is done on the filename variable itself, using bash substitution (match any globbing pattern .DAT* and replace it with .DAT). The loop itself just iterates over files in the current directory with names ending with .gz. |
_softwareengineering.21463 | When doing TDD and writing a unit test, how does one resist the urge to cheat when writing the first iteration of implementation code that you're testing?For example:Let's I need to calculate the Factorial of a number. I start with a unit test (using MSTest) something like:[TestClass]public class CalculateFactorialTests{ [TestMethod] public void CalculateFactorial_5_input_returns_120() { // Arrange var myMath = new MyMath(); // Act long output = myMath.CalculateFactorial(5); // Assert Assert.AreEqual(120, output); }}I run this code, and it fails since the CalculateFactorial method doesn't even exist. So, I now write the first iteration of the code to implement the method under test, writing the minimum code required to pass the test. The thing is, I'm continually tempted to write the following:public class MyMath{ public long CalculateFactorial(long input) { return 120; }}This is, technically, correct in that it really is the minimum code required to make that specific test pass (go green), although it's clearly a cheat since it really doesn't even attempt to perform the function of calculating a factorial. Of course, now the refactoring part becomes an exercise in writing the correct functionality rather than a true refactoring of the implementation. Obviously, adding additional tests with different parameters will fail and force a refactoring, but you have to start with that one test.So, my question is, how do you get that balance between writing the minimum code to pass the test whilst still keeping it functional and in the spirit of what you're actually trying to achieve? | Writing the minimum code to pass a unit test - without cheating! | unit testing;tdd | It's perfectly legit. Red, Green, Refactor.The first test passes. Add the second test, with a new input. Now quickly get to green, you could add an if-else, which works fine. It passes, but you are not done yet.The third part of Red, Green, Refactor is the most important. Refactor to remove duplication. You WILL have duplication in your code now. Two statements returning integers. And the only way to remove that duplication is to code the function correctly.I'm not saying don't write it correctly the first time. I'm just saying it's not cheating if you don't. |
_unix.363917 | I want to run programs made as student assignments in an SELinux sandbox (to check output and behaviour as a first part of grading the assignments without having to check very closely if some students are trying to do anything fun first).Most of the assignments should only read their input and produce output. Some might read files on the system. Then I only want it to be able to read world readable files on the system.Just sandbox assignment.py works fine in some respects, where sandbox is from policycoreutils-python in SElinux sandbox in CentOS 7. Then assignment.py can't write files, access the net, and some other bad things. But it can still read my files.Actually it can read local files, but not NFS mounted files. With sandbox -t sandbox_min_t I can access NFS mounted files as well (which I want), but the problem is still that the tested program has access to all my files. How can I tell it to only have access to world readable files, or to files only readable by a named user?(I'm open to using another sandbox available on CentOS, if it's easier to achieve this in some other sandbox.)(I'd prefer not having to make a new user account just for testing programs. I would prefer not, partly because this might be needed for several teachers/assistants and I want accounts to be personal, and not the user name space being cluttered with lots of these.) | How to access only world readable files in SElinux sandbox | linux;security;selinux;account restrictions;sandbox | null |
_cs.21649 | What is the correct way?Hamilton path, Hamilton's path or Hamiltonian path?To be clear, I am referring to the correct way to name a graph such that there exists a single path (without repeated vertices) through all the vertices.In Wikipedia it says Hamiltonian path, whereas in an article I found Hamilton path. | Correct nomenclature: Hamilton path, Hamilton's path or Hamiltonian path? | hamiltonian path | I have seen both Hamilton path (or Hamilton cycle) and Hamiltonian path (or Hamiltonian cycle). A graph, however, is always Hamiltonian (if it contains a Hamilton/Hamiltonian cycle). Consider for example the titles of two papers: Hamiltonian cycles in random regular graphs (Fenner & Frieze) and Generating and counting Hamilton cycles in random regular graphs (Frieze, Jerrum, Molloy, Robinson & Wormald). Alan Frieze apparently doesn't care too strongly about the issue.However, I've never seen Hamilton's path or cycle. |
_unix.336746 | When attempting to compile and run a program using a non-standard version of gcc in a non-standard location, I get errors which I have found are due to the system version of libc (specifically some headers) being incompatible with the newer version of gcc:In file included from /usr/modules/gcc/6.1.0/include/c++/6.1.0/bits/localefwd.h:40:0, from /usr/modules/gcc/6.1.0/include/c++/6.1.0/ios:41, from /usr/modules/gcc/6.1.0/include/c++/6.1.0/ostream:38, from /usr/modules/gcc/6.1.0/include/c++/6.1.0/iostream:39, from test.cpp:1:/usr/modules/gcc/6.1.0/include/c++/6.1.0/x86_64-pc-linux-gnu/bits/c++locale.h:52:23: error: 'uselocale' was not declared in this scope extern C __typeof(uselocale) __uselocale; ^~~~~~~~~/usr/modules/gcc/6.1.0/include/c++/6.1.0/x86_64-pc-linux-gnu/bits/c++locale.h: In function 'int std::__convert_from_v(__locale_struct* const&, char*, int, const char*, ...)':/usr/modules/gcc/6.1.0/include/c++/6.1.0/x86_64-pc-linux-gnu/bits/c++locale.h:75:53: error: '__gnu_cxx::__uselocale' cannot be used as a function __c_locale __old = __gnu_cxx::__uselocale(__cloc); ^/usr/modules/gcc/6.1.0/include/c++/6.1.0/x86_64-pc-linux-gnu/bits/c++locale.h:100:33: error: '__gnu_cxx::__uselocale' cannot be used as a function __gnu_cxx::__uselocale(__old);So I built a newer version of libc in a non-standard location. Then I can build a program linking to the new glibc and including it's headers using the following, g++ -L${HOME}/glibc/lib64 \ -I${HOME}/glibc/usr/include \ -Wl, -rpath=${HOME}/glibc/lib64 \ -Wl,--dynamic-linker=${HOME}/glibc/lib64/ld-2.20.so \ test.cpp Which works, but then running the program, I get the following error:Inconsistency detected by ld.so: get-dynamic-info.h: 134: elf_get_dynamic_info: Assertion `info[15] == ((void *)0)' failed!I can instead just include the new headers and compilation works and the program seams to run fine:g++ -I${HOME}/glibc/usr/include test.cppBut could doing so cause any side effects or undefined behavior since I am including headers from a new version of glibc and linking to an older version? test.cpp :#include <iostream>using namespace std;int main() { std::cout << hello world\n;}Anyone know how I can best solve this problem? By the way, I am working on a machine where I don't have root privileges. | Trouble compiling and running programs with g++ and libc in non-standard locations | gcc;glibc | null |
_softwareengineering.263947 | I am currently working on a ecommerce system that is slightly different in structure to a typical ecommerce system in that you have multiple stores, accessing the same database from different URLs.So for example i might have:http://www.site1.comhttp://www.site2.comthe above are essentially the same store, they point to the same database, in the main will share the same products (this may seem weird but these are the requirements of the client). The only difference is, based on the URL the users, baskets, orders etc are split so that they do not cross each other. I.e. the orders/baskets/users of site1 are not visible to site2 so a pretty standard single database multitenant model.The above is implemented, i am just slightly stuck on how to implement the checkout process. The requirement is to have a shared checkout, so instead of:https://www.site1.com/checkoutyou would have (for clarity this will link to the same database as the above sites)https://checkout.somesite.com/storeid/basketidYou could tie this in to the way it is handled at Shopify, multiple stores one checkout process. The checkout process in the main is not difficult, i can use the storeId and basketId to identify what i need to identify in terms of create an order from a basket and assigning to a store if the user is a guest. The issue i am facing is what to do when an existing user wants to checkout and login so that the order is associated to their account and some basic information (Email Address, Billing Address) is pre-populated for them.The checkout process (https://checkout.somesite.com/storeid/basketid) does not concern itself with logins or account management of any sort, its just there to facilitate checkout so users, if they are at the beginning of the checkout process and wish to login will be redirected back to the corresponding sites login page. From there i am thinking about this process, but just wanted to share it to see if there is something glaringly wrong with it:User Logs in with correct credentialsSome object (may be the Cart or an intermediary CartOrder object) is updated to contain the id of the user, a unique session key (possibly a GUID) and a timestamp to state the expiry of the checkout session User is redirected back to the checkout site with the session id appended in the querystring (i can't use cookies as the sites are on different domains)Option: At this point i may create a local session to hold onto the value for the remainder of the checkout process making sure it is still valid along the way (a new login would also expire the session key)Checkout!Now there is a slight concern in that placing the session id in the query string it could be picked up by some malicious person, used and some information (name, address) could be visible. On the flip side to that, the checkout will be all SSL, the sessions are short lived and not really able to spoof accounts (or do anything on behalf of the account it represents) so i am not sure if it is being over thought in this process? | Design for a shared checkout | design;e commerce;multitenancy | null |
_codereview.13714 | The following is a symmetric encryption/decryption routine using AES in GCM mode. This code operates in the application layer, and is meant to receive user specific and confidential information and encrypt it, after which it is stored in a separate database server. It also is called upon to decrypt encrypted information from the database. I am looking for a review of the code with respect to its level of security, which in this case refers primarily to the correct implementation of the class called AuthenticatedAesCng found here:http://clrsecurity.codeplex.com/ My encryption/decryption routines are based on the code found here:source 1Any comments or advice is very much appreciated.Here is the code: class encryptionHelper{ // Do not change. private static int IV_LENGTH = 12; private static int TAG_LENGTH = 16; // EncryptString - encrypts a string // Pre: passed a non-empty string // Post: returns the encrypted string in the format [IV]-[TAG]-[DATA] public static string EncryptString(string str) { if (String.IsNullOrEmpty(str)) { throw new ArgumentNullException(encryption string invalid); } using (AuthenticatedAesCng aes = new AuthenticatedAesCng()) { byte[] message = Encoding.UTF8.GetBytes(str); // Convert to bytes. aes.Key = getEncryptionKey(); // Retrieve Key. aes.IV = generateIV(); // Generate nonce. aes.CngMode = CngChainingMode.Gcm; // Set Cryptographic Mode. aes.AuthenticatedData = getAdditionalAuthenticationData(); // Set Authentication Data. using (MemoryStream ms = new MemoryStream()) { using (IAuthenticatedCryptoTransform encryptor = aes.CreateAuthenticatedEncryptor()) { using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { // Write through and retrieve encrypted data. cs.Write(message, 0, message.Length); cs.FlushFinalBlock(); byte[] cipherText = ms.ToArray(); // Retrieve tag and create array to hold encrypted data. byte[] authenticationTag = encryptor.GetTag(); byte[] encrypted = new byte[cipherText.Length + aes.IV.Length + authenticationTag.Length]; // Set needed data in byte array. aes.IV.CopyTo(encrypted, 0); authenticationTag.CopyTo(encrypted, IV_LENGTH); cipherText.CopyTo(encrypted, IV_LENGTH + TAG_LENGTH); // Store encrypted value in base 64. return Convert.ToBase64String(encrypted); } } } } } // DecryptString - decrypts a string // Pre: passed the base 64 string from the database to be decrypted // Post: returns the decrypted string public static string DecryptString(string str) { if (String.IsNullOrEmpty(str)) { throw new ArgumentNullException(decryption string invalid); } using (AuthenticatedAesCng aes = new AuthenticatedAesCng()) { byte[] encrypted = Convert.FromBase64String(str); // Convert string to bytes. aes.Key = getEncryptionKey(); // Retrieve Key. aes.IV = getIV(encrypted); // Parse IV from encrypted text. aes.Tag = getTag(encrypted); // Parse Tag from encrypted text. encrypted = removeTagAndIV(encrypted); // Remove Tag and IV for proper decryption. aes.CngMode = CngChainingMode.Gcm; // Set Cryptographic Mode. aes.AuthenticatedData = getAdditionalAuthenticationData(); // Set Authentication Data. using (MemoryStream ms = new MemoryStream()) { using (ICryptoTransform decryptor = aes.CreateDecryptor()) { using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write)) { // Decrypt through stream. cs.Write(encrypted, 0, encrypted.Length); cs.FlushFinalBlock(); // Remove from stream and convert to string. byte[] decrypted = ms.ToArray(); return Encoding.UTF8.GetString(decrypted); } } } } } // getEncryptionKey - retrieves encryption key from somewhere close to Saturn. // Pre: nada. // Post: Don't worry bout it private static byte[] getEncryptionKey() { // Normally some magic to retrieve the key. // For now just hard code it. byte[] key = { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }; return key; } // generateIV - generates a random 12 byte IV. // Pre: none. // Post: returns the random nonce. private static byte[] generateIV() { using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) { byte[] nonce = new byte[IV_LENGTH]; rng.GetBytes(nonce); return nonce; } } // getAdditionalAuthenticationData - retrieves authentication data. // Pre: none;. // Post: returns the AAD as a byte array. private static byte[] getAdditionalAuthenticationData() { // hardcode for now string str_1 = A promise that I know the key; return Encoding.UTF8.GetBytes(str_1); } // getTag - parses authentication tag from the ciphertext. // Pre: passed the byte array. // Post: returns the tag as a byte array. private static byte[] getTag(byte[] arr) { byte[] tag = new byte[TAG_LENGTH]; Array.Copy(arr, IV_LENGTH, tag, 0, TAG_LENGTH); return tag; } // getIV - parses IV from ciphertext. // Pre: Passed the ciphertext byte array. // Post: Returns byte array containing the IV. private static byte[] getIV(byte[] arr) { byte[] IV = new byte[IV_LENGTH]; Array.Copy(arr, 0, IV, 0, IV_LENGTH); return IV; } // removeTagAndIV - removes the tag and IV from the byte array so it may be decrypted. // Pre: Passed the ciphertext byte array. // Post: Peturns a byte array consisting of only encrypted data. private static byte[] removeTagAndIV(byte[] arr) { byte[] enc = new byte[arr.Length - TAG_LENGTH - IV_LENGTH]; Array.Copy(arr, IV_LENGTH + TAG_LENGTH, enc, 0, arr.Length - IV_LENGTH - TAG_LENGTH); return enc; }} | Symmetric encryption/decryption routine using AES | c#;security;aes | null |
_codereview.83065 | I'm a beginner in MVC programming, repository, and UOW using Entity framework. I tried to calling my existing SP in my MVC project using UOW and EF.Here is my code to mapping my SP in myDbContext file:modelBuilder.Entity<Applicant>().MapToStoredProcedures( s => s.Insert( i => i.HasName(InsertApplicant) .Parameter(fn => fn.First_Name,FirstName) .Parameter(ln => ln.Last_Name,LastName) .Parameter(em => em.Email,Email) .Parameter(tn => tn.Tel_No,TelNo) .Parameter(mn => mn.Mobile_No,MobileNo) .Parameter(vt => vt.Visa_Type,VisaType) .Parameter(lu => lu.LinkedIn_URL,LinkedInURL) .Parameter(ob => ob.Objective, Objective) .Parameter(ac => ac.Active, Active)));And, below is the code I used to call the SP on my controller (i don't know if it's right or not):using (var context = new MyExperienceDbContext()) { var fn = new SqlParameter(@FirstName, entity.First_Name); var ln = new SqlParameter(@LastName, entity.Last_Name); var em = new SqlParameter(@Email, entity.Email); var pn = new SqlParameter(@TelNo, entity.Tel_No); var mn = new SqlParameter(@MobileNo, entity.Mobile_No); var vt = new SqlParameter(@VisaType, entity.Visa_Type); var lu = new SqlParameter(@LinkedInURL, entity.LinkedIn_URL); var ob = new SqlParameter(@Objective, entity.Objective); var ac = new SqlParameter(@Active, entity.Active); context.Database.ExecuteSqlCommand(InsertApplicant @FirstName,@LastName,@Email,@TelNo,@MobileNo,@VisaType,@LinkedInURL,@Objective,@Active , fn, ln, em, pn, mn, vt, lu, ob, ac); return RedirectToAction(Index); }It works fine for me, but I noticed if I delete the mapping's code in myDbContext file everything still works fine. I believe i'm failed to implemented the UOW and repository concept in EF when calling my existing SP, right? Do you have any idea with my question above or do you have tutorial suggestion to calls SP using UOW and EF in MVC project? | Calling Stored Procedure insert query using EF 6, UOW, and MVC 5 | c#;mvc;entity framework;repository | null |
_softwareengineering.264501 | I have a fairly simple application that is divided into two classes. The first class is the Manager class and the second class is the employee class. These are simple classes and do not inherit from any other class. Now what I want is to keep others from instantiating the employee class.The Manager class has an instantiated pointer to the employee class and controls all the methods of the employee class from there.My first idea is to keep the constructor of the employee as private and putting the manager as its friend. Such as this:class employee{ friend class manager; private: employee() { }}class manager{ private: boost::shared_ptr<employee> emp; public: bar() { emp = boost::shared_ptr<employee>(new employee()); //Now manager uses this pointer to control employee } } This is something i came up with but wanted to know if there was a design pattern or a better approach to accomplish this . My objective is to prevent others from creating or using the employee class the only drawback i see to this is exposing the private variables of employee class to the manager class | Which design pattern restricts limits class creation to certain classes | design patterns;c++ | I guess the way you have solved the problem of having a private Constructor might just serve your need. I don't see any creational design pattern fit this requirement, but you should be fine without one here. |
_softwareengineering.290955 | I was assigned to maintain an application written some time ago by more skilled developers. I came across this piece of code:public Configuration retrieveUserMailConfiguration(Long id) throws MailException { try { return translate(mailManagementService.retrieveUserMailConfiguration(id)); } catch (Exception e) { rethrow(e); } throw new RuntimeException(cannot reach here); }I'm curious if throwing RuntimeException(cannot reach here) is justified. I'm probably missing something obvious knowing that this piece of code comes from more seasoned colleague.EDIT:Here is rethrow body that some answers referred to. I deemed it not important in this question.private void rethrow(Exception e) throws MailException { if (e instanceof InvalidDataException) { InvalidDataException ex = (InvalidDataException) e; rethrow(ex); } if (e instanceof EntityAlreadyExistsException) { EntityAlreadyExistsException ex = (EntityAlreadyExistsException) e; rethrow(ex); } if (e instanceof EntityNotFoundException) { EntityNotFoundException ex = (EntityNotFoundException) e; rethrow(ex); } if (e instanceof NoPermissionException) { NoPermissionException ex = (NoPermissionException) e; rethrow(ex); } if (e instanceof ServiceUnavailableException) { ServiceUnavailableException ex = (ServiceUnavailableException) e; rethrow(ex); } LOG.error(internal error, original exception, e); throw new MailUnexpectedException(); }private void rethrow(ServiceUnavailableException e) throws MailServiceUnavailableException { throw new MailServiceUnavailableException(); }private void rethrow(NoPermissionException e) throws PersonNotAuthorizedException { throw new PersonNotAuthorizedException();}private void rethrow(InvalidDataException e) throws MailInvalidIdException, MailLoginNotAvailableException, MailInvalidLoginException, MailInvalidPasswordException, MailInvalidEmailException { switch (e.getDetail()) { case ID_INVALID: throw new MailInvalidIdException(); case LOGIN_INVALID: throw new MailInvalidLoginException(); case LOGIN_NOT_ALLOWED: throw new MailLoginNotAvailableException(); case PASSWORD_INVALID: throw new MailInvalidPasswordException(); case EMAIL_INVALID: throw new MailInvalidEmailException(); }}private void rethrow(EntityAlreadyExistsException e) throws MailLoginNotAvailableException, MailEmailAddressAlreadyForwardedToException { switch (e.getDetail()) { case LOGIN_ALREADY_TAKEN: throw new MailLoginNotAvailableException(); case EMAIL_ADDRESS_ALREADY_FORWARDED_TO: throw new MailEmailAddressAlreadyForwardedToException(); }}private void rethrow(EntityNotFoundException e) throws MailAccountNotCreatedException, MailAliasNotCreatedException { switch (e.getDetail()) { case ACCOUNT_NOT_FOUND: throw new MailAccountNotCreatedException(); case ALIAS_NOT_FOUND: throw new MailAliasNotCreatedException(); }} | Is throwing new RuntimeExceptions in unreachable code a bad style? | java;programming practices | First, thanks for udpating your question and showing us what rethrow does. So, in fact, what it does is converting exceptions with properties into more fined-grained classes of exceptions. More on this later.Since I did not really answer the main question originally, here it goes: yes, it is generally bad style to throw runtime exceptions in unreachable code; you'd better use assertions, or even better, avoid the problem. As already pointed out, the compiler here cannot be sure that the code never walks out of the try/catch block. You can refactor your code by taking advantage that...Errors are values(Unsurprisingly, it is well-known in go)Let's use a simpler example, the one I used before your edit: so imagine that you are logging something and building a wrapper exception like in Konrad's answer. Let's call it logAndWrap.Instead of throwing the exception as a side-effect of logAndWrap, you could let it do its work as a side-effect and make it return an exception (at least, the one given in input). You don't need to use generics, just basic functions:private Exception logAndWrap(Exception exception) { // or whatever it actually does Log.e(Ouch! + exception.getMessage()); return new CustomWrapperException(exception);}Then, you throw explicitely, and your compiler is happy:try { return translate(mailManagementService.retrieveUserMailConfiguration(id));} catch (Exception e) { throw logAndWrap(e);}What if you forget to throw?As explained in Joe23's comment, a defensive programming way to ensure that the exception is always thrown would consists in explicitely doing a throw new CustomWrapperException(exception) at the end of logAndWrap, as it is done by Guava.Throwables. That way, you know that the exception will be thrown, and your type analyzer is happy. However, your custom exceptions need to be unchecked exceptions, which is not always possible. Also, I'd rate the risk of a developper missing to write throw to be very low: the developer must forget it and the surrounding method should not return anything, otherwise the compiler would detect a missing return. This is an interesting way to fight the type system, and it works, though.RethrowThe actual rethrow can be written as a function too, but I have problems with its current implementation:There are many useless casts like Casts are in fact required (see comments):if (e instanceof ServiceUnavailableException) { ServiceUnavailableException ex = (ServiceUnavailableException) e; rethrow(ex);}When throwing/returning new exceptions, the old one is discarded; in the following code, a MailLoginNotAvailableException does not allow me to know which login is not available, which is inconvenient; moreover, stacktraces will be incomplete:private void rethrow(EntityAlreadyExistsException e) throws MailLoginNotAvailableException, MailEmailAddressAlreadyForwardedToException { switch (e.getDetail()) { case LOGIN_ALREADY_TAKEN: throw new MailLoginNotAvailableException(); case EMAIL_ADDRESS_ALREADY_FORWARDED_TO: throw new MailEmailAddressAlreadyForwardedToException(); }}Why doesn't the originating code throws those specialized exceptions in the first place? I suspect that rethrow is used as a compatibility layer between a (mailing) subsystem and busineess logic (maybe the intent is to hide implementation details like thrown exceptions by replacing them by custom exceptions). Even if I agree that it would be better to have catch-free code, as suggested in Pete Becker's answer, I don't think you'll have an opportunity to remove the catch and rethrow code here without major refactorings. |
_unix.291438 | I am on fresh Debian jessie system and trying to install lvm2:# apt-get install lvm2The following packages have unmet dependencies:lvm2 : Depends: watershed (>= 2) but it is not going to be installedE: Unable to correct problems, you have held broken packagesapt-get update, upgrade, -f, autoremove etc did not help, most importantly, my version of watershed is 7:# aptitude versions watershedPackage watershed: i 7 How can I install lvm2? | Broken dependency for lvm2 | debian;software installation;apt;lvm | null |
_unix.36128 | Using the vim text editor, I am looking for a method to copy content highlighted in visual mode to the system clipboard (i.e. I would then be able to Ctr-v that content say in a browser window). Is there a standard way to copy content directly to the system clipboard? If not is there a suited hack to enable it for Mac OS 10.7.3? | Vim visual mode to system clipboard? | vim;osx;copy paste | If your VIM was built with the clipboard feature enabled, then you select your text in visual mode, and then type *y.To paste from the clipboard, do *p. |
_webapps.108981 | I'm trying to get LastPass to import my passwords in a CSV file exported from Avast Passwords. For some strange reason, the option to import passwords doesn't seem to work. The screenshots below showcase the issue I'm currently having.When I press Other, nothing happens. I've scoured the Internet for a solution. I do have BinaryComponent set to true. I have also clicked on the Firefox Password Manager option, it doesn't work. | LastPass import feature does not work, v4.1.62 on Firefox v55.0.2 (64-bit) | import;lastpass;firefox extensions | null |
_cs.75593 | Is there any computable real number which can not be computed by a higher order primitive recursive algorithm?For computable real number I mean those that can be computed by a Turing machine to any desired precision in finite time. For higher order primitive recursive algorithm I mean common primitive recursive functions theory extended with first-class functions (as in Ackermann function).Turing machines are more powerful than higher order primitive recursive functions so there exists the possibility that some computable reals numbers are not expressible by them. | Total functional computable real numbers | computability;primitive recursion;real numbers | The set of higher-order primitive recursive reals is essentially the class of functions $\mathbb{N}\rightarrow\mathbb{N}$ which can be represented by a term $\mathrm{Nat}\rightarrow\mathrm{Nat}$ in Gdel's system T.Since every such function is total, and every well-typed term in the system can be enumerated effectively, there is a relatively easy proof by diagonalization that there is some computable real which cannot be represented. |
_unix.46191 | I want to make a shell script that updates a config file.The file present on the server has information, like various IP addresses.The new file has more code, from new configs added to the system, I want to be able to add these new configurations to the server file without changing what's already configured thereexample:server file[config]ip=127.0.0.1port=22new file[config]ip=XXX.XXX.XXX.XXXport=XXuser=rootI want the resulting file to be[config]ip=127.0.0.1port=22user=rootHow would be a good way to do that? I don't want to rely on line position and such, because the actual config files are quite large and more lines could have been added to the server file.I've tried to make a diff from the files and apply the patch, but it didn't work.Thanks for any help. | How to make and apply (patch) one side diff? | text processing;scripting;configuration;diff;patch | null |
_webapps.73723 | My primary domain name is foobar.com. My secondary domain name is fizbaz.com. When I create links in Google Calendar to do a Hangout, the URL always includes foobar.com no matter what, but I'd like have it have the fizbaz.com name.There doesn't seem to be a way to change either the primary domain or the Hangouts URL to fizbaz.com.Can anyone help with this? It's pretty much a branding disaster to be forced to use an irrelevant domain name and have to explain to people every time about why your business has some random Hangouts URL. | Using secondary domain for Google Hangouts URL | google;google apps;google calendar;google hangouts | null |
_unix.382099 | When I parameterize the date in the code as :str_last_log_date=2017-07-24last_log_date=$(date -d '${str_last_log_date}' +%s)threshold_days_ago=$(date -d 'now - 2 days' +%s)echo last_log_date ${last_log_date} thres_days_ago ${threshold_days_ago}Gives the error :date: invalid date ${str_last_log_date} last_log_date thres_days_ago 1500969455But if I don't parameterize the date and pass directly, it gives the correct result : last_log_date=$(date -d '2017-07-24' +%s)threshold_days_ago=$(date -d 'now - 2 days' +%s)echo last_log_date ${last_log_date} thres_days_ago ${threshold_days_ago}last_log_date 1500854400 thres_days_ago 1500969511Any tips? | Bash : date -d throws invalid date when date is parameterized | linux;shell script;date | last_log_date=$(date -d '${str_last_log_date}' +%s)Should be updated to be (remove single quotes):last_log_date=$(date -d ${str_last_log_date} +%s) |
_unix.43713 | The following command will tar all dot files and folders:tar -zcvf dotfiles.tar.gz .??*I am familiar with regular expressions, but I don't understand how to interpret .??*. I executed ls .??* and tree .??* and looked at the files which were listed. Why does this regular expression include all files within folders starting with . for example? | What does .??* mean in a shell command? | wildcards;tar | Globs are not regular expressions. In general, the shell will try to interpret anything you type on the command line that you don't quote as a glob. Shells are not required to support regular expressions at all (although in reality many of the fancier more modern ones do, e.g. the =~ regex match operator in the bash [[ construct). The .??* is a glob. It matches any file name that begins with a literal dot ., followed by any two (not necessarily the same) characters, ??, followed by the regular expression equivalent of [^/]*, i.e. 0 or more characters that are not /.For the full details of shell pathname expansion (the full name for globbing), see the POSIX spec. |
_cogsci.13816 | I just discovered voltage sensitive dyes technique: I have seen that figures are labelled with dF/F0, what does it stands for? | Voltage sensitive dyes technique: What is the underlying measure? | neurobiology;terminology;neuroimaging;electrophysiology | null |
_unix.80968 | This is what I'd like to be able to do:After a user's account is created, they should be able to ssh-tunnel, but their account is automatically removed after 30 days unless the countdown is reset by the root user.How can I automate this? I'll have to handle around 15 users. | How can I create automatically expiring user accounts? | users;account restrictions;accounts;guest account | useraddYou can control how long a user's account is valid through the use of the --expiredate option to useradd. excerpt from useradd man page-e, --expiredate EXPIRE_DATE The date on which the user account will be disabled. The date is specified in the format YYYY-MM-DD. If not specified, useradd will use the default expiry date specified by the EXPIRE variable in /etc/default/useradd, or an empty string (no expiry) by default.So when setting up the user's account you can specify a date +30 days in the future from now, and add that to your useradd command when setting up their accounts.$ useradd -e 2013-07-30 someuserchageYou can also change a existing accounts date using the chage command. To change an accounts expiration date you'd do the following:$ chage -E 2013-08-30 someusercalculating the date +30 days from nowTo do this is actually pretty trivial using the date command. For example:$ date -d 30 daysSun Jul 28 01:03:05 EDT 2013You can format using the +FORMAT options to the date command, which ends up giving you the following:$ date -d 30 days +%Y-%m-%d2013-05-28Putting it all togetherSo knowing the above pieces, here's one way to put it together. First when creating an account you'd run this command:$ useradd -e `date -d 30 days +%Y-%m-%d` someuserThen when you want to adjust their expiration dates you'd periodically run this command:$ chage -E `date -d 30 days +%Y-%m-%d` someuserSpecifying time periods of less than 24hIf you want a user to only be active for some minutes, you cannot use the options above since they require specifying a date. In that case, you could either set up a crontab to remove/lock the created user after the specified time (for example, 10 minutes), or you could do one of:adduser someuser && sleep 600 && usermod --lock someuseror$ adduser someuser$ echo usermod --lock someuser | at now + 10 minutesReferencesuseradd man pagechage man page |
_webmaster.56046 | I have removed some pages from the Google index using webmaster tools but it still shows up in the search results. So you have any idea what would be the problem? You can see the screenshots below | I have removed some pages from the Google index using webmaster tools but it still shows up in the search results | google search console | null |
_datascience.12768 | I am using SMOTE in Python to perform oversampling of the minor class in an unbalanced dataset. I would like to know the way SMOTE formats its output, that is, whether SMOTE concatenates the newly generated samples to the end of the input data and returns that as the output or whether the new synthetic data points are positioned randomly among the input data points. I'd appreciate your help. | location of the resampled data from SMOTE | unbalanced classes | There is not that much package managing the under-/over-sampling in python. So if you are using imbalanced-learn, it will return a numpy array which concatenate the original imbalanced set with the generated new samples in the minority class. |
_webmaster.105891 | BackgroundI have shared hosting with hostgator and have two domains on the hosting account. My primary domain which is metalbot.org and another domain with is twocan.co.Each of these are separate websites: http://www.metalbot.org and https://twocan.co respectively.When I type in 'TwoCan English', which is my main keyword for the second domain I get the following result!Uh oh! That is not good at all... Questionswhy is my domain showing up as a sub-folder of my primary domain?And my main question: How can I fix this so that when someone types in TwoCan English it shows https://twocan.co? | Website showing up as part of another domain on google | seo;google;subdomain;pagerank;subdirectory | All right, it appears you didn't stop your dev folder to crawl by bots.Do this and it should fix it.Firstly, make sure your website works perfectly on your .co domain.And then set a permanent 301 redirect in your .org domain (.org/two_can) to your primary .co domain. Meaning if you will fetch .org/two_can then it should redirect to the primary .co domain.Leave this about for a week, you will see the incorrect will disappear from Google.Hope this will help. |
_unix.203284 | I have a machine with a built-in NIC (eth0), which serves as a DHCP server for a Raspberry Pi. I also have a USB 3G modem, which shows up as ethernet device eth1. eth0 has the static ip 192.168.100.1 in /etc/network/interfaces.When I connect the Pi to the server, /var/log/syslog shows NetworkManager[2366]: <info> Policy set 'Ifupdown (eth0)' (eth0) as default for IPv4 routing and DNS.and after, ip route show gives default via 192.168.1.100 dev eth0 proto staticI then need to manually ip route delete defaultip route add default via 192.168.1.1to get it to connect to the internet via the 3G modem again.I am using CrunchBang Linux, based on Debian 7 wheezy, on the server, and the latest Raspbian on the Pi.How can I choose the default pathway for NetworkManager to prefer?Edit: here's my /etc/network/interfaces:# This file describes the network interfaces available on your system# and how to activate them. For more information, see interfaces(5).# The loopback network interfaceauto loiface lo inet loopbackallow-hotplug eth0auto eth0iface eth0 inet static address 192.168.100.1 netmask 255.255.255.0allow-hotplug eth1auto eth1iface eth1 inet dhcpNote that I've changed /etc/NetworkManager/NetworkManager.conf to have[ifupdown]managed=truebecause I want to be able to disconnect eth1, the 3G Modem, using nm-applet.Here's /etc/NetworkManager/NetworkManager.conf:[main]plugins=ifupdown,keyfile[ifupdown]managed=true | NetworkManager changes default routing policy | debian;routing;networkmanager | null |
_unix.385632 | I have a list of identifiers in column 1 and corresponding counts in column 2. The file looks something like this: KDO65387 65KDO65387 27XP_006465447 971XP_006482015 1207XP_003630414 194XP_002513282 500XP_003630414 23What I want is to sum the values in column#2 if the values in the column#1 in consecutive rows match. The output will look like this:KDO65387 92XP_006465447 971XP_006482015 1207XP_003630414 217XP_002513282 500 | How to get count of unique rows in a file? | text processing | null |
_unix.87152 | I have a site on a server that is basically a bunch of HTML pages, pictures and sounds. I have lost my password to that server and I need to grab everything that is stored there. I can go page by page and save everything but the site has more than 100 pages.I am using OSX. I have tried to use wget but I think the server is blocking that.Is there any alternative I can use to grab that content? | Alternatives to wget | wget | If the server is blocking wget, it is most likely doing it on the basis of the User-agent: field of the http header, since that is the only way for it to know in the first place. It could also be blocking your IP, in which case using different software won't help, or some scheme which identifies automation on the basis of how rapid a set of requests are (since real people don't browse 100 pages in 3.2 seconds). I have not heard of anyone doing that, but it is possible.I also have not heard of a way to slow down wget, but there is a way to spoof the user-agent field:wget --user-agent=Will according to the man page drop User-agent: completely, since it is not mandatory. If the server doesn't like that, try --user-agent=Mozilla/5.0 which should be good enough.Of course, it would help if you explained better why you think the server is blocking that. Does wget say anything, or just time out? |
_softwareengineering.266534 | I am using the Accord.Math Namespace for Visual Studio in c#. I am trying to use the method MeshGrid<> under the Matrix class for the Accord.Math namespace. However, I am unsure how to implement this method even after reading the documentation for it seen here:http://accord-framework.net/docs/html/M_Accord_Math_Matrix_MeshGrid__1.htmCan anybody show me how to properly implement this method?I have two Double[,] variables named xa and ya that I am trying to pass to MeshGrid. I have tried calling by using: var q = Matrix.MeshGrid(xa,ya);But for this is says that the type arguments cannot be inferred from their usage.The output of MeshGrid is a 2-Tuple.T1 is T[,]T2 is T[,] | How to use MeshGrid method in Accord.Math Matrix Class? | c# | null |
_datascience.14220 | I have a graph which plots training datasize on X axis and accuracy on y axis. I plotted the curves using sklearn's learning_curve.It is observed that the accuracy of training dataset decreases but the accuracy of validation dataset increases. I am not able to justify this behavior. Normally, as training dataset increases, the training accuracy is supposed to increase right?Also, assuming that the dataset is very noisy and hence training accuracy is decreasing as dataset size increases. But this doesn't explain why validation accuracy increases because noise is supposed to affect that too. | Training and cross validation error curves | machine learning;dataset;cross validation;accuracy | null |
_webmaster.91524 | So, UTMs work really well for tracking external campaigns in Google Analytics. I use UTMs all the time for the sites that I work with. But I'm wondering how to properly track these campaigns easily if I migrate the target site into its parent site.I've read through a few different recommendations. Justin Cutroni says create a new Google Analytics view and use site search. This sounds easy, but also seems pretty darn hacky. Site search wasn't meant for that (and site search has a few limitations that aren't present when tracking external campaigns in GA).Escape Studio says site search is one of 3 ways to do this. The others: Enhanced ecommerce, Event tracking, and Custom dimensions. Event tracking, it appears, is the most common solution for this problem, but it involves touching code any time a new campaign is created.Is it possible to simply create a new internal campaign just by adding a querystring to a URL, and then somehow telling GA that the querystring is an internal campaign? And then how to properly monitor these internal campaigns in GA... without touching code. | How to track internal campaigns (without writing any code)? | google analytics;url;campaigns | null |
_unix.168383 | I'm looking for a simple X window manager that :stacks new windows over all others on screenhas no window decorations at all (no title, no borders, no min/max buttons)opens all windows in max mode | Simple X window manager | x11;software rec;window manager | null |
_datascience.19842 | I am building a standard RandomForest classifier (named model, see the code below) using scikit-learn package. Now, I want to get all parameters of one Randomforest classifier (including its trees (estimators)), so that I can manually draw the flow chart for each tree of the RandomForest classifier. I wonder if anyone knows how it can be done?Thank you in advance.Manh#Import Libraryfrom sklearn.ensemble import RandomForestClassifier #use RandomForestRegressor for regression problem#Assumed you have, X (predictor) and Y (target) for training data set and x_test(predictor) of test_dataset# Create Random Forest objectmodel= RandomForestClassifier(n_estimators=10, max_depth=5) #n_estimators=1000 oob_score = True#====#X, y = input_X, input_yfrom sklearn.cross_validation import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.2, random_state = 4)# Train the model using the training sets and check scoremodel.fit(X_train, y_train)#Predict Outputy_pred_train = model.predict(X_train)y_pred_test = model.predict(X_test)#accuracyfrom sklearn.metrics import accuracy_scoreprint(accuracy_score(y_train,y_pred_train))print(accuracy_score(y_test,y_pred_test)) | Anyway to know all details of trees grown using RandomForestClassifier in scikit-learn? | scikit learn;random forest;decision trees | null |
_webapps.83066 | Is it possible to make a new friend list on Facebook to include all those who speak the same language? | Make a Facebook list with people that speak the same language | facebook | null |
_webapps.18950 | Using Trello on an iPad. Obviously Q is the shortcut to display the cards in Condensed List view, but how do I access Q on an iPad? The only way to get the keyboard to display is if I am editing a card, and then (of course) Q is just typed in the text box. | How do I switch to Condensed List view using Trello on iPad? | trello;ipad | null |
_codereview.126211 | My code right now look like this @contextmanagerdef smtp_connection(host, user=None, passwd=None, timeout=5): conn = None # smell here try: conn = SMTP(host=host, timeout=timeout) conn.ehlo_or_helo_if_needed() if user and passwd: conn.login(user=user, password=passwd) logger.debug('SMTP connected') yield conn except Exception as e: raise e finally: if conn: # and here conn.quit()In recipes for ExitStack there is a suggestion to replace try-finally and flag variables with thiswith ExitStack() as stack: stack.callback(cleanup_resources) result = perform_operation() if result: stack.pop_all()But this doesn't use result in cleanup_resources. So in my case it still would bewith ExitStack() as stack: result = None stack.callback(lambda conn: conn.quit()) result = POP3() # code from above here if result: stack.pop_all() | Context manager for SMTP connections | python;error handling;email | except Exception as e: raise eFirst, you could simplify this toexcept Exception: raiseSecond, since you only re-raise it, you are not prepared to handle any Exception that could appear either with your code or the code managing the connection returned by your context manager. Thus you don't need that except clause.Now the only thing left to manage is the state of the connection. Since there is no exception handling performed by your code, you are free to create the connection out of the try finally and use that mechanism to only close the connection whatever happened:@contextmanagerdef smtp_connection(host, user=None, passwd=None, timeout=5): conn = SMTP(host=host, timeout=timeout) try: conn.ehlo_or_helo_if_needed() if user and passwd: conn.login(user=user, password=passwd) logger.debug('SMTP connected') yield conn finally: conn.quit()You could also simplify the design by separating concerns. As it stand, your function does two things:manage the connection;perform some initial setup.By delegating to a second context manager, you could separate these two behaviors into reusable bits:@contextmanagerdef smtp_connection(host, timeout): connection = SMTP(host=host, timeout=timeout) try: yield connection finally: connection.quit()@contextmanagerdef smtp_setup(host, user=None, passwd=None, timeout=5): with smtp_connection(host, timeout) as conn: conn.ehlo_or_helo_if_needed() if user and passwd: conn.login(user=user, password=passwd) logger.debug('SMTP connected') yield connBut, looking at the second context manager, there is nothing to manage anymore since there is no teardown/cleanup anymore. Thus it is best to provide it as an independant function:@contextmanagerdef smtp_connection(host, timeout=5): connection = SMTP(host=host, timeout=timeout) try: yield connection finally: connection.quit()def smtp_setup(conn, user=None, passwd=None): conn.ehlo_or_helo_if_needed() if user and passwd: conn.login(user=user, password=passwd) logger.debug('SMTP connected')You would then need to change your calling code fromwith smtp_connection(h, u, p, t) as conn: # do stufftowith smtp_connection(h, t) as conn: smtp_setup(conn, u, p) # do stuffIn the end, I personally don't like to have to manage the try ... finally inside the context manager. I don't find that natural as I preffer to write an explicit class using __enter__ and __exit__:class smtp_connection: def __init__(self, host, timeout): self.smtp = SMTP(host=host, timeout=timeout) def __enter__(self): return self.smtp def __exit__(self, exc_type, exc_value, exc_trace): self.smtp.quit()Using a class could also let you wrap this thing around SMTP directly:class smtp_connection(SMTP): def __init__(self, host, timeout): super().__init__(host=host, timeout=timeout) def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_trace): self.quit() def setup(self, user=None, password=None): self.ehlo_or_helo_if_needed() if user and passwd: self.login(user=user, password=passwd) logger.debug('SMTP connected')Use it like:with smtp_connection(h, t) as conn: conn.setup(u, p) # do stuff |
_unix.46028 | Got my USB flash automount broken after reboot.Using Debian 6, GNOME 2My NTFS hard disk is still mounting correctly.When i connect my Android smartphone (with SD and local drive) my messages log looks like:tail -f /var/log/messagesAug 21 11:46:14 pp-hideout kernel: [ 139.461734] sd 4:0:0:0: [sdc] Attached SCSI removable diskAug 21 11:46:14 pp-hideout kernel: [ 139.466484] sd 4:0:0:2: [sdd] Attached SCSI removable diskAug 21 11:46:14 pp-hideout kernel: [ 139.514664] cdrom: This disc doesn't have any tracks I recognize!Aug 21 11:46:22 pp-hideout kernel: [ 148.005560] sd 4:0:0:2: [sdd] 4268032 512-byte logical blocks: (2.18 GB/2.03 GiB)Aug 21 11:46:22 pp-hideout kernel: [ 148.006180] sd 4:0:0:0: [sdc] 7761920 512-byte logical blocks: (3.97 GB/3.70 GiB)Aug 21 11:46:22 pp-hideout kernel: [ 148.010305] sdd:Aug 21 11:46:22 pp-hideout kernel: [ 148.010679] sdc:Aug 21 11:46:22 pp-hideout kernel: [ 148.014944] sdc1Aug 21 11:46:22 pp-hideout halevt: Running: halevt-mount -u /org/freedesktop/Hal/devices/volume_uuid_DACE_470F -o sync -m 002 -o gid=plugdevAug 21 11:46:23 pp-hideout halevt: Running: halevt-mount -u /org/freedesktop/Hal/devices/volume_uuid_3E19_07CA -o sync -m 002 -o gid=plugdevSo the problem is somewhere on software level.And the problem is I want it to automount, but it isn't working.Can anybody help?p.s.: How do Debian USB automounting is working from the box? Where can i read about it? UPDATE:Did some apt-get ideas from web and now I have:Running: halevt-mount -u /org/freedesktop/Hal/devices/volume_uuid_DACE_470F -o sync -m 002 -o gid=plugdevAug 22 03:06:05 pp-hideout usbmount[15471]: executing command: mount -tvfat -osync,noexec,nodev,noatime,nodiratime /dev/sdc1 /media/usb0Aug 22 03:06:05 pp-hideout halevt: Running: halevt-mount -sAug 22 03:06:05 pp-hideout usbmount[15471]: executing command: run-parts /etc/usbmount/mount.dAug 22 03:06:07 pp-hideout usbmount[15436]: executing command: mount -tvfat -osync,noexec,nodev,noatime,nodiratime /dev/sdd /media/usb1Aug 22 03:06:07 pp-hideout halevt: Running: halevt-mount -sAug 22 03:06:07 pp-hideout usbmount[15436]: executing command: run-parts /etc/usbmount/mount.dNow USB flash mounts, BUT read-only. How can I fix read-only? Any ideas? | Debian USB automount | debian;mount;usb;devices | null |
_webmaster.1217 | Possible Duplicate:How to find web hosting that meets my requirements? I'm currently using shared hosting.I want more control over my IIS and also I need to run in full trust.There are a lot of options out there for Windows VPS hosting.Which ones do you recommend is the best?Some must havesHas to have great supportAutomatic hardware fail oversAccess through Remote Desktop (you would be amazed some don't offer this)No limit on what I can install on it | Whats is the best Windows VPS hosting? | web hosting;vps;asp.net mvc | null |
_datascience.6908 | I am still new to data mining but I really want (and need) to learn it so badly. I know that before I can actually process my data in softwares like WEKA, I need to do some filtering like cleaning the data, integrating, transforming, etc to actually get your data cleaned from any kind of duplicate, missing value, noise, etc. But I only know all of these theoretically. The problem I have now is I have a very big set of data that I need to filter first before going on to the processing part. But I don't know where to start. Fyi, my dataset is very big that the usual spreadsheet programs like Ms Excel, Libre Office, WPS,etc can't open it. I have to use Linux terminal and commands to count the number of rows, columns etc. What do I do in the preprocessing start? How do I 'clean' my data? I have been thinking to use Linux commands to do all of these, but I am also wondering how real data scientists clean their data. Do they do these manually or they already have some sort of software to help them? Because seriously I don't know where to start or to do. Every reference I found in the internet only explain things theoretically. ANd I need something more practical to help me understand. What do I do with my dataset? Help please? | Preprocessing in Data mining? | data mining;dataset;data cleaning;preprocessing | null |
_softwareengineering.150824 | I'm trying to understand how the puts function fits in Ruby's Everything is an object stance.Is puts is the method of a somehow hidden class/object? Or is it a free-floating method, with no underlying object? | Is the puts function of ruby a method of an object? | ruby | I'm trying to understand how the puts function fits in Ruby's Everything is an object stance.First off, puts is not a function. It's sole purpose is to have a side-effect (printing something to the console), whereas functions cannot have side-effects that's the definition of function, after all.Ruby doesn't have functions. It only has methods. Thus, puts is a method.Is puts is the method of a somehow hidden class/object?No, it's just a boring old instance method of a boring old class. (Well, a boring old instance method of a boring old mixin, actually, but a mixin is just a class which abstracts over its superclass.)Kernel is mixed into Object, which is the (default) superclass of all objects (modulo BasicObject, of course), thus, Kernel is a common superclass (or supermixin, if you prefer) of (almost) all objects in Ruby.Or is it a free-floating method, with no underlying object?There is no such thing. A method is always associated with an object (the receiver of the message), that's what makes it a method. (At least in OO parlance. In ADT-oriented languages, the word method means something slightly different.)By the way, the easiest option is always to just ask Ruby herself:method(:puts).owner# => Kernel |
_webapps.14344 | When I delete an email message from my Gmail inbox, is it also deleted and removed from the servers at Google?This is to say that I deleted it knowing that I wanted to and was sure and that I don't also have a copy of it in another label/folder in my account. What happens to the deleted emails? | Are deleted Gmail messages deleted from Google servers? | gmail | There are several levels of delete and you'd need to ask Google how far they went when you pressed the delete button.The file (for that's what a mail message actually is) is moved from your inbox to a trash folder in your account. This removes it from your inbox but you can still recover it quite easily.The file is completely removed from your account. In this case it might still exist somewhere on the Gmail servers but you'd have to contact Google for it to be restored. I don't know whether this is the case, but it's a reasonable assumption.The file is removed from the Gmail servers. In this case it might have been backed up before deletion.The file is removed from all backups. In this case the mail has, to all intents and purposes gone.This doesn't cover the use of forensic data recovery to analyse the hard drive of the server to recover a deleted file - but with the volume of data passing through Gmail I'd assume that any deleted file would get overwritten quite quickly. |
_codereview.84476 | I am burdened with the requirement of interacting with a C based library, which has a bunch of constant sized arrays (e.g. char[17]).When trying to assign or read those properties from swift, they are represented as a Tuple type of that size.. As far as I know, you can't access tuples with subscripts, and it is not trivial to convert an array to a tuple .. so I am left with this ugly code to interact with the library:Note for the curious: The C library uses the eatLength to determine which values of the tuple are valid, and which shouldn't be considered. That is why I don't care about what the padded value is.typedef struct _DMMove{ uint8_t steps[17]; uint8_t eats[16]; uint8_t eatLength;} DMMove;extension DMMove { init(steps: [Int], eats: [Int]) { var paddedSteps = Array(0..<17) as [UInt8] var paddedEats = Array(0..<16) as [UInt8] for (i, v) in enumerate(steps) { paddedSteps[i] = Int8(v) } for (i, v) in enumerate(eats) { paddedEats[i] = Int8(v) } var stepsTuple = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) as (Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8) var eatsTuple = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) as (Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8) stepsTuple.0 = paddedSteps[0] stepsTuple.1 = paddedSteps[1] stepsTuple.2 = paddedSteps[2] stepsTuple.3 = paddedSteps[3] stepsTuple.4 = paddedSteps[4] stepsTuple.5 = paddedSteps[5] stepsTuple.6 = paddedSteps[6] stepsTuple.7 = paddedSteps[7] stepsTuple.8 = paddedSteps[8] stepsTuple.9 = paddedSteps[9] stepsTuple.10 = paddedSteps[10] stepsTuple.11 = paddedSteps[11] stepsTuple.12 = paddedSteps[12] stepsTuple.13 = paddedSteps[13] stepsTuple.14 = paddedSteps[14] stepsTuple.15 = paddedSteps[15] stepsTuple.16 = paddedSteps[16] eatsTuple.0 = paddedEats[0] eatsTuple.1 = paddedEats[1] eatsTuple.2 = paddedEats[2] eatsTuple.3 = paddedEats[3] eatsTuple.4 = paddedEats[4] eatsTuple.5 = paddedEats[5] eatsTuple.6 = paddedEats[6] eatsTuple.7 = paddedEats[7] eatsTuple.8 = paddedEats[8] eatsTuple.9 = paddedEats[9] eatsTuple.10 = paddedEats[10] eatsTuple.11 = paddedEats[11] eatsTuple.12 = paddedEats[12] eatsTuple.13 = paddedEats[13] eatsTuple.14 = paddedEats[14] eatsTuple.15 = paddedEats[15] self.init( steps: stepsTuple, eats: eatsTuple, eatLength: Int16(eats.count) ) }}More NotesIf you don't know how a C struct is exposed to Swift, well it's as simple as though there is an actual Swift struct with an init that takes all the struct's attributes as parameters.I am sure someone will suggest using Tuple initializers ... Here ya go:Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions | Array to Tuple in Swift | collections;swift | null |
_scicomp.4757 | When evaluating cylindrical harmonics, one needs to evaluate trigonometric functions $\cos(m\theta)$ and $\sin(m\theta)$, potentially for large integer $m$ and $\theta\in[-\pi,\pi]$. What is the best way of doing this in C code? Currently, I just evaluate at the angle $m\theta$ but I would suspect that standard libraries lose accuracy at large arguments. I was considering using double angle formulas and the like to recursively reduce the magnitude of the arguments, but I'm wondering if that ends up incurring more error. | Evaluating sine and cosine of an integer multiple of an angle | numerics;special functions | If you do it iteratively, by computing $\sin(n \theta)$ and $\cos(n \theta)$ from $\sin((n - 1) \theta)$ and $\cos((n - 1) \theta)$, then floating point errors will not blow up by accumulation. This is because the transition matrix is orthonormal. It is a simple rotation matrix. |
_unix.362100 | Do I need to check & create /tmp before writing to a file inside of it?Assume that no one has run sudo rm -rf /tmp because that's a very rare case | is /tmp guaranteed to exist? | tmp | The FHS mandates that /tmp exist, as does POSIX so you can rely on its being there (at least on compliant systems; but really its pretty much guaranteed to be present on Unix-like systems). But you shouldnt: the system administrator or the user may prefer other locations for temporary files. See Finding the correct tmp dir on multiple platforms for more details. |
_unix.89248 | I've made a programmable power switch using Raspberry Pi (although this question is not RPi specific - it's more of generic Linux with problem caused by hardware shortcomings.) Raspberry has no battery-backed RTC; it's intended to work networked and sync its clock soon after boot-up over network.My problem is, that while I do programming of said switch over the net, and I can get given sockets to switch on/off at given hour that way, the device itself is to be used at different locations, including non-networked ones. When if I carry it from where I programmed it to where it's to be plugged in, it's unpowered and the clock loses state. After I power it back up, it has no connectivity to restore the date.The few minutes when it's unpowered is not a problem for me - I don't mind the clock being off by a minute or two. I mind if it's off by 43 years as is the case after I switch it on non-networked.Is there some neat way to restore the clock on boot-up to a state from before the system went down due to power loss? (writing it every second to SD card which is the memory medium of RPi will kill the card quite fast so that's not quite an option.) | Restore clock after short powerdown for no-network, no-RTC system | clock | I see a few ways you can approach thisScan the filesystem for the file with the newest modification or access time. Use that time to set the clock. It's slow, and the accuracy is probably going to be far off, but it'll work. If you have a directory/file you know is modified fairly frequently, you could just use that as the source.Go with the idea you mentioned; 'touch a file every few seconds'. Many SD cards have wear leveling. So you're not writing to the exact same location all the time, and thus it isn't an issue at all.Use NVRAM. Write the current date to the NVRAM as often as you want, and then restore that on boot. NVRAM is tiny, but you can store a few bytes in it without issue.Use GPS for time sync. This is what I do on devices which need time, but don't have access to a network. USB GPS devices are cheap, and they provide very accurate time sources. |
_codereview.141048 | I spent an hour or so this morning compiling this, and since I have started reading Clean Code and The Pragmatic Programmer I figured I would let you help me get slightly better at this.Due to some crappy limitations with the specifics I was forced to work in Excel VBA instead of Access (someone doesn't want to build tables for the two lists in the Excel sheet).The code pulls a list of defects from a production table, checks a master list to see if it ever existed, then checks an open list to see if it's current and updates the table accordingly. This could be super easy and potentially 100% automated if they would make tables for the two lists. The log of what was found per defect# (writing to sheet) is something I added just in case they want a log.Private Sub thisbetheshitmane() Dim db As DAO.Database Dim rst As DAO.Recordset Dim vAr As String Dim i As Integer Dim y As Integer Dim InCombined As Boolean Dim InOpen As Boolean Set db = DBEngine.OpenDatabase(C:\Users\dzcoats\Documents\Microsoft.accdb) Set rst = db.OpenRecordset(SELECT DISTINCT [VDefects].Defect FROM [VDefects] WHERE [VDefects].Defect IS NOT NULL;) Dim QResult() As Variant QResult = rst.GetRows(rst.RecordCount) For a = LBound(QResult, 2) To UBound(QResult, 2) vAr = QResult(0, a) Debug.Print ; vAr Next a Dim CombinedList() As Variant CombinedList = Application.Transpose(Worksheets(1).Range(b2:b2000).Value) Dim OpenList() As Variant OpenList = Application.Transpose(Worksheets(1).Range(a2:a2000).Value) For y = LBound(QResult, 2) To UBound(QResult, 2) vAr = Trim(QResult(0, y)) InCombined = False For a = LBound(CombinedList) To UBound(CombinedList) If vAr = CombinedList(a) Then InCombined = True Next a InOpen = False For a = LBound(OpenList) To UBound(OpenList) If vAr = OpenList(a) Then InOpen = True Next a If vAr <> Defect And vAr <> vbNullString And vAr <> Then If InCombined = False And InOpen = False Then set rst = db.OpenRecordSet (UPDATE [VDefects] SET [VDefects].Status ='Bad Defect Number' WHERE ((([VDefect].Defect)='& vAr &'));) Debug.Print BAD ; vAr ThisWorkbook.Sheets(Sheet2).Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = Bad ThisWorkbook.Sheets(Sheet2).Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(0, 1).Value = vAr End If If InCombined = True And InOpen = False Then set rst = db.OpenRecordSet (UPDATE [VDefects] SET [VDefects].Status ='Completed' WHERE ((([VDefects].Defect)='& vAr &'));) Debug.Print CLOSED ; vAr ThisWorkbook.Sheets(Sheet2).Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = Closed ThisWorkbook.Sheets(Sheet2).Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(0, 1).Value = vAr End If If InCombined = True And InOpen = True Then Debug.Print OPEN ; vAr ThisWorkbook.Sheets(Sheet2).Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = Open ThisWorkbook.Sheets(Sheet2).Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(0, 1).Value = vAr End If End If Next y rst.Close Set rs = Nothing db.Close Set db = NothingEnd Sub | Updating access records | vba;excel;ms access | Here is the code refined using these features:rst.Filterrst.UpdateScripting.DictionaryRange(A1).CopyFromRecordset rstSub ThisBeTheShitMane() Const DBPath = C:\Users\dzcoats\Documents\Microsoft.accdb Const DebugMode As Boolean = False Dim db As DAO.Database Dim rst As DAO.Recordset Dim key As String Dim vAr Dim d As Object: Set d = CreateObject(Scripting.Dictionary) Set db = DBEngine.OpenDatabase(DBPath) Set rst = db.OpenRecordSet(SELECT [VDefects].Defect, [VDefects].Status FROM [VDefects] WHERE [VDefects].Defect IS NOT NULL;) 'Combined List With Worksheets(1) For Each vAr In .Range(B2, .Range(B & .Rows.Count).End(xlUp)).Value key = vAr d(key) = Completed Next End With 'Open List With Worksheets(1) For Each vAr In .Range(A2, .Range(A & .Rows.Count).End(xlUp)).Value key = vAr If d.Exists(key) Then d(key) = OPEN Else If DebugMode Then Debug.Print vAr: ; vAr, ID is in the Open List but is missing from the Combined List End If Next End With With rst .MoveFirst Do Until .EOF key = ![Defect] .Edit ![Status] = IIf(d.Exists(key), d(key), Bad Defect Number) .Update .MoveNext Loop .MoveFirst End With Worksheets(Sheet2).Range(A1).CopyFromRecordset rst rst.Close Set rst = Nothing db.Close Set db = NothingEnd SubBut we could just let the database do the work for us by converting the Open and Combined list into a comma separated values list and using IN() to check the values. If [Defect] is a text field you will has to wrap the values in quotes.Sample Query:UPDATE VDefects SET VDefects.Status = IIf([VDefects]![Defect] NOT IN (1,2,3,4,5,6) And [VDefects]![Defect] NOT IN (4,5,6,7,8,9),'Bad Defect Number',IIf([VDefects]![Defect] NOT IN (1,2,3,4,5,6),'Completed','OPEN'));Sub JustDoIt() Const DBPath = C:\Users\best buy\Desktop\Microsoft.accdb Dim db As DAO.Database: Set db = DBEngine.OpenDatabase(DBPath, , True) Dim rst As DAO.Recordset Dim sSQL As String, t1 As String, t2 As String Dim arr1 As Variant, arr2 As Variant With Sheet1 t1 = getValueList(.Range(A2, .Range(A & rows.Count).End(xlUp)), False) t2 = getValueList(.Range(B2, .Range(B & rows.Count).End(xlUp)), False) End With sSQL = UPDATE VDefects SET VDefects.Status = IIf([VDefects]![Defect] NOT IN ( & t1 & ) And [VDefects]![Defect] NOT IN ( & t2 & ),'Bad Defect Number',IIf([VDefects]![Defect] NOT IN ( & t1 & ),'Completed','OPEN')); db.Execute sSQL Set rst = db.OpenRecordSet(SELECT [VDefects].Defect, [VDefects].Status FROM [VDefects] WHERE [VDefects].Defect IS NOT NULL;) Worksheets(Sheet2).Range(A1).CopyFromRecordset rst rst.Close Set rst = Nothing db.Close Set db = NothingEnd SubFunction getValueList(Target As Range, WrapInQuotes) As String Dim arr As Variant arr = Application.TRanspose(Target.Value) If WrapInQuotes Then getValueList = Join(arr, ,) & Else getValueList = Join(arr, ,) End IfEnd Function |
_unix.115612 | I right clicked a post request in Chrome and selected Copy as cURLI got a cURL command that includes the following --data-binary $'------WebKitFormBoundI am used to seeing cURL requests that have a single flag and string. Like this $curl -0 output.txtI understand that the --data-binary command will post binary data (presumably after converting the string after the --databinary switch into binary). But what does the dollar sign mean?What does the curl request mean if it has two dashes and a dollar sign? | Understanding two flags and a dollar sign in a CURL command | command line;curl | The notation being used there $'...' is a special form of quoting a string recognised by a few shells like ksh (where it originated), zsh and bash. excerptStrings that are scanned for ANSI C like escape sequences. The Syntax is $'string'Example$ echo $'hola\n'hola$ReferencesQuotes and escaping3.1.2.4 ANSI-C Quoting |
_cstheory.31972 | Here is a variant of the SAT problem in which a satisfying assignment must have additional properties.Input: A 3-CNF formula $f$ with variables $x_{1\dots k}$.Output: For an assignment $S$ of $x_{1\dots k}$, let $\overline S$ be defined such that $x_i=true$ in $\overline S$ if and only if $x_i=false$ in $S$.Is there an assignment $S$ such that both $f(S)$ and $f(\overline S)$ hold?Is this problem still NP-hard?Examples:$f=(x_1\lor x_2\lor x_3)\land(x_1\lor x_2\lor \neg x_3)\land(x_1\lor \neg x_2\lor x_3)\land(x_1\lor \neg x_2\lor \neg x_3)$This requires $x_1=true$ in $S$, but then $x_1=false$ in $\overline S$, so $f(S)$ and $f(\overline S)$ cannot simultaneously hold.$f=(x_1\lor x_2\lor x_3)\land(x_1\lor x_2\lor \neg x_3)\land(x_1\lor \neg x_2\lor x_3)$$S=\{x_1:true,~x_2:false,~x_3:false\}$$\overline S=\{x_1:false,~x_2:true,~x_3:true\}$Then both $f(S)$ and $f(\overline S)$ hold. | Is SAT with two opposite solutions NP-hard? | cc.complexity theory;np hardness;sat | Turning my comment to an answer:The problem you describe is known as Not All Equal SAT (NAE-SAT), but is phrased differently. A NAE assignment for a CNF-formula $\phi$ over variables is one where in each clause there is at least one false variable and one true variable.It is easy to see that an assignment is NAE iff its inverse is also NAE.Showing that NAE-SAT is NP-complete is a well-known exercise, and it can be easily solved by splitting it to two parts.First, given a 3-CNF formula, we can convert it to a 4-CNF formula by adding a variable $w$ and converting every clause of the form $(x\vee y\vee z)$ to $(x\vee y\vee z\vee w)$.It is easy to see that the original formula is satisfiable iff the resulting formula is in NAE-SAT.Then, standard techniques can be used to convert this formula back to 3-CNF, while maintaining the NAE property. |
_codereview.12959 | Recently me and colleague had a discussion about the following piece of code (simple bool function that checks if string is a number, +1000 not allowed, -1000, 1234 ... allowed). He felt that it was hackish, while I thought it was nice, clean and elegant (since it uses STL, not hand made loops).So is this a judgement call or one of us is wrong? Is this code elegant or hack? bool validate(const std::string& m) { if (m.empty()) return false; return m.end() == find_if(*m.begin() == '-'? ++m.begin() : m.begin(), m.end(), not1(ptr_fun(isdigit))); } | Checking if a string is a number with STL | c++;stl | null |
_unix.240470 | I was wondering if there is a best way to run the following commandcat cisco.log-20151103.log | grep -v 90.192.142.138 | grep -v PIX | grep -v IntrusionI triedcat cisco.log-20151103.log | grep -v 90.192.142.138|PIX|Intrusionbut it doesn't work. | Excluding multiple patterns with one grep command | grep | two other optionsgrep -v -e 90.192.142.138 -e PIX -e Intrusion cisco.log-20151103.logand assuming fixed strings grep -vF '90.192.142.138PIXIntrusion' cisco.log-20151103.log |
_unix.158856 | I am currently writing my third ever shell script and I have run into a problem. This is my script so far:#!/bin/bashecho choose one of the following options : \ 1) display all current users \ 2) list all files \ 3) show calendar \ 4) exit scriptwhile read do case in 1) who;; 2) ls -a;; 3) cal;; 4) exit;; esac donewhen I try to run the script it says this:line2 : unexpected EOF while looking for matching '' line14 : syntax error: unexpected end of file. What am I doing wrong? | Unexpected EOF and syntax error | shell;shell script | The problem is, that your case statement is missing the subject - the variable which it should evaluate. Hence you probably want something like this:#!/bin/bashcat <<EODchoose one of the following options:1) display all current users2) list all files3) show calendar4) exit scriptEODwhile true; do printf your choice: read case $REPLY in 1) who;; 2) ls -a;; 3) cal;; 4) exit;; esac doneHere case uses the default variable $REPLY which read fills when it's not given any variable names (see help read for details).Also note the changes: printf is used to display the prompt in each round (and doesn't append a newline), cat is used to print instructions on several lines so that they don't wrap and are easier to read. |
_webmaster.44894 | I need to create a domain alias alias.domain.com to forward http to www.domain.com.It has to be a forward and not a redirect (I was told it can be done by creating CNAME).Note I am using Plesk and creating a domain alias in plesk creates an A record not a CNAME.Any thoughts please? | Domain Alias with forward in plesk | plesk;domain forwarding | null |
_unix.83734 | On this VPS there are three users: root, another_one, nobody. All webserver files, configs, &c. are owned by root. However, I'm in doubt for what regards running things. If I use root for the web server I may expose the system to security holes, whereas if I try to login into nobody it asks me a password which I never set and I don't know. Should I create yet another user? For now I'm only sure about nginx: I run it as root and it spawns processes as nobody. But what about web servers and other services like db and redis? Note: I should mention that another_user can sudo, so it's not that different from root. | With which user should I run web servers, redis & mongodb? | security;users;webserver | I always run services with a dedicated user. So I would create these users:nginxmongoapachemysqlredisYou should never run the actual services as root!Often when installing these applications using your distributions package manager, as part of the installation, a user will be automatically created for each of these services.I typically use CentOS/RHEL and when I install things like Apache, the user apache is created automatically at that point. So too for MySQL, and Nginx. |
_unix.153525 | I have (and often change) 3 keyboard layouts on my Mint 17/Mate. I would like to see a notification on my screen when layout is changed, e.g. Switched to English/US. I tried to do it via keyboard settings, to find a program or script to do it, but I couldn't.The question is: are there any programs to show current layout OR is there a way to catch layout change event from X11 in user script? Any advice or guide to information would be appreciated.Update: I've found notify-send to actually send notification, now I need to catch layout change event. | Keyboard layout change indicator | x11;keyboard layout;xkb;notifications | I didn't change my keyboard layout very often, but when i do it, i use (for exemple) :setxkbmap frThere's also an option to show the current layout of your keyboard :setxkbmap -queryresult :rules: evdevmodel: pc105layout: froptions: terminate:ctrl_alt_bkspConsidering this, you could do something with the notify-send command to send the layout as a notification. Something like this :notify-send $(setxkbmap -query | grep layout)Hope this help |
_unix.77831 | I want to replace either every odd or even occurrence of a pattern. Look at the following example:$ echo aaaaa | sed -e 's/a/b/' -e 's/a/c/' -e 's/a/b/' -e 's/a/c/' -e 's/a/b/'bcbcbIs there some command that can do this more concisely? What I'm actually doing is converting *s into BBCode [i] and [/i] tags, so if there's a markdown-to-BBCode converter out there, I'd like to hear about it too. | Replace every odd or even occurrence of a pattern in a file | text processing;sed;markdown | sed 's|\*\([^*]*\)\*|[i]\1[/i]|g' |
_scicomp.25896 | I am an engineer writing a program to solve municipal hydraulics networks using the linear method solved by sparse matrix methods.So far I have solved the loop identification where Number of loops = number of lines - number of nodes + 1 using a sample network of 143 lines joined by 113 nodesThe algorithm always generates 31 closed loops no matter at which node begins the scan and adding node and energy equations to construct a 143 x 143 matrix always iterates to a solution when a smaller matrix is used except in the case I am now at.In the course of elimination to obtain upper triangular during Gauss eliminationmy original elements of 500 or so grow to about 2700 including pointers which I have not counted but believe to be a large proportion of the fill-in.However I notice during elimination I get a lot of very small numbers that impede the solution.I wrote algorithms for row and column interchanges and use Hall's method to complete the diagonal.I have not yet tried to go to double-precision math preferring to use threshold pivoting with Markowitz's strategy to maintain sparsity but I really wonder whether this is worth all the effort since computer power and RAM are now so great that these methods from the sixties and seventies may no longer be needed and that I should only concentrate on stability methods for pivot selection.I am not a computer scientist, just a civil engineer who struggled thru a Numerical Methods course as part of my third year so I wonder if there exist numerical examples to describe the steps that I could more easily follow than try to understand all the complicated notation in scientific papers. My only references are Water Supply and Pollution Control - Viessman & Hammerand Sparse Matrix Technology - Sergio Pissanetsky | Numerical examples for pivot selection in Gauss elimination | fortran | null |
_unix.19728 | I need to edit lines in a file using sed. Now the problem is I am replacing a particular pattern with a combination of text and number. This number is a variable which keeps on incrementing for every subsequent line. Now as sed executes the command for all lines in one go, it is replacing the pattern found with the text and fixed number (i.e initial value of number).For example:k = 10sed s/raj/ram${k++}/ | Using sed to edit lines in a file with a variable | sed;awk | null |
_datascience.13105 | I'm building a simple feedforward neural network in Tensorflow and something seems to be broken. I have adopted the basic structure from http://joelgrus.com/2016/05/23/fizz-buzz-in-tensorflow/ and have tried to adapt it to spit out 1 output unit instead. The input is 10 numerically represented players ex:(5, 17, 19, 54, 110, 3, 112, 78, 60, 63), 5 on the 'North' team and 5 on the 'South' team, and the output is a 1 or 0 (if the 'North' team won or not). 3 hidden layers (200 parameters each). With how this is set up, the algorithm trains to constantly predict 1 (North victory). What can I fix that allows this to train to predict which team is going to have a higher chance of winning? My expected outcome is ex: [.54] (slight edge to the north team) or [.40] (edge to the south team) etc.import numpy as npimport tensorflow as tfimport sqlite3def get_matches(start, stop): connection = sqlite3.connect('5v5.db') cursor = connection.cursor() result = cursor.execute('''SELECT * FROM matches WHERE rowid>=? AND rowid<=?''', (start, stop)) return result.fetchall()def init_weights(shape): return tf.Variable(tf.random_normal(shape, stddev=0.01))def model(X, w_h1, w_h2, w_h3, w_o): h1 = tf.nn.sigmoid(tf.matmul(X, w_h1)) h2 = tf.nn.sigmoid(tf.matmul(h1, w_h2)) h3 = tf.nn.sigmoid(tf.matmul(h2, w_h3)) return tf.nn.sigmoid(tf.matmul(h3, w_o))if __name__ == __main__: TRAINING_GAMES = 2500 #number of games to train on TEST_GAMES = 500 #number of games to test the results on NUM_DIGITS = 10 #input units FIRST_HIDDEN_LAYER = 200 SECOND_HIDDEN_LAYER = 200 THIRD_HIDDEN_LAYER = 200 BATCH_SIZE = 150 training_matches = get_matches(1, TRAINING_GAMES) trX = np.array([match[1:11] for match in training_matches]) trY = np.array([[match[11]] for match in training_matches]) X = tf.placeholder(float) Y = tf.placeholder(float) w_h1 = init_weights([NUM_DIGITS, FIRST_HIDDEN_LAYER]) w_h2 = init_weights([FIRST_HIDDEN_LAYER, SECOND_HIDDEN_LAYER]) w_h3 = init_weights([SECOND_HIDDEN_LAYER, THIRD_HIDDEN_LAYER]) w_o = init_weights([THIRD_HIDDEN_LAYER, 1]) py_x = model(X, w_h1, w_h2, w_h3, w_o) cost = tf.square(Y - py_x) train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost) predict_op = py_x with tf.Session() as sess: tf.initialize_all_variables().run() for epoch in range(10000): p = np.random.permutation(range(len(trX))) trX, trY = trX[p], trY[p] for start in range(0, len(trX), BATCH_SIZE): end = start + BATCH_SIZE sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]}) print(epoch, sess.run(predict_op, feed_dict={X: trX, Y:trY})) test_matches = get_matches(TRAINING_GAMES+1, TRAINING_GAMES+TEST_GAMES) teX = np.array([match[1:11] for match in test_matches]) teY = sess.run(predict_op, feed_dict={X: teX}) print(teY) | Simple feed forward neural network on Tensorflow question | machine learning;python;neural network;tensorflow | null |
_cstheory.34749 | Checking if there are two edge-disjoint paths from $s$ to $t$ in a given undirected graph $G$ is in P via a standard solution based on maxflow. I am interested in the complexity of the following edge-labeled version andwhether it is in P or not.Input: An edge-labeled graph $G$ and two vertices $s$ and $t$ satisfying the following condition:every label in $G$ occurs exactly twice. Output: are there two label-disjoint paths in $G$ from $s$ to $t$?Two paths are label disjoint iffthe labels appearing in the respective paths are disjoint.Example: suppose $G$ is given by $(s, a, v1)$, $(v1, b, t)$, $(s, b, v2)$, $(s, c, v2)$, $(v2, a, t)$, $(v2, c, t)$. Then $s-a-v1-b-t$ and $s-c-v2-c-t$ are two label-disjoint simple paths from $s$ to $t$. | Label-disjoint paths in directed graphs | ds.algorithms;graph theory;graph algorithms;disjoint paths | The problem becomes NP-complete ... this is a graphical :-) reduction from 3-SAT ... it should be self-explanatory (... if not let me know).Two notes:+X1a, -X1a, +X1b, -X1b,...,+X2a,-X2a, ...,dum1,...,dum4 are all distinct labels;in the figure each label appears $\leq 2$ times; but it is straightforward to make each label appears exactly 2 times adding some dum nodes+edges+labels to pair them up. |
_softwareengineering.147451 | I keep hearing people (Crockford in particular) saying the DOM is a terrible API, but not really justifying this statement. Apart from cross-browser inconsistencies, what are some reasons why the DOM is considered to be so bad? | What's so bad about the DOM? | javascript;api;api design;dom | null |
_cs.40808 | Directly from Wikipedia, a set of vertices $X \subseteq V(G)$ of a graph $G$ is independent if and only if its complement $V(G) \setminus X$ is a vertex cover.Does this imply that the complement of the independent set problem is the vertex cover problem? | Relationship between Independent Set and Vertex Cover | graph theory;np complete | Well, strictly speaking it's not the complement; co-VC is co-NP-complete whereas Independent Set is NP-complete. If they were the same, we would know that co-NP was equal to NP, which we do not, and indeed most people believe they are not.But an easy way of seeing that they are not the same if to consider $(K_4, 2)$, the complete graph on four vertices) which is neither a yes-instance of Vertex Cover nor of Independent Set. Similarly, the instance $(K_2,1)$ is a yes-instance for both.However, they are related in the following way.A set of vertices $C \subseteq V(G)$ of a graph $G$ is a vertex cover if and only if $V(G) \setminus C$ is an independent set. This is easy to see; for every endpoint of an edge, at least one vertex must be in $C$for $C$ to be a vertex cover, hence not both endpoints of an edge are in $V(G) \setminus C$, so $V(G) \setminus C$ is an independent set. This holds both directions.So $(G,k)$ is a yes instance for Vertex Cover (a minimization problem) if and only if $(G,n-k)$ is a yes instance for Independent Set (a maximization problem). |
_unix.4615 | Is it possible to set regex patterns for color matching in the LS_COLORS variable? So instead of just*.jpg=38;5;220Can I do \.(jpg|gif)=38;5;220That's just an example, I'd like to get more complicated than that. Am I asking too much from this? Is there another way to do terminal color schemes that I can get fancier?I'm using zsh btw, so if I can do it there but not bash, that's fine. | Set ls color listings based on regex instead of globbing | shell;colors;ls | null |
_datascience.11716 | Suppose you have a classification task and accuracy is what you care about. Now an old system $s_1$ has an accuracy of $a(s_1) = 0.9$ and a new system $s_2$ has an accuracy of $a(s_2) = 0.99$. This is an absolute improvement of $a(s_2) - a(s_1) = 0.09$ percentage points and a relative improvement of $\frac{a(s_2)-a(s_1)}{a(s_1)} = \frac{0.09}{0.9} = 0.1$.However, when you now try to get a system of $a(s_3) = 0.999$ this seems to be much more difficult, although it is only an absolute improvement of $0.009$ and a relative improvement of $0.00\overline{90}$. So neither the absolute nor the relative difference in accuracy seems to capture this well.Is there a common other way to quantify how much better the system is? | What is a reasonable way to compare the improvement in accuracy? | accuracy | null |
_computerscience.2208 | I have an .STL file (ascii and binary format) that contains several different CAD models. How can I read the file and create separate .stl files for each of the single different models. Even some hints/reference would be helpful. | Model Separation - Several models reside in a single .stl file | computational geometry | null |
_softwareengineering.171591 | First off, sorry if this is answered somewhere else. I did a brief search, but wasn't sure how to ask in search terms.I'm looking at some code and came across lot's of statements like this:if ( ($a != empty_or_null_or_notDefined && $a == 5 )Is this the same as just saying:if ( $a == 5 )?(language is PHP.) | Is saying if ( $a != null && $a == 5) the same as if ($a == 5) | php;programming logic;logic programming | At a purely logical level, presuming & is the local and operator, then $a being 5 precludes it from being null.That said, in some languages, and short circuits (that is, if one operand fails, it does not check the others, as the whole clause is known to fail when one does). In this case, this could be a move for efficiency, although it's highly unlikely equality is an expensive enough operation to make this worthwhile (especially as PHP doesn't offer operator overloading).As it's PHP, a single ampersand is a bitwise and operation, not a logical one, as such, it will not be lazy. Your topic has one ampersand, while the question itself has two, I think the latter is more likely to be the real option (as what is happening is a logical check), but you should clarify. |
_softwareengineering.221592 | I have a function that linearly remaps a value from a given interval to an other interval?The function remaps a value from a given interval [oldMin, oldMax] to another interval [newMin, newMax] using this formula:newVal = newMin + (newMax - newMin) * (oldVal - oldMin) / (oldMax - oldMin)If it helps identify what type of transform it is, the above formula is just a reformulation of the following equation. All I did was re-arrange the terms to express newVal on the left hand side of the equation so it is a function of all the other parameters:Is there a standard name for the remapping transformation? | What kind of transform is this? | algorithms;naming | This is known as Linear Interpolation.Very common and powerful, in game development it's shorthand is LerpIt is used to map one value (in a range) to another value (in a range). For example one might map health to color (for tinting the health bar) or time to rotation (for animation). |
_codereview.121018 | Hope, it's my last question about current project. Yeah, it's still about respecting SOLID-principles.And it's still about calculator, so i've got realization of ITerm interface:public interface ITerm : IStackManipulator{ Object Value { get; } /// <summary> /// Term type. 0 for operands, 1 for operators, 2 for brackets /// </summary> int ValueType { get; }}So, my interviewer requires that clients of this interface (classes which uses ITerm objects) should always know, what current term is: operand, operator or smth else (e.g. brackets).The easiest (and currently implemented way) is to create this int ValueType { get; }property and to set it directly in class constructor. Example of my code is here:public class Addition : IOperator //IOperator implements ITerm{ public int Priority { get; } public object Value { get; } public int ValueType { get; } = 1;//etcAnd it's violates Single-Responsibility principle :CAs i know from reading titles about SRP-Validation the easiest way to refactor this, is to create something like ValueTypeGeneratorclass and call for something like ValueTypeGenerator.Generate() in constructor (i know about DI, but i want to simplify code there) but it looks pretty ...weird and i really don't like to use this way in my case.So, i'm asking for an another advice, may be there is some other ways to improve that? | Generating property for a class instance | c#;.net | null |
_webmaster.27083 | I have a few domains hosted at GoDaddy, and it's posting my address, phone number, and email address on my whois results.It looks like they charge an exorbitant $10/year for private registration to hide this. Is that correct? Every other company I've used does this for free.This means that my domains at GoDaddy will effectively cost me twice as much per year. Is there any way around this? e.g. I believe I can go into my GoDaddy and just change the details, but someone told me that doing so would hamper my ability to defend my ownership of the domain if it was contested. Any truth to that? | Hiding whois information on GoDaddy registered domains | domain registration;whois | There is no way around this. If you want to use godaddy as your registrar that's the price you have to pay for private registration. If you can get a domain name with private registration cheaper elsewhere, and cost is an issue to you then register your domain at the cheaper registrar. From this question asked previously about entering fake information when registering your domain:ICANN (not the domain registrar) requires that all information in your registration be valid. If any dispute arises (see the ICANN Uniform Domain Name Dispute Resolution Policy rules here) you will be contacted via the means specified in your domain registration. Notice that section 14 of the rules is a section that defines what happens as part of a 'default' (in other words, they can't contact you): They'll proceed with a judgement, and you won't get a say in the proceedings.ICANN has the power to take a domain from you and give it to somebody else. So yes, it's important that you include valid information in your registration information.For a comparison of a what a private domain registration looks like (compared to a regular domain registration) see this: http://www.domainsbyproxy.com/popup/whoisexample.aspx |
_unix.193762 | This one is maybe a bit theoretical, but... How the heck can X11 touch the video hardware? As I understand it, X11 is an unprivileged user-mode program. But only kernel-mode software can access the hardware. So... how?(It's a simple enough question, but I haven't been able to find any documentation that explains this simple point. There's a lot of documentation about how to set up X11, or how the X11 client/server arrangement works, but not much about how it drives the hardware...)Basically I'm interested in knowing how much of the work is X11, and how much of it is the kernel, and where the two meet. | Why can X11 access the video card? | linux;x11;devices;architecture | null |
_unix.277106 | I have access to an IBM IDataplex Cluster with CentOS v.6.2. If I want to run the following R script on R:library(data.table) library(mgcv) library(reshape2) library(dplyr) library(tidyr) library(lubridate) library(DataCombine)temp_hist <- as.data.table(temp_hist)humid_hist <- as.data.table(humid_hist)# Mergemykey<- c(FIPS, year,month, week)setkeyv(temp_hist, mykey)setkeyv(humid_hist, mykey)hist<- merge(temp_hist, humid_hist, by=mykey)# Minhist_min <- histhist_min$FIPS <- hist_min$year <- hist_min$month <- hist_min$tmax <- hist_min$tmean <- hist_min$hmax <- hist_min$hmean <- NULL# Adding Factorshist_min$citycode <- rep(101,nrow(hist_min)) hist_min$year <- rep(2010,nrow(hist_min))hist_min$week <- rep(1,nrow(hist_min)) hist_min$lnincome <- rep(10.262,nrow(hist_min))# Predictionspred_hist_min <- predict.gam(gam_mean_count_wk, hist_min)pred_hist_min <- as.data.table(pred_hist_min)pred_hist_min <- cbind(hist, pred_hist_min)pred_hist_min$tmax <- pred_hist_min$tmean <- pred_hist_min$tmin <- pred_hist_min$hmax <- pred_hist_min$hmean <- pred_hist_min$hmin <- NULL# Aggregate by FIPSmin_hist <- pred_hist_min %>% group_by(FIPS) %>% summarise(pred_hist = mean(pred_hist_min))How do I utilise the performance of the cluster (specifying cores) using qsub/bsub to run this script? | Running R scripts on a Linux cluster | linux;cluster;r | null |
_cs.70626 | Question: Let $A$ and $B$ be finite alphabets and let $\#$ be a symbol outside both $A$ and $B$. Let $f$ be a total function from $A^{*}$ to $B^{*}$. We say $f$ is computable if there exists a Turing machine $M$ which given an input $x \in A^{*}$, always halts with $f(x)$ on its tape. Let $L_{f}$ denote the language $\Bigl \{x\# f(x) \mid x\in A^{*} \Bigr \}$. Which of the following statements is true:(A) $f$ is computable if and only if $L_{f}$ is recursive.(B) $f$ is computable if and only if $L_{f}$ is recursively enumerable.(C) If $f$ is computable then $L_{f}$ is recursive, but not conversely.(D) If $f$ is computable then $L_f$ is recursively enumerable, but not conversely.My Attempt:if $f$ is computable then given $x$ on tape of TM, it will always halt in $f(x)$ on Tape.$L_f$ denote the language $\Bigl \{x\# f(x) \mid x\in A^{*} \Bigr \}$, which means $L_f$ strings of type which has image and pre image to left and right of $\#$.Now consider a function $f(x)$ is computable and its corresponding language $L_f$, will $L_f$ be recursive ? (given that $f(x)$ is computable )Yes, $L_f$ wil be recursive if $f(x)$ is computable. Because if $x\# f(x)$ is given then i will first convert $x$ in $f(x)$ (i can do it because $f(x)$ is computable ) this gives me $f(x)\# f(x)$ on table and i just left to match left strings to the right string of $\#$ .Now consider a function $L_f$ is recursive, will $f(x)$ be computable ?(i need exlanation of this part) | recursive language and computable function | computability;turing machines;computation models | null |
_codereview.25661 | It took me a lot of poking around and unit testing to get the code to look like it is right now. So I have a XML file which in part looks like this<FunctionKeys> <Name>F13</Name> <Name>F14</Name> <Name>F15</Name> <Name>F16</Name></FunctionKeys>and So I want to take that data and put it back into my class.This is in part what I have public override void Load(string elementText) { var ele = XElement.Parse(elementText); if (ele.Element(FunctionKeys).HasElements) { var funcs = ele.Element(FunctionKeys) .Descendants(Name) .Select(x=>x.Value) .ToList(); foreach (string s in funcs) { dliUnit.FunctionKeyList.Add( (System.Windows.Forms.Keys)System.Enum.Parse(typeof(System.Windows.Forms.Keys), s)); } } }Class to save topublic class DLIUnit{ public List<Keys> FunctionKeyList { get;set; } //Other Members}Somethign about the way that I parse the string back to the Enum (well the entire process really) doesn't sit well with me. I'm very bad at LINQ but have been trying hard to learn it and use it more and more when I play with XML. Is there a better/cleaner way to parse the FunctionKeys?EDITI forgot to mention that I can change any portion of the code or XML file. Right now this is a new idea and can be changed to make it better. | XML to Windows.Forms.Keys List | c#;array;linq;parsing;xml | Sticking with the approach you used how about this as an alternative.public override void Load(string elementText) { var ele = XElement.Parse(elementText); var xElement = ele.Element(FunctionKeys); if (xElement != null && xElement.HasElements) { _dliUnit.FunctionKeyList.AddRange(xElement .Descendants(Name) .Select(x => EnumHelper.GetEnum<Keys>(x.Value)) ); } }I created a little Enum Extensions class just because I like typing GetEnum:public static class EnumHelper{ public static T GetEnum<T>(string name) { if (IsValidEnumFor<T>(name)) return (T)Enum.Parse(typeof(T), name); else throw new ArgumentException(typeof(T) + does not contain a value member = + name); } public static T GetEnum<T>(int number) { if (Enum.IsDefined(typeof(T), number)) { return (T)Enum.ToObject(typeof(T), number); } else { throw new ArgumentException(typeof(T) + does not contain a value member = + number.ToString()); } } public static bool IsValidEnumFor<T>(string name) { return Enum.IsDefined(typeof(T), name); }}Alternative - XmlSerializerOne alternative I have used in the past to parse Xml into objects is the .NET XmlSerializer. In your case you might do something like:StringReader sr = new StringReader(xml);// Create an XmlSerializer object to perform the deserializationXmlSerializer xs = new XmlSerializer(typeof(DLIUnit));return (DLIUnit)xs.Deserialize(sr);This may not work for you but I would recommend having a look into this class as it is fairly easy to use once you get going. Once I got my head around the basics it helped immensely. |
_softwareengineering.122802 | I am part of a software deveopment team. Originally there were just 2 of us, and two applications. To ease our job we create a set of libraries, handling stuff like GUI, database access, calculation, business rules etc, so that we can reuse them in our applications without implementing them twice. Now the team grew, 6 people and ~5 applications (and growing). The applications use the same library, which are great because we don't have to develop and maintain the same thing more than once. I and the other initial guy developed and are mostly responsible for the library, but other people have access to the code and occasionally update it to fix bugs and add improvements.But soon we notice that the more we grow and the more people can modify the code, there is a risk that improvements/bug fixes that someone does can unintentionally break someone else's application which depends on the old behavior. On the other hand, assigning one guy to maintain the libraries and make sure modifications won't break anything is not practical because there are many applications, and possibly many improvement requests to be done, and he can't be sure of everything either.How do teams normally manage situation like this? Perhaps by implementing rules on allowed modification? Defining behaviours that shouldn't be changed? There are a lot of libraries in the internet used by a lot of people, for example open-source/free to use libraries like Apache, Castle, etc. How do they make sure that changes won't break existing client codes? | How do you maintain a common library used by different clients? | libraries;team | You create a public API and version it. The consumers ( the other projects ) get to follow the API and you get to unit test it thoroughly. Also it is a good practice to do code reviews. They should be done by you and the other core developer whenever something is about to change in your common library code. Before any changes are to be included either you or the other core developer must sign off the code. Then and only then should the change be merged into the trunk. Be careful of changes that break unit tests on the public side of the api, in that case you should change the api's version. A good idea is to follow semantic versioning like it is suggested in the comments.Be strict about this. |
_unix.329769 | I'm running Ubuntu 16.04 with VMWare Fusion, I've enabled retina support and set a screen scale in system settings.It works great.What is the equivalent configuration for xfce4? | Scale menu in xfce4? | gnome;xfce;resolution;dpi | null |
_cs.10848 | I want to know if the following problem is decidable:Instance: An NFA A with n statesQuestion: Does there exist some prime number p such that A accepts some string of length p.My belief is that this problem is undecidable, but I can't prove it. The decider can easily have an algorithm to figure out if a particular number is prime, but I don't see how it would be able to analyze the NFA in enough detail to know exactly what lengths it can produce. It could start testing strings with the NFA, but for an infinite language, it may never halt (and thus not be a decider).The NFA can easily be changed to a DFA or regular expression if the solution needs it, of course.This question is something I've been pondering as a self-made prep question for a final I have coming up in 2 weeks. | Can a Turing Machine decide if an NFA accepts a string of prime length? | computability;finite automata | The lengths of the strings accepted by a DFA form a semilinear set (like in Parikh's theorem for context free languages), the description of those isn't too hard to come by (essentially splice up all possible cycles of the automaton), and by Dirichlet's theorem any arithmetic progression of the form $a + b k$ with $\gcd(a, b) = 1$ contains an infinitude of primes.Pulling the above together gives an algorithm to check if your regular (or even context free language) contains strings of prime length. Definitely not a simple question, IMVHO... |
_codereview.150950 | The challengeA ring is composed of n (even number) circles as shown in diagram. Put natural numbers 1,2,...,n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.Note: the number of first circle should always be 1.Input\$n\quad (0 \lt n \le 16)\$OutputThe output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. You are to write a program that completes above process.Sample Input68Sample OutputCase 1:1 4 3 2 5 6 1 6 5 2 3 4 Case 2:1 2 3 8 5 6 7 4 1 2 5 8 3 4 7 6 1 4 7 6 5 8 3 2 1 6 7 4 3 8 5 2 My solution#include <iostream>#include <algorithm>const int MAX_P = 50;bool primes[MAX_P];void gen_primes(){ std::fill(primes, primes + MAX_P, true); primes[0] = primes[1] = false; // discard 2's multiples for ( int i = 4; i < MAX_P; i += 2 ) { primes[i] = false; } // discard other prime numbers(3, 5, ..)'s multiples for ( int p = 3; p < MAX_P; p += 2 ) { if ( !primes[p] ) continue; for ( int i = p * p; i < MAX_P; i += 2 * p ) { primes[i] = false; } }}const int MAX = 17;int prime_ring_idx, n;int prime_ring[MAX];bool number_taken[MAX];void print_prime_ring(){ std::cout << 1; for ( int i = 2; i <= n; ++i ) { std::cout << << prime_ring[i]; } std::cout << std::endl;}void gen_prime_ring(){ // all n numbers filled, print the solution if ( prime_ring_idx >= n ) { print_prime_ring(); return; } for ( int i = 2; i <= n; ++i ) { if ( !number_taken[i] && primes[i + prime_ring[prime_ring_idx]] ) { // if it is nth number check if it can make a prime // with the first number, so as to complete the circle if ( prime_ring_idx == n - 1 && !primes[i + prime_ring[1]] ) { continue; } number_taken[i] = true; prime_ring[++prime_ring_idx] = i; gen_prime_ring(); number_taken[i] = false; prime_ring[prime_ring_idx--] = 0; } }}int main(){ int c = 1; gen_primes(); prime_ring[1] = 1; // initially no numbers are taken for ( int i = 0; i < MAX; ++i ) { number_taken[i] = false; } // 1 will always be the first number for the circle so take it number_taken[1] = true; while ( std::cin >> n ) { if ( c != 1 ) { std::cout << std::endl; } std::cout << Case << c++ << : << std::endl; prime_ring_idx = 1; gen_prime_ring(); } return 0;}Share your ideas to improve my code on:EfficiencyCode styleDesign patternsReadability | UVa 524 - Prime Ring | c++;programming challenge;primes;c++03 | null |
_unix.286887 | I am using i3-wm with Archlinux, and I nowadays are wandering that: is it possible to clone a specific work space to another output(monitor)?It is different from --same-as as well as --left-of --right-of --above --below, which means that the second monitor(DP2) can only show one of my ten work spaces, my main monitor(eDP1) able to work on that work space at the mean time.The --same-as option make the DP2 follow all my focus on any work space, and the other four option make eDP1 cannot show the specific work space!So, is there any median way which make DP2 focus on one work space, without the prevention of eDP1 focusing on it? | How can I clone a specific work space to other outputs? | linux;xorg;window manager;xrandr;monitors | null |
_unix.165721 | I am using Fedora 20 with the Mate desktop. I sometimes give talks, using LibreOffice Impress for a slide show, with a laser to point out details on the screen. I will be giving a talk where the slides are displayed on a TV screen, which is non-reflective so the little red spot does not show. The mouse pointer is an obvious substitute, but the arrow icon does not show up very well. Is there a way of using a different, more visible icon, say one that I can choose from a set provided, or that I can design for myself?I see my question has been edited, but I'm not sure it was needed or that it is now an improvement on what I wrote originally. Especially the comma after more visible, that has changed the sense of it, and I particularly do not like to see the Please deleted, I like to be polite.I have followed switch87 suggestions and downloaded a new theme, which is now installed thanks to his help. I very much appreciate his patient help. | Changing the mouse pointer in Mate | x11;mate | Mate uses themes and mouse pointers of gnome2 (gtk2 actualy), so a good place to start looking is gnome-look.org , here you can find many themes for the mouse pointer to install, and it works, I use mate myselve.After downloading the theme file (do not extract it!) go to the appearance screen of gnome/mate, there you have a install button, use it to install the downloaded theme. afterwards you can go to customize to change it. |
_unix.272313 | I've read the systemd service manpage a few times, but I still cannot figure out a basic systemd pattern:I want to run a startup process once (like a docker container, or format a drive) at bootup, successfully to completion. But if I use Type=oneshot for that, then I can't use Restart=on-failure, and if it fails, then it won't retry the job. Am I missing something obvious here?I also tried setting Type=simple with Restart=on-failure, but this in many cases I need the following behavior (from the manpage) that oneshot services give:Behavior of oneshot is similar to simple; however, it is expected that the process has to exit before systemd starts follow-up units.Updates:Relevant upstream systemd bug.And we'd also want RemainAfterExit semantics | Systemd: How to assure a oneshot service gets retried if it fails the first time? | systemd | null |
_unix.106341 | I'm using the following sequence of commands in my .bashrc file to alter the appearance of my linux terminal. It fills the screen line by line with a pattern made out of characters. There is no abstraction, the characters are from a set within the command itself:for i in $(seq 1 $(expr $(tput lines))); do echo -en '\E[0;32m'$(tr -dc ',.o;:~' < /dev/urandom | head -c $(tput cols)); done; tput cup 1 -->the setThe main idea is to read 80 cols (bytes) from some random characters from the set, and to print that * number of lines. Now, I've run the following contributed script in order to explore adding new characters to the set. To maintain compatibility with the linux terminal I'm using, I've run this outside of X etc, with the following result: I'd like to to use the available characters in the sequence above. So I took many of them and did the following, for instance with :echo -n | hexdump0000000 97e2 00980000003so the UTF-8 sequence is \xE2\x97\x98I build all the sequences I need: \xE2\x95\x99, \xE2\x95\x9a to f, \xE2\x96\x90 to 93So I simply add to my .bashrc file A=$(echo -e '\xE2\x97\x98') and B=$(echo -e ',.o;:~') and I modify my command sequence like this (i.e. echo $A$B):for i in $(seq 1 $(expr $(tput lines))); do echo -en '\E[0;32m'$(tr -dc $(echo $A$B) < /dev/urandom | head -c $(tput cols)); done; tput cup 1 If I echo $A or $B at the prompt, it prints the char(s). But when the sequence is called in .bashrc this mostly doesn't work at all. On an entire screen appears 3-5 times total along with many placeholder chars meaning the output is not supported by the term. The other characters from the set are there. Of interest is that if I kept the original syntax with no $B variable and simply tried to add $A to the set i.e. tr -dc ',.o'$A';:~' I get the exact same sort of output, suggesting it's something else than syntax - because of /dev/urandom. Other variations on the syntax using quotations introduce more unrelated echo.As a side note, in xterm, the result is similar with different placeholder chars, and a few and .Is there a way to bring the variable in the set like that or does this need to be redesigned from scratch to account for this case? | Using a variable inside a sequence of commands in bash to supplement an existing string - syntax error or flawed design? | bash;terminal | This is a non universal solution which achieves the intended result without exploring the difference between tr and the one in the heirloom toolchest or redesigning what I have for the moment. As such, it is flawed but pragmatic. As a contributor alluded in relation to tr, there is a restriction to the use of this command:Currently tr fully supports only single-byte characters. Eventually it will support multibyte characters; when it does, the -C option will cause it to complement the set of characters, whereas -c will cause it to complement the set of values. This distinction will matter only when some values are not characters, and this is possible only in locales using multibyte encodings when the input contains encoding errors.So actually only 8bit 1 byte chars (non Unicode) like the ones in my initial set are supported through my sequence. I also have a constraint that I'm rendering one screen worth of characters and I don't want more so the idea of adding some other randomness for the new chars was less appealing i.e. how to control total chars written. So I decided to post process the output. The scope of available characters to be used as a pattern will be smaller than the total 1 byte chars available so I can use those I never intended to use in the first place and repurpose them as variables like this:Z1=$(echo -en '\xe2\x97\x98') \\ Z1 to Z9 will be used toZ2=$(echo -en '\xe2\x95\x9a') \\ bring in our non unicodeZ3=$(echo -en '\xe2\x95\x9c') \\ charsZ4=$(echo -en '\xe2\x95\x9d')Z5=$(echo -en '\xe2\x95\x9e')Z6=$(echo -en '\xe2\x95\x9f')Z7=$(echo -en '\xe2\x96\x91')Z8=$(echo -en '\xe2\x96\x92')Z9=$(echo -en '\xe2\x96\x93')Z11=$(tr -dc '123456789a' < /dev/urandom | head -c 1) \\Z11 to Z13 used toZ12=$(tr -dc '123456789a' < /dev/urandom | head -c 1) \\reintroduce the charsZ13=$(tr -dc '123456789a' < /dev/urandom | head -c 1) \\used as variablestput setf 6tput setaf 6echo -en $(tr -dc ',.o;:~123456789a' < /dev/urandom | head -c $(echo -en $[$(tput cols) * $(tput lines)]) | sed -e s/1/$Z1/g -e s/2/$Z2/g -e s/3/$Z3/g -e s/4/$Z4/g -e s/5/$Z5/g -e s/6/$Z6/g -e s/7/$Z7/g -e s/8/$Z8/g -e s/9/$Z9/g -e 0,/a/s//$Z11/ -e 0,/a/s//$Z12/ -e s/a/$Z13/g); tput cup 1 ^set ^^vars ^ variables ouput are replaced with intended char>___________________________________________________________________________________________^...then vars themselves reintroduced here as chars, one 'a' at a time(only 3 shown here, last one is global) |__________________________________________________________________________________|The updated sequence is slightly different than in the Q and is simply rendered in one clean sweep instead of line per line. It uses sed and its ability to accept many commands to apply to the stream with -e. The numbers 1 to 9 and the letter a are randomized into the full page pattern. The output pattern is then filtered with sed and 1 to 9 (if present in the random stream) are all converted into our intended non unicode chars - only a is remains. Those a are then processed and used to reintroduce the chars 1 to 9 and a itself in the pattern using variables Z11 to Z13 (random generator with head 1 byte that uses 1-9 and a as a set now that we don't need them anymore). Each instance of a could be individually randomized (see pattern sample below) or left as is (another char than a can be chosen of course, one that we might enjoy seeing in the final pattern). This proof of concept is incomplete as you would ultimately need to intercept all the a chars in this example and transform them into something really random. But it works. This is just to show these chars (and I would select in practice chars that I don't want to use in the pattern so there would be no need to reintroduce them like this in the first place) can be reintroduced. The tr obstacle has been avoided.We can see what happened to the a's - the first one was converted to 8 and the second one to 1, whereas the rest were converted to 4s (sed global). 1,4 and 8 were all chars used to bring in our special chars, and now they can be used too if need be. No doubt an elegant solution exists but this is not one of those. This is all generated in the blink of an eye.Here's a simplified version formatted like a script which uses digits 1-9 for our pattern without 'redeeming' them like explained above:#!/bin/bash## spptr_dfp.sh - Display a chosen pattern of chars using tr, while using sed post processors to deal with## multibyte chars that tr can't stomach. Rely on single chars not used for the pattern to bring in the## multibyte ones later on in the pipeline.## Z1 to Z9 will be used as primitives variables## to bring in our non unicode charsZ1=$(echo -en '\xe2\x97\x98')Z2=$(echo -en '\xe2\x95\x9a')Z3=$(echo -en '\xe2\x95\x9c') Z4=$(echo -en '\xe2\x95\x9d')Z5=$(echo -en '\xe2\x95\x9e')Z6=$(echo -en '\xe2\x95\x9f')Z7=$(echo -en '\xe2\x96\x91')Z8=$(echo -en '\xe2\x96\x92')Z9=$(echo -en '\xe2\x96\x93')## the color we wanttput setf 6tput setaf 6## the main event, generated for cols*lines## the pattern is made out of ,.o;:~## the single chars used as vars are 123456789## after tr outputs, sed converts any of the single chars to our multibyte charsecho -en $(tr -dc ',.o;:~123456789' < /dev/urandom | head -c $(echo -en $[$(tput cols) * $(tput lines)]) | sed -e s/1/$Z1/g -e s/2/$Z2/g -e s/3/$Z3/g -e s/4/$Z4/g -e s/5/$Z5/g -e s/6/$Z6/g -e s/7/$Z7/g -e s/8/$Z8/g -e s/9/$Z9/g)tput cup 1exit |
_webmaster.47675 | Ok, I'm a bit confused by all of this, I have 2 main questions.The company I work for has a Google Places account, now Google+ Local as I understand. Where I'm getting confused is, what is the difference between a Google+ Local page and a Google+ page?In search results, there are a few competitors showing in the rankings with map markers to the right (not in the right hand side of the page) and under the web site name - Google+ page. The company I work for does better than these in the search results, but doesn't have a map marker or a link below to a Google+ page. Can anyone give me an idea how to get ranked like these other web sites?I have only today created a Google+ account, and would like some advice before I go creating a page when there already exists a Google+ Local page. I read here that these 2 pages should be merged? | Google+ Local and Google+ Page | google plus;google local search;google places | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.