id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_unix.312962
Nested Tunneling with AH and ESP both of these security protocols work together in tunnel mode. https://www.ietf.org/rfc/rfc2401.txt Does anyone have a manual for this specific configuration with OpenBSD https://www.openbsd.org/ --> OpenIKED http://www.openiked.org/ OpenIKED is a FREE implementation of the Internet Key Exchange (IKEv2). Thank you very much
Nested Tunneling with AH and ESP with OpenBSD --> OpenIKED
vpn;openbsd;bsd;ipsec
null
_cstheory.16957
Recall that in the vertex cover problem we are given an undirected graph ${G=(V,E)}$ and we want to find a minimum-size set of vertices ${S}$ that touches all the edges of the graph, that is, such that for every ${(u,v)\in E}$ at least one of ${u}$ or ${v}$ belongs to ${S}$.Let us apply the methodology described in the first section. Given a graph ${G=(V,E)}$ and vertex costs ${c(\cdot)}$, we can formulate the minimum vertex cover problem for ${G}$ as an ILP by using a variable ${x_v}$ for each vertex ${v}$, taking the values $0$ or $1$, with the interpretation that ${x_v=0}$ means that ${v\not\in S}$, and ${x_v=1}$ means that ${v\in S}$. The cost of the solution, which we want to minimize, is ${\sum_{v\in V} x_v c(v)}$, and we want ${x_u+x_v \geq 1}$ for each edge ${(u,v)}$. This gives the ILP$\displaystyle \begin{array}{lll} {\rm minimize} & \sum_{v\in V} c(v) x_v \\ {\rm subject\ to} \\ & x_u + x_v \geq 1 & \forall (u,v) \in E\\ & x_v \leq 1 & \forall v\in V\\ & x_v \in {\mathbb N} & \forall v\in V \end{array} \ \ \ \ \ (2)$Next, we relax the ILP $(2)$ to a linear program.$\displaystyle \begin{array}{lll} {\rm minimize} & \sum_{v\in V} c(v) x_v \\ {\rm subject\ to} \\ & x_u + x_v \geq 1 & \forall (u,v) \in E\\ & x_v \leq 1 & \forall v\in V\\ & x_v \geq 0 & \forall v\in V \end{array} \ \ \ \ \ (3)$Let us solve the linear program in polynomial time, and suppose that ${{\bf x}^*}$ is an optimal solution to the LP $(3)$; how do we round it to a $0/1$ solution, that is, to a vertex cover? Lets do it in the simplest possible way: round each value to the closest integer, that is, define ${x'_v = 1}$ if ${x^*_v \geq \frac 12}$, and ${x'_v = 0}$ if ${x^*_v < \frac 12}$. Now, find the set corresponding to the integral solution ${{\bf x}'}$, that is ${S:= \{ v : x'_v = 1 \}}$ and output it. We have:The set ${S}$ is a valid vertex cover, because for each edge ${(u,v)}$ it is true that ${x^*_u + x^*_v \geq 1}$, and so at least one of ${x^*_u}$ or ${x^*_v}$ must be at least ${1/2}$, and so at least one of ${u}$ or ${v}$ belongs to ${S}$; The cost of ${S}$ is at most twice the optimum, because the cost of ${S}$ is$\displaystyle \sum_{v\in S} c(v)$$\displaystyle = \sum_{v\in V} c(v)x'_v$$\displaystyle \leq \sum_{v\in V} c(v)\cdot 2 \cdot x^*_v$$\displaystyle = 2\cdot opt(LP)$$\displaystyle \leq 2\cdot opt(VC)$And thats all there is to it! We now have a polynomial-time 2-approximate algorithm for weighted vertex cover.Question:I realize that depending on what we pick as our rounding point, that is what our approximation bound is going to be. Therefore since we picked $1/2$ as our rounding point, approximation bound is $2$. If we picked $1/3$ as our rounding point, meaning if $x_v >= 1/3$ then $x_v=1$ and if $x_v < 1/3$ then $x_v=0$, our approximation bound would be $3$.My question is how to find and show that the rounding we pick is optimal?Thanks in advance!
How to determine proper rounding in linear programming relaxations?
ds.algorithms;linear programming;integer programming
null
_softwareengineering.314834
So I came across this post while researching about package structuring for MVC. I just need some clarifications on what a business domain and technical domain are. Examples would be helpful.
Business domain vs technical domain
architecture;terminology
Business Domain refers to real-world aspects of your solution (e.g. Healthcare, Aviation, Finance, Military, Retail, etc). The business domain informs your requirements and acceptance criteria for the system; it can be suggestive of a very high-level form of segregation for different areas. For example, if you happen to be building a solution for a Business' ERP, you might create high-level divisions in your overall system as follows:SecurityFinanceSalesStock ControlShippingCustomer SupportIT HelpdeskI would expect these kinds of divisions to exist at the top level of software - i.e. there's probably not very much cross-over between IT Helpdesk or Stock Control, so it could make sense to keep those separate. In the question you've linked to, Technical domain refers to technologies used, including patterns and frameworks (e.g. ASP.NET/Ruby on rails, MVC Pattern, etc). These tend to inform specific design choices and architectures for applications or related groups of applications.Technologies are often suggestive or prescriptive of particular structures - usually used at an application-level rather than the top level. For example, MVC might suggest a project structure for a particular application as follows:ModelsViewsControllersShared/CommonScriptsThat structure might happen to be mirrored across multiple different applications, or maybe other applications will use different technologies. Ultimately, the Business domain will have some bearing on the choice of technologies used (e.g. We need a website or We're only willing to pay for X), and may help inform a very high-level structure, but typically not to the degree of dictating technical decisions about design or architecture.
_unix.20044
After I run yum install gitit shows the errorError: Package: git-1.7.6.1-1.el5.rf.i386 (rpmforge) Requires: libcurl.so.3You could try using --skip-broken to work around the problemYou could try running: rpm -Va --nofiles --nodigestDo I need to install libcurl.so.3 or download git from the web and install?
Package: git-1.7.6.1-1.el5.rf.i386 (rpmforge) Requires: libcurl.so.3
centos;software installation;yum
null
_unix.15016
I am facing a slight problem in my project. I have a menu driven program and one of my options is Display all, which displays all the entries from a map using a loop. The display is on the terminal and I am not being able to view all the entries because it only shows the last few entries before my prompt comes again. I want the output to be redirected to a file so that I can use more commands and give the user a view accordingly. Please suggest few commands or code.
Redirection of output from the terminal to a file in unix/linux
vi
null
_codereview.141235
I have a standard Edit action in Asp.Net MVC 5 and I want to avoid throwing the unhandled exception when is made a get request without the id like ~/food/edit, so I did this.public ActionResult Edit(int id = 0){ if (id == 0) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } string result = _foodAppService.GetById(id); FoodVm food = string.IsNullOrEmpty(result) ? null : JsonConvert.DeserializeObject<FoodVm>(result); if (food == null) { return RedirectToAction(Index); } return View(food);}My question is: Is it a good practice to handled it in this way or there are more suitable strategies ?I'm new to this asking question thing, if a should I ask in another way, just let me know, thank you for your time.
An Edit action in ASP.NET MVC, with handling for missing id parameter
c#;asp.net;asp.net mvc;asp.net mvc 5
null
_unix.324073
On a fresh install of Fedora 19 I am attempting to change the password to something simple, like Password01 (this is just a simple testing VM, nothing fancy), but the password complexity requirements prevent me from setting anything easy to remember.How can I bypass the complexity requirements or disable them?the contents of /etc/pam.d/passwd:#%PAM-1.0auth include system-authaccount include system-authpassword substack system-auth-password optional pam_gnome_keyring.so use_authtokpassword substack postloginEven as root I cannot bypass the requirements: justincase@localhost ~ $ sudo -s[sudo] password for justincase: [root@localhost justincase]# passwd justincaseChanging password for user justincase.New password: BAD PASSWORD: The password fails the dictionary check - it is based on a dictionary wordRetype new password: [root@localhost justincase]#
How can I bypass Fedora's password complexity requirments?
fedora;pam;passwd
As root you can bypass the requirements. Your example shows this happening:# passwd justincaseChanging password for user justincase.New password:BAD PASSWORD: The password fails the dictionary check - it is based on a dictionary wordRetype new password:#Notice it does not repeat the New password prompt but instead it asks you to retype the (bad) new password you are entering. If you had continued with the alleged bad password you would have been able to set it as the password for justincase.
_cs.40216
I've read the Wikipedia article explaining the complexity analysis of the Karatsuba algorithm, but I'm not fully grasping it. I seem to have gotten about 75% of the way to the solution on my own, but lack the last 25% to fully understand why the complexity is $O(N^{\log3})$ where the log function is base $2$.I worked out myself that the recursion tree has height $\log N$ (easy to see), and I understand the coefficient $3$, which can trade places with $N$ due to the properties of logs, comes from the fact that each level of recursion results in three leaves per node of the tree.I think the main thing that's tripping me up is I'm that not clearly seeing why $\log N$ can be expressed as the exponent of $3$, although I see where $\log N$ and $3$ come from, and I see how in the next step you can swap $N$ and $3$ to get $N^{\log3}$ (something I learned in highschool).To put this another way, I've been unable to work this problem out to visualize sequentially how this formula plays out for the algorithm. I.E, without already knowing the Master theorem, how does one derive this formula (I assume it's possible) by simply walking through the Karatsuba algorithm and watching the patterns emerge.UPDATE: In writing out my understanding of the wikipedia explanation line by line to identify where I got stuck, I finally saw the pattern. However, maybe putting it here will help someone else.
How do we derive the runtime cost of Karatsuba's algorithm?
algorithm analysis;runtime analysis;master theorem
Karatsuba's basic step works for any base B and any m, but the recursive algorithm is most efficient when m is equal to n/2, rounded up. I understood this to mean that for integers with n digits, m is the ceiling of half n (m being the exponent applied to the Base in the algorithm). This can be seen if you simply look at the definition of the algorithm.In particular, if n is $2^k$, for some integer k, and the recursion stops only when n is 1, then the number of single-digit multiplications is $3^k$, which is nc where c = ${\log3}$I took this to mean, given n is some power of 2 (2, 4, 8, ...), the number of single digit multiplications performed is 3 * (exponent of 2). I worked out how this conclusion was reached by writing out the tree and finding that each sub-problem involves 3 multiplications, and at the base of the recursive tree, you should have $3^{m - 1}$ sub-problems for that bottom level. However, the -1 can be ignored as, using the properties of exponents, you can factor that out into a constant, which Big-O doesn't consider. Therefore, if we are looking for the exponent of 2, we can get that exponent of 3 as a log relative to n, thus $3^{\log n}$, which by a law of logarithms turns into $n^{\log 3}$. Since the computational complexity of each sub-problem by itself is a constant 7 (4 additions and 3 multiplications) independent of the number of digits in the number representation, the computation itself can be ignored in the efficiency analysis, giving us $O(n^{log 3})$
_cs.9133
Given a directed acyclic graph $D = (V,A)$, a vertex $v \in V$ is a source if its indegree is zero, meaning that it has only outgoing arcs.Does there exist a linear time algorithm to find a source in a given directed acyclic graph?Follow-up question: Can one in linear time find all sources?
Finding a source of a directed acyclic graph in linear time
algorithms;graph theory
null
_cogsci.9764
Some time ago I remember reading about how the human brain breaks down visual information into a number of individual channels.For example, one channel might focus on edges and lines, another might focus on being a contrast map, while another provide a color information overlay. Each channel being a much more simplified part of the entire visual input.From what I understood, modern research into the visual cortex has provided some insight into what the channels might be and how they're broken down. If my understanding of current research is correct I was hoping to find some more detailed information explaining how the visual information is broken down and processed (articles at the technical level of Scientific American are fine, so long as they detail the types of channels present).My desired take-away from this is to brainstorm ideas for how I might better pre-process an image into feature data for a standard neural network learning algorithm, based on the human experience.
How does the brain break down visual information for processing? What channels is visual input broken into?
vision;neural network
null
_unix.387532
I have a MacBook pro that I used to install Ubuntu into a USB, and I have already booted Ubuntu in my laptop to install SSH. Now that I have tested the system and it works, my goal is to install it into a new computer that does not have an OS yet and has no keyboard nor monitor.The motherboard has USB ports where I can insert the USB stick that already has Ubuntu installed, but I would like the OS to live in the hard drive.My question has two parts:How to boot Ubuntu in the headless device, what do I have to do besides turning the device on and connecting the USB?And after this, how do I keep the OS in the hard drive?
How to install Ubuntu into headless machine from a USB?
ubuntu;system installation;headless
null
_unix.260906
I believe Ctrl-C can be trapped in bash scripts. Is it also possible to trap it inside an Awk script in order to handle that event?For example, for aborting processing, but printing the results of what has been processed already, instead of just silenty quitting?
Trap Ctrl-C in awk script
shell script;awk;trap
I'm not aware of any awk implementation that has support for that. You could write an extension for gawk for that, but here, I'd rather switch to another language.perl makes it easy to convert awk scripts with its a2p script.For instance, if you have an awk script like:{count[$0]++}END { for (i in count) printf %5d %s\n, count[i], i}a2p on it will give you something like:#!/usr/bin/perleval 'exec /usr/bin/perl -S $0 ${1+$@}' if $running_under_some_shell; # this emulates #! processing on NIH machines. # (remove #! line above if indigestible)eval '$'.$1.'$2;' while $ARGV[0] =~ /^([A-Za-z_0-9]+=)(.*)/ && shift; # process any FOO=bar switcheswhile (<>) { chomp; # strip record separator $count{$_}++;}foreach $i (keys %count) { printf %5d %s\n, $count{$i}, $i;}Which you can edit to add your signal handling (and remove that processing of var=value arguments which we don't want here, and the part intended for systems that don't support #!):#!/usr/bin/perlsub report { foreach $i (keys %count) { printf %5d %s\n, $count{$i}, $i; }}$SIG{INT} = sub { print STDERR Interrupted\n; report; $SIG{INT} = 'DEFAULT'; kill('INT', $$); # report dying of SIGINT.};while (<>) { chomp; # strip record separator $count{$_}++;}report;Another alternative could be to interrupt the feeding of data to awk, and have awk ignore the SIGINT, like instead of:awk '{count[$0]++};END{for (i in count) printf %5d %s\n, count[i], i}' filedo:cat file | ( trap '' INT awk '{count[$0]++};END{for (i in count) printf %5d %s\n, count[i], i}')Ctrl+C will then kill cat but not awk. awk will still keep on processing remaining input still in the pipe.To detect the Ctrl+C in awk, you could do:(cat file && echo cat terminated normally) | ( trap '' INT awk '{count[$0]++} END{ if ($0 == cat terminated normally) delete count[$0] else print Interrupted for (i in count) printf %5d %s\n, count[i], i}')
_codereview.13153
This was for an assignment. I had to write a function to compare two roman numerals. This had to return true only if the second number was larger than the first and had to be done without converting the letters into integers. Also prefix subtraction didn't apply so all the letters came in descending order.Here is what I came up with:<?phpfunction x_smaller_than_y($x_num,$y_num) {//Create array with ordered list of roman numerals. $evaluation= array(M,D,C,L,X,V,I);//Splits submitted numbers into arrays$x_num_arr = str_split($x_num);$y_num_arr = str_split($y_num);//Loops through each roman numeral in the given listfor ($evaluate = 0; $evaluate<7;$evaluate++) { //For every letter in the numerals' list loops through //every letter in the given numbers looking for a match. $counter = 0; while ($counter < ((strlen($x_num)))&& $counter < ((strlen($y_num)))) { //If in any specific position x=y, it simply ignores it and moves forward. if ($x_num_arr[$counter]==$y_num_arr[$counter]) {$counter++;} //If in any given position the letter in Y is higher in the list than //the letter in X then Y is larger than X and the function is true. //break ends the while loop and $evaluate=8 ends the for loop. elseif(($x_num_arr[$counter]!=$evaluation[$evaluate])&&($y_num_arr[$counter]==$evaluation[$evaluate])) {return true; $evaluate=8; break;} //Same as above but this time the letter in X is before the letter //in Y so the function is false. elseif(($x_num_arr[$counter]==$evaluation[$evaluate])&&( $y_num_arr[$counter]!=$evaluation[$evaluate])) {return false; $evaluate=8; break;} //If none of the above cases apply simply move to the next letter. else {$counter++;} } }//Since the number of iterations in the while loop is determined by the //shorter number there can still be a case in which 2 numbers are exactly //the same up to a point but one is simply longer than the other, //eg. MXVI and MXVII.//When this happens the for loop will have run through its natural //course, $evaluate will be equal to 7, and the code below will determine //the larger number by looking at their lenght. if ($evaluate<8&&(strlen($x_num) < strlen($y_num))){return true;}elseif ($evaluate<8&&(strlen($x_num) > strlen($y_num))){return false;}}How could have I made it better?
PHP function to compare two Roman numerals
php;algorithm;homework
null
_datascience.961
These are 4 different weight matrices that I got after training a restricted Boltzman machine (RBM) with ~4k visible units and only 96 hidden units/weight vectors. As you can see, weights are extremely similar - even black pixels on the face are reproduced. The other 92 vectors are very similar too, though none of weights are exactly the same. I can overcome this by increasing number of weight vectors to 512 or more. But I encountered this problem several times earlier with different RBM types (binary, Gaussian, even convolutional), different number of hidden units (including pretty large), different hyper-parameters, etc. My question is: what is the most likely reason for weights to get very similar values? Do they all just get to some local minimum? Or is it a sign of overfitting? I currently use a kind of Gaussian-Bernoulli RBM, code may be found here. UPD. My dataset is based on CK+, which contains > 10k images of 327 individuals. However I do pretty heavy preprocessing. First, I clip only pixels inside of outer contour of a face. Second, I transform each face (using piecewise affine wrapping) to the same grid (e.g. eyebrows, nose, lips etc. are in the same (x,y) position on all images). After preprocessing images look like this: When training RBM, I take only non-zero pixels, so outer black region is ignored.
Why a restricted Boltzman machine (RBM) tends to learn very similar weights?
rbm
null
_codereview.7202
This is the proof-of-concept code with drafts for widgets for my current project that uses Google Maps. As a result the code produces 3 buttons in the top right corner:Any advice on how I may improve it? (personally I'm specifically server-side developer and don't use JavaScript extensively, so expect a lot of no-no's in my code):$(function() { var latlng = new google.maps.LatLng(-41.288771, 174.775314); var myOptions = { zoom: 11, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false, panControl: false }; var map = new google.maps.Map(document.getElementById(map_canvas), myOptions); var terrainBtn = new MapTypeButton({ title: 'Terrain', mapType: google.maps.MapTypeId.TERRAIN }); terrainBtn.attach(map, google.maps.ControlPosition.TOP_RIGHT); var satelliteBtn = new MapTypeButton({ title: 'Satellite', mapType: google.maps.MapTypeId.SATELLITE }); satelliteBtn.attach(map, google.maps.ControlPosition.TOP_RIGHT); var mapBtn = new MapTypeButton({ title: 'Map', mapType: google.maps.MapTypeId.ROADMAP }); mapBtn.attach(map, google.maps.ControlPosition.TOP_RIGHT);});/** * Helper function to implement JS inheritance */Function.prototype.subclass= function(base) { var c = Function.prototype.subclass.nonconstructor; c.prototype = base.prototype; this.prototype = new c();};Function.prototype.subclass.nonconstructor= function() {};function CustomButton(options){ var defaults = {}; this.settings = $.extend({}, defaults, options);}CustomButton.prototype.render = function() { this.jq = $('<div class=custom-map-button>' + this.settings.title + '</div>'); if (this.settings.classes) { for (var i in this.settings.classes) { this.jq.addClass('custom-map-button-' + this.settings.classes[i]); } } return this.jq[0];};CustomButton.prototype.attach = function(map, position) { this.map = map; map.controls[position].push(this.render());};function MapTypeButton(options){ CustomButton.apply(this, arguments);}MapTypeButton.subclass(CustomButton);MapTypeButton.prototype.render = function() { var result = CustomButton.prototype.render.apply(this, arguments); if (this.map.getMapTypeId() == this.settings.mapType) { this.jq.addClass('custom-map-button-selected'); } this.jq.addClass('custom-map-button-mapType'); return result;};MapTypeButton.prototype.attach = function(map, position, init) { var t = this; CustomButton.prototype.attach.apply(this, arguments); t.jq.click(function() { t.click(); });};MapTypeButton.prototype.click = function() { $('.custom-map-button-mapType.custom-map-button-selected').removeClass('custom-map-button-selected'); this.map.setMapTypeId(this.settings.mapType); this.jq.addClass('custom-map-button-selected');};
Google Maps buttons
javascript;google maps
Pretty good Zmayte!But, if I had to nitpick...var defaults = {};this.settings = $.extend({}, defaults, options);The defaults is redundant, whilst an empty object.for (i in this.settings.classes) { this.jq.addClass('custom-map-button-' + this.settings.classes[i]);}i is not defined, so you are doing property assignment on the global object, making i a global variable. A for in also iterates over all enumerable properties on the prototype chain. This can lead to problems when you don't know what has augmented Object and so on. Use hasOwnProperty() to prevent this problem.
_unix.246839
Background: I am trying to set up an access point on Linux. The ultimate aim is to run SSLStrip (for an exercise) so I need to be able to do something like this, to redirect port 80 traffic through port 10000, on which SSLStrip listens.iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000Using Linux - Kali2, 64bit. Machine has internet access via eth0.This is how I am setting up the access point:airmon-ng start wlan0 6modprobe tunifconfig wlan0mon downiwconfig wlan0mon mode monitorifconfig wlan0mon upairbase-ng -e MyAccessPoint -c 6 wlan0mon &ifconfig at0 upifconfig at0 10.0.0.1 netmask 255.255.255.0ifconfig at0 mtu 1500route add -net 10.0.0.0 netmask 255.255.255.0 gw 10.0.0.1 dev at0Into /etc/dhcp/dhcpd.conf I put the following:subnet 10.0.0.0 netmask 255.255.255.0 { authoritative; range 10.0.0.100 10.0.0.200; default-lease-time 3600; max-lease-time 7200; option subnet-mask 255.255.255.0; option broadcast-address 10.0.0.255; option routers 10.0.0.1; option domain-name-servers 8.8.8.8; option domain-name freeinternet.co.uk }Check that /etc/default/isc-dhcp-server has INTERFACES=at0Start the DHCP Server:/etc/init.d/isc-dhcp-server restartConfigure NAT and enable ip forwarding:iptables --flushiptables --table nat --flushiptables --delete-chainiptables --table nat --delete-chainiptables -P FORWARD ACCEPTiptables -t nat -A POSTROUTING -o eth0 -j MASQUERADEecho 1 > /proc/sys/net/ipv4/ip_forwardAt this stage I believe I should be able to connect a client to my access point and browse the web.The client sees the access point, connects, gets an IP address from the server's DHCP (10.0.0.101) and then has the following routing table:mark@laptop15:~/TT$ route -nKernel IP routing tableDestination Gateway Genmask Flags Metric Ref Use Iface0.0.0.0 10.0.0.1 0.0.0.0 UG 0 0 0 wlan010.0.0.0 0.0.0.0 255.255.255.0 U 9 0 0 wlan0However it cannot even ping the server (10.0.0.1) - no errors, we just don't get the pings back:mark@laptop15:~/TT$ ping 10.0.0.1PING 10.0.0.1 (10.0.0.1) 56(84) bytes of data.And it stays like that forever.What am I doing wrong please?
Linux access point (airmon-ng/airmon-ng) not working
linux;nat;access point;airmon ng
Turns out it was network-manager interfering. Switched it offservice network-manager stopand everything works fine.I suspect there exists a less drastic solution than disabling it altogether, but it does what I need for now.
_cs.14050
In trying to gain a better understanding of finite state machines, I stumbled across this idea and have been confused as to how to approach this case in terms of a DFA.The set of binary strings of length at least 3 where every substring of length 3 contains at least two 0s.So in other words, something like 100100010 should be in the language (L) for this DFA but something like 11001010 would not be in the language.I know that you can start off by writing/drawing smaller DFAs for the substrings that are the pattern 000, 010, 100, 001, etc, but I cannot seem to get a hold of how it should look all together.Any help in understanding this would be appreciated.
DFA drawing for binary string with substrings of minimum length 3 with at least two zeroes in each substring
formal languages;automata;finite automata
The condition that all words have length $\geqslant 3$ makes the computation of the minimal DFA much more difficult. Thus let us first consider the language $$K = \{ u \in A^* \mid \text{every substring of length 3 of $u$ contains at least two $0$} \}$$where $A = \{0,1\}$. The forbidden patterns of the words of $K$ are $11$ and $101$, so that $K$ is the complement of the language $A^*(11 + 101)A^*$. But there is a nicer way to write $K$, using the comment of Luke Mathieson. Indeed, apart from the last two letters, every $1$ has to be followed by two $0$. This leads to the regular expression$K = (0 + 100)^*(\varepsilon + 1 + 10)$. I let you compute the minimal DFA of $K$ which has only three states (plus a sink state if you want a complete DFA).Now $L = A^3A^* \cap K$ and you can use standard algorithms to get its minimal DFA(9 states, 10 if you count the sink state).
_softwareengineering.347421
I am developing a small application and trying my best to make it as professional as possible in regards to design pattern etc. It is a JavaFX app, and my app works fine but I am uneasy at the fact that I am instantiating the back end in the front end. I tried my best to follow MVC pattern and I think I have so far, but I can't see any other way around this. Basically, my application has difficulty levels, and based on the difficulty level chosen by user (which is required to create the backend) a game with that difficulty level is created. And I can't think of any other way to start the backend without first knowing the difficulty level, thus it is instantiated in the front end. However, besides that the front end has no logic. It only draws and sends user input to the back-end, the back end of course then has the logic and tells the front end where to draw the changes.Is this considered ok? If not how should each side of the pipe be launched?
Which End should start first? (MVC)
java;programming practices;mvc;javafx
null
_codereview.115807
Here is what I've written for a program to print upper half triangle of a matrix. Now I need a way to do it without using goto: #include <iostream>using namespace std;int main(){ int a[10][10], r, c, i, j; cout << Enter the number of rows and columns; cin >> r >> c ; cout << Enter the matrix :; for(i=0;i<r;++i) { for(j=0;j<c;++j) { cin >> a[i][j]; } } cout << The matrix is : \n; for(i=0;i<r;++i) { for(j=0;j<c;++j) { if(j<i) goto loop; cout << a[i][j] << \t; loop: if(j<i) cout<< \t; if(j==(c-1)) cout<<\n; } } cin >> r;} Any help is appreciated.
Print the upper half triangle of a matrix
c++;matrix
The only goto I see is the following:if(j<i) goto loop;cout << a[i][j] << \t;loop: if(j<i) cout<< \t;if(j==(c-1)) cout<<\n; You can easily change that to a simple if-else:if(j<i) { cout<< \t;} else { cout << a[i][j] << \t;}if(j==(c-1)) { cout<<\n; }
_webmaster.51616
I want to place my website ad on another website B in the sidebar. It will be a direct link back to my website. I am doing this to get the PR juice from website B. website B is highly related to the same topic as my own websiteNow since there are many pages on website B, and the link is on each page in sidebar, it will instantly generate thousands of backlinks to my site.So ...Does google understand that this is non-natural backlink.Does google prevent the PR juice to flow in such cases ?Does it have any negative effect on seo ?
How does the google search engine deal with links placed in ads
seo
null
_cs.57860
I have a Travelling Salesman Problem, where I want to retrieve the shortest (approximate solution) circuit including the nodes n_1..n_n in a graph. The graph, however, includes a second set of nodes, say, o_1..o_n, which CAN but do not NEED to be included in the route (see picture).i.e., this means, in the graph, I do not know the shortest paths between the nodes n_1..n_n which I want to travel.Is there a more elegant way to retriev a relativley optimal solution than transforming the original graph into a graph only including the nodes n_1..n_n (e.g. by solving the shortest path problem for each pair of nodes [n_i|n_j]) and then using e.g. an evolutional algorithm to get a solution for the TSP?
Travelling Salesman Problem with unknown shortest paths between nodes
algorithms;optimization;traveling salesman
null
_unix.288768
I have got a 300mbit symmetrical fiberoptic line, and I have got to transfer a 51MBYTE tar file from HOST A (fiberoptic 300mbit) to HOST B (digitalocean machine with more than gigabit bandwith).On both side I have got nice speedtests results (300mbit on A, 700 on B) but when I scp from A to B I have got this:assets.tar 100% 51MB 220.3KB/s 03:55only 220kbit of maximium speed.But if I do from HOST B to A I have got a really nice result:assets.tar 100% 51MB 8.4MB/s 00:06 ***REALLY GOOD SPEED***What can be the issue?
Slow scp transfer speed over wan
networking;performance;scp
null
_codereview.161848
I have an array which handles all the games being hosting on the server. Users can host games and cancel the host as they please. What I have below seems to work, but I'm not sure if it adds the object to the lowest free index, but it adds them and removes just fine. The code is a bit of a mess so I've commented a lot to help you understand.var hostingGames = [];server.em.addListener('hostGame', function(settings){ if (hostingGames.length != 0) //If the array that contains all the games being hosted, contains at least 1 game { for (i in hostingGames)//Scroll through every game being hosted { if(hostingGames[i] != null)//If the current index in the array does contain a game being hosted { if(hostingGames[i].userId === settings.userId)//If the user thats trying to host a game, is already hosting a game { break; //Then break } else if (i == (hostingGames.length - 1))//If hes not hosting a game and all the games have finished being scrolled through { hostGame(settings, i + 1); //Then host one in the next avaliable space } } else //If the game is null { for(var i = 0; i < hostingGames.length; i++) //Scroll through the list of the games being hosted again { if(hostingGames[i] === null) //If theres a free slot { hostGame(settings, i); //Host a game } } } } } else { hostGame(settings, 0); //If there is no games currently being hosted, host one } function hostGame (settings, index) { var hostGame = new HostGame(); hostGame.initialise(settings.userId, settings.userName, settings.boardSize, settings.gameMode, settings.gameNote); hostingGames.splice(index, 0, hostGame); server.updateGamesList(hostingGames); server.consoleLog('APP', settings.userName + ' is hosting a game. ID: ' + settings.userId); }});server.em.addListener('cancelHostGame', function(userId, userName){ for (i in hostingGames)//For every game { if (hostingGames[i] != null) //If its not null { if (hostingGames[i].userId === userId) //If that user is hosting a game { hostingGames.splice(i, 1); //Remove their game server.updateGamesList(hostingGames); server.consoleLog('APP', userName + ' has stopped hosting a game. ID: ' + userId); } } }});
Array of hosted games
javascript;array
null
_unix.36544
I had installed bind-chroot from yum not long ago, and saw that there were errors in the daily logs from named. Under further investigation, I noticed a directory loop. The named files resided under /var/named, with the chroot being in /var/named/chroot. For whatever reason, /var/named/chroot/var/named just leads back to /var/named. ls -al doesn't show any link between the directories. OS: CentOS 6.2uname -a: Linux plutonium 2.6.32-220.7.1.el6.x86_64 #1 SMP Wed Mar 7 00:52:02 GMT 2012 x86_64 x86_64 x86_64 GNU/LinuxI'm not really the most linux savvy, so I don't really know what more information I can provide you all with. Please let me know if there is some other piece of information I can give you that would be helpful.
Unabled to get rid of BIND 9 chroot
linux;centos;chroot;bind
null
_unix.31130
What's exactly the command to show files younger than 2 days? I thought about something like this:$ find / -mtime -2...but I'm not sure how to print the date of the found files. My target is to find file on a mounted ntfs system which are new or changed within the last days.Moreover it would be very helpful to sort the results from the newst to the oldest. Is that possible?
Show files from the last 2 days on a mounted ntfs system?
bash;command line;find
Files created or modified less than 48 hours agosorted from the newest to the oldest:find / -mtime -2 -printf %T@ -ls | sortI have found %T@ from man find: last modification time (seconds since epoch)
_unix.297116
I am reading the source code to understand sysctl in FreeBSD.It looks like the most important functionint __sysctl(const int *name, u_int namelen, void *oldp, size_t *oldlenp, const void *newp, size_t newlen);is not defined in lib/libc/gen/sysctl.c.I tried to grep over FreeBSD's source code but I failed to find the defintion of __sysctl.Where is it defined?
Where is the __sysctl function defined in FreeBSD?
freebsd;sysctl;source code
Here's what I've learnt:__syscall is not defined in any C source file; According to Mark Plotnick:libc's __sysctl is a system call wrapper written in a few lines of assembly language, generated during the compilation of libc [1].The system calls' entry point is here in kern_sysctl.c [2]. The system calls are called sys_foo() in the kernel.LinksConfiguration file for generating syscalls.The kern_sysctl.c source.Thanks to edje, Ed Schouten (@EdSchouten), @FreeBSDHelp and Mark Plotnick.
_webmaster.86728
I maintain a Rails app. Every page except login and forgot password requires user authentication. Yesterday I noticed entries like this one in the access logs:54.209.60.63 - - [03/Nov/2015:19:09:53 +0000] GET /compendia HTTP/1.1 302 120 - Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.1.25 (KHTML, like Gecko) Version/8.0 Safari/600.1.2554.209.60.63 - - [03/Nov/2015:19:09:53 +0000] GET /login HTTP/1.1 200 927 - Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.1.25 (KHTML, like Gecko) Version/8.0 Safari/600.1.2554.209.60.63 - - [03/Nov/2015:19:10:37 +0000] GET /noumena/428 HTTP/1.1 302 120 - Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.1.25 (KHTML, like Gecko) Version/8.0 Safari/600.1.2554.209.60.63 - - [03/Nov/2015:19:10:37 +0000] GET /login HTTP/1.1 200 928 - Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.1.25 (KHTML, like Gecko) Version/8.0 Safari/600.1.2554.209.60.63 - - [03/Nov/2015:19:15:11 +0000] GET /data_ranges/1208/edit HTTP/1.1 302 120 - Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.1.25 (KHTML, like Gecko) Version/8.0 Safari/600.1.2554.209.60.63 - - [03/Nov/2015:19:15:11 +0000] GET /login HTTP/1.1 200 926 - Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.1.25 (KHTML, like Gecko) Version/8.0 Safari/600.1.2554.209.60.63 - - [03/Nov/2015:20:22:01 +0000] GET /fields/392 HTTP/1.1 302 120 - Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.1.25 (KHTML, like Gecko) Version/8.0 Safari/600.1.2554.209.60.63 - - [03/Nov/2015:20:22:01 +0000] GET /login HTTP/1.1 200 926 - Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.1.25 (KHTML, like Gecko) Version/8.0 Safari/600.1.2554.209.60.63 - - [03/Nov/2015:21:55:29 +0000] GET /users HTTP/1.1 500 1477 - Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.1.25 (KHTML, like Gecko) Version/8.0 Safari/600.1.25Each of the requests was properly redirected back to the login page. Still, those URLs would be valid for authenticated users. And anonymous users could not be able to know those URLs.Is there some legitimate use case here? Or is one of my users compromised, and somehow they are leaking URLs but not credentials?
Mysterious visits to privileged URLs from anonymous user/bot
web crawlers;logging
Are you displaying ads on your site from Amobee (formerly known as Kontera)?The PTR record for this IP is nat.aws.kontera.com, suggesting that it is a crawler looking for your page's content in order to determine what ads may be relevant to that URL.If you've loaded the Kontera JavaScript on login-protected pages, then you will find that they are crawled any time a logged-in user visits those pages. Try removing the JavaScript call from protected pages, and see if the crawling of those pages stops.It's also possible that code has been added to the web page by a man in the middle attack before it reached the user who actually visited your site. Such an attack might have been launched by a network operator or malicious party in order to gain revenue from your content, or for other reasons.This is one of many reasons that every web site should run on HTTPS.
_softwareengineering.290232
The company I work at is initializing all of their data structures through an initialize function like so: //the structuretypedef struct{ int a,b,c; } Foo;//the initialize functionInitializeFoo(Foo* const foo){ foo->a = x; //derived here based on other data foo->b = y; //derived here based on other data foo->c = z; //derived here based on other data}//initializing the structure Foo foo;InitializeFoo(&foo);I've gotten some push back trying to initialize my structs like this: //the structuretypedef struct{ int a,b,c; } Foo;//the initialize functionFoo ConstructFoo(int a, int b, int c){ Foo foo; foo.a = a; //part of parameter input (inputs derived outside of function) foo.b = b; //part of parameter input (inputs derived outside of function) foo.c = c; //part of parameter input (inputs derived outside of function) return foo;}//initialize (or construct) the structureFoo foo = ConstructFoo(x,y,z);Is there an advantage to one over the other?Which one should I do, and how would I justify it as a better practice?
Should I initialize C structs via parameter, or by return value?
c;coding style;constructors;initialization
In the 2nd approach you will never have a half-initialised Foo. Putting all the construction in one place seems a more sensible, and obvious place.But... the 1st way isn't so bad, and is often used in many areas (there's even a discussion of the best way to dependency-inject, either property-injection like your 1st way, or constructor injection like the 2nd). Neither is wrong.So if neither is wrong and the rest of the company uses approach #1, then you should be fitting in with the existing codebase and not trying to mess it up by introducing a new pattern. This is really the most important factor at play here, play nice with your new friends and don't try to be that special snowflake who does things differently.
_webmaster.20595
I have a site that runs since 4 months now with category and products. I put breadcrumbs on my page but I still don't see them in the SERP. I use the Google breadcrumbs help page to create them.<ul class=breadcrumbs> <li><a href=/ title=>My Page Name</a> <span>&gt; </span></li> <li><a href=/category-abc/ title=>Category ABC</a> <span>&gt; </span></li> <li>Current Page</li></ul>How long will it takes for my breadcrumbs to show up?
How long it takes to get the breadcrumbs to show up in Google SERP?
html;google search;rich snippets;breadcrumbs
There is no definitive timeframe. In fact, there's no guarantee Google will use breadcrumbs in their search results for your pages. As with anything related to Google displaying search results, you can give them clues and express your wishes as for what to display in the search results but ultimately Google will decide if and when it will happen. All you can do is make sure your markup and other signals (http headers, etc) are done correctly. (It also doesn't hurt to increase the link popularity of your pages but that is pretty much true for anything related to Google).
_cs.41412
When speaking of neural networks, I don't get the difference between nonlinear and non-deterministic. Basically, both say that the output of something is not directly correlated to the input?Hope someone can illuminate me.
Differences between linear/nonlinear vs. deterministic/nondeterministic neural nets
terminology;artificial intelligence;neural networks
null
_softwareengineering.165520
In a few weeks, my project is going to be finished and I want to start getting my code ready for other people to use it.I am going to be posting everything to GitHub so people can tweak it and hopefully make it better.I guess what I'm asking is, what would be the best way to make sure my code is sufficiently documented and worded right for other people to use?I know you should always comment everything and I'm going to be putting in the @params feature for every method, but are there any other tips in general?
How should I get my code ready for OpenSourcing it and putting it on GitHub?
coding style;coding standards;github
Make sure there is a README.txt file in the root of the repository that points people to instructions on how to build it. The instructions could be in that file, or they could be in a separate file or wiki page. Ideally, make it so that you can completely build and test the code with a single command. Don't require a bunch of manual steps. Make sure you have tests for the code. This provides a convenient place for other developers to see how your code is used, plus it provides a safety net for people who modify your code. Knowing I can edit your code and then run a suite to see if I broke something is invaluable. Follow common coding standards, or publish the ones you use. If your code uses OO, make sure at least all public methods and attributes have sufficient documentationMake sure it's clear what license your code uses. Typically this means to include a LICENSE.txt file, or follow whatever mechanism your specific license requires. Also, make a conscious choice about the license. Don't just use GPL because that's all you know. Likewise, don't just use BSD or MIT or Apache if that's all you're familiar with... spend an hour researching those so you at least understand the fundamental difference between GPL and non-GPL licenses.Remove all sensitive information from the code, such as hard-coded usernames, passwords, email addresses, ip addresses, API keys, etc. (thanks to Hakan Deryal for the suggestion)
_unix.355001
I'm seeing what I believe to be throttling somewhere in my connection.I can only get 13 MB/s per connection with scp.If I run two scp sessions, I get 13 MB/s per connection on both.I'm using SuddenLink. This form of throttling only seems to affect SSH. BroadbandSpeedTest and Steam seem unaffected by the per-connection throttling. Is there a technology that can either help me diagnose the kind of throttling they're employing, if any. help me work around it. Perhaps something like NFS/Multiple SSH sessions, or the like? Anything that can utilize multiple SSH session to transfer a single file.
Question on per-connection bandwidth throttling
ssh;networking;rsync;scp
null
_unix.231444
I have a bash script using dialog which basically just checks the status of certain services and displays it as either up or down. It works fine when I run it while logged in. I can't seem to figure out how to configure CentOS 7 to run this script and dialog when the system boots up. Ideally once CentOS finishes loading all services, instead of display the login prompt it'll just present this dialog to the user. My research seems to keep pointing at creating a service using systemd but I can't seem to find an example to fit my needs. Thanks in advance.
How to run bash script with dialog at startup Centos 7
linux;bash;centos
Honestly, systemd services shouldn't be running interactive events. However, you should investigate the initial-setup-text.service, which does something like what you're asking for.
_webapps.16391
Is there a document hosting service, allowing editing the documents using only Markdown or just raw text?Requirements:web 2.0 interface (quick saving with a shortcut, probably Ctrl-S; also auto-saving would be great), but lightweight (Google Docs is too slow and clunky for me here),permanent storage (not cookie-based or lost-on-leave), for free,multiple files per user, password protected (https would be a plus),optional: ability to view older revisions/versions of the text would be a plus.I've found two sites that looked very promising (for the rawtext option):http://www.simpletext.wshttp://writer.bighugelabs.combut both of them can't handle entering the character of my native language (Polish), because they intercept AltGr+s keyboard shortcut as a shortcut to [S]ave file command. So that disqualifies them as for now.
Lightweight (markdown or writeroom-like) free online text editor
markdown
null
_unix.218379
I want to create a USB stick that I can use to boot multiple iso files. I want to do this through uEFI.The usb stick would look something like this:/EFI /bootx64.efi /something.conf/isos /foo.iso /bar.iso ...Here, /isos holds a bunch of uEFI bootable iso files. From what I understand these isos have a /EFI/BOOT<some arch>.efi file that the uEFI booloader would normally execute.On the drive /EFI/bootx64.efi is some to be determined efi booloader and /EFI/something.conf is its configuration file.What I need is some uEFI executable that can somehow call /EFI/BOOT<some arch>.efi within one of the iso files. I don't know if this is theoretically possible.I know that something similar can be done with GRUB2, but it requires specifying the linux image, its options and the initrd file. This is different from one iso to the other and sometimes, it doesn't work at all. My hope is that by calling /EFI/BOOT<some arch>.efi, I don't have to specify these and I can have one recipe to boot any iso image.My question is: Is there a uEFI bootloader that can let me call an EFI executable that is located inside an iso file?
Boot iso file through uEFI by calling EFI executable inside the iso
boot loader;live usb;uefi
null
_reverseengineering.13547
I am starring at the following exe file, see main page here. It seems pretty clear (using -E entropy option) that the exe contains compressed section. For some reason binwalk is not capable of finding the start of those sections.Here is what I have:$ binwalk -v -B PmsDView.exe Scan Time: 2016-09-22 14:42:04Target File: /tmp/PmsDView.exeMD5 Checksum: 911d92675f559a40400f7ca2b69c8544Signatures: 344DECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 Microsoft executable, portable (PE)2015 0x7DF Copyright string: Copyright 1995-2005 Mark Adler However it seems like they are using gzip:$ hexdump -C PmsDView.exe000007a0 30 00 30 00 31 00 35 00 00 00 00 00 4c 64 72 47 |0.0.1.5.....LdrG|000007b0 65 74 50 72 6f 63 65 64 75 72 65 41 64 64 72 65 |etProcedureAddre|000007c0 73 73 00 00 6e 74 64 6c 6c 00 00 00 00 00 00 00 |ss..ntdll.......|000007d0 20 69 6e 66 6c 61 74 65 20 31 2e 32 2e 33 20 43 | inflate 1.2.3 C|000007e0 6f 70 79 72 69 67 68 74 20 31 39 39 35 2d 32 30 |opyright 1995-20|000007f0 30 35 20 4d 61 72 6b 20 41 64 6c 65 72 20 00 00 |05 Mark Adler ..|Am I missing something ? Or did they mask the gzip signature ?
binwalk cannot find gzip sections
binary analysis;decompress
Binwalk did not find the zlib blob because it is also encrypted. It uses the following code to decrypt the compressed data. The decryption uses a table stored in the stack, which is filled with generated values before the loop.Thus, you have to reverse the decryption code or save the decompressed data from the memory.
_unix.59462
I successfully installed MySQL Workbench in Centos 6.2. When I run MySQL Workbench and try to store a password by clicking Store in Keychain, I get the following error:Could not store password: The gnome-keyring-daemon application is not running.N.B: after clicking Store in Keychain, I do enter a the MySQL user/password.When I try to run the following command /usr/bin/gnome-keyring-daemon -d, I get the following message:gnome-keyring-daemon: couldn't lookup ssh component setting: Failed to contact configuration server; some possible causes are that you need to enable TCP/IP networking for ORBit, or you have stale NFS locks due to a system crash. See http://projects.gnome.org/gconf/ for information.(Details - 1: Server ping error: IDL:omg.org/CORBA/COMM_FAILURE:1.0)gnome-keyring-daemon: couldn't lookup pkcs11 component setting: Failed to contact configuration server; some possible causes are that you need to enable TCP/IP networking for ORBit, or you have stale NFS locks due to a system crash. See http://projects.gnome.org/gconf/ for information.(Details - 1: Server ping error: IDL:omg.org/CORBA/COMM_FAILURE:1.0) GNOME_KEYRING_SOCKET=/tmp/keyring-FazjOu/socket SSH_AUTH_SOCK=/tmp/keyring-FazjOu/socket.ssh GNOME_KEYRING_PID=20933
Running gnome-keyring-daemon in CentOS?
centos;gnome keyring
null
_unix.234701
After changing my desktop from Arch Linux to NixOS, playing HTML5 videos in Firefox has become buggy. They will fast forward when you play them, but only when using the USB audio adapter. Pulseaudio is used and ALSA is configured to use pulseaudio as well. A few solutions I found stated that I had to install pavucontrol and disable all other audio adapters and try to change the output from digital to analog, none of which made a difference. When I connect my speakers to the built-in adapter, the problem is resolved, the HTML5 videos in Firefox will play as they should. The only error message I got was that an assertion failed about it not being a GVC mixer. Which I could source back to the following code:g_return_val_if_fail (GVC_IS_MIXER_CARD (card), 0);However I do not know whether this is the real cause, or how to resolve it, but since it worked fine on Arch Linux, it should be fixable.
USB audio adapter causes HTML5 videos in Firefox to fast forward
audio;nixos;usb audio
null
_codereview.64027
DescriptionGenerate Property Classes for JavaFXJava 1.8 is used.This code can also be downloaded from PCloud:Zip File , GithubFile SummaryFXMLController.java: Controller for Scene.fxmlJavaDataType.java: Java Data Type EnumMainApp.java: Main Application Sub ClassPropertyClassBuilder.java: Code GeneratorPropertyInfo.java: Property Info property classpom.xml: Maven (Generated)Scene.fxml: Main FXML file (Generated from SceneBuilder)DependenciesjavafxCodeFXMLController.java: (111 lines, 3198 bytes)/** * Controller for Scene.fxml * * @author Bhathiya */public class FXMLController { //------ //Table of Properties @FXML private TableView<PropertyInfo> tvProperties; @FXML private TableColumn<PropertyInfo, String> tcName; @FXML private TableColumn<PropertyInfo, String> tcType; //------ @FXML private ComboBox<String> cmbPropertyType; @FXML private TextArea txtCode; @FXML private TextField txtProperty; @FXML private TextField txtClassName; //property info observable list : this is bind to table view private ObservableList<PropertyInfo> propertyInfoList; //property type observable list : this is bind to combobox of data types private ObservableList<String> propertyTypeList; @FXML void addOnAction(ActionEvent event) { String name = txtProperty.getText().trim(); if (name.isEmpty()) { return; } String type = cmbPropertyType.getValue(); propertyInfoList.add(new PropertyInfo(name, type)); //clear txtProperty.clear(); cmbPropertyType.getSelectionModel().selectFirst(); } @FXML void generateOnAction(ActionEvent event) { String className = txtClassName.getText().trim(); if (className.isEmpty()) { return; } PropertyClassBuilder generator = new PropertyClassBuilder(className); txtCode.setText(generator.generateCode(propertyInfoList)); } @FXML void btnClearOnAction(ActionEvent event) { propertyInfoList.clear(); txtClassName.clear(); txtCode.clear(); txtProperty.clear(); cmbPropertyType.getSelectionModel().selectFirst(); } @FXML void btnRemoveOnAction(ActionEvent event) { PropertyInfo propertyInfo = tvProperties.getSelectionModel(). getSelectedItem(); if (propertyInfo != null) { propertyInfoList.remove(propertyInfo); } } @FXML void initialize() { //Create Observable List for types propertyTypeList = cmbPropertyType.getItems(); propertyTypeList.clear(); propertyTypeList.addAll(String, Integer, Boolean, Double, Float, Long); cmbPropertyType.getSelectionModel().selectFirst(); //Create Observable List for propertyInfoList propertyInfoList = tvProperties.getItems(); propertyInfoList.clear(); //Bind Columns tcName.setCellValueFactory( new PropertyValueFactory<>(name)); tcType.setCellValueFactory( new PropertyValueFactory<>(type)); }}JavaDataType.java: (58 lines, 1207 bytes)/** * Java Data Types : contains basic wrapper class names * @author Bhathiya */public enum JavaDataType { STRING(String), INTEGER(Integer), BOOLEAN(Boolean), DOUBLE(Double), FLOAT(Float), LONG(Long); /** * String value */ private final String value; private JavaDataType(String value) { this.value = value; } /** * * @return string value */ @Override public String toString() { return value; } /** * convert String to JavaDataType * @param type String type * @return JavaDataType or null if not found */ public static JavaDataType fromString(String type) { switch (type) { case String: return STRING; case Integer: return INTEGER; case Boolean: return BOOLEAN; case Double: return DOUBLE; case Float: return FLOAT; case Long: return LONG; } return null; }}MainApp.java: (32 lines, 766 bytes)/** * Main Application * @author Bhathiya */public class MainApp extends Application { /** * Start Application * @param stage main stage * @throws Exception */ @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource(/fxml/Scene.fxml)); Scene scene = new Scene(root); stage.setTitle(Java FX Property Class Builder); stage.setResizable(false); stage.setScene(scene); stage.show(); }}PropertyClassBuilder.java: (115 lines, 3922 bytes)/** * * @author Bhathiya */public class PropertyClassBuilder { /** * class name for code generator to use */ private final String className; /** * constructor for code generator * * @param className class name */ public PropertyClassBuilder(String className) { this.className = className; } /** * constructor for code generator, Class name used is : PropertyClassName */ public PropertyClassBuilder() { this(PropertyClassName); } /** * generate code * * @param propertyInfoList * @return */ public String generateCode(List<PropertyInfo> propertyInfoList) { String code = import javafx.beans.property.*;\n + \n + /**\n + * Class Information\n + * @author Your Name\n + */\n + public class %s {\n + \n + %s\n + \n + public %s() {\n + %s\n + }\n + \n + %s\n + \n + }; StringBuilder fields = new StringBuilder(); StringBuilder initCodes = new StringBuilder(); StringBuilder methods = new StringBuilder(); propertyInfoList.forEach((PropertyInfo propertyInfo) -> { JavaDataType type = JavaDataType.fromString(propertyInfo.getType()); String name = propertyInfo.getName(); fields.append(toPrivateField(type, name)); initCodes.append(toInitCode(type, name)); methods.append(toGetterMethod(type, name)); methods.append(\n\n); methods.append(toSetterMethod(type, name)); methods.append(\n\n); methods.append(toPropertyMethod(type, name)); methods.append(\n\n); }); return String.format(code, className, fields.toString(), className, initCodes.toString(), methods.toString()); } //create private field code private static String toPrivateField(JavaDataType type, String name) { return String.format( private final %s %s;\n, toPropertyType(type), name); } //create code for creating new property object private static String toInitCode(JavaDataType type, String name) { return String.format( %s = new %s();\n, name, toPropertyType(type)); } //to upper camel case private static String toUpperCamelCase(String name) { return name.substring(0, 1).toUpperCase() + name.substring(1); } //create getter method private static String toGetterMethod(JavaDataType type, String name) { String code = public %s %s%s() {\n + return %s.get();\n + }; String getPrepend = get; if (type == JavaDataType.BOOLEAN) { getPrepend = is; } return String.format(code, type, getPrepend, toUpperCamelCase(name), name); } //create setter method private static String toSetterMethod(JavaDataType type, String name) { String code = public void set%1$s(%2$s %3$s) {\n + this.%3$s.set(%3$s);\n + }; return String.format(code, toUpperCamelCase(name), type, name); } //create property method private static String toPropertyMethod(JavaDataType type, String name) { String code = public %1$s %2$sProperty() {\n + return %2$s;\n + }; return String.format(code, toPropertyType(type), name); } //get property type based on Wrapper Class name private static String toPropertyType(JavaDataType type) { return String.format(Simple%sProperty, type); }}PropertyInfo.java: (64 lines, 1323 bytes)/** * Property info property class * @author Bhathiya */public class PropertyInfo { /** * field name for a property */ private final SimpleStringProperty name; /** * data type for a property */ private final SimpleStringProperty type; /** * PropertyInfo default constructor * initialize final fields */ public PropertyInfo() { name = new SimpleStringProperty(); type = new SimpleStringProperty(); } /** * PropertyInfo constructor * @param name field name for a property * @param type data type for a property */ public PropertyInfo(String name, String type) { this(); this.name.set(name); this.type.set(type); } public SimpleStringProperty nameProperty() { return name; } public SimpleStringProperty typeProperty() { return type; } public String getName() { return name.get(); } public void setName(String name) { this.name.set(name); } public String getType() { return type.get(); } public void setType(String type) { this.type.set(type); }}pom.xml: (110 lines, 5039 bytes)<?xml version=1.0 encoding=UTF-8?><project xmlns=http://maven.apache.org/POM/4.0.0 xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation=http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd> <modelVersion>4.0.0</modelVersion> <groupId>info.simpll</groupId> <artifactId>FXPropertyClassBuilder</artifactId> <version>0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>FXPropertyClassBuilder</name> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <mainClass>info.simpll.fxprop.MainApp</mainClass> </properties> <organization> <!-- Used as the 'Vendor' for JNLP generation --> <name>Your Organisation</name> </organization> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.6</version> <executions> <execution> <id>unpack-dependencies</id> <phase>package</phase> <goals> <goal>unpack-dependencies</goal> </goals> <configuration> <excludeScope>system</excludeScope> <excludeGroupIds>junit,org.mockito,org.hamcrest</excludeGroupIds> <outputDirectory>${project.build.directory}/classes</outputDirectory> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <executions> <execution> <id>unpack-dependencies</id> <phase>package</phase> <goals> <goal>exec</goal> </goals> <configuration> <executable>${java.home}/../bin/javafxpackager</executable> <arguments> <argument>-createjar</argument> <argument>-nocss2bin</argument> <argument>-appclass</argument> <argument>${mainClass}</argument> <argument>-srcdir</argument> <argument>${project.build.directory}/classes</argument> <argument>-outdir</argument> <argument>${project.build.directory}</argument> <argument>-outfile</argument> <argument>${project.build.finalName}.jar</argument> </arguments> </configuration> </execution> <execution> <id>default-cli</id> <goals> <goal>exec</goal> </goals> <configuration> <executable>${java.home}/bin/java</executable> <commandlineArgs>${runfx.args}</commandlineArgs> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> <compilerArgument>-Xlint:unchecked</compilerArgument> <compilerArguments> <bootclasspath>${sun.boot.class.path}${path.separator}${java.home}/lib/jfxrt.jar</bootclasspath> </compilerArguments> <showDeprecation>true</showDeprecation> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.16</version> <configuration> <additionalClasspathElements> <additionalClasspathElement>${java.home}/lib/jfxrt.jar</additionalClasspathElement> </additionalClasspathElements> </configuration> </plugin> </plugins> </build></project>Scene.fxml: (49 lines, 3051 bytes) <?import java.lang.*?><?import java.util.*?><?import javafx.scene.*?><?import javafx.scene.control.*?><?import javafx.scene.layout.*?><AnchorPane id=AnchorPane prefHeight=530.0 prefWidth=677.0 xmlns=http://javafx.com/javafx/8 xmlns:fx=http://javafx.com/fxml/1 fx:controller=info.simpll.fxprop.FXMLController> <children> <TitledPane animated=false collapsible=false layoutX=25.0 layoutY=26.0 prefHeight=171.0 prefWidth=297.0 text=Property> <content> <AnchorPane minHeight=0.0 minWidth=0.0 prefHeight=155.0 prefWidth=295.0> <children> <Label layoutX=14.0 layoutY=14.0 text=Property Name /> <TextField fx:id=txtProperty layoutX=110.0 layoutY=10.0 promptText=Property Name /> <Label layoutX=14.0 layoutY=57.0 text=Property Type /> <ComboBox fx:id=cmbPropertyType layoutX=110.0 layoutY=53.0 prefWidth=150.0 promptText=Property Type /> <Button layoutX=110.0 layoutY=101.0 mnemonicParsing=false onAction=#addOnAction text=Add /> </children> </AnchorPane> </content> </TitledPane> <TitledPane animated=false collapsible=false layoutX=334.0 layoutY=27.0 prefHeight=171.0 prefWidth=332.0 text=Field Information> <content> <AnchorPane> <children> <AnchorPane prefHeight=179.0 prefWidth=306.0 AnchorPane.bottomAnchor=0.0 AnchorPane.leftAnchor=0.0 AnchorPane.rightAnchor=0.0 AnchorPane.topAnchor=0.0> <children> <TableView fx:id=tvProperties prefHeight=126.0 prefWidth=252.0 AnchorPane.bottomAnchor=0.0 AnchorPane.leftAnchor=0.0 AnchorPane.rightAnchor=55.0 AnchorPane.topAnchor=0.0> <columns> <TableColumn fx:id=tcName prefWidth=116.0 text=Name /> <TableColumn fx:id=tcType prefWidth=114.0 text=Type /> </columns> </TableView> <Button layoutX=272.0 layoutY=2.0 mnemonicParsing=false onAction=#btnRemoveOnAction text=- /> </children> </AnchorPane> </children> </AnchorPane> </content> </TitledPane> <TextArea fx:id=txtCode layoutX=25.0 layoutY=236.0 prefHeight=280.0 prefWidth=641.0 /> <Button layoutX=226.0 layoutY=205.0 mnemonicParsing=false onAction=#generateOnAction text=Generate Code /> <Button layoutX=620.0 layoutY=205.0 mnemonicParsing=false onAction=#btnClearOnAction text=Clear /> <Label layoutX=25.0 layoutY=209.0 text=Class Name /> <TextField fx:id=txtClassName layoutX=94.0 layoutY=205.0 prefHeight=25.0 prefWidth=124.0 promptText=Class Name /> </children></AnchorPane>QuestionsDoes this follow Java/Java8/JavaFX Conventions ?
Generate Property Classes for JavaFX
java;javafx
Duplicated string literals in FXMLController.initializeYou're duplicating the names used by the enums:propertyTypeList.addAll(String, Integer, Boolean, Double, Float, Long);This is not good. As usual, if you make a change in one place, you have to remember to make the same change at the other too. It's fragile.It would be better to iterate over the values of the enum, for example:for (JavaDataType javaDataType : JavaDataType.values()) { propertyTypeList.add(javaDataType.toString());}Or if you fancy Java 8:propertyTypeList.addAll(Arrays.asList(JavaDataType.values()).stream() .map(JavaDataType::toString) .collect(Collectors.toList()));Duplicated string literals in JavaDataType.fromStringSimilar to the earlier point,it's a pity to duplicate the string values of the enums in the case statements.Better build a static map from them and use it, without duplicating anything.private static final Map<String, JavaDataType> STRING_TO_ENUM = new HashMap<>();static { for (JavaDataType javaDataType : values()) { STRING_TO_ENUM.put(javaDataType.toString(), javaDataType); }}public static JavaDataType fromString(String type) { return STRING_TO_ENUM.get(type);}Hardcoded Java class namesStill about JavaDataType...Instead of hardcoding the class names of String, Double, ...,how about using the real class types instead?STRING(String.class),INTEGER(Integer.class),BOOLEAN(Boolean.class),DOUBLE(Double.class),FLOAT(Float.class),LONG(Long.class);private final String value;JavaDataType(Class<?> klass) { this.value = klass.getSimpleName();}Minor thingsThis javadoc comment is really pointless, especially on a private field:/** * String value */private final String value;This is really hard to read:String code = import javafx.beans.property.*;\n + \n + /**\n + * Class Information\n + * @author Your Name\n + */\n + public class %s {\n + \n + %s\n + \n + public %s() {\n + %s\n + }\n + \n + %s\n + \n + };For one thing, why write a string segmented like this:import javafx.beans.property.*;\n + \n + /**\nwhy not as:import javafx.beans.property.*;\n\n/**\nAnd the whole expression would become a lot easier to read if you break a line after each actual \n in the string, like this:String code = import javafx.beans.property.*;\n\n + /**\n + * Class Information\n + * @author Your Name\n + */\n + public class %s {\n\n + %s\n\n + public %s() {\n + %s\n + }\n\n + %s\n\n + };You don't need to call .toString() on parameters when formatting a string:return String.format(code, className, fields.toString(), className, initCodes.toString(), methods.toString());That is:return String.format(code, className, fields, className, initCodes, methods);You could chain these together, which will make it slightly shorter:methods.append(toGetterMethod(type, name));methods.append(\n\n);methods.append(toSetterMethod(type, name));methods.append(\n\n);methods.append(toPropertyMethod(type, name));methods.append(\n\n);like this:methods.append(toGetterMethod(type, name)).append(\n\n).append(toSetterMethod(type, name)).append(\n\n).append(toPropertyMethod(type, name)).append(\n\n);
_softwareengineering.13061
I was just thinking of something that would be really cool to have in my if-elif-else controls.if condition: stuff()elif condition: otherstuff()then: stuff_that_applies_to_both()else: stuff_that_doesnt_aply_to_either()So basically a then will be run when any of the conditions are run EXCEPT the else condition. Do you think this is useful? It's similar to the try-except-else of python.I think some of you are nitpicking a very preliminary implementation. The then block would be just like the else block in a try-except block in python. The real reason I suggest this is for situations like this.m = {}if condition == '1': m['condition'] = conditionelif condition2 == '3': m['condition2'] = condition2elif condition3 == 'False': m['condition3'] = Truethen: run_test_that_relies_on_one_of_the_conditions_being_true()return mThe then block is scoped to the first if just like the else is. So nesting works fine. And if you need to run a method before the if statements, that really has nothing to do with this use case.
What do you think of this new if-then syntax
syntax
null
_unix.188898
On hpux i use mptconfig to show speed and other info about scsi controller.There is something similar on aix?
AIX: mptconfig equivalent
aix;scsi
Is possible to see the max speed with smitty devices and then select scsi
_softwareengineering.261585
I often run into this problem, especially in Java, even if I think it's a general OOP issue. That is: raising an exception reveals a design problem.Suppose that I have a class that has a String name field and a String surname field.Then it uses those fields to compose the complete name of a person in order to display it on some sort of document, say an invoice.public void String name;public void String surname;public String getCompleteName() {return name + + surname;}public void displayCompleteNameOnInvoice() { String completeName = getCompleteName(); //do something with it....}Now I want to strengthen the behavior of my class by throwing an error if the displayCompleteNameOnInvoice is called before the name has been assigned. It seems a good idea, doesn't it?I can add a exception-raising code to getCompleteName method. But in this way I'm violating an 'implicit' contract with the class user; in general getters aren't supposed to throw exceptions if their values aren't set. Ok, this is not a standard getter since it does not return a single field, but from the user point of view the distinction may be too subtle to think about it.Or I can throw the exception from inside the displayCompleteNameOnInvoice. But to do so I should test directly name or surname fields and doing so I would violate the abstraction represented by getCompleteName. It's this method responsibility to check and create the complete name. It could even decide, basing the decision on other data, that in some cases it is sufficient the surname.So the only possibility seems to change the semantic of the method getCompleteName to composeCompleteName, that suggests a more 'active' behavior and, with it, the ability of throwing an exception.Is this the better design solution? I'm always looking for the best balance between simplicity and correctness. Is there a design reference for this issue?
Should a getter throw an exception if its object has invalid state?
java;class design
null
_unix.89107
I need to find my OS (not hardware) is 32-bit / 64-bit. Which command is best?uname -puname -iuname -marchAll the above commands returns the same answer:On 32 bit systems: i686/i386 On 64 bit systems: x86_64
Which cmd is the best for determining the OS' word size (32/64)-bit?
linux;command line;shell script
I would recommend instead using getconf LONG_BIT.[root@mymachine ~]# getconf LONG_BIT64This will clearly output either 32 or 64, depending on your installed kernel, whereas uname -m (and etc.) indicate the underlying hardware name.See also the Stack Overflow question How to determine whether a given Linux is 32 bit or 64 bit?, but be sure to read the helpful commentary.
_unix.234390
This only happens when using Gnome.I have an Acer Aspire V3-772GTX54206G1TMakk laptop with an NVIDIA GeForce GTX 760M graphics card running Debian 8 (jessie) 64-bit, and I'm using Gnome 3.14.1.The problem is every time I plug in a second monitor the brightness of my (built-in) primary monitor falls at 0, turning the backlight off and making the monitor unusable.Luckily when this happens whilst a session is already open, the brightness can easily be turned back up, making the issue a minor inconvenience. But the real problem is it happens with GDM as well, and when I try to increase the brightness with the built-in keyboard shortcut (Fn + right arrow) the brigntess icon shows up (on both screens even if can only see the second one) but the bar doesn't move. It remains stuck at 0 no matter what I do.Thus I have found another temporary workaround : Switching to another tty then switching back to the main tty. This somehow resets the brightness to 100%.I said this bug is gnome specific because both SLiM (as an alternative to GDM) and XFCE (as an alternative to Gnome) work perfectly well with dual monitors. I have tried them on the same computer with the same setup.
Brightness falls at 0 when plugging second monitor
gnome;dual monitor;gdm;brightness;backlight
null
_cs.56972
I've read that the human eye can only really decipher around 10 million different colours, so what's the point in technology that uses 48-bit colour, which allows for $2.81\times 10^{14}$ colours. Is this not like giant, super inefficient overkill?
What's the point of 48 bit colour?
graphics;hci
Some reasons for using more bits per color channel:Tetrachromats. There are rare humans with four types of cone receptors in their retinas instead of the usual three. These people can distinguish an order of magnitude more color shades than the rest of us.Color gamut. Your question assumes that the 16 million colors available in 8-bit per channel RGB exactly covers the colors that normal humans can see. But if that were so then we would only need one RGB color space. We have more.. More bits per channel allows a wider gamut of colors to be represented without posterization, because the increased bit depth means smaller gaps between the individual shades.Image manipulation. Every image manipulation, from switching color models for printing, to sharpening, to resizing, to tone curve adjustment, loses information. The more information you start with the more you have at the end of post-processing. The more information you start with the easier it is to avoid the introduction of visible artifacts like posterization.
_unix.154050
I have a large file with the logs as shown below. There are about 30000 instance of such events logged. I need to extract those lines beginning with RINGING and CLOSE (included) and which does NOT contain 30 30.The requirement is :Of the two instances seen below, I need only Instance 2 retained. Instance 1 needs to be deleted entirely (they form the large chunk of the file)Instance 1:313782 Aug 19 18:37:04.925: <DATA> RINGING|254|01136097645|5950|$hostIp|$size |$data313783 Aug 19 18:37:05.262: <DATA> TRAINING|254|01136097645|5950|$hostIp|$size |$data313784 Aug 19 18:37:09.028: <DATA> OUT |254|01136097645|5950|$hostIp|2 bytes |30 93313785 Aug 19 18:37:09.705: <DATA> IN |254|01136097645|5950|$hostIp|4 bytes |30 73 F9 F8313786 Aug 19 18:37:18.532: <DATA> IN |254|01136097645|5950|$hostIp|336 bytes |30 10 60 00 06 00 00 6F 12 00 ...313787 Aug 19 18:37:19.485: <DATA> OUT |254|01136097645|5950|$hostIp|133 bytes |30 30 60 00 00 00 06 6F 12 10 ...313788 Aug 19 18:37:20.898: <DATA> TRAINING|254|01136097645|5950|$hostIp|$size |$data313789 Aug 19 18:37:22.006: <DATA> CLOSE|254|01136097645|5950|$hostIp|$size |$dataInstance 2:(Line with 30 30 is not present)313782 Aug 19 18:37:04.925: <DATA> RINGING|254|01136097645|5950|$hostIp|$size |$data313783 Aug 19 18:37:05.262: <DATA> TRAINING|254|01136097645|5950|$hostIp|$size |$data313784 Aug 19 18:37:09.028: <DATA> OUT |254|01136097645|5950|$hostIp|2 bytes |30 93313785 Aug 19 18:37:09.705: <DATA> IN |254|01136097645|5950|$hostIp|4 bytes |30 73 F9 F8313786 Aug 19 18:37:18.532: <DATA> IN |254|01136097645|5950|$hostIp|336 bytes |30 10 60 00 06 00 00 6F 12 00 ...313788 Aug 19 18:37:20.898: <DATA> TRAINING|254|01136097645|5950|$hostIp|$size |$data313789 Aug 19 18:37:22.006: <DATA> CLOSE|254|01136097645|5950|$hostIp|$size |$data
Extract specific set lines matching a rule
text processing;regular expression
Assuming that your logfile is called logfile, here is an awk solution with the sample output:$ awk '/RINGING/,/CLOSE/ {if (/30 30/){f=1}; a=a\n$0} f==0 && /CLOSE/ {print a} /CLOSE/{a=;f=0}' logfile 313782 Aug 19 18:37:04.925: <DATA> RINGING|254|01136097645|5950|$hostIp|$size |$data313783 Aug 19 18:37:05.262: <DATA> TRAINING|254|01136097645|5950|$hostIp|$size |$data313784 Aug 19 18:37:09.028: <DATA> OUT |254|01136097645|5950|$hostIp|2 bytes |30 93313785 Aug 19 18:37:09.705: <DATA> IN |254|01136097645|5950|$hostIp|4 bytes |30 73 F9 F8313786 Aug 19 18:37:18.532: <DATA> IN |254|01136097645|5950|$hostIp|336 bytes |30 10 60 00 06 00 00 6F 12 00313788 Aug 19 18:37:20.898: <DATA> TRAINING|254|01136097645|5950|$hostIp|$size |$data313789 Aug 19 18:37:22.006: <DATA> CLOSE|254|01136097645|5950|$hostIp|$size |$dataExplanationTaking each awk command in turn:/RINGING/,/CLOSE/ {if (/30 30/){f=1}; a=a\n$0}The expression /RINGING/,/CLOSE/ is a range: it specifies that this command only applies to groups of lines. A group starts when a line is encountered that includes the text RINGING. The group ends when a line including the text CLOSE is encountered. For any line in such a group, the commands in braces are executed. The first of these sets the flag f to one if the line contains 30 30. The second command appends the current line to the variable a.f==0 && /CLOSE/ {print a}The commands in braces here are preceded by two conditions and'd together. The first condition specifies that the flag f is zero (meaning that 30 30 was not found in this group) and the second specifies that this line contain the text CLOSE. If both those conditions are met, then the group of lines, stored in the a variable, are printed./CLOSE/{a=;f=0}Lastly, on any line containing the text CLOSE, the variable a is reset to the empty string and the flag f is set to zero. When this is done, the code is prepared to start on the next group of lines, should there be one.
_unix.125286
I have set up a Django project to run with uwsgi and nginx and it's all running as expected, except that when I reboot uwsgi will not launch correctly until the /run/ folder is recreated on the fs. /run is mapped to 'tmpfs' so it needs to be recreated at each boot.I have a systemd service file that I created for uwsgi:[Unit]Description=uWSGI ModuleAfter=syslog.target[Service]ExecStart=/usr/bin/uwsgi --ini /etc/uwsgi.iniRestart=alwaysKillSignal=SIGQUITType=notifyStandardError=syslogNotifyAccess=main[Install]WantedBy=multi-user.targetAnd the /etc/uwsgi.ini file looks like this:[uwsgi]uid = uwsgigid = uwsgipidfile = /run/uwsgi/uwsgi.pidstats = /run/uwsgi/stats.socksocket = /run/uwsgi/uwsgi.sockmaster = trueprocesses = 1chdir = /path/to/our/django/appmodule = icscadamax-requests = 100daemonize = /var/log/uwsgi.logWhat is the recommended way for the /run/uwsgi folder to be recreated at each boot?
What's the best way to have uwsgi create a '/run/uwsgi' folder on reboot?
systemd;uwsgi
The way I eventually solved this problem was to use the latest distributions. Fedora 20 and yum install uwsgi built an environment where all of these details were handled automatically for me, while I was previously trying to fudge this onto a Fedora17 system where it wasn't available in the yum repositories.The way Fedora 20 solves this is by having this in its uwsgi service unit: ExecStartPre=/bin/mkdir -p /run/uwsgi ExecStartPre=/bin/chown uwsgi:uwsgi /run/uwsgi
_softwareengineering.349514
I was working in a story and in last minute, I have been asked to hide something from UI and we will used it next release. Should i remove it or comment it Should i remove or comment anything related to this part from code or leave it if it won't effect in anything.
Should I comment or remove any un-used code from my Solution?
programming practices;code quality;code reviews;clean code
If you value clean work practices, I would suggest that instead of commenting out code (which is an OK enough practice in the very short term, i.e. when we're talking a few weeks or less), prefer to use a source control system (Git, Mercurial, Subversion, etc.) instead:Move the feature's code, and all that's specifically related to it and not used by other code, to a separate feature branch (i.e. a fork off your current development branch). Make sure the code is completely removed in the main development branch. That way, all you will have to do to reactivate the feature is to merge the feature branch back into the main development branch. What you will not have to do is undoing the commenting-out on a line-by-line basis (running the chance that you forget to uncomment something, somewhere).It might be a little bit more work, but a much cleaner work practice than commenting out code. Commented-out code has the habit of accumulating over time, and it's often never uncommented again (against previous expectations). For that reason, unless a piece of commented-out code has explicit documentation stating why it's commented out, and when it should be uncommented again, I tend to purge commented-out code from a code base whenever I stumble upon it.For the same reason, I would suggest that you don't only disable/remove the triggering code of a feature, but all other code that is also related to only it (even if it would never have any effect if you removed the core feature code). Because, if you eventually don't put the feature in the next release, you might forget about the dependent code. So treat it the same was as the core / triggering feature code.
_scicomp.17569
Let given$M =$ 1 0 1 0 1 1 1 1 1and$b =$ 1 0 1How to find the solution $x_3$ where $x=${$x_1,x_2,x_3$}? Solution: Based on Wiedemann algorithm we has $u_i=[0; 0; 1]$. I am getting confused in the Step2. How to find $M_s$? Is it just the $3^th$ columns of $M_t$ as $M_s=[1 1 1]$ or it is created from Krylov sequence? Please help me find M_s and minimal polynomial? Matlab code:%% Input Generation Matrix M, b and index ith%% Output single symbol xM=[1 0 1;0 1 1;1 1 1];b=[1; 0; 1];index=2;[K N]=size(M);Mt=M';Imatrix=eye(K,K);x=[];for index=1:Ku_i=Imatrix(:,index);se_Krylov=[];se_Krylov(:,1)=u_i; for i=2:(2*K) % due to i=1 is u_i se_Krylov(:,i)=mod((Mt^i)*u_i,2); end%% M_s is the operator Mt retricted to S M_s=se_Krylov(index,:);%% Compute the polynominal using Berlekmap Massey[f, LCP] = Berlekamp_Massey2(M_s);d=size(f,2)-1; %deg of f: x^d+x^(d-1)+....x_comma=zeros(K,1); for i=d:-1:1 x_comma=mod(x_comma+f(d).*(Mt)^(i-1)*u_i,2); endx_single=mod(x_comma'*b,2) ;%Inner product x(index)=x_single;end
Find the solution of linear equation using Wiedemann/ Krylov method
matlab;linear algebra
null
_softwareengineering.138601
I am curious as to what technology is needed to create a service such as stageit.com and livestream.com. What hardware and software is involved, besides a camera and microphone, from the broadcaster's computer to a viewer's computer?
What technology is needed to create a live video streaming service?
web services
null
_softwareengineering.52064
Let's say you're in a computer store looking at 10 laptops, you want to really compare the system's capabilities. What will be an efficient your fav language goes here script that will allow you to do this?As an example, when I go to the store I usually open a macbook and a pro's terminal and write an equation in python, iterate it a million or so times, and time them. I like to compare the difference in time. What would be an ideal and simple script that can efficiently compare systems?
What will be a good python script (or your favorite language goes here) to test a system's performance and capabilities?
performance;benchmarking
null
_cs.79255
$$L_1= \{\langle M \rangle \mid \text{\(M\) takes at least 2016 steps on all inputs} \}$$Is this language decidable?I will write my way of understanding it. Please answer it in the way I understand & tell if my understanding is wrong.It means L1 is a language, which includes all such Turing machines, which takes at least 2016 steps on all inputs. So we need to say it is decidable or not...We are talking about which machine? We are talking about that machine whose language is L1. Other TMs are input to the new turing machine as encoding of 0 &1. We need to say for all inputs (for all Turing machine encodings) the new turing machine halts or not. When it will halt? When the new turing machine can either say...Yes, the turing machine I am considering took at least 2016 steps but still it is on progress...it also can say No, the turing machine you gave me went to final state before 2016 steps If it will say either of this, then the new turing machine, language L1 is decidable.When it will be undecidable? When the new turing machine is still on progress unable to say yes or no. So solution is run new Turing machine for 2016 steps only. If it is saying yes, the other turing machine halted...or the other turing machine did not halt.... then for both answer our new turing machine will halt... It is simple to understand that the new turing machine will always halt... bcz it's task is just to check the other turing machine halted or not within 2016 steps.
Is it decidable if a TM takes at least 2016 steps on all inputs?
computability;turing machines;undecidability
null
_cstheory.16965
Recursion utilizes some self similar nature of an object (some representation of the given problem) to produce some quantitative measure (output) on the object through some algorithm (utilizing the self similar nature). Can one represent algorithms as fractals (such a representation is not possible is not obvious nor how the representation should be if one exists) of some measurable information of the object the algorithm works on? Has the tools used in the study of fractals provided any illuminating examples for lower or upper bounds for recursive complexity of algorithms?I am looking for examples and references along the lines of whether algorithms can be treated as fractals and tools about fractals can be used to prove results about algorithms.just added Would we be compelled to redefine some essential property of Sierpinski triangle if Walsh Transform or Sierpinski triangle transform is shown to be fully linear?http://en.wikipedia.org/wiki/Walsh_matrix
Algorithms as fractals
cc.complexity theory;fractals
Blum, Shub, and Smale proved that membership in the Mandelbrot set is undecidable in the Real RAM model of computation (known in some upstart circles as the BSS model). The high-level argument is one sentence long: Any Real RAM computable set is the countable union of semi-algebraic sets, so its boundary has Hausdorff dimension 1, but the boundary of the Mandelbrot set has Hausdorff dimension 2. By the same argument, almost every interesting fractal is uncomputable in the real-RAM model.
_softwareengineering.220616
I'm hunting a metric to measure the cost of cut-and-paste programming. We already use tools to detect duplicated code - but if we don't clean up our duplicated code, how much will it cost us? We know that the DRY principle, Don't Repeat Yourself, is a core principle of Extreme Programming. How can we actually measure the impact of non-DRY code on our projects? I'm referring to the simplest duped code problem of the same expressions in two or more places. Other cases of duplication such as the same logic written differently in different places is trickier to detect.I'm hunting a metric, a solid number that I can offer management. I am aware of the WTF metric of Robert Martin, but that is not precise enough.What is the purpose of insisting on a metric? Management is insisting on this metric and they won't be dissuaded. I'm really afraid that they may mandate that duplicated code be reduced on each sprint. Because we are so pressed to deliver, developers will find the duplicated code and hack it so it does not get detected. This would be a ticking time bomb!
A metric to measure the cost of cut and paste programming
coding style;dry
null
_unix.124067
I have a bluetoothmodule here on my UART and would like to use it via hciattach.It is a KC21v6.3 Module from kc-Wirefree. As far I found out, it has a CSR-Chip on it. So is tried the following:# hciattach -n -s 115200 /dev/ttyS0 csrThat gives me a Initialization timed out.If I try the same with the type any it works so far that I get a Device setup complete. # hciconfiggives me a:hci0: Type: BR/EDR Bus: UART BD Address: 00:00:00:00:00:00 ACL MTU: 0:0 SCO MTU: 0:0 DOWN RX bytes:22 acl:0 sco:0 events:0 errors:0 TX bytes:150 acl:0 sco:0 commands:30 errors:0But after that, when i try to# hciconfig hci0 upI always get anCan't init device hci0: Connection timed out (110)I have no idea what to try any-more. Don't I have to specify the csr chip? Or does it have anything to do with the firmware of my KC21 (it understands AT Commands and also has an AT HciMode Command) ... I already tried this one before using the hciattach command, but nothing changed.Any help would be appreciated.kindly regardsTom
Using UART bluetooth module via hciattach
bluetooth
Okay, today we found out the solution:The problem was, to set the device in raw mode, because of the AT HciMode command.# hciattach -r /dev/ttyS0 bcsp 115200Maybe it helps somebody.
_unix.80683
I have a reverse ssh tunnel through a middleman server set up and working. I'm running Kubuntu 12.04 here and on the remote machine. I want to open a remote desktop session. Until now I've been using Team Viewer to log in to the remote desktop. I'd like to achieve similar results without Team Viewer. I understand X over SSH will achieve this. If I need vnc, that's fine too.Here's my issue at the moment. When I am connected to the remote machine via the tunnel I get this error:$ startkde &$ $DISPLAY is not set or cannot connect to the X server.I'm connecting with the -Y SSH option and using keys (not passwords). Everything related to SSH seems to be working fine. The only problem I see is with X. Here's another example:$ xeyes &$ Error: Can't open display: And$ echo $DISPLAY$ (returns nothing)These answers seem relevant but I haven't been able to understand them in enough detail to work out a solution in my case:Can I launch a graphical program on another user's desktop as root?https://superuser.com/questions/190801/linux-wmctrl-cannot-open-display-when-session-initiated-via-sshscreen/190878#190878
Remote desktop (KDE) over SSH reverse tunnel
ssh;x11;kde;ssh tunneling;remote desktop
If you are using a server-in-the-middle to interconnect two systems, chances are at least one of the lines is rather slow. In that case VNC is likely to give you better performance, since you can tune the bandwidth/performance requiremens/quality ratios better (this is actually valid for most setups, unless you are on a reliable 100Mbit+ network).I personally like x11vnc, which connects to a running X server and forwards the inputs/output over the VNC protocol (this can be done as soon the X server is running, so you can interact even with a display manager). The X server in question can be both a regular one (which outputs to a real display) or a framebuffer based one like Xvfb. You can then use any VNC client to connect to the exported X server. And of course you probably want to tunnel the transmissionn through ssh or stunnel. The man page of x11vnc is quite exhaustive and even has a frequently used command line example at the beginning.Ths also allows you to remotely connect to a running session to help somebody solve a problem remotely. As an important bonus, since just the inputs and output are forwarded rather than the X protocol itself, network disconnects will just interrupt the session, but all of the programs remain running, which is not the case of X through SSH.If for some reason you really want to tunnel X11 through SSH, you must ensure that the DISPLAY environment variable is set up properly by ssh. Without it you can't proceed, because the applications won't know which server to connect to. Check whether the X11Forwarding directive is set to yes in your sshd configuration.Last but not the least, you probably don't want to run startkde4 (or any other X session for that matter) over SSH - the network load will likely be quite heavy - VNC will serve you better again.
_codereview.32313
I needed a utility function/method that would get the next available filename to save as.An example would be, if I need to save a file as MyTestFile.html but it already exists.This method would then check to see what the next availble filename would be, and it would return MyTestFile2.html. If MyTestFile2.html exists, then it would return MyTestFile3.html, and so on.I wrote the method, but it feels sloppy, and isn't really very elegant.Any ideas for improving the readability of this code, or a better way to do it?public string GetNextAvailableName(List<string> files, string baseFile){ var baseFileWithoutExt = Path.GetFileNameWithoutExtension(baseFile); var baseExt = Path.GetExtension(baseFile); //clean files and get the ones containing oure baseFileName var cleanFiles = files .Select(i => Path.GetFileNameWithoutExtension(i.ToLower())) .Where(i => i.Contains(baseFileWithoutExt.ToLower())); var count = cleanFiles.Count(); if (count == 0) return baseFile; int indexCount = 1; do { indexCount++; } while (cleanFiles.Contains(baseFileWithoutExt.ToLower() + indexCount)); return baseFileWithoutExt + indexCount + baseExt;}This would then be called like this:GetNextAvailableName(Directory.GetFiles(C:\\MyFiles\\, MyTestFile.html);Then if MyTestFile.html is already in use, it will return MyTestFileX.html, where X is the lowest positive integer where the filename doesn't exist yet.
Method to get next available filename
c#
I don't understand why you want to pass a list of files. Simply check the existence of your filename candidates. Start with the base filename. If it does not exist, start counting. In my eyes this a straightforward approach and therefore easy to understand.public string GetNextAvailableFilename(string filename){ if (!System.IO.File.Exists(filename)) return filename; string alternateFilename; int fileNameIndex = 1; do { fileNameIndex += 1; alternateFilename = CreateNumberedFilename(filename, fileNameIndex); } while (System.IO.File.Exists(alternateFilename)); return alternateFilename;}private string CreateNumberedFilename(string filename, int number){ string plainName = System.IO.Path.GetFileNameWithoutExtension(filename); string extension = System.IO.Path.GetExtension(filename); return string.Format({0}{1}{2}, plainName, number, extension);}
_unix.85550
I've just made a debian package, when all the files are zipped together the size is 60 MB, however my .deb file made from the same directory is ~150 MB. Have I done something wrong or are there lots of overheads involved with .deb files, and if so would it be possible to get a brief run-down of what is added to the raw files?
Debian package very large compared to zip file
debian;dpkg
A .deb file is an ar archive with typically those files:$ ar tv apache2_2.4.6-2_amd64.debrw-r--r-- 0/0 4 Jul 23 12:51 2013 debian-binaryrw-r--r-- 0/0 7422 Jul 23 12:51 2013 control.tar.gzrw-r--r-- 0/0 179960 Jul 23 12:51 2013 data.tar.xz(the used compression can be gz, bz2 or xz).The ar archive is not compressed itself, only the components are.Only data.tar.xxx should be significantly large as it contains the actual files that make up the package.You can check the content with:$ ar p apache2_2.4.6-2_amd64.deb data.tar.xz | tar --xz -tvf - | headdrwxr-xr-x root/root 0 2013-07-23 12:50 ./drwxr-xr-x root/root 0 2013-07-23 12:47 ./var/drwxr-xr-x root/root 0 2013-07-23 12:47 ./var/cache/drwxr-xr-x root/root 0 2013-07-23 12:47 ./var/cache/apache2/drwxr-xr-x www-data/www-data 0 2013-07-23 12:47 ./var/cache/apache2/mod_cache_disk/drwxr-xr-x root/root 0 2013-07-23 12:47 ./var/www/[...]
_unix.18524
How do I load a Fedora DVD iso onto USB so I can install it from there.I've tried dd as in here: Fedora instructions but for some reason this didn't work.Here's what I've tried:sudo dd if=Fedora-15-x86_64-netinst.iso of=/dev/sdb1andsudo dd if=Fedora-15-x86_64-netinst.iso of=/dev/sdbThe USB key contains DVD information - I've looked it up, but the laptop simply skips the USB key and boots from harddrive. I've obviously configured BIOS to boot from USB first and I also tried selecting USB key from F12 menu.What am I doing wrong? Has anyone tried installing from USB key using dd before?
Installing Fedora from USB key
linux;fedora;boot;install;usb
The second command is the correct. Try this:sudo umount /dev/sdb*sudo dd if=/dev/zero of=/dev/sdbsudo syncsudo dd if=Fedora-15-x86_64-netinst.iso of=/dev/sdbsudo syncIf you have the same errors, try the GNOME or KDE livecd in your USB stick. If all fail, the problem is your hardware.
_unix.194172
Say, you have filesystem Btrfs formatted, then you, all of the sudden as it happens, wonder what files occupy blocks #356 and #789, how you gonna answer this question?
Btrfs: Is there an easy way to find a file by block numbers it occupies?
btrfs
null
_codereview.159536
Since train rides can be long and boring, I've decided to make use of that time and fiddle around with some good ol' C.What I did was to create a way to enumerate words of a certain length of an arbitrary alphabet. Basically, suppose you have an alphabet{ '0', '1' }(ooh, binary!) and want to get all words of length 7, you'd callenumerate(01, 7);and have a nice array of pointers containing the strings 0000000 to 1111111. What for, you ask? Dunno. Stuff.I've written it on my phone, so it may be a tad slimmer than the usual 80 characters. It's also not split into files for the very same reason.#include <math.h>#include <stddef.h>#include <stdio.h>#include <stdlib.h>#include <string.h>/* * Translates a numeric value into it's representation * in the given alphabet. The alphabet must contain * at least 2 letters, of which the first must be a * zero-like letter which will be used to fill eventual * empty spaces. * * @param value The numeric value to be translated. * @param alphabet The alphabet to translate into. * The decimal alphabet e.g. would * be 0123456789. * @param length The length of the generated string. * If length is 0, the minimum length * needed to represent the translation is * used. * * @return A newly allocated string of length + 1 bytes, * containing the translated value. If an error * occurs, NULL is returned. */char *translate( unsigned long value, const char *alphabet, size_t length) { size_t base; char *result; if (!alphabet || (base = strlen(alphabet)) < 2) { return NULL; } if (length == 0) { length = 1 + floor(log(value) / log(base)); } result = malloc(length + 1); if (!result) { return NULL; } memset(result, alphabet[0], length); result[length] = 0; for (int i = length - 1; i >= 0 && value > 0; --i) { unsigned long mod = value % base; result[i] = alphabet[mod]; value -= mod; value /= base; } return result;}/* * Enumarates all words of given length of the * given alphabet. Each word is contained in an * allocated string; pointers to those words are * sequentially stored in the returned array. * * @param alphabet The alphabet to be enumerated. * @param length The length of each word. * * @return An array of strings or NULL, if * either allocation or translation * of any word failed. When NULL is * returned, no memory has to be freed. */char **enumerate( const char *alphabet, const size_t length) { size_t base; if (!alphabet || (base = strlen(alphabet)) < 2) { return NULL; } if (length == 0) { return NULL; } unsigned long end = pow(base, length); char **array = malloc((end + 1) * sizeof(char*)); if (!array) { return NULL; } array[end] = NULL; for (int i = 0; i != end; ++i) { char *storage = malloc(length + 1); char *translated = translate(i, alphabet, length); if (!storage || !translated) { if (storage) { free(storage); } if (translated) { free(translated); } array[i] = NULL; goto error_cleanup; } strcpy(storage, translated); free(translated); array[i] = storage; } return array; error_cleanup: for (int i = 0; array[i] != NULL; ++i) { free(array[i]); } free(array); return NULL;}Example usage; simply concatenate the listings.int main(int argc, char *argv[]) { if (argc < 2) { printf(Usage: %s <length> <alphabet>, argv[0]); exit(0); } size_t length = atoi(argv[1]); char *alphabet = argv[2]; char **array = enumerate(alphabet, length); if (!array) { printf(Error while enumerating.); exit(1); } for (int i = 0; array[i] != NULL; ++i) { printf(%s\n, array[i]); free(array[i]); } free(array); exit(0);}What I'm most concerned about is idiomaticality (is that even a word?) of the code, since my C is rusty and self-taught, especially concerning the use of that string array. Also, is my goto used well and with good reason?
Enumerating an alphabet
c;strings;pointers
If you want to improve usability, you should introduce some kind of type for your array (typedef the pointer, or introduce some type of struct that will contain useful metadata) and provide the appropriate free function for it. This way, the user doesn't have to free all the elements themselves and can just call my_free(&my_type_ptr) when he's done. Your error_cleanup should just call this function as well.This bit of code does unnecessary work:char *storage = malloc(length + 1);char *translated = translate(i, alphabet, length);if (!storage || !translated) { if (storage) { free(storage); } if (translated) { free(translated); } array[i] = NULL; goto error_cleanup;}strcpy(storage, translated);free(translated);array[i] = storage;in the form of allocating an extra block of memory and copying things there from an already allocated block of memory. Simplify to:array[i] = translate(i, alphabet, length);if (array[i] == NULL) { // Error in translating, abort goto error_cleanup;}is my goto used well and with good reason?No. You only have one user of the goto. If you look above at the more concise version of your function, it's completely reasonable just to say no more goto and replace it with free_word_array(array); return NULL;. Any time you have a need to clean multiple resources on any failure, goto can be a good choice.(argc < 2) needs to be (argc < 3). As it is written, running your program with only one extra argument ./main 6 results in Error while enumerating. instead of printing the help message. Remember, the program invocation is the 0th argument but counts in the count as well.I prefer return from main rather than exit.translate could use more comments within the algorithm, for quicker reading/understanding. It looks like you're just enumerating all possible words within a given set, and this recovers the word.Maybe it makes sense not to have an array of arrays, but rather an array of numbers that you then convert to the string representation if the user wants to print it? But then the logical conclusion of that is that you don't really need to allocate memory at all then: you can just as easily return the number of permutations, and work out the appropriate requested permutation when it is requested.Your code will only work with single-wide characters, and produce gibberish for any alphabet that contains characters that aren't (think UTF-8, for instance, where the character can be wider than a byte, meaning that you'll shuffle the character incorrectly). This might not be in your requirements, but thought I'd mention it since this always plagues non-ASCII character stuff in C.
_softwareengineering.278305
Consider multiple relational database schemas that have an inheritance dependency structure as known from OOP systems:Tables are just a placeholder for arbitrary database objects such as Views, Stored Procedures, etc.Are there any methods or tools that might help me express this abstraction? Such as a package manager that builds modular create and upgrade scripts?(I am not talking of O/R Mapping within one database schema. Actually I am primarily thinking about an BI application, so there is no ORM anyway.)
Modular Database, Inheritance of Schema
database design;inheritance
null
_unix.173947
Can someone tell me the differences from:du -s dir 3705012 dirdu -s --apparent-size dir3614558 dirthese dirs are inside a block device (created using cryptsetup). Or better: why I need add --apparent-size only with files inside a crypted block device?
du -s --apparent-size VS du -s
disk usage
null
_unix.266931
Say I started a su command, and I want to cancel it. Control+C doesn't work for su like it does for sudo... I have to finish the prompt (either by getting the password wrong enough times or by getting it right).Is there something that I can type to kill a password prompt?
How can I CTRL^C out of a password prompt?
bash;shell;command line;kill;authentication
su is running with elevated privileges, and you are not seeing it respond to ^C (which sends a signal with your privileges). You could su to another shell and kill it from the other shell. Also (depending on the system), it might respond to SIGHUP (a hangup signal) if you closed the terminal session where the awkward su is in progress.There's more than one way that su can ignore your ^C, e.g.,establishing signal handlers orrunning under a different controlling terminal.A quick read of Debian's su seems that it uses the latter. Your system of course may be different.Further reading:/bin/su no longer listens to SIGINT!how to terminate some process which is run with sudo with kill
_codereview.46242
Here is my single parse code for splitting a std::string on a char into a std::vector<std::string>:#include <iostream>#include <vector>std::vector<std::string> split_uri(std::string, unsigned chr='/');int main() { std::vector<std::string> uri_v = split_uri(uri, '/'); for (auto elem: uri_v) std::cout << elem << std::endl;}std::vector<std::string> split_uri(std::string uri, unsigned chr) { bool start=true; std::string part; std::vector<std::string> vec; vec.reserve(uri.length()/2); for(char c: uri) { switch(c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': part += c; break; default: if (c == chr) { if (!start) vec.push_back(part); else start = false; part.clear(); part += c; } else { std::cerr << Invalid URI; from: \' << c << \' (hex: << std::hex << 0x << (unsigned int)c << )\n; vec.clear(); return vec; } } } return vec;}What can I do to improve its efficiency?
split string into container on char; efficiently?
c++;performance;memory management;vectors;cyclomatic complexity
First, consider passing potentially expensive-to-copy objects such as std::string as const reference rather than by-value. The obvious approach is to use std::istringstream and std::getline.std::vector<std::string> split_uri(const std::string uri&, char chr){ std::istringstream iss(uri); std::vector<std::string> vec; for(std::string token; getline(iss, token, chr); ) vec.push_back(token); return vec;}With the input being \bar\can, the output is {, bar, can}.However, std::istringstream is not known for its speed. If you don't want to use std::istringstream, you don't have to. The following should be much faster:std::vector<std::string> split_uri(const std::string& uri, char chr){ std::string::const_iterator first = uri.cbegin(); std::string::const_iterator second = std::find(first+1, uri.cend(), chr); std::vector<std::string> vec; while(second != uri.cend()) { vec.emplace_back(first, second); first = second; second = std::find(second+1, uri.cend(), chr); } vec.emplace_back(first, uri.cend()); return vec;}With the input being \bar\can, the output is {\bar, \can}.
_unix.218901
I am attempting to open an image and a text file that my Python (3.3.2) program is creating (the files are created without issue). The last two lines of the program are:subprocess.call(['leafpad', filename + '.tsv'])subprocess.call(['gpicview',filename + '_fig.png'])The text file is successfully opened, with the following warnings returned to the terminal:(leafpad:3676): GLib-GObject-WARNING **: Attempt to add property GtkSettings::gtk-menu-bar-popup-delay after class was initialised(leafpad:3676): GLib-GObject-WARNING **: Attempt to add property GtkSettings::gtk-label-select-on-focus after class was initialised(leafpad:3676): GLib-GObject-WARNING **: Attempt to add property GtkSettings::gtk-can-change-accels after class was initialised(leafpad:3676): GLib-GObject-WARNING **: Attempt to add property GtkSettings::gtk-menu-popup-delay after class was initialised(leafpad:3676): GLib-GObject-WARNING **: Attempt to add property GtkSettings::gtk-menu-popdown-delay after class was initialised(leafpad:3676): GLib-GObject-WARNING **: Attempt to add property GtkSettings::gtk-menu-images after class was initialised(leafpad:3676): GLib-GObject-WARNING **: Attempt to add property GtkSettings::gtk-scrolled-window-placement after class was initialisedThe image file does not open until I close the text file window, and then returns the following similar warnings to the terminal:(gpicview:3682): GLib-GObject-WARNING **: Attempt to add property GtkSettings::gtk-scrolled-window-placement after class was initialised(gpicview:3682): GLib-GObject-WARNING **: Attempt to add property GtkSettings::gtk-button-images after class was initialised(gpicview:3682): GLib-GObject-WARNING **: Attempt to add property GtkSettings::gtk-label-select-on-focus after class was initialisedThrough reading other threads online, I've figured out that the warnings aren't an issue for me (just something that most likely exists as a result of the latest dist, warnings don't really bother me). My problem is primarily that the warnings (it would appear) are preventing the script from continuing along and opening the image viewer as well, and secondarily cluttering up the terminal in a way that looks rather unprofessional. Thanks for any help you could offer in suppressing these warnings and getting both the text editor window and the image viewer window to open simultaneously and without a mess of warnings on my terminal.
Warnings when opening programs via Python subprocess calls
python
Your current method means two things are happening:You are seeing the output of subproccessprocesses can have a few outputs, here are two that can occur:STDOUT - information from the program being runSTDERR - information on warnings errors the program has encountered. This is probably the one that is annoying you.Using options on the subprocess should mean you can pipe the outputs to /dev/null (i.e. the won't appear in the output):DEVNULL = open(os.devnull, 'wb')subprocess.call(['leafpad', filename + '.tsv'], stdout=DEVNULL, stderr=DEVNULL)This is the version for python 2.4+, the bit defining DEVNULL may not be needed in 3.3+Note that even if you remove hide all the output it will still wait for the process, so....and it waits for the processes to finish before continuingIf you want to get the process to continue in the background, you can use this:subprocess.Popen(['leafpad', filename + '.tsv'])Popen does not wait for the process to exit, so it will continue in the background (unlike call) - for more info see here.Putting these 'fixes' together should give you:DEVNULL = open(os.devnull, 'wb')subprocess.Popen(['leafpad', filename + '.tsv'], stdout=DEVNULL, stderr=DEVNULL)For python 2.4+ againYou can get more information from the documentation here.I am a amateur at python whose version of leafpad gives no errors, so if anything does not work please say :)
_unix.314814
I have about 40 Maildir directories in /var/vmail/ with the structure of Domain1.com-- user----- new----- cur----- tmpDomain2.com-- user----- new----- cur----- tmpInside each of those new, cur, tmp directories there are email files. What can I use, configure, and how, to read those emails in an easy manner, not via the editor?
How can I easily read many Maildir directories?
files;email;maildir
null
_codereview.18160
I have the following .click() functions:$('.tab').click(function(){ $('.tab').removeClass('activeTab'); $(this).addClass('activeTab');});$('.edit').click(function(){ $(this).hide(); $(this).next().show();});$('.cancel').click(function(){ $(this).parent().hide(); $(this).parent().prev().show();});Is it possible to combine these functions doing something like this?Pseudocode:$.click(function(){ for $('.tab'){ //do this } for $('.edit'){ //do this } for $('.cancel'){ //do this }});HTML:<a href=javascript:void(0); class=edit>Edit</a><span class=controls> <a href=javascript:void(0); class=cancel>Cancel</a> | <a href=javascript:void(0); class=save>Save</a> </span>
Different way of writing multiple click functions
javascript;jquery;html
First off, I'd rewrite the HTML to get rid of the javascript href attributes. I'd also use a data-action attribute for the action name. You can still use class to do the styling of course, but style is not behavior, so keep those things separate (i.e. the class might be action-button primary highlighted or something, but the action would still be save):<a href=# data-action=edit>Edit</a><span class=controls> <a href=# data-action=cancel>Cancel</a> | <a href=# data-action=save>Save</a> </span>Code-wise, what each link has in common is that they should preventDefault so the links aren't followed when clicked. So at the very least, we'll need this:$(a[data-action]).on(click, function (event) { event.preventDefault();});Then of course, there are the actions/behaviors themselves. I'd suggest putting the logic for each in an object, and expanding the generic click handler like so:var actions = { edit: function (event) { ... }, cancel: function (event) { ... }, save: function (event) { ... }};$(a[data-action]).on(click, function (event) { var link = $(this), action = link.data(action); event.preventDefault(); // If there's an action with the given name, call it if( typeof actions[action] === function ) { actions[action].call(this, event); }});Now you have a generic click handler, and an easily extensible list of actions. The action functions themselves behave exactly like normal jQuery event handlers (i.e. this will refer to the link clicked, and the first argument will be the event).
_unix.157815
I have a log file that exists in multiple directories one for each client. I am trying to run the following:find . -iname 20140926.log -exec cat {} \; | grep 123456 | grep 'food=100' | wc -lthis returns me the result I want but I want to know for each fullpath what the individual count was. For example I tried this:for f in /path/*; do result=`eval grep 123456 $f/logs/20140926.log | grep 'food=100' | wc -l` echo $f - $result doneBut it just returning a list of all my directories and then the final result. I am expecting something like this:/path1/log/file.log - 0/path2/log/file.log - 2/path3/log/file.log - 39etc...This way I can see the wc for my grep for each path/file
run grep cmd recursively and print path name and result
shell script;grep;find
grep -H will print file names for you, but since you're doing multiple greps you can just echo the file name yourself:for f in $(find . -name '20140926.log'); do echo -n $f grep 123456 $f | grep -c 'food=100' # grep -c prints count of matchesdone
_webmaster.47936
I cannot tell from the Opera Desktop team blog or from the Presto Wikipedia page if Opera 12.15 is utilizing the WebKit or Presto rendering engine. The phrasing from Wikipedia can be interpreted either way:It [Presto] remained in use until Opera 12.15, when the browser's developer Opera Software ASA began phasing Presto out of its products in favor of the WebKit layout engine and V8 JavaScript engine combined with a modified Chromium browser.Is Opera Version 12.15 using WebKit or Presto?
Is Opera Version 12.15 using WebKit or Presto for its rendering engine?
browsers
12.15 is still using Presto, but it's being phased out after 12.15 in favour of WebKit Blink, a WebKit fork.
_webmaster.59728
I am hosting my site on HostGator. The problem is that I can not receive e-mails from some domains.Here is the SMTP transaction response received:H=(sv2.elanceonline.com) [162.242.179.29]:38251 I=[192.185.51.218]:25 F=<[email protected]> temporarily rejected RCPTH=(sv2.elanceonline.com) I=[192.185.51.218]:25 sender verify defer for <[email protected]>: host lookup did not completeUnable to resolve svbounce.elanceonlineThe support person at HostGator insisted that the problem is on domain-side, but I am very sure it is on HostGator's side because I never had any such problems before using HostGator, and now in the course of 2 days I'm having the same problem with 2 different senders. I can receive from both domain's emails to Gmail at the same time without any problem, but once I type [email protected] (mydomain.com is hosted on HostGator) I cannot receive e-mail.What could be reasons for not being able to resolve svbounce.elanceonline or other domains? Should I trust HostGator and believe them that it's not a problem on their side?
Mailserver at my hosting company is unable to resolve certain domains
web hosting;email;shared hosting;hostgator
null
_unix.97428
If I am doing several substitutions which need to be consecutive, e.g.sed -i '/^[[:space:]]*browser.*\.should/s/browser/expect(browser/' t1_spec.rbsed -i '/expect(browser.*\.should/s/\.should/).should/' t1_spec.rbsed -i 's/\.should/\.to/' t1_spec.rb sed -i 's/==/eq/' t1_spec.rb Is there a better way to do this that will only go through the t1_spec.file once and do the the 4 substitutions for each line rather than going through the file 4 times?
sed - how to do several consecutive substitutions but process file only once?
sed
In GNU (e.g. on my Ubuntu machine), simply using multiple lines is supported and works well and looks good (imho) as it avoids super long lines, e.g.sed -i '/^[[:space:]]*browser.*\.should/s/browser/expect(browser/ /expect(browser.*\.should/s/\.should/).should/ s/\.should/\.to/ s/==/eq/' t1_spec.rb
_codereview.101241
Folow up of diary-applications-with-accountsDiary ClassAccountLogin objAccountLogin = new AccountLogin();AccountRemover objAccountRemover = new AccountRemover();AccountCreator objAccountCreator = new AccountCreator();Accounts objAccounts = new Accounts();Exit objExit = new Exit();public static void main(String[] args) { Diary d = new Diary(); d.startDiary(); }public void startDiary(){ objAccounts.loadAccounts(); while(true){ showMainMenu(); usersChoice(); }}public void showMainMenu(){ System.out.println(); System.out.println(Welcome to Diary!); System.out.println(1- New Account); System.out.println(2- Login To Your Account); System.out.println(3- Remove Account); System.out.println(4- Exit); System.out.println();}public void usersChoice(){ int choice = 0; Scanner scan = new Scanner(System.in); while(true){ try{ scan = new Scanner(System.in); System.out.print(Choose an option: ); choice = scan.nextInt(); break; } catch(Exception e){ System.out.println(Invalid Input!\n); } } switch (choice){ case 1: choiceNewAccount(scan); break; case 2: choiceLogin(scan); break; case 3: choiceRemoveAccount(scan); break; case 4: exit(scan); break; default: System.out.println(Invalid Input!\n); break; }}public void choiceNewAccount(Scanner scan){ objAccountCreator.createAccount(scan);}public void choiceLogin(Scanner scan){ objAccountLogin.login(scan);}public void choiceRemoveAccount(Scanner scan){ objAccountRemover.removeAccount(scan); }public void exit(Scanner scan){ objExit.tryExit(scan); } }AccountCreatorpublic void createAccount(Scanner scan){ try{ System.out.print(Enter Your Username: ); String username = scan.next(); if(!isValidUsername(username)) System.out.println(Username Already Exists!); else{ while(true){ System.out.print(Enter Your Password: ); String pass1 = scan.next(); System.out.print(Re-Enter Your Passowrd: ); String pass2 = scan.next(); if(!arePasswordsMatch(pass1,pass2)) System.out.println(Passowrds Don't Match!); else { addToAccountsList(username,pass1); createTheUsersFile(username); System.out.println(The Account Has Been Successfully Created!); break; } } } } catch(Exception e){ System.out.println(Could Not Create Account!); } }private boolean isValidUsername(String username){ return getUsernamesList().stream().noneMatch((valid) -> (valid.equals(username)));}private boolean arePasswordsMatch(String pass1, String pass2){ return pass1.equals(pass2); }private boolean createTheUsersFile(String username){ File newUserFile = new File(D:+username+.txt); try { newUserFile.createNewFile(); } catch (IOException ex) { Logger.getLogger(AccountCreator.class.getName()).log(Level.SEVERE, null, ex); } return newUserFile.exists();}AccountLoginprotected String loginName(Scanner scan){ System.out.print(Enter Username: ); String username = scan.next(); System.out.print(Enter Password: ); String password = scan.next(); if(getUsernamesList().contains(username)){ if(password.equals(getPasswordsList().get(getUsernamesList().indexOf(username)))) return username; return -1; } return -1;}public void login(Scanner scan){ String username = loginName(scan); if(username.equals(-1)) System.out.println(Can Not Log In!); else{ System.out.printf(%s Has Logged In! \n,username); System.out.println(); outerloop: while(true){ showLoginMenu(); int usersLoginChoice = usersChoice(scan,username); if(usersLoginChoice == 3) break; switchTo(usersLoginChoice,scan,username); } } }private void showLoginMenu(){ System.out.println(); System.out.println(1- Write Diary); System.out.println(2- Read Diary); System.out.println(3- Logout); System.out.println();}private int usersChoice(Scanner scan , String username){ System.out.print(Choose An Option: ); while(true){ try{ return scan.nextInt(); } catch(Exception e){ System.out.println(Invalid Input!); return -1; } }}private void switchTo(int usersLoginChoice, Scanner scan, String username){ switch(usersLoginChoice){ case 1: writeDiary(scan,username); break; case 2: readDiary(username); break; default: System.out.println(Invalid Input!); break; }}private void writeDiary(Scanner scan, String username){ File diaryFile = new File(D:+username+.txt); String input = 1; System.out.println(Start Writing Your Diary (-1 to stop): ); while(!input.equals(-1)){ try (PrintWriter writeDiary = new PrintWriter(new BufferedWriter(new FileWriter(diaryFile, true)))){ input = scan.nextLine(); if(!input.equals(-1)) writeDiary.println(input); } catch(Exception e){ System.out.println(Could Not Write Diary!); break; } } System.out.println(); System.out.println(Diary Saved!);}private void readDiary(String username){ File diaryFile = new File(D:+username+.txt); try(Scanner readDiary = new Scanner(diaryFile)){ while(readDiary.hasNext()) System.out.println(readDiary.nextLine()); } catch(Exception e){ System.out.println(Could Not Open Diary File!); } }AccountRemoverpublic void removeAccount(Scanner scan){ remove(scan); refresh(); }public void remove(Scanner scan){ String accountName = loginName(scan); if(!accountName.equals(-1)){ removeFile(accountName); removeFromList(accountName); System.out.println(Account Has Been Successfully Removed!); } else System.out.println(Could Not Remove Account!);}public void removeFile(String accountName){ File deleteUsername = new File(D:+accountName+.txt); deleteUsername.delete(); }public void removeFromList(String accountName){ if(!accountName.equals(-1)) { for(int i = 0; i < getUsernamesList().size();i++) if(getUsernamesList().get(i).equals(accountName)){ getUsernamesList().remove(i); getPasswordsList().remove(i); break; } } else System.out.println(Can Not Erase Account!);}public void refresh(){ refreshUsernames(); refreshPasswords();}public void refreshUsernames(){ try (PrintWriter usernamesOverWriter = new PrintWriter(new BufferedWriter(new FileWriter(this.usernamesFile)))){ getUsernamesList().stream().forEach((b) -> { usernamesOverWriter.println(b); }); usernamesOverWriter.flush(); } catch (IOException ex) { Logger.getLogger(AccountRemover.class.getName()).log(Level.SEVERE, null, ex); }}public void refreshPasswords(){ try (PrintWriter passwordsOverWriter = new PrintWriter(new BufferedWriter(new FileWriter(this.passwordsFile)))){ getPasswordsList().stream().forEach((b) -> { passwordsOverWriter.println(b); }); passwordsOverWriter.flush(); } catch (IOException ex) { Logger.getLogger(AccountRemover.class.getName()).log(Level.SEVERE, null, ex); }}Exitpublic char readExit(Scanner scan){ System.out.print(Are you sure you want to exit? (y/n): ); return scan.next().charAt(0);}public void tryExit(Scanner scan){ boolean invalidExitInput = true; while(invalidExitInput){ invalidExitInput = false; char userConfirmedExit = readExit(scan); if(userConfirmedExit == 'y') System.exit(0); else if(userConfirmedExit != 'n') { System.out.println(Invalid Input); invalidExitInput = true; } }}Accountsprotected File usernamesFile = new File(D:Usernames.txt);protected File passwordsFile = new File(D:Passwords.txt);private static ArrayList<String> accounts_Usernames = new ArrayList<>();private static ArrayList<String> accounts_Passwords = new ArrayList<>(); protected void addToAccountsList(String username, String password){ addToAccounts(username,password); loadAccounts();}private void addToAccounts(String username,String password){ addToUsernames(username); addToPasswords(password);}private void addToUsernames(String username){ if(usernamesFile.exists()){ try (PrintWriter usernamesWriter = new PrintWriter(new BufferedWriter(new FileWriter(this.usernamesFile, true)))) { usernamesWriter.println(username); usernamesWriter.flush(); } catch (IOException ex) { Logger.getLogger(Accounts.class.getName()).log(Level.SEVERE, null, ex); } } else System.err.println(File: Usernames Does Not Exist!); }private void addToPasswords(String password){ if(passwordsFile.exists()){ try (PrintWriter passwordsWriter = new PrintWriter(new BufferedWriter(new FileWriter(this.passwordsFile, true)))) { passwordsWriter.println(password); passwordsWriter.flush(); } catch (IOException ex) { Logger.getLogger(Accounts.class.getName()).log(Level.SEVERE, null, ex); } } else System.err.println(File: Passwords Does Not Exist!); }protected void loadAccounts(){ loadUsernames(); loadPasswords();}private void loadUsernames(){ try (Scanner usernamesScanner = new Scanner(usernamesFile)) { while(usernamesScanner.hasNext()){ String username = usernamesScanner.next(); if(!accounts_Usernames.contains(username))accounts_Usernames.add(username); } } catch (FileNotFoundException ex) { Logger.getLogger(Accounts.class.getName()).log(Level.SEVERE, null, ex); }}private void loadPasswords(){ try (Scanner passwordsScanner = new Scanner(passwordsFile)) { while(passwordsScanner.hasNext()){ String password = passwordsScanner.next(); if(!accounts_Passwords.contains(password))accounts_Passwords.add(password); } } catch (FileNotFoundException ex) { Logger.getLogger(Accounts.class.getName()).log(Level.SEVERE, null, ex); }}protected ArrayList<String> getUsernamesList(){ return accounts_Usernames;}protected ArrayList<String> getPasswordsList(){ return accounts_Passwords;}
Diary Application with accounts (v.2)
java;console;authentication
Diary class should have its collaborators passed in constructor - API doesn't lie about its dependencies then, and code can be easily tested thanks to not being forced to use concrete object instances. In most cases, things like loading collaborators should be done in constructor.class Dairy { AccountLogin objAccountLogin; AccountRemover objAccountRemover; AccountCreator objAccountCreator; Accounts objAccounts; Exit objExit; public static void main(String[] args) { Diary d = new Diary(new AccountLogin(), new AccountRemover(), ...); d.startDiary(); } public Dairy(AccountLogin accountLogin, AccountRemover accountRemover, AccountCreator accountCreator Accounts accounts, Exit exit) { this.objAccountLogin = accountLogin; this.objAccountRemover = accountRemover; //etc. }}In your switch cases your methods just delegate to another single ones - it leads to spaghetti code - you can do it in your case: switch (choice){ case 1: objAccountCreator.createAccount(scan); break; }If there'd appear more logic than one line of code in your choiceNewAccount() method, it can be left, but there's no need for it to be accesible for other objects - make it private.Why loginName() in AccountLogin is protected? You don't seem to have any class inheritance, different packages, so you can make it public.In AccountCreator you loose all information about error and its place - log this information contained in e:catch (Exception e) { System.out.println(Could Not Create Account!); e.printStackTrace(); }loadUsernames() and loadPasswords() duplciate code. Do job in loadAccounts() and pass files as a parameter, to be explicit in what those methods need to work. In other methods consider passing parameters for preventing prematurely coupled design.
_unix.105373
I am trying to create a script that will add a user to the UserDir enabled list or will remove it from UserDir disabled list in userdir.conf.For the sake of my question, let's say I have the following file:Lorem ipsumLorem ipsum List 1 enabledLorem ipsumLorem ipsum List 2 disabledLorem ipsumWhat I would like to do is when I run my script with the following ./script enabled user is to modify my file to:Lorem ipsumLorem ipsum List 1 enabled userLorem ipsumLorem ipsum List 2 disabledLorem ipsumAfterwards, if I do ./script disabled user it will remove user from List 1 and add it two list 2. Thus, the output of the file would be:Lorem ipsumLorem ipsum List 1 enabledLorem ipsumLorem ipsum List 2 disabled userLorem ipsumMy question is not about how to write this script, it is about how to add/delete text into/from a file at a specific location.Off-topic question: Is there a better way to add/remove users in the UserDir list of the apache2?
Write In A File at Specific Location
files;text processing
This can be done with sed or awk. Take your pick. Personally, I like to use the tool with the smallest footprint. You can, of course, do it in any programming language like Perl, C, SNOBOL or PDP-8 machine code, but this may be ever so slightly beyond the scope of the question. ;)To delete a user from the UserDir enable line using sed:sed -e '/^[^#]*UserDir\s\+enabled\s\+/ s/\bfoo\b//g' -e 's/\s\+/ /g' FILE-IN >FILE-OUTThis does two things:For all lines that start with a non-commented out UserDir enabled, it removes the user foo (but not, for example, a user foobar).It removes superfluous white space.To add a user:sed -e '/^[^#]*UserDir\s+enabled\s+/ s/\(\s\+#\|$\)/ bar\1/' FILE-IN >FILE-OUTThis will look for all lines like Userdir enabled that isn't commented out, same as before. For any such lines found, it will add the user bar at the end. If the line ends in a comment, the comment is respected and left in there.To add a new UserDir enabled line after the UserDir disabled line:sed -e '/^[^#]*UserDir\s+enabled\s+/ a UserDir disabled foo bar baz' FILE-IN >FILE-OUTThis uses the append (a) sed command to add text after every non-commented-out line like UserDir enabled .... Change the a to an i to insert before the matched line.Some notes:Obviously, change enabled to disabled at will.We use \s+ instead of spaces to catch cases where other forms of white space are used (e.g. tabs), and/or multiple white space characters are encountered.You can combine both operations. Sed can run multiple expressions on each file. Each expression is provided after the -e option and they run in order, from left to right.Note that some characters that aren't escaped in some regular expression dialects are escaped for the regular expression flavour used by sed.These will require a temporary file (FILE-OUT) to store the edited file (FILE-IN).If you want to invoke these in-place (without redirecting to a temporary file), replace the FILE-IN >FILE-OUT with -i FILE.These work for sure on Linux. Your mileage may vary with sed versions from other Unices. You may find -i (above) isn't available and that regular expression support is more limited.Off-topic answer: it would so much easier if Apache would let you enter multiple UserDir directives and added up the user lists. It may do that, but a cursory check came up blank. I've never had to do this, so I'm not sure whether is possible.
_unix.186215
Can I use vmlinux instead of vmlinuz with GRUB2 (Fedora)?I've seen this:Can vmlinux be used instead of uImage?but it speaks of U-Boot, not GRUB2.
can I use vmlinux instead of vmlinuz with GRUB2 (Fedora)?
fedora;grub2;boot loader
null
_cs.50816
From what I've read, conditionals (like the cond statement in lisp) do not need to be primitive if normal order evaluation is used.Using lambda calculus and normal order evaluation, how can you emulate if and cond statements?(cond (<p1> <e1>) (<p2> <e2>) ... (<pn> <en>))(if <predicate> <consequent> <alternative>)References to SICP are welcome, though a simpler example would be helpful.(Definitions of cond and if taken from Section 1.1.6 of SICP)
Conditionals with normal order evaluation
lambda calculus;evaluation strategies
Here is the church notation:TRUE: $\lambda ab.a$FALSE: $\lambda ab.b$IF: $\lambda pxy.pxy$By passing a church boolean as a predicate to the IF function, we choose one of two alternatives. TRUE chooses the first argument passed to it, and FALSE chooses the second.We can derive COND by folding IF across a list of (condition, result) pairsYou can find wikipedia's explanation here, as well as assorted lambda calculus derivations here.
_unix.85306
when I try to run in the terminal, I get the error The command could not be located because '/usr/bin' is not included in the PATH environment variable.e..g.jeper@jeper:~$ clearCommand 'clear' is available in '/usr/bin/clear'The command could not be located because '/usr/bin' is not included in the PATH environment variable.clear: command not foundand likejeper@jeper:~$ viCommand 'vi' is available in '/usr/bin/vi'The command could not be located because '/usr/bin' is not included in the PATH environment variable.vi: command not foundWhat is the issue is and what is the way to resolve it?
When I try to run a comment I get the error `The command could not be located because '/usr/bin' is not included in the PATH environment variable'
bash
null
_webapps.55113
Is it possible to add PayPal to your Microsoft account without adding a credit card to your PayPal account? As a youngster, I do not have a credit card and I am not planning on getting one.
Add Paypal to Microsoft payment account, without adding a credit card
paypal;microsoft account
null
_vi.2964
I just learned of the existence of include-search, but even after reading :help include-searchand :help includeexpr I'm not sure what I need to do to have [I find included and required files.How do I configure include-search for both included and required PHP files?I think I need to set includeexpr such that it allow searching files whether they were included using require, require_once, include, or include_once; but I'm not sure. And I don't quite get what the variable is supposed to have.
Configuring include-search for PHP
vimrc;search;include;filetype php
The default php ftplugin already does that for you:setlocal include=\\\(require\\\|include\\\)\\\(_once\\\)\\\?Add filetype plugin indent on to your ~/.vimrc if it's not already there to benefit from Vim's filetype detection.
_webapps.28394
If I want to tag a page in a photo (new way of adding a photo to a page's photo album), I type @ and then the page name, and a dropdown is shown with a list of candidates. What happens is that some times it doesn't show the page I want among the options, only finding pages with, for instance, very few people on it. Or if I want a page for a musician, it shows the wikipedia page, not the official one.I have the page link, I like the page, the page has photos added to it (so it's in theory possible and permitted to do this), but the page still doesn't show on the list.
How can I tag a page in a Facebook photo that isn't among the three pages found by the search?
facebook;facebook photos;facebook tags
null
_unix.219312
I'm using Linux Mint 17.2 Cinnamon.There are multiple partitions on /dev/sda. /dev/sda1 is where the system resides, /dev/sda2, ..., /dev/sdaX are NTFS partitions. There are two users admin and user. admin can mount any drive through the menu (the method involves udiskctl, IIRC). user was created as a standard user and can do it too. How can I deny this to user?user belongs to the following groups: adm,audio, cdrom, dialout, dip, fax, floppy, fuse, plugdev, scanner, tape, video.Is plugdev the group I should remove him from or maybe fuse?
The Deny the permission of mounting any drives to a user
linux;permissions;users;disk
null
_softwareengineering.235361
I am working on a C# net micro framework project, in particular an I2C bus class.I have several different I2C devices each defined in separate classes which contain all of the devices' unique methods. In my case, I can only have ONE I2CDevice object defined and to switch to another I2C device, I have to change the I2CDevice.Config = DeviceConfig.For example (pseudo-code):Class Device1 -DeviceConfig1-Method 1-Method 2-Method 3Class Device2-DeviceConfig2-Method 1-Method 2-Method 3Main Program{I2cBus = new I2CDevice(configuration)Device1.Method1Device2.Method3}When switching between devices, I need to change the I2CDevice.Config property. I'm looking for an elegant way such that whenever I call a Method for a device, that the I2CBus.Config is automatically changed. Is there a way that I don't need to re-type this config code in each method? Have a separate internal method that's called each time I access any of those methods?I hope my description is clear.Update, As an alternative, is there a way I can have my make my I2C Bus class and then ADD the devices to the this class? Then To access The Devices, I would Do something likeI2CBus.AddDevice(Device1ObjectClass)I2CBus.AddDevice(Device2ObjectClass)I2CBus.Device1.Method1I2CBus.Device2.Method2I still have the same problem that I need to automatically switch the I2C configuration between Different Device calls.
How to invoke a method in a class always when the class is accessed - like a reaction?
c#;class
null
_unix.61239
I am trying to install package on Redhat 5.5 using YUM but it always give me this error[root@redhat64 Desktop]# yum install perl-Net-Server-0.97-1.el5.rf.noarch.rpm Loaded plugins: rhnplugin, securityThis system is not registered with RHN.RHN support will be disabled.Setting up Install ProcessExamining perl-Net-Server-0.97-1.el5.rf.noarch.rpm: perl-Net-Server-0.97-1.el5.rf.noarchMarking perl-Net-Server-0.97-1.el5.rf.noarch.rpm to be installedResolving Dependencies--> Running transaction check---> Package perl-Net-Server.noarch 0:0.97-1.el5.rf set to be updated--> Finished Dependency ResolutionDependencies Resolved================================================================================ Package Arch Version Repository Size================================================================================Installing: perl-Net-Server noarch 0.97-1.el5.rf /perl-Net-Server-0.97-1.el5.rf.noarch 357 kTransaction Summary================================================================================Install 1 Package(s)Upgrade 0 Package(s)Total size: 357 kIs this ok [y/N]: yDownloading Packages:warning: rpmts_HdrFromFdno: Header V3 DSA signature: NOKEY, key ID 6b8d79e6Public key for perl-Net-Server-0.97-1.el5.rf.noarch.rpm is not installedNote :: OS is 5.5 64bit running on virtual box and I have set GPGCHECK=0 in local YUM repository. Output of Repository[root@redhat64 ~]# cat /etc/yum.repos.d/* | grep -v ^#[rhel-debuginfo]name=Red Hat Enterprise Linux $releasever - $basearch - Debugbaseurl=ftp://ftp.redhat.com/pub/redhat/linux/enterprise/$releasever/en/os/$basearch/Debuginfo/enabled=0gpgcheck=1gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release[rhel-debuginfo-beta]name=Red Hat Enterprise Linux $releasever Beta - $basearch - Debugbaseurl=ftp://ftp.redhat.com/pub/redhat/linux/beta/$releasever/en/os/$basearch/Debuginfo/enabled=0gpgcheck=1gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-beta,file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release[rhel-local.repo]name=Local RepoBaseurl=file:///RPMSenabled=1gpgcheck=0Im using the Local.repo as my main packages repository
Public key not found for RPM
rhel;yum;rpm;gpg
You need to install the Repoforge GPG key:# rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt
_webmaster.43279
I tried to integrate codeigniter authorize.net payment gateway by using the docs http://ci-merchant.org , I can successfully integrate the paypal but unfortunately i couldn't do authorize.net. The below code i have tried,but not working, how to do it ?$this->load->library('merchant');$this->merchant->load('authorize_net_sim');$settings = array('api_login_id' => 'xxxx','transaction_key' => 'xxxx','test_mode' => true);$this->merchant->initialize($settings);$params = array( 'amount' => 10, 'currency' => 'USD', 'card_no' => '4111111111111111', 'exp_month' => '12', 'exp_year' => '14', 'csc' => 123, 'first_name' => 'Ashok', 'last_name' => 'KS', 'return_url' => 'http://www.ioss.in/success', 'cancel_url' => 'http://www.ioss.in/cancel' );$response = $this->merchant->purchase($params); print_r($response) returns:Merchant_response Object ( [_status:protected] => failed [_message:protected] => [_reference:protected] => [_data:protected] => [_redirect_url:protected] => [_redirect_method:protected] => GET [_redirect_message:protected] => [_redirect_data:protected] =>)UPDATE 1 after change the code, its working fine...$params = array('amount' => 10.00,'currency' => 'USD','return_url' => 'http://www.ioss.in','cancel_url' => 'http://www.google.in');
Codeigniter ci-merchant library - authorize.net payment gateway integration issue
payment gateway;codeigniter
Per the comments, if the $response is failing with no error message it's generally because you are trying to submit credit card details unencrypted (not using HTTPS), which isn't supported by CI Merchant (for obvious security reasons).In this case, the credit card details wern't necessary anyway because the Auth.net SIM gateway is an off-site gateway (card details are not entered on your site). Changing the $request to this fixed the problem:$params = array( 'amount' => 10.00, 'currency' => 'USD', 'return_url' => 'http://www.ioss.in', 'cancel_url' => 'http://www.google.in',);In addition, to use the Authorize.net developer endpoint, developer_mode must be set to true in the gateway settings. This is different from test_mode (Auth.net specific feature):$settings = array( 'api_login_id' => 'xxxx', 'transaction_key' => 'xxxx', 'developer_mode' => true,);$this->merchant->initialize($settings);
_softwareengineering.345125
I'm in the process of writing Doxygen comments for this library of mine; it's a header-mostly C++ library, but it does have some code which gets linked rather than included.For that code, which has .h/.hpp headers - should I also add Doxygen comments in the .cpp file, for the library to be properly documented, with the same level of commenting extensiveness as the headers? e.g. should I have file-level comments and detailed function-level comments on static (file-scope) code?PS - In case it's relevant (it probably isn't): link to the actual library on GitHub.
Should I doxygenate implementation files in a library of mine, in addition to the headers?
documentation;comments;implementations;headers
null
_scicomp.5386
I wanted to compare the speeds of the GMRES implementations in the CUSP and the PETSc libraries. The matrix (A) used for testing was a 3d Laplacian matrix obtained by using the 7 point stencil on a 20x20x20 grid => the matrix is of size 8000 x 8000. This is a banded matrix with 7 diagonals.The RHS (b) was obtained by multiplying A by a vector of 1's. I wanted to solve Ax=b by GMRES For both PETSC and CUSP I timed only the time taken for 200 iterations of the GMRES solver(ie time taken for reading in the matrix is not counted) On Petsc the timings were done with PetscGetTime() and on Cusp with Cuda events.%--------------------------TimingsPetsc (1 cpu) took 0.0558379 sec to do 200 iterations of GMRES.Cusp took 0.1183 sec to do the same. %----------------------------As you can see Petsc is 2.14 times faster than the Cusp library even on a single processor. The speed gap gets larger (obviously) on using more than 1 processor.This experiment was done on a GTX 570 card on an Ubuntu 10.10 running CUDA 4.0 having cusp v 0.3.1 and thrust 1.6.0 I have read this paper by one of the authors of CUSP. However, they have not compared the performance of CUSP with Petsc in it.The paper also says that the data-structure used for storing the sparse matrix matters. Accordingly they have provided several formats like DIA, ELL, HYB, COO etc. but even after I tried them all, the Cusp GMRES performance does not change and still takes 0.1183 seconds for the 200 iterations.Here is the (quite-short) GPU code on pastebin I used while using CUSP. I am not sure if I am using the Cusp library in an optimal manner.Although it is possible PETSc is still genuinely better than CUSP I want to know if significant speedup is possible with CUSP if used properly.If more information is needed to answer this question please let me know. Thank you.
Cusp Library performance worse than PETSC (GMRES 200 iterations) Why?
petsc;performance;cuda;gmres
null
_softwareengineering.171773
An order can be in the status of Completed, Corrected or some other status. I saw some code that is checking it like this, the purpose is to disable some stuff when the status is in Completed or Corrected status. if (model.CurrentStatus != DSRHelper.OrderStatusEnum.Complete && model.CurrentStatus != DSRHelper.OrderStatusEnum.Corrected)I can't get it why the engineer has used AND for this, shouldn't it be an OR?
Should I use AND or should I use OR
conditions;programming logic
No, AND appears to be correct here. If you switched it to OR, the condition would always be true. If it was Completed, then the second condition would be true. If it was Corrected, then the first would be true. Keep in mind that the condition currently used is equivalent to!(model.CurrentStatus == DSRHelper.OrderStatusEnum.Complete || model.CurrentStatus == DSRHelper.OrderStatusEnum.Corrected)
_webapps.35191
I can see the development board and vote for ideas, but I cannot seem to create a new idea/feature request.In this questions tool I've seen responses that say NOT to put feature requests into Questions.
How do I create a feature request?
trello
null
_unix.167428
I'm using Fedora 20 and I'm using the most recent kernel (3.16.7). Whenever I try to poweroff, shutdown or reboot it freezes on my desktop or when I shut down with Firefox open, it freezes on a blank Firefox page.All ways of shutting down I know do this(systemctl poweroff, systemctl reboot, shutdown -h now, shutdown -r now), however about once every five times it doesn't freeze, which I find strange.I'm dual booting Fedora 20 with Windows 8.1 and I don't have this problem on Windows.
Fedora 20 freezes on reboot and shutdown
fedora;freeze
null
_softwareengineering.203829
We have a point-of-sale system that was developed using ado.net, our current concern is to make the application real fast in creating transactions (sales). Usually there are no performance concerns with high end PCs but with with low end PCs, the transactions take really slow.The main concern is on saving transactions which usually calls a lot of stored procedures for inserting records within a single transaction. This usually takes time on low end PCs. We need to improve the performance since most clients will only use low end PCs to act as cashier machines. One solution we are thinking is to use entity framework for data access. The entire project is written using ado.net and development time if we shift to entity framework would be alot. Any suggestions?
ado.net or EF for a point-of-sale system
c#;sql server;entity framework;ado.net
I would like to point out that Entity Framework (full name: ADO.NET Entity Framework) is an ORM (Object Relational Mapper) that uses ADO.NET under the hood for connecting to the database. So the question should we use ADO.NET or EF? doesn't really make sense in that respect. Unless you re-architect your application, adding EF to the mix is simply adding another layer on top of ADO.NET. I sincerely doubt that ADO.NET is the source of your performance problems, however. It sounds like the problem exists in your stored procedures themselves. I think Luc Franken's comments are on the right track, though. You need to measure and determine exactly where the delays are happening. Then concentrate on fixing exactly that problem. Anything else is groping around in the dark.
_webmaster.68589
Is it possible to force browser to not using cache and download all files (html/js/css) every time?I am looking for a server side solution.
How to force browser to download all static files every time?
server;cache;browsers
null
_unix.36281
I've read here that it's possible for any app using the X server to sniff keystrokes to any other app which is also using the X server, including su (on a terminal) or gksu. I've heard of a few ways to make the X server secure like Xephyr, but I'm not sure which one to use. I just want to prevent any app like xinput from easily sniffing the keystrokes when I'm typing a password in the terminal or gksu. I'm currently using Debian sid.
How do I prevent programs from sniffing keystrokes to su/gksu?
debian;security;x11
null
_softwareengineering.71510
In this paper, it is recommended that one document the following:module structuremodule interfacesIf I'm writing detailed module structures and interfaces in a standalone document, aren't I repeating work that is also done with object declaration statements, unit tests, and docstrings?If so, and if this is bad repetition in the DRY sense of the term, how do professional programmers avoid this kind of repetition?Automatically generate tests/docstrings/code from documentation?Automatically generate documentation from tests/docstrings/code?Rely on the code as documentation and don't duplicate in the first place?Suck it up, Nancy! It's called work for a reason.
How do I follow DRY when documenting module structure and interfaces?
documentation;documentation generation
Automatically generate documentation from tests/docstrings/codeCorrect.Find a tool that fits your language and creates documentation from comments embedded in the code.
_codereview.147865
I have written the below to populate/create tables (t_) from all of the corresponding views (v_) in my database. I converted a previous script from using a cursor to improve running speed. Is there anything else I can do to make this more performant.Any help is appreciated.Please see code below.USE [Database]GO/****** Object: StoredProcedure [dbo].[P_populate_tables_from_views] Script Date: 22/11/2016 16:15:17 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[P_populate_tables_from_views] @dropTables BITASDECLARE @viewName NVARCHAR(100);DECLARE @formattedTableName NVARCHAR(100);DECLARE @dropTableSql NVARCHAR(MAX);DECLARE @viewId intSET @viewId = (SELECT MIN(object_id) FROM sys.views)WHILE @viewId IS NOT NULLBEGINSET @viewName = (SELECT name FROM sys.views where object_id = @viewId)PRINT 'Time: ' + CONVERT(varchar, SYSDATETIME(), 121)PRINT('Processing ' + @viewName)SET @formattedTableName = REPLACE(@viewName,'v_','t_');IF @dropTables = 1BEGIN SET @dropTableSql = 'IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '''+@formattedTableName+''')) DROP TABLE '+@formattedTableName EXEC (@dropTableSql);ENDIF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @formattedTableName)) BEGIN EXEC('TRUNCATE TABLE '+@formattedTableName) EXEC('INSERT INTO '+@formattedTableName +' SELECT * FROM '+ @viewName) END ELSE BEGIN EXEC ('SELECT * INTO '+@formattedTableName+' FROM '+@viewName); ENDSET @viewId = (SELECT MIN(object_id) FROM sys.views WHERE object_id > @viewId)END
SQL Procedure to populate or create tables from views - performance issues
performance;sql;cursor
null
_cs.49482
I want to find the minimal period of any state of an LFSR (except the initial state of all zeroes) whose characteristic polynomial is the product of two primitive polynomials.In particular, $f(x),g(x) \in GF(2)[x]$ are primitive polynomials of order $n$, and the characteristic polynomial of the LFSR is given by:$$c(x)=f(x)g(x).$$What is the minimal period of any state of this LFSR, other than the all-zeros state? I've tried to say that if $c(x)$ is a product of two primitives then it has a period of$$\pi=2^{2n}-1 $$but my math gets me to$$\pi =2^{n+1}-2$$What did I do wrong?
Periods of an LFSR with characteristic polynomial that is a product of primitive polynomials
polynomials;pseudo random generators
The states of a LFSR with characteristic polynomial $p(x)$ correspond to elements of the multiplicative group of $GF(2)[x]/(p(x))$. The period of a LFSR state is the order of the corresponding group element. So, we can rephrase this as a group theory question, and use facts we know from group theory to answer the question.The LFSR state with minimal period is exactly the group element $g \in G$ with minimal order, where here $G_c$ is the multiplicative group of $GF(2)[x]/(c(x))$.The LFSR state with minimal period (other than the all-zeros state) is the group element with minimal order (other than the identity element).Thus, to find the minimal period you want, you need to find the order of the minimal-order group element of $G_c$ (other than the identity element $1$).Assuming $f,g$ have no common factor (i.e., $f\ne g$), the structure of $G_c$ is $G_c \cong G_f \times G_f$, where $G_f$ is the multiplicative group of $GF(2)[x]/(f(x))$ and $G_g$ is the multiplicative group of $GF(2)[x]/(g(x))$. This follows from an analog of the Chinese remainder theorem.Let $g_1$ be the group element of minimal order in $G_f$, and $g_2$ the group element of minimal order in $G_g$. From what we know about the structure of $G_c$, the group element of minimal order in $G_c$ is either $(g_1,1)$ or $(1,g_2)$. So it suffices to find the group elements of minimal order in $G_f$ and $G_g$.From the fact that $f$ and $g$ are primitive, we know that $G_f,G_g$ are cyclic groups of order $2^{n_f}-1$, $2^{n_g}-1$, respectively, where $n_f = \deg f$ and $n_g = \deg g$. Per Lagrange's theorem, we know that the divisors of $2^n-1$ correspond to the orders of the group elements of $G_f,G_g$.Let $d_f$ be the smallest divisor of $2^{n_f}-1$ (such that $d_f>1$), and similarly for $d_g$. Then the group element of minimal order in $G_f$ will have order $d_f$, and the group element of minimal order in $G_g$ will have order $d_g$. It follows that the group element of minimal order in $G_c$ will have order $d=\min(d_f,d_g)$, and the LFSR state of minimal period will have period $d$.So, the answer to your question is: the minimal period (other than the all-zeros state) is exactly $\min(d_f,d_g)$ where $d_f$ is the smallest divisor of $2^{\deg f}-1$ (other than 1) and $d_g$ is the smallest divisor of $2^{\deg g}-1$ (other than 1).
_cstheory.27215
The question on cstheory What is NP restricted to linear size witnesses? asks about the class NP restricted to linear size $O(n)$ witnesses, butAre there natural NP-complete problems in which (yes) instances of size $n$ require witnesses of size greater than $n$?Clearly we can build artificial problems like:$L = \{ 1^nw \mid w \text{ encodes a satisfiable formula and } |w|=n \}$$L = \{ \varphi \mid \varphi \text{ is SAT formula with more than } |\varphi|^2 \text{ satisfying assignments}\}$After a quick look at G&J, every natural NPC problem seems to have witnesses (strictly) smaller than $n$.Is there a reason/explanation for it ?
Natural NP-complete problems with large witnesses
cc.complexity theory;np;proof complexity
null
_unix.290443
I am currently having a strange issue and it doesn't really match anything I have found here so I am hoping someone can shed some light on my issue for me.I am currently running an Ubuntu 14 linux server. That server acts as a CDN for real estate property images for my website. I used upstart to create a script which respawns a PHP image batcher script. The image batcher script and everything is running just fine. It connects to the database, selects a new property, creates a directory for the images, and downloads the images as expected.The problem I am having is since the PHP file is in essence being called by root (since it runs as a service) all new image directories being created are owned by root instead of my ApachedUser:ApacheGroup.The main issue with this is if for some reason an image download stops in the middle and doesn't grab all of its images, it won't let me go back in and download the remaining images since the folder is owned by root and not the apache user.Things I have already done:chown -R $user:www-data /var/www/images.domain.com/chmod g+s /var/www/images.domain.comsetfacl -Rdm d:www-data:rx /var/www/images.domain.com/From everything I have ready this should cause any new files / folders created by a script to be owned by by my apache user and group.From what I can tell however this is not the case. If I upload a file of any type to any folder under /var/www/images.domain.com it is owned by the FTP user and the group is set as the FTP user as well. My FTP User and Group defaults to the same as what apache should be.Essentially I just need any file / folder under my /var/www/images.domain.com directory to be owned by $user:www-data by default, even for scripts that may be run by root.Any thoughts or help would be greatly appreciated.
Folder Permissions Issue
permissions;acl
null
_vi.7258
This drives me crazy, I do :set ft=textTo see something, otherwise all the links disappear in markdown and quotes in JSON.How do disable this once and for all?
How do I prevent vim from hiding symbols in markdown and json?
syntax highlighting
(guessing here, please provide a screenshot/more information)You may want to change your conceallevel setup::h 'conceallevel''conceallevel' 'cole' *'conceallevel'* *'cole'* number (default 0) local to window {not in Vi} {not available when compiled without the |+conceal| feature} Determine how text with the conceal syntax attribute |:syn-conceal| is shown: Value Effect ~ 0 Text is shown normally 1 Each block of concealed text is replaced with one character. If the syntax item does not have a custom replacement character defined (see |:syn-cchar|) the character defined in 'listchars' is used (default is a space). It is highlighted with the Conceal highlight group. 2 Concealed text is completely hidden unless it has a custom replacement character defined (see |:syn-cchar|). 3 Concealed text is completely hidden.
_codereview.59559
Scenario:I wanted a task scheduler/doer that enables my application to schedule some tasks to be executed in a specified time but in the same order they were scheduled in or depending on their priorities (DataFlow like). I also wanted it to enable the usage of C# 5 Async/Await functionality so I looked up over the Internet and didn't found something the truly fit my needs so I decided to implement one... a simple yet advanced (in my opinion) task scheduler that exactly achieved what I want. However, I want to improve it by hearing your opinions about it.Implementation:1) Scheduler Classusing System;using System.Collections.Generic;using System.Linq;using System.Threading;using System.Threading.Tasks;namespace ATScheduler{ public abstract class Scheduler { #region Fields private readonly TimeSpan _baseInterval; private readonly TimeSpan _executionTimeOut; private readonly List<IJob> _jobs; private readonly object _sync; private readonly Timer _timer; private bool _paused; #endregion #region Constructors protected Scheduler() { _jobs = new List<IJob>(); _sync = new object(); _baseInterval = TimeSpan.FromMilliseconds(12000); _executionTimeOut = TimeSpan.FromMilliseconds(30000); _timer = new Timer(ProcessJobs, null, Timeout.Infinite, Timeout.Infinite); } #endregion #region Methods public abstract Task JobTriggered(IJob job); public abstract Task JobException(IJob job, Exception exception); private void ProcessJobs(object state) { lock (_sync) { IJob[] jobsToExecute = (from jobs in _jobs where jobs.StartTime <= DateTimeOffset.Now && jobs.Enabled orderby jobs.Priority select jobs).ToArray(); if (jobsToExecute.Any()) { foreach (IJob job in jobsToExecute) { try { JobTriggered(job).Wait(_executionTimeOut); } catch (AggregateException exception) { JobException(job, exception).Wait(_executionTimeOut); } if (job.Repeat) { job.StartTime = DateTimeOffset.Now.Add(job.Interval); } else { _jobs.Remove(job); } if (_jobs.Count <= 0 || _paused) { _timer.Change(Timeout.Infinite, Timeout.Infinite); } else { _jobs.Sort((first, second) => first.StartTime.CompareTo(second.StartTime)); TimeSpan delay = _jobs[0].StartTime.Subtract(DateTimeOffset.Now); long dueTime = Math.Min(Math.Max(100, (long)delay.TotalMilliseconds), (int)_baseInterval.TotalMilliseconds); _timer.Change((int)dueTime, Timeout.Infinite); } } } } } public void PauseScheduler() { if (!_paused) { _paused = !_paused; } } public void ResumeScheduler() { if (_paused) { _paused = !_paused; } } public void AddJob(IJob job) { _jobs.Add(job); _jobs.Sort((first, second) => first.StartTime.CompareTo(second.StartTime)); TimeSpan delay = _jobs[0].StartTime.Subtract(DateTimeOffset.Now); long dueTime = Math.Min(Math.Max(100, (long)delay.TotalMilliseconds), (int)_baseInterval.TotalMilliseconds); _timer.Change((int)dueTime, Timeout.Infinite); } public Task<T> AddJob<T>(IJob<T> job) { if (job.Repeat) { throw new Exception(Repeatable jobs can't be awaited!); } _jobs.Add(job); _jobs.Sort((first, second) => first.StartTime.CompareTo(second.StartTime)); TimeSpan delay = _jobs[0].StartTime.Subtract(DateTimeOffset.Now); long dueTime = Math.Min(Math.Max(100, (long)delay.TotalMilliseconds), (int)_baseInterval.TotalMilliseconds); _timer.Change((int)dueTime, Timeout.Infinite); return job.TaskCompletionSource.Task; } public void RemoveJob(IJob job) { _jobs.RemoveAll(x => x.Equals(job)); } #endregion }}2) IJob Interfaceusing System;using System.Threading.Tasks;namespace ATScheduler{ public interface IJob { TimeSpan Interval { get; } DateTimeOffset StartTime { get; set; } int Priority { get; } bool Repeat { get; } bool Enabled { get; set; } } public interface IJob<T> : IJob { TaskCompletionSource<T> TaskCompletionSource { get; set; } void Return(T result); }}3) How to use:using System;using System.Threading.Tasks;using ATScheduler;namespace AdvancedScheduler{ internal class Program : Scheduler { private static void Main() { Console.WriteLine(- Advanced yet simple Flow Task Scheduler!); Console.WriteLine(); new Program().DoApplication(); Console.Read(); } private async void DoApplication() { AddJob(new SimpleJob()); AddJob(new SimpleUndefinedJob()); Console.WriteLine(Awaitable job returned: {0}, await AddJob(new SimpleAwaitableJob())); } public override async Task JobTriggered(IJob job) { if (job is SimpleJob) { await Task.Delay(1); //or time consumable task. Console.WriteLine(Simple Job executed for {0} times, ((SimpleJob)job).ExecutionCounter); ((SimpleJob)job).ExecutionCounter++; } else if (job is SimpleAwaitableJob) { ((SimpleAwaitableJob) job).Return(5); } else { throw new Exception(Undefined Job!); } } public override async Task JobException(IJob job, Exception exception) { Console.WriteLine({0} threw an exception of {1}, job.GetType().Name, exception.InnerException.Message); } private class SimpleAwaitableJob : IJob<int> { public SimpleAwaitableJob() { Priority = 1; Repeat = false; Enabled = true; TaskCompletionSource = new TaskCompletionSource<int>(); Interval = TimeSpan.FromSeconds(5); StartTime = DateTime.Now; } public TimeSpan Interval { get; private set; } public DateTimeOffset StartTime { get; set; } public int Priority { get; private set; } public bool Repeat { get; private set; } public bool Enabled { get; set; } public void Return(int result) { TaskCompletionSource.SetResult(result); } public TaskCompletionSource<int> TaskCompletionSource { get; set; } } private class SimpleJob : IJob { public SimpleJob() { Priority = 0; Repeat = true; Enabled = true; Interval = TimeSpan.FromSeconds(5); StartTime = DateTime.Now.AddSeconds(10); } public TimeSpan Interval { get; private set; } public DateTimeOffset StartTime { get; set; } public int Priority { get; private set; } public bool Repeat { get; private set; } public bool Enabled { get; set; } //We can extend it! public int ExecutionCounter { get; set; } } private class SimpleUndefinedJob : IJob { public SimpleUndefinedJob() { Priority = 2; Repeat = false; Enabled = true; Interval = TimeSpan.FromSeconds(5); StartTime = DateTime.Now; } public TimeSpan Interval { get; private set; } public DateTimeOffset StartTime { get; set; } public int Priority { get; private set; } public bool Repeat { get; private set; } public bool Enabled { get; set; } }}}
Flow Task Scheduler
c#;multithreading;scheduled tasks
null
_webapps.107594
Since the transition at the end of June 2017, my previously displayed chat contacts in the desktop Gmail interface have not appeared. Now, I am presented with a large empty space that the contacts list used to occupy that invites me to make a call:I can utilize https://hangouts.google.com/ and Hangouts on my mobile device works as expected. However, I utilize the desktop client for a majority of the day.Is there a way I can restore my chat contacts to this side bar in Gmail on my desktop?
Since the transition from Google Chat to Hangouts, I don't see chat messages in Gmail. Can I restore those?
google hangouts
null