id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_cs.23215
I'm trying to work through various exercises in Skiena's Algorithm Design Manual. One problem that I am stuck on is as follows:What value is returned by the following function? Express your answer as a function of n. Give the worst-case running time using Big Oh notation.function conundrum(n) r:=0 for i:=1 to n do for j:=i+1 to n do for k:=i+j-1 to n do r:=r+1 return(r)My first attempt at this problem began with trying to solve it when $n$ is even and my first observation was that $r$ is never incremented for any value of $i$ greater than $n/2$ (I am assuming that a statement along the lines of $k:=l$ to $n$ is not executed for any $l>n$. Indeed, upon working out the above function for several different values of $n$, I thought that I could intuit that the sum calculated by the function had the following form $\sum_{p=1}^{n/2}\sum_{q=1}^{2p-1}q$-- to intuit this, I began the first loop at $i=n/2$ and worked backwards. Working this sum out, I got $\frac 1 {24} n(n(2n-3)-26)$. To my dismay, upon checking this answer, I found that the correct answer for even $n$ is $\frac 1 {24} n(n+2)(2n-1)$. Any thoughts or hints about what I am doing wrong?
Complexity of a nested for loop
algorithm analysis;runtime analysis;loops
null
_codereview.46395
Let's say I need to write a function that applies a function to each item in a List, and then appends it to an accumulator. When the List is empty, return the accumulator.go :: [a] -> (a -> [b]) -> [b] -> [b]go [] f acc = accgo (x:xs) f acc = go xs f (acc ++ f x)myFold :: [a] -> (a -> [b]) -> [b]myFold as f = go as f []I used the go function so that I wouldn't force the myFold caller to have to provide an empty [b] type. Also, I used the go function to achieve tail recursion. In Scala, I would've put @annotation.tailrec to make the compilation fail if the compiler could not perform tail-call optimization.Is the above code idiomatic in Haskell?
Implement a fold-like Function in Haskell
haskell
null
_unix.261131
I'm using Raspbian jessie (ubuntu).I made a .sh that makes a backup .img of everything (excluding mnt, tmp, run, dev, boot, etc.) and let this run once a week with crontab. It checks for modified files and only copies those. This is very useful I find since there is no need to make a big, full backup of everything, every time anew. This works perfectly. The .sh contains following command:sudo rsync -aAHvpE --delete-during --exclude-from=/etc/rsync-exclude.txt / /mnt/usb0/backup/partition2However, after checking the backup I noticed it still contained a file that I had already deleted on my original system. For example the file /test.txt was backed up to /mnt/usb0/backup/partition2/test.txt , however after deleting the original and making a new backup it didn't disappear on the backup.Now my question is: what ways are there to check for files that don't exist in the original folder anymore, then delete those in my backup folder too? (WITHOUT having to delete everything first and then make a full backup from scratch).
Comparing original & backup folder, then deleting non-existing files
shell;shell script;rsync
null
_unix.101429
I recently bought a Raspberry Pi. I already have configured it, and I install a cross compiler for arm on my desktop (amd64). I compiled a simple hello world program and then I copy it from my desktop to my Pi with scp ./hello [email protected]:~/hello.After login in my Pi I run ls -l hello and I get a normal response:-rwxr-xr-x 1 david david 6774 Nov 16 18:08 helloBut when I try to execute it, I get the following:david@raspberry-pi:~$ ./hello-bash: ./hello: No such file or directorydavid@raspberry-pi:~$ file hellohello: ELF 32-bit LSB executable, ARM, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.26, BuildID[sha1]=0x6a926b4968b3e1a2118eeb6e656db3d21c73cf10, not strippeddavid@raspberry-pi:~$ ldd hello not a dynamic executable
No such file or directory when executing a cross-compiled program on a Raspberry Pi
compiling;executable;raspberry pi;arm
If ldd says it is not a dynamic executable, then it was compiled for the wrong target.Obviously you did cross-compile it, as file says is a 32-bit ARM executable. However, there's more than one ARM architecture, so possibly your toolchain was configured incorrectly.If you are using crosstool-NG, have a look at the .config for the value of CT_ARCH_ARCH. For the raspberry pi, it should be armv6j1 -- or at least, that's what's working for me. There are other specifics, but I think that should be enough. Unfortunately, if it's wrong, you now have to rebuild.IMO getting a cross-compiler toolchain to work can be tedious and frustrating, but, presuming the host is not a significant factor (it shouldn't be), in this case it can be done. Crosstool-ng uses a TLI configurator, so if you end up having to try multiple builds, write down your choices each time so you know what worked.1 I believe armv7 is a much more common arch (lots of phones and such), so if you are just using something you believe is a generic ARM cross-compiler, that's probably the issue. These numbers are confusing as, e.g., the pi's processor is an ARM11, but (as per that page), the ARM11 family of processors uses the ARMv6 architecture -- i.e. ARM11 is an implementation of ARMv6.
_unix.360013
Of the user, system, and idle readings provided by top, which would reflect the time spent in a blocking system call?I have read that blocking disk i/o calls are reflected as idle time, but not so for blocking network i/o calls. But then where?
Where does a blocking system call show up in CPU readings?
top;system calls
null
_softwareengineering.260067
I want to know how whileTrue: works. I searched the implementation that is in BlockClosure:whileTrue: aBlock ^ [self value] whileTrue: [aBlock value]And another implementation with no parameter:whileTrue ^ [self value] whileTrue: []But I don't know how that works, that's a recursive method, but this led me to ask several questions:How does this recursive call terminate?If [self value] returns a Boolean object, why is whileTrue: not implemented in the Boolean type?Why is there another implementation named whileTrue that just do not receive any block and evaluates self?
How does whileTrue: works in Smalltalk?
smalltalk
whileTrue: is inlined by the compiler, that's why you don't see the actual implementation. Here's the comment out of Pharo:Ordinarily compiled in-line, and therefore not overridable. This is in case the message is sent to other than a literal block. Evaluate the argument, aBlock, as long as the value of the receiver is true.If you look at the byte code of #whileTrue: you'll see that the compiler simply uses a jump to make the loop:17 <70> self18 <C9> send: value19 <9C> jumpFalse: 2520 <10> pushTemp: 021 <C9> send: value22 <87> pop23 <A3 F8> jumpTo: 17 <---- here's the jump25 <7B> return: nil#whileTrue is also inlined directly (slightly optimized byte code).The inlining is also the reason why there's no implementation of this on Boolean (apart from the fact that there's no point in reevaluating a boolean...).#whileTrue is there so that you can easily create endless loops the only terminate e.g. when the process terminates, a semaphore is signaled, an exception occurs etc.
_datascience.13417
What are good films for teaching data-driven decision making? In one of my classes, I asked my students to watch Moneyball at home and we discussed it in the class. It was successful and they learned much more than they could by reading a chapter of a textbook.Are there films with similar theme suitable for my purpose?
What are good films for teaching data-driven decision making? (like Moneyball)
beginner;reference request
null
_codereview.80457
Everything you need to do OOP in one neat little package without having to do all the work by hand. Almost like C++.Here is how you would use it:var A = Object.extend(A, {static : {counter_start : 5 // all static propertiers and methods should // be initialized ,get_counter : function () { var cnt = this.counter_start; this.get_counter = function () { return ++cnt; }; return cnt; } } ,public : {a_public_property_of_A : (This value does not matter. It will be +initialize with undefined before the constructor is called.) ,constructor : function (a, other) { this.id(A.get_counter()); this.a_public_property_of_A(a); } ,$virtual_method : function () {return this.a_public_property_of_A(); } ,print : function () { console.message(The value is +this.virtual_method()); } } //,protected : {} ,private : {id : does not matter } });var B = A.extend(B, {//static : {}, public : {base_constructor_arguments : function () { var arg_A = [arguments[0], other]; return arg_A; } ,constructor : function (b) {} ,$virtual_method : function () {return this.a_public_property_of_A() * 100; } } //,protected : {} //,private : {} });// *// * - Example of object instantiation:var a = (new A(3)).constructor();a.print();var b = (new B(5)).constructor();b.print();b.$uper.print();var old_val = b.a_public_property(); // getting a propertyvar new_val = b.a_public_property(1000); // setting a propertyconsole.log(the old value is +old_val);console.log(the new value is +new_val);Here are a few of the members shared by all objects:instance_of(_class)cast_to(_class)dynamic_cast(_class)type_info_name()clone()$uper Any idea on what could be missing? Or suggestion on how to improve it?Here is the up-to-date code and here is a copy:(function _Package_MyJOOP_ (global) { /* ********************************************filename: MyJOOP.js version 1.0Copyright 2015 Dominique FortinLicensed under the Apache License, Version 2.0 (the License);you may not use this file except in compliance with the License.You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an AS IS BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License. * * Caracteristic of MyJOOP (my Javascript Object Oriented Programming) * * - No method overloading. * - Single inheritence. * - All protected properties and methods must be prefixed with P$. to be * used (ex. this.P$.a_property). The protected space is seperate from the * public and private space (i.e. you can have two different property, one * in the public space and one in the protected space, with the same name, * but it is not recommended). * - Private properties and methods hide public ones, but not protected ones. * All private properties and methods are shared within one class level. If * you do this.a_property_not_defined = ({some_expression}); and * a_property_not_defined was not defined in any definition (public, * protected or private), it will be added as a pravate properties that only * exists in this instance of the class. * - It is possible access only public properties and methods by prefixing * with public. (ex. this.public.a_property). * - Virtal methods name must be prefixed $ in the definition. You acces a * virtual version of the method by not prefixing with $ (ex. * this.a_virtual_method(); ). To acces the original method use the $ * prefix (ex. this.$a_virtual_method(); ). * - Lower level class properties and methods can be accessed with the * prefix $uper.. * - Lower level static class properties and methods can be accessed with the * prefix $uperClass.. * - Base class constructor is called before the current level class * constructor,like in C++. The creation of an object is done calling the * constructor functon after the new function (ex. var o = * (new myClass(param1 , param2 , ...)).constructor(); ) * * - Example of class creation:* / var A = Object.extend(A, {static : {counter_start : 5 // all static propertiers and methods should // be initialized ,get_counter : function () { var cnt = this.counter_start; this.get_counter = function () { return ++cnt; }; return cnt; } } ,public : {a_public_property_of_A : (This value does not matter. It will be +initialize with undefined before the constructon is called.) ,constructor : function (a, other) { this.id(A.get_counter()); this.a_public_property_of_A(a); } ,$virtual_method : function () { return this.a_public_property_of_A(); } ,print : function () { console.log(The value is +this.virtual_method()); } }// ,protected : {} ,private : {id : does not matter } }); var B = A.extend(B, {//static : {}, public : {base_constructor_arguments : function () { var arg_A = [arguments[0], other]; return arg_A; } ,constructor : function (b) {} ,$virtual_method : function () { return this.a_public_property_of_A() * 100; } }// ,protected : {}// ,private : {} }); * * - Example of object instanciation: var a = (new A(3)).constructor(); a.print(); var b = (new B(5)).constructor(); b.print(); b.$uper.print(); var old_val = b.a_public_property_of_A(); // getting a property var new_val = b.a_public_property_of_A(1000); // setting a property console.log(the old value is +old_val); console.log(the new value is +new_val); *************************************************************************/ if (global.Object.extend) { if (typeof console !== 'undefined' && typeof console.warn === 'function') { console.warn('The function extend is already defined in the Object class. ' +'This framework is going to overwrite it.'); } } var local_context = this; function _extend_class(Base_class, new_class_name, new_class_definitions) { if (typeof Base_class !== 'function') throw The base class must be a function.; if (typeof new_class_definitions !== 'object') throw The new class definition must be an object.; if (new_class_definitions.public && typeof new_class_definitions.public !== 'object') throw The new class public definition must an object.; if (new_class_definitions.protected && typeof new_class_definitions.protected !== 'object') throw The new class protected definition must an object.; if (new_class_definitions.private && typeof new_class_definitions.private !== 'object') throw The new class private definition must an object.; if (new_class_definitions.static && typeof new_class_definitions.static !== 'object') throw The new class static definition must an object.; var _New_class = function _class () { var args = Array.prototype.slice.call(arguments, 0); this.constructor = function _const_ () { var contx = _initialize.call(_New_class.prototype, args); return contx.public; }; }; _New_class.class_name = new_class_name; _add_extend(_New_class); if (new_class_definitions.static) { _transfer_static_properties.call(_New_class, new_class_definitions.static); } _New_class.prototype = Object.create(Base_class.prototype); _New_class.prototype.constructor = _New_class; _New_class.prototype.$uperClass = Base_class.prototype; _New_class.prototype.public = new_class_definitions.public || {}; _New_class.prototype.protected = new_class_definitions.protected || {}; _New_class.prototype.private = new_class_definitions.private || {}; return _New_class; } function _initialize(args, to_clone) { if (this === global.Object.prototype) { return {base: undefined ,public: global.Object.prototype ,state: {P$: global.Object.prototype} }; } var local_class = this.constructor; var local_proto = this; var contx = {}; var base_args = []; if (this.public.base_constructor_arguments) { if (typeof this.public.base_constructor_arguments !== function) throw The base_constructor_arguments must be a function.; base_args = this.public.base_constructor_arguments.apply({}, args || []); if (! (typeof base_args === object && base_args instanceof Array)) throw The base_constructor_arguments function must returned an Array.; } contx.base = _initialize.call(this.$uperClass, base_args, (to_clone ? to_clone.base : undefined)); contx.public = global.Object.create(contx.base.public); contx.state = global.Object.create(contx.public); contx.state.P$ = global.Object.create(contx.base.state.P$); contx.public.$uper = contx.base.public; contx.state.public = contx.public; contx.state.P$.$uper = contx.base.state.P$; _set_ref(); _create_class_members.call(contx.public, this.public, contx.state); _create_class_members.call(contx.state, this.private, contx.state); _create_class_members.call(contx.state.P$, this.protected, contx.state); var vmethods = {}; var P$_vmethods = {}; if (local_proto.$uperClass.hasOwnProperty(vmethods)) vmethods = local_proto.$uper.vmethods; if (local_proto.$uperClass.hasOwnProperty(P$_vmethods)) P$_vmethods = local_proto.$uper.P$_vmethods; local_proto.vmethods = _correct_virtual_methods(vmethods, contx.public); local_proto.P$_vmethods = _correct_virtual_methods(P$_vmethods, contx.state.P$); _percolate_virtual_methods({}, contx.public); _percolate_virtual_methods({}, contx.state.P$); if (to_clone) { _overwrite_properties(contx.public, to_clone.public); _overwrite_properties(contx.state, to_clone.state); _overwrite_properties(contx.state.P$, to_clone.state.P$); } contx.public.instance_of = function _instance_of_ (_class) { return (local_class === _class) || (contx.base.public.instance_of && contx.base.public.instance_of(_class)) || false; }; contx.public.cast_to = function _cast_to_ (_class) { if (local_class === _class) return contx.public; if (contx.base.public.cast_to) return contx.base.public.cast_to(_class); return null; }; contx.public.dynamic_cast = function _dynamic_cast_ (_class) { var c = contx.public.cast_to(_class); if (c === null) c = contx.ref.cast_to(_class); return c; }; contx.public.type_info_name = function _type_info_name_ () { return local_class.class_name; }; contx.public.clone = function _clone_ () { var local_contx = _initialize.call(local_proto, undefined, contx); return local_contx.public; }; if (this.public && this.public.hasOwnProperty(constructor) && !to_clone) { this.public.constructor.apply(contx.state, (args || [])); } return contx; function _set_ref() { var ctx = contx; while (ctx.base) { ctx.ref = contx.public; ctx = ctx.base; } } } function _correct_virtual_methods (vmethods_list, obj) { var my_list = {}; for (var vmn in vmethods_list) { if (vmethods_list.hasOwnProperty(vmn)) { my_list[vmn] = undefined; if (obj.hasOwnProperty(vmn)) { if (typeof obj[vmn] !== 'function') throw vmn+ must be function.; if (obj.hasOwnProperty('$'+vmn)) throw Too many definition for +vmn; obj['$'+vmn] = obj[vmn]; obj[vmn] = undefined; } } } for (var pn in obj) { if (obj.hasOwnProperty(pn) && typeof obj[pn] === 'function' && pn.charAt('0') === '$') { var vmethode_name = pn.substr(1); if (obj.hasOwnProperty(vmethode_name)) throw Too many definition for +vmethode_name; if (!vmethods_list.hasOwnProperty(vmethode_name)) { vmethods_list[vmethode_name] = undefined; } } } return my_list; } function _percolate_virtual_methods (vmethods, obj) { if (obj === global.Object.prototype) { return; } for (var pn in obj) { if (typeof obj[pn] === 'function' && pn.charAt('0') === '$') { var vmethode_name = pn.substr(1); if (!vmethods.hasOwnProperty(vmethode_name)) { vmethods[vmethode_name] = obj[pn]; } } } for (var mn in vmethods) { if (obj.hasOwnProperty('$'+mn)) { obj[mn] = vmethods[mn]; } } _percolate_virtual_methods(vmethods, obj.$uper); } function _is_keyword(name) { return name === constructor || name === base_constructor_arguments || name === private || name === public || name === P$ || name === protected || name === instance_of || name === cast_to || name === clone || name === extend || name === '$uperClass' || name === $uper; } function _create_class_members(definition, state) { for (var pn in definition) { if (definition.hasOwnProperty(pn) && !_is_keyword(pn)) { var prop = definition[pn]; if (typeof prop === function) { this[pn] = _bind_method(prop, state); } else { if (pn.charAt(0) === $) throw 'The '+pn+' property name connot start with an $.' this[pn] = (function () { var mem; return function _property_accessor_ () { if (arguments.length >= 1) { mem = arguments[0]; } return mem; }; })(); } } } } function _transfer_static_properties(definition) { for (var pn in definition) { if (definition.hasOwnProperty(pn) && !_is_keyword(pn) && !this.hasOwnProperty(pn)) { this[pn] = definition[pn]; definition[pn] = undefined; delete definition.pn; } } } function _bind_method(method, state, args) { return function () { var args2 = Array.prototype.slice.call((args || arguments), 0); return method.apply(state, args2); }; } function _overwrite_properties(dest, sour) { for (var pn in sour) { if (sour.hasOwnProperty(pn) && !_is_keyword(pn)) { if (typeof sour !== function) { dest[pn] = sour[pn]; } } } } function _add_extend (_class) { _class.extend = function () { var args = _bind_method(Array.prototype.slice, arguments)(0); args.unshift(_class); return _extend_class.apply(local_context, args); }; } _add_extend(global.Object);})(window);
JavaScript OOP with virtual, private, protected and public members
javascript;object oriented
null
_codereview.134362
I'm creating a web page which has two types of users with very similar permissions: Person and Company. The main difference is in their attributes and probably different billing.I've created only one UserProfile for both types of users. What do you think? Is it safe? Should I expect some problems later because of this? The first problem I met is that I can't tell Django that if the user is a person, then username can't be blank and the same with company and company_name.class UserProfile(models.Model): user = models.OneToOneField(User, related_name='userprofile',on_delete=models.CASCADE) TYPE_OF_USER_CHOICES = (('company', 'Company'), ('person', 'Person')) type_of_user = models.CharField(max_length=40, choices=TYPE_OF_USER_CHOICES) IBAN = models.CharField(max_length=80, null=True) # PERSON username = models.CharField(max_length=20,blank=True,null=True) # COMPANY company_name = models.CharField(max_length=100,blank=True,null=True) ICO = models.CharField(max_length=30, blank=True, null=True, unique=True, help_text=u'Zadajte firemn IO alebo nechajte przdne') DIC = models.CharField(max_length=30, blank=True, null=True, unique=True, help_text=u'Zadajte firemn DI alebo nechajte przdne') @property def is_firm(self): return self.type_of_user == 'company' @property def is_person(self): return self.type_of_user == 'person' def __str__(self): if self.is_firm: return '{} - Company'.format(self.company_name) else: return '{} - Person'.format(self.username)
One user profile for company and person
python;mvc;django
null
_cs.28273
I'm looking around for a good garbage collection technique for my language and found this paper, where Benjamin Goldberg describes a garbage collection technique for strongly typed languages, which removes the need for type information during runtime.Briefly, this is done by placing a pointer to a garbage collection function right after a function call, directly in the compiled code. They then extend this to support ML-like parametric polymorphism.Now my question: Has there been any work on how this technique could be implemented in an object oriented language, where much functionality is implemented through indirect calls using pointers in a virtual table?
Tag-free garbage collection for object oriented languages
programming languages;compilers;memory management;empirical research;garbage collection
null
_unix.179067
On 2 partitions of my HD I have installed Debian 7.7 and Debian 7.8 (upgraded from 7.7). The first OS has suspend to ram or disk working, the latter not anymore.I made some tests, changing home and etc directories, without success. It seems that after restore, the HD is working, but the OS not (it's freezed?). The screen is black and the keyboard doesn't respond. CTRL ALT F1, CapsLock, NumLock don't work.s2ram and s2disk don't work too.I did think that it was related to some file in /etc/X11 directory or in /home, that's why I copied those from the working OS to the other.Can someone tell me what file suspend depends on? I could copy the right one from Debian 7.7 to 7.8.I cannot believe that a so small problem forces a user to reinstall Debian. What the difference from Windows?Thanks to all who will spend some time to resolve this very common issue.EDIT: I have KDE, GNOME, LXDE. The problem persists if I change Desktop Environment.EDIT After upgrading the kernel to 3.2.65-1+deb7u1 suspend works but not hibernate. I installed uswsusp package and now hibernate works.Thanks to all helping me to solve this annoying bug.
suspend doesn't work after upgrading to Debian 7.8
debian;suspend
This is probably a known regression with suspend in the current kernel of Debian 7.8. See this blog entry for more information and links.
_unix.365911
I want to edit an interface's VLAN tag on the fly. networksetup can create and delete VLAN interfaces. I can go this route if I have to but I would prefer editing the tag on an existing VLAN instead of constantly recreating it. Is there a way to do this?
Edit VLAN tag of an existing interface
networking;osx;network interface;vlan
null
_vi.10656
I have a file full of expressions like this:0.100000000000000000000*10^(1) 0.000000000000000000000*10^(0)0.911403977421716024142*10^(-15) 0.983917614423065751378*10^(-15)and I would like to evaluate each term and round the value to 2 decimal points to get:1.00 0.000.00 0.00Using bc -l on each token seperated by white space would accomplish the first step, but I don't know how to do this. Moreover, there is the issue with rounding.Any suggestions are welcome!FYI: There are three types of lines in the file. Those which are empty, those which contain a single integer and those which are of the form demonstrated above.
Evaluating and rounding a file of numbers in scientific form
regular expression;replace
You can use substitute feature with a submatch and system function like so:%s/\([^ ]\+\)/\=system('printf %.2f $(echo scale=2; ' . submatch(1) . ' | bc -l)')/g this performs a substitute on whole file (%).\([^ ]\+\) - matches every string stream which doesn't contain space.Then we replace all occurrences with an expression \= that's after it.system() runs shell script/command and returns it's output.printf %.2f $(echo scale=2; ' . submatch(1) . ' | bc -l) - submatch(1) returns result of our match - so every math expression and whole is processed as a shell command.
_opensource.3971
I want to know the following:Can open and closed exist in terms of a specific module being closed? What licences allow this?What licence is used for paid modules for, say, Prestashop?Can an open and closed source version of software exist in parallel? I imagine that code can't be ported from open source but perhaps the opposite is possible?What becomes of intellectual property? I imagine that the software becomes the property of the community.Can project analysis documents be packaged along with software on Github or should these be kept separate?What advice can you give in terms of the commercialization of associated services?Thanks in advance.
Can open source and closed source co-exist?
license compatibility;license recommendation;software;closed source
null
_softwareengineering.152266
Are symbolic programming and metaprogramming the same thing? I've always read about symbolic programming while using Mathematica, but I've never searched about it's meaning, I've searched about it today and I found that both concepts are similar, are there any differences?
Are symbolic programming and metaprogramming the same thing?
meta programming
null
_webapps.101611
Is it possible to index arrays in cognito forms?The only members that are shown in auto-complete drop-down of an array are .Length and .ToString().JavaScript allows inline indexing like the following:value = [0.5, 1.5, 2.5, 3.0][RatingScale.Question1_Rating]there are other ways like using multiple condition ? trueval : falseval statements but using arrays is much cleaner and allows for more complex computations.
Cognito forms: How to index arrays?
cognito forms
null
_unix.274334
I try to gzip a file abc.log which has size of 111 bytes, but after gzip, the size of the file increased to 125 bytes, why is that? Is it when i perform gzip, it will create header and trailer that has certain size?Command used:gzip -5 abc.log
Linux Gzip increasing size
compression;gzip
Not just gzip, but attempting to compress a file which is already as small as possible can increase the size (because each method for compression has some overhead in the form of header, tables, etc). This is also referred to as negative compression.Further readingWhat's the most that GZIP or DEFLATE can increase a file size?Why GZip compression increases the file size for some extension?Optimizing encoding and transfer size of text-based assets
_softwareengineering.260374
I use Unit of work pattern to commit all new, dirty, deleted entities to the DB (using a db_mapper).Example of entities are: Student and ClassSo Student->registerDirty() will add this entity to the dirty pool that will be saved to the DB when commit() will be called.My problem is that Student can also hold collection of classes (Student->getClasses) and I am not sure how to integrate this into the unit of work pattern so it will only commit the new, updated or deleted.Can any one recommend me how to integrate this?
How to save entities relations using unit of work pattern
design patterns;patterns and practices;unit of work
Simple : the collection of Classes will record what was added or removed and will commit those items accordingly.
_cogsci.5546
Do people with chromesthesia and tinnitus see the ringing caused by tinnitus?
Do people with chromesthesia and tinnitus see the ringing caused by tinnitus?
synesthesia
null
_cogsci.6241
Does taking SSRI and antipsychotic result in cognitive dysfunctions? What should happen to restore the Cognitive functions like problem solving skills, thinking, memory? What are the most effective ways either medication or program?
SSRI and Antipsychotic Effect on Cognitive Functions
cognitive psychology;cognitive neuroscience
null
_unix.324079
I used to work with Windows. When I wanted to stop using my laptop I only closed the lid and even if the Laptop runs out of battery, the state of the machine was saved. So, when I plugged to the AC the Laptop, I was able to continue working. But now I have Ubuntu 14.04 and when I close the lid and the Laptop runs out of battery, the Laptop is completely powered off. Even when I try to turn it on again the power button do not responds (in windows the LED used to tick 3-2 times as a signal of low batt.). So, I have to keep the power button pressed 5 times for completely shutting of the system in order to press the button again turn the PC on.What can I do? Can I enable some kind of automatic hibernation when the lid is closed and runs out of battery?
Ubuntu not hibernating after running out of battery when the lid is closed?
ubuntu;suspend;hibernate
null
_codereview.47749
I made this math script, where you enter an equation and it solves it for you. I was wondering what you thought of the code, and what I could have done better or what doesn't follow Ruby best practices. The code is also on Github here if you want to see the readme and how to use define_equation()#!/usr/bin/env rubyrequire readlinerequire cmath# PREFIXES = { -15 => f, -12 => p, -9 => n,# -6 => , -3 => m, 0 => ,# 3 => k, 6 => M, 9 => G,# 12 => T, 15 => P, 18 => E }def define_equation(file) File.foreach(file) { |line| name, var, equation = line.split(:) Equations.class_eval %[ def #{name}(#{var}) #{equation} end ] }enddef all_formulas (Equations.instance_methods(false) - [:method_missing]) .map { |i| i.to_s.gsub(/_/, -) }endclass Equations C = 3e8 def m_with_hz(frequency) C / frequency end alias_method :hz_with_m, :m_with_hz def qudrtc_frml_with_a_b_c(a, b, c) positive = (-b + CMath.sqrt(b ** 2 - 4 * a * c)) / 2 * a negative = (-b - CMath.sqrt(b ** 2 - 4 * a * c)) / 2 * a # possibly add positive and negative .to_r as well as the float [positive, negative] end def pythgrn_thrm_with_a_b(a, b) a = Math.sqrt(a ** 2 + b ** 2) a = sqrt(#{(a ** 2).round}) unless a.to_i == a a end def pythgrn_thrm_with_b_c(b, c) a = Math.sqrt(c ** 2 - b ** 2) a = sqrt(#{(a ** 2).round}) unless a.to_i == a a end def method_missing(m, *args, &block) That equation doesn't exist here. (yet) endendclass Cli attr_reader :equations def initialize @equations = Equations.new end def help [To use an equation, just type something like this: hz-with-m 100, Thats 100 meters, converted to hertz, Or something like this: pythgrn-thrm-with-b-c 4 5, That's a^2 = 5^2 - 4^2, or more familiarly, a^2 + 4^2 = 5^2, You also can use e for scientific notation. Eg. 3e5 = 300000, Type quit to quit, , Available Equations:, all_formulas] end def method_missing(m, *args, &block) # checks if it only contains numbers, math symbols, and e if args.all? { |arg| arg.match(/\A[\d+\-*\/.e ]+\z/) } args.map! { |arg| eval(arg) } @equations.send(m, *args) else Invalid number end end def quit exit endendcli = Cli.newcase ARGV[0]when -l, --load ARGV.shift define_equation(ARGV.shift) # I will add more stuff hereendif __FILE__ == $0 puts Type help for help. Readline.completion_append_character = Readline.completion_proc = proc { |s| all_formulas.grep(/^#{Regexp.escape(s)}/) } loop do command, *variables = Readline::readline(> , true) .downcase.strip.squeeze( ).split( ) unless command.nil? command.gsub!(/-/, _) puts begin cli.send(command, *variables) rescue ArgumentError argc = cli.equations.method(command).arity arg_list = (1..argc).map { |i| <number_#{i}> }.join( ) Usage: #{command} #{arg_list} end end endendHere are the tests:#!/usr/bin/env rubyrequire rubygemsgem minitestrequire minitest/autorunrequire minitest/prideload solvedescribe Equations do before do @equations = Equations.new end describe m_with_hz do it must return correct value do @equations.m_with_hz(300e12).must_equal 1.0e-06 @equations.m_with_hz(3e6).must_equal 100 end end describe hz_with_m do it must return correct value do @equations.hz_with_m(100e3).must_equal 3e3 @equations.hz_with_m(100.0e-12).must_equal 3e18 end end describe qudrtc_frml_with_a_b_c do it must return correct value do @equations.qudrtc_frml_with_a_b_c(1, 2, -3).must_equal [1.0, -3.0] end end describe pythgrn_thrm_with_a_b do it must return correct value do @equations.pythgrn_thrm_with_a_b(3, 4).must_equal 5 @equations.pythgrn_thrm_with_a_b(4, 5).must_equal sqrt(41) end end describe pythgrn_thrm_with_b_c do it must return correct value do @equations.pythgrn_thrm_with_b_c(4, 5).must_equal 3 @equations.pythgrn_thrm_with_b_c(3, 4).must_equal sqrt(7) end end describe equation does not exist do it must warn user do @equations.doesnt_exist(500).must_equal That equation doesn't exist here. (yet) end endenddescribe Cli do before do @cli = Cli.new @error_msg = Invalid number end describe an equation is ran do it must warn user if an invalid number is used do @cli.doesnt_matter(hello).must_equal @error_msg @cli.doesnt_matter(34five).must_equal @error_msg @cli.doesnt_matter(q12).must_equal @error_msg end it must work if a valid equation is ran do @cli.doesnt_matter(123.3).wont_equal @error_msg @cli.doesnt_matter(12e3).wont_equal @error_msg @cli.doesnt_matter(1e-4).wont_equal @error_msg end endenddescribe flags do describe --load do before do @cli = Cli.new end it must load equations do # in progress define_equation(sample_equations) end endend# write tests for importing equations
Math Equation Solver
ruby;mathematics;meta programming
There is a bug in your quadratic formula. Watch your operator associativity!I'm not a fan of the method names qudrtc_frml_with_a_b_c and pythgrn_thrm_with_a_b, and I think that the poor naming is a symptom of a poor class design.First of all, drpng vwls makes your interface hard for others to use. Learn from Ken Thompson's greatest regret.Next, I would remove formula and theorem from the method names. The caller generally doesn't care how you solve the quadratic equation whether you do it by using the quadratic formula, completing the square, etc. Similarly, the fact that there is a Pythagorean Theorem is unimportant; the focus should be on the subject of the Pythagorean Theorem, which is the right triangle.Third, I question the benefit of adding all of these unrelated equations as methods of one class.Finally, the suffixes _with_a_b and _with_b_c for your Pythagorean solver suggest that your solution is too rigid. It would be nice if the user could enter all but one of the variables as constraints, and ask the program to solve for the remaining unknown.I suggest the following design. It takes advantage of one of Ruby's strengths, which is the ability to craft a human-friendly domain-specific language.require 'cmath'class QuadraticEquation attr_writer :a, :b, :c, :x def x positive = (-@b + CMath.sqrt(@b ** 2 - 4 * @a * @c)) / (2 * @a) negative = (-@b - CMath.sqrt(@b ** 2 - 4 * @a * @c)) / (2 * @a) [positive, negative] end def a (-@b * @x - @c) / (@x ** 2) end def b (-@a * @x ** 2 - @c) / @x end def c -@a * @x ** 2 - @b * @x endendclass RightTriangle attr_writer :a, :b, :c def a Math.sqrt(@c ** 2 - @b ** 2) end def b Math.sqrt(@c ** 2 - @a ** 2) end def c Math.sqrt(@a ** 2 + @b ** 2) end alias :hypotenuse :c alias :hypotenuse= :c=endHere it is in use:irb(main):001:0> require 'formula'=> trueirb(main):002:0> triangle = RightTriangle.new=> #<RightTriangle:0x007fe14301f500>irb(main):003:0> triangle.hypotenuse = 5=> 5irb(main):004:0> triangle.a = 3=> 3irb(main):005:0> triangle.b=> 4.0
_unix.384494
I am having trouble understanding the difference between the EFI System Partition (ESP) and the linux /boot partition. Reading online tells me that /boot partition is going to contain the boot loader i.e. GRUB2. Then, if that's the case, and if I store GRUB on the ESP, then is it same as the /boot partition ?Or is it that GRUB2 is suppose to be stored on the ESP (something I have done before, and it worked) and the /boot partition is suppose to contain files for GRUB to find, typically files needed to be loaded before, let's say, an encrypted LVM is loaded.What are the difference between these two ?
EFI partition vs /boot partition
boot;partition;uefi;boot loader
null
_cstheory.32473
Almost the exact same question was asked here, but nobody proved or cited its #P-completeness! I found this question because I proved it is #P-complete (proof below), and the proof was trivial, but I couldn't find it anywhere on the web or in the discussion on that question! (One person commented I suspect it is #P-complete.) So either my proof is wrong, which you can judge for yourself, or the result is novel, which I would think is highly unlikely. Which is it?Proof:Consider the set of regular expressions formed by the union and concatenation of symbols from $(\Sigma\cup{.})$, where $\Sigma$ is an alphabet and $.$ is a symbol for any $l\in\Sigma$. I will show that #SAT reduces in $O(mn)$ time to counting the number of strings that satisfy such a regex, where $m$ is the number of clauses and $n$ is the number of variables in the given formula $\varphi$.The reduction is very simple. First, reduce #SAT to #UNSAT by noting that if $\varphi$ has $n$ variables, then $\#\text{SAT}(\varphi) = 2^n - \#\text{UNSAT}(\varphi)$. So now we have to count the number of falsifying assignments of the variables of $\varphi$.To falsify $\varphi$, it suffices to falsify just one clause. We therefore want to find $$\left|\bigcup \limits_{C\in\varphi}F(C)\right|$$where $F(C)$ is the set of assignments of literals that falsify $C$. We thus write a regex representing the language of falsifying assignments for each clause. Using $\Sigma = \{0,1\}$, and letting $r_i$ be the $i^{th}$ symbol of a regex $r$, the regex for the language of assignments that falsify a clause $C$ is$$r_i = \begin{cases} 0 & \text{if } x_i\in C \\ 1 & \text{if } \overline{x_i}\in C \\ . & \text{otherwise} \end{cases}$$We then take the union of the regexes for each clause $C\in\varphi$. For example, if $\varphi = (x_1\vee \overline{x_2}\vee x_3) \wedge (x_1\vee x_3\vee \overline{x_4})\wedge (\overline{x_1}\vee \overline{x_4})$ we would have $r = $010.|0.01|1..1, where | denotes union. The construction yields a union of $m$ strings, each of $n$ symbols. Thus the reduction takes $O(mn)$ time and the size of the regex-counting instance is polynomial in the size of the formula. Further, any regular expression that uses only concatenation, dot, and union represents a finite regular language (specifically, there is no Kleene star). So since we can solve #SAT by counting strings that satisfy such a regex, we can say that counting the words in a finite language is #P-complete.
Is counting the words in a finite regular language #P-complete?
cc.complexity theory;reference request;complexity classes
null
_unix.251621
When i am trying to use yum groups commands in RHEL 7 it is giving me following output.#yum groups listThere is no installed groups file. Maybe run: yum groups mark convert (see man yum)I have created my own repository and gpgkey is disabled for it.All yum related commands are working except the yum groups command.
problem while using yum groups
centos;rhel;yum;rpm;man
null
_cstheory.8151
Note: This is about the standard 9x9 sudoku puzzle. The solution only has to support solved, legal puzzles. So a solution doesn't need to support empty cells and can rely on the properties of a solved sudoku puzzle.I was wondering this, but I couldn't think of an answer that I was content with. A naive solution would use one byte for each cell (81 cells), totalling 648 bits. A more sophisticated solution would store the entire sudoku puzzle in a base-9 number (one digit per cell) and require $\lceil\log_2(9^{81}))\rceil = 257$ bits.But it can still be improved, for example, if you know 8 of the 9 numbers in a 3x3 subgrid you can trivially deduce the 9th. You can continue these thoughts to the point where this question boils down to What is the amount of unique solved sudokus? Now you can use a huge lookup table that maps each binary number to a sudoku puzzle, but that wouldn't be an usable solution.So, my question:Without using a lookup table, what is the minimum amount of bits required to store a sudoku puzzle and with what algorithm?
What is the minimum number of bits required to store a sudoku puzzle?
co.combinatorics;puzzles
null
_datascience.2642
Are there any algorithms which were developed using partial differential equations for tackling some of the machine learning problems? Most works I see online are in the field of computer vision and a few bizarre ones in topic modelling. But just curious if someone has used or seen it being used for some decision making process or classification problems?
Machine Learning & Partial Differential Equations
machine learning;algorithms
null
_cstheory.19434
I have the following Equivalent DNF problem:Input:Two DNF formulas, $F_1$ and $F_2$,with variables $a_1,a_2,...a_n.$Output: $1$ if $F_1$ and $F_2$ are equivalent, $0$ otherwise.$F_1$ and $F_2$ are equivalent if for all $(a_1,a_2,...a_n)\{0,1\}^n,F_1(a_1,a_2,...a_n)= F_2(a_1,a_2,...a_n).$ Is the DNF-Equivalence problem polynomial or in $\mathsf{NP\mbox{-Hard}}$? If in $P$, how do we find an efficient algorithm and determine its complexity. How do we prove it if it's $\mathsf{NP\mbox{-Hard}}$.
Is DNF-Equivalence Problem $\mathsf{NP\mbox{-Hard}}$?
cc.complexity theory;ds.algorithms;np hardness
A special case of DNF equivalence is DNF tautology: Given a DNF formula $F$, is it satisfied for all assignments? This can be seen by setting $F_1 = F$ and $F_2$ to be a trivial tautology. CNF non-satisfiability is co-NP-complete. Negating the input formula turns a CNF formula into a DNF formula and vice versa and non-satisfiability into tautology. Thus, DNF tautology is co-NP-complete.
_reverseengineering.6872
I'm trying to reverse a server executable(linux) and I need to find what calls sendmsg. Usually I can just use the xrefs in IDA, but in this case it doesn't show me anything. However, if I set a breakpoint at it I can see it being called when I connect. So my question to you is: how can I find out how the program got to the sendmsg?
IDA: Finding out what calls sendmsg
ida;linux
If you're breaking at the beginning of sendmsg you can look at the return value on the stack to see where the call came from. As long as no stack frame has been created the return value should be the first thing on the stack above ESP. Take the image below:Assuming sendmsg is where Bar() is located, the return address would be the location in Foo() after sendmsg was called. I'm not sure which debugger you're using (would be useful information), but in GDB you can look at the top of the stack (the return value) by using the following command:(gdb) x/20xw $esp This technique is useful when following object-oriented code, and xrefs are hard to come by.BacktraceOr as suggested by Guntram Blohm you can use a backtrace. In GDB:(gdb) bt ; Prints entire backtrace(gdb) bt n ; Prints 'n' innermost frames(gdb) bt -n ; Prints 'n' outermost frames
_vi.3681
On MS Windows using gVim, is it possible to select several files from the explorer and open them in the same instance of gVim in different buffers?At the moment if I select 3 different files on Windows graphical explorer and press enter they get open in 3 different instances of gVim. What I want is to open them in the same instance.When I work on linux and I want to edit all the files of a directory with vim I can simply from command line do the folowing:$ vim ./*.shThis will open all the files in the same instance of vim in different buffers. I'm looking for a way to do the same but from Windows GUI with gVim.Note 1: Using MS Windows command line is not an option here neither is using a cygwin console.Note 2: I know that I can open only one file and then, from gVim open the others but that would be slower than simply openning them all in one time from GUI.Note 3 (edit): Out of curiosity I just tried to do it on a Debian Jessie with a gVim 7.3 and it worked as I want (one instance - several buffers) out of the box with the same .vimrc as the one of the windows machine (without any .gvimrc file). So I deduce that:It is possible to do what I want.The behavior of gVim depends on the OS running it which is a little bit disturbing.
Gvim how to open several files in different buffers from MS Windows explorer
gvim;microsoft windows;filesystem;multiple files
By default gVim for Windows adds an option to the Explorer right-click menu that contains an option Edit with single Vim when multiple files are selected and that works as expected, opening them in a single window. That doesn't handle pressing Enter with multiple files selected though.There is a solution presented on the vim wiki though. In short, you need to modify the registry (using Registry Editor, regedit.exe) so that the appropriate file associations call gvim.exe with the --remote-tab-silent option. Searching for any occurrences of the vim executable with a full path and %1 as a parameter and changing them to include that parameter before the %1 should do it. I just did this and the only occurrence I found was:HKEY_CLASSES_ROOT\Applications\gvim.exe\shell\edit\commandSee below for the key after editing.Once the change was made, hitting Enter with multiple files associated with gVim opened them all in the same session.Note: You almost certainly need Administrator privileges to edit that registry key.
_hardwarecs.7516
I'm looking for a weather station that works without a display but allows querying the data via an API instead.It needs tohave a rain sensormeasure wind speedhave a hygrometermeasure temperaturepower itself via solar energyhave an accumulator to measure at night from solar energy collected during daytimeoperating temperature from -25 C to +40 Chave connectors for additional sensors for future use, e.g. UV sensor, solar sensor, snow sensor and snow height sensorprovide wireless connectivity in a range of ~20 meters. We want to mount it on our roofaccess to the data must be secure, especially the Wifi connection must not open a hole into our corporate networkbuilt-in data logging for at least 14 days incase the data cannot be fetchedIdeally, the software is open source. Commercial software is acceptable, but must be included in the price then.Also ideally, the firmware is open source (Arduino based?) so that our students could modify it.My budget is 750 net.Optional:weather forecastFeatures not needed:webcamscientific data measurementNon-feature:cloud based stuff. We must own our data.I have tried:most weather stations are just too cheap (< $200) and for home use / indoor use only.I'm asking froggit for their WH 4000 (German) whether data can be accessed via API and whether operating conditions are within -25 C to +40 C. The housing looks a bit cheap and uses lots of plastic material. Also, it seems I pay for the display, which I neither need nor want. All in all I wonder why I have a budget of 750 if I only need 119 . (But that may just be due to lack of knowledge by managers)Davis Vantage Pro 2 is the closest I could find until now. With $595 + $175, the price is even suitable. It is advertised as withstand scorching sun, corrosion, 200 mph (321 kmh) winds, temperature extremes, and more, which sounds great. There are resellers that seem to sell the same hardware under their own label.Maybe I'm just looking for alternatives to the Davis Vantage Pro 2 in order to be able to compare and decide for one.
Weather station with API access
wifi;data storage;mini pc
null
_webapps.61094
Is there a way to select words that are not all together like you can with the Ctrl key in Word? Sorry if this is obvious, but I haven't been able to find an answer elsewhere.
Select words that are not adjacent in Google Docs?
google documents
null
_cstheory.21014
Consider the following problem:Input: (G1, G2) where G1 and G2 are undirected graphsQuestion: Is the size of the max independent set of G1 at least as large as the size of the max independent set of G2?This seems like a fairly natural question to ask, and yet I have been unable to find a complexity class for which this problem is complete. Does anyone know of such? As a starting point, it is readily seen that the problem is NP-hard and contained in P with access to an NP oracle with log many queries.
Complexity of Comparative Independent Set Decision Problem
cc.complexity theory
This problem is indeed complete for the class of polynomial time Turing machines with access to an NP oracle with log many queries (also known as $\Theta_2^p$). The result appears in a 2000 FST TCS paper by Spakowski and Vogel titled $\Theta_2^p$-Completeness: A Classical Approach for New Results. The proof presented there and a proof that I arrived at independently both rely on the $\Theta_2^p$-completeness criterion of Wagner (Bounded Query Classes SIAM Journal on Computing archive Volume 19 Issue 5, Oct. 1990).
_unix.86978
I have a fresh Debian installation with LAMP. There is a PHP script that sends email messages to arbitrary addresses using the mail function, but it does not work - the messages don't get delivered.I have been searching the internet for quite a while and found out that there already is a SMTP server installed by default on Debian - the exim4 package. So I tried the following things so far.Launch the dpkg-reconfigure exim4-config command and choose the internet site; mail is sent and received directly using SMTP option. Follow the wizard and set the default options.Edit the /etc/php5/apache2/php.ini file and add the sendmail_path = /usr/sbin/sendmail -t line on the appropriate spot.None of those things have helped. When I try to send emails to my testing GMail address, it is not delivered, even though the address otherwise works fine.The following lines appear in my /var/log/exim4/mainlog file everytime I try to send an email.2013-08-16 10:46:51 1VAFgI-0006FP-UU <= [email protected] U=www-data P=local S=4232013-08-16 10:46:51 1VAFgI-0006FP-UU => [email protected] R=dnslookup T=remote_smtp H=aspmx.l.google.com [2a00:1450:4001:c02::1b] X=TLS1.2:RSA_ARCFOUR_SHA1:128 DN=C=US,ST=California,L=Mountain View,O=Google Inc,CN=mx.google.com2013-08-16 10:46:51 1VAFgI-0006FP-UU Completed
PHP + Exim4 on Debian - mail does not get delivered
debian;php;sendmail;exim
You need to configure exim4 to relay as a smarthost. There are a (lengthy) set of instructions here at the Debian wiki: GmailAndExim4, but it's really easy to get up and running. Your PHP sendmail_path is good to go.
_unix.352345
When I run postsuper -d ALL all messages from mailq are deleted. For a few seconds I am able to send emails from terminal just fine. However, even if I just stand still and do nothing after clearing the mailq, after about 20 seconds some new entries starts to show up in the queue, which prevents any other email message to be sent. In other words, if I clear the mail queue, and do nothing, new entries shows in the mail queue... and they prevent me to be able to send new email messages through the server.I already tried: Restarting the serverpostfix stoppostqueue -fpostfix flushpostsuper -d ALL deferredI also tried to: - Uninstall postfix - Uninstall cyrus-sasl - Uninstall cyrus-imapd - Uninstall mailxBut when I re-install them, the issue comes back.Nothing seems to prevent those new messages to show up on the mail queue again and again every 20 seconds.How can I fix that?
CentOS: postqueue -p show a message that keeps coming back to queue
centos;email;postfix
I believe the issue was fixed by fixing permissions on the folder: /var/lib/imap/socket/lmtpThere was also a small difference between the server's hostname and the hostname actually defined on the postfix config file. After those two things were fixed, the postfix was restarted. Hope this help someone in the future.
_softwareengineering.351773
In Swift, if I have a class with only type properties and methods (everything declared static) would that be considered a singleton object? If not, why?
Trying to understand singleton objects in Swift
ios;singleton;swift language
null
_softwareengineering.271376
It's clear to everyone (I hope) that storing passwords without at least salting/hashing them is a terrible idea.What about emails? Let's say you keep the subscription email address, if you encrypt it properly it may not be usable to send emails to the users. On the other hand, if you don't encrypt it and the database gets stolen, all your users risk a potential spam.This question is not about law-specific issues (although they may be given, they remain country-dependent) or about encrypting the database itself.
Should I keep email addresses as plaintext in database?
database;security;email
Storing a salted hash of the email addresses could be on option if you keep those records just for account confirmation / authentication.In other cases, it seems to me that encrypting the emails would make the job of maintaining the database harder while gaining little in return.Probably securing the access of the database itself is a better choice: usually there are a lot of other information in the database that you wouldn't like to be gathered.A similar question on Stackoverflow: Is it worth encrypting email addresses in the database?
_webmaster.9082
Possible Duplicate:What Forum Software should I use? I need to assemble a GetSatisfaction/Lithium/Jive type support forum/community. The first is not available in the desired language and the last two are priced for the enterprise market. I did research some other options (open source or SaaS) but they all seem to be either:kind of dead (open source options)too focused in gathering ideas/feedback (uservoice)strictly support without the community/voting features (zendesk) I need an open forum (people powered support/UGC with community/voting features) & Facebook/Google/Yahoo/MSN account sign-in.Therefore I will have to do some of the work on my own. I want to piece things (plugins/mods/etc) on top of a standard forum platform to give it the features I need. For this purpose, I want to use a mature product with widespread userbase, active community and lots of plugin options. I believe most will agree that my options therefore are:vBulletinphpBBSMFHere are the questions: Which one of the three above offers the easier path towards thedesired goal?Which one of the three above has the most advanced features related to thedesired goal?Of course I dont expect anyone to know these answers cut and dry. I am hoping to hear some experiences and see some examples. Also, it would be great if both those questions had the same answer, but I am not going to get my hopes up...PS: I wish I could add the tags phpbb and smf ;)
Which forum software has the most advanced community/GetSatisfaction type features?
looking for a script;forum;phpbb;community;vbulletin
null
_unix.183279
In my understanding, awk array is something like python dict.So I write down the code bellow to explore it:awk '{my_dict[$1] = $2} END { print my_dict}' zenAnd I got: awk: can't read value of my_dict; it's an array name.As the first column isn`t a number, how could I read the total content of the array or traverse it?
How to view all the content in an awk array?
awk
You can loop over the array's keys and extract the corresponding values:awk '{my_dict[$1] = $2} END { for (key in my_dict) { print my_dict[key] } }' zenTo get output similar to that you'd get with a Python dictionary, you can print the key as well:awk '{my_dict[$1] = $2} END { for (key in my_dict) { print key : my_dict[key] } }' zenThis works regardless of the key type.
_computergraphics.4029
I know in computer graphic, we can set a world window in world coordinate system, and then mapping it to viewport which is the display window. Things that are not in the world window should not be displayed and we can do this through Clipping (like in OpenGL). I have a question that do we have alternative methods?
Alternatives to Clipping in avoiding display problem
clipping
null
_unix.274511
For bash completion, I would like to replace youtube-dl with youtubedl.I can make an alias for youtubedl, however, both youtube-dl with youtubedl will exist.Primarily, I just want to remove youtube-dl from bash completion, and create a custom function for youtubedl.
How can I remove a command from bash completion?
bash;autocomplete
null
_unix.303004
We have a Debian Web server and would like our local LAN user to access the server by local ip - but would like the public to access the server using the static ip.how can we set this up so that when local user open www.domain.com - they are transferred to 192.168.1.111(our web server ip); but if outside the network access www.domain.com they are sent to [PUBLIC IP]. [PUBLIC IP] access is working but our local users are also use the public route to return back to web server.
Website Access Local & Public
linux;debian;webserver
null
_cs.6541
I have a book that proves the halting problem with this simple statement:$$A_\text{TM} \le_m \text{HALTING} \le_m \text{HALTING}^\varepsilon$$It states that halting problem reduces to the language consisting of $\langle M, \omega \rangle$ for which a Turing machine $M$ accepts $\omega$ is undecidable.What does this mean? What does the notation $\le_m$ indicate?
Why does $A_\text{TM} \le_m \text{HALTING} \le_m \text{HALTING}^\varepsilon$?
turing machines;reductions;undecidability;halting problem
The symbol $\leq_m$ means many-one reducible, contrast to reductions such as turing reducible (denoted by $\leq_T$) and one-one reducible (denoted $\leq_1$).A many-one reduction from $L$ to $L$ (given an alphabet $\Sigma$) is a (computable) function $f:\Sigma^* \to \Sigma^*$ such that for every $w \in \Sigma^*$, we have that $w \in L$ if and only if $f(w) \in L$. The many-one means that we allow $f(w) = f(w)$ (it does not have to be injective). In your setting, it basically means that you can transform an input to $A_{TM}$ to $HALTING$ such that $A_{TM}$ accepts an input $w$ if and only if $HALTING$ accepts the transformed input $f(w)$.
_cstheory.18219
Eve is an intelligence agency with the capability to scan all cleartext communications and do traffic analysis against encrypted communications.There are n Alices, who each want to communicate secretly with some of the other Alices. So, they want the content of their communication to be secret, and the fact that they are actively trying to communicate secretly to be secret.There are also N>>n Bobs, who disagree with mass surveillance but don't want to do anything which would give them any legal liability, such as transmitting illegal material (IE, they don't want to run TOR nodes). So the Bobs decide to help by sending junk communications to other Bobs, which are indistinguishable from encrypted data. An individual Bob, if challenged, can show that his transmissions are junk, thus avoiding legal liability (NB - I Am Not A Lawyer). For the purpose of the exercise Eve in not allowed to challenge 'many' Bobs.Eve wins if she can distinguish the Alices from the Bobs, or at least, as many Alices as possible. In particular, Eve may start by knowing at least some of the Alices; we don't want the security of the other Alices to collapse if she does.A dumb approach is as follows: For each period of time, each Bob (or masquerading Alice) chooses another Bob(Alice) to communicate with at random from a public list. The Bobs send junk, the Alices send their encrypted message. In this scheme, the Alices are indistinguishable from the Bobs, but the Alices only obtain 1/N of the bandwidth of an individual communication, which is very low since N is large, and have very high latency, since they have to wait many time periods before they happen to communicate with who they want.Is it possible to do better?
Can decoying provide security against traffic analysis?
cr.crypto security
null
_cstheory.25611
Let $M$ be an acyclic NFA.Since $M$ is acyclic, $L(M)$ is finite.In a related question, it was suggested that exact counting of the number of words accepted by $M$ is $\#P$-Complete.The second answer for that question provides a counting algorithm, but only works for unambiguous NFAs (where every word is accepted by at most a single path).Given an NFA $M$, can we approximate $|L(M)|$ in polynomial time?As automata is a highly studied subject, I was surprised that I couldn't find anything about this, so if someone knows of a reference it'll be great :).
Can we approximate the number of words accepted by an NFA?
ds.algorithms;fl.formal languages;approximation algorithms;automata theory;counting complexity
null
_cs.59466
What is the cardinality of the set of regular grammars? The caveat is that I'm only interested in grammars which are 'structurally' different. Sorry I don't know how to talk about this in a formal way, but what I mean is that the actual symbols are arbitrary to me.So for example the grammar with:{N={},={x},P={x},S=}Is equivalent to the grammar:{N={},={y},P={y},S=}Hopefully I am being understood! I believe this set is countable because for every N and there are only a finite number of production rules which can be formulated. For example, for:N={} and ={x}The only unique sets of production rules are:{{x}}{{x}}{{x}, {x}}
What is the cardinality of the set of regular grammars?
regular languages;formal grammars;combinatorics
There is at least one regular grammar per regular language, and all of them are pairwise inequivalent (for any meaningful equivalence relation). Since there is at least a countably infinite number of regular languages, that's a lower bound for the number of regular grammars as well.Without loss of generality, you can write down every regular grammar as finite string over a finite alphabet. Therefore, there are at most as many regular grammars as binary strings, of which there are countably infinitely many.Combine the bounds to get your answer.The lower bounds follows from $\{a\}^n$ being regular for every $n \in \mathbb{N}$.Encode all symbols using binary numbers.
_unix.350145
I'm using the old ncompress to create a backup file.And what i see is amazing:Here are the commands i use:compress -c mytest.iso>mytest.iso.bak.ZThe size of mytest.iso(which actually is centos6.8-livecd.iso) changes from 1033741824(1.0G) to 88099(87K).When i use:tar -cvf mytest.iso.tar.gz mytest.isothe tar.gz file doesn't change a lot in size.Is this normal?The iso file works just fine if i uncompress it.
Can ncompress compress a file to 99.99% rate?
linux;tar;compression
Compression algorithms have varying compression ratios depending on the properties of the data they are compressing. For instance:$ dd if=/dev/zero of=test.img bs=1m count=1024$ compress -c test.img > test.img.Z$ gzip -c test.img > test.img.gz$ wc -c test.img test.img.gz test.img.Z 1073741824 test.img 4685486 test.img.gz 84781 test.img.Z 1078512091 totalHaving a file made up of mostly repeated zeroes is probably a best-case situation for this algorithm. Since you are getting similar compression ratios, and since your file is of such a round size (1GB), it is likely that the image is much larger than necessary and merely filled with repeated data.Of course, gzip, compress, bzip2, and others will all have differing compression ratios on a given file. This is why many large open-source projects offer several downloads compressed by different algorithms so that users can download the smallest file for which they have a decompression utility.
_unix.152332
Morning, can some body help me about MIME email?I want to send HTML email like this:MIME-Version: 1.0Content-type: multipart/alternative; boundary=lazuardi--lazuardiAfter that email. I have html email.Content-type: text/html; charset=UTF-8<html><body>......This is HTML message</body></html>--lazuardiThen i also include plain textContent-type: text/plainthis is plain text message--lazuardi--My question is, am I wrong that I include header in my body.html?Where should I put the header?I using Mutt email client, everytime I send the email, mutt always give me this message: No boundary parameter found! [report this error]...Could not send the message.Can somebody help me to solve this?
Header about MIME email
shell script;mutt
null
_unix.340575
It's not a good idea to use set -e inside functions1, because it will cause one's shell to terminate on error.Therefore, in shell functions a lot of my code looks like this:[[ -e $file ]] || { printf -- 'foo: %s does not exist\n' $file >&2 return -1}...which is not only bulky, but also ineffective beyond the first frame of funcstack.It would be great if there were an error function that would allow at least to condense the code above to something like this[[ -e $file ]] || error -1 '%s does not exist' $fileWriting such an error function for use in interpreted scripts (as opposed to functions) is not too difficult:error () { local exitstatus=$1 shift { printf -- '%s: ' ${funcstack[2]} printf -- $@ printf -- '\n' } >&2 exit $exitstatus}...but calling this function from within other functions is a bad idea, for the same reason that set -e inside functions is a bad idea.What's needed to implement the desired error function is a way to return control to the invoking shell's top level (thereby clearing funcstack, which could be arbitrarily long at the time error gets invoked).Is there a way to do this?PS: Of course, I did try the naive way to this:error () { local exitstatus=$1 shift { printf -- '%s: ' ${funcstack[2]} printf -- $@ printf -- '\n' } >&2 funcstack=()}...but (unsurprisingly), zsh will have none of it:error:10: read-only variable: funcstack1In this post I'll use expressions like from within a function as shorthand for from within shell functions intended for interactive use or from within scripts meant to be sourced.
How to unwind `funcstack`?
shell script;zsh
null
_codereview.100609
My goal is to obtain the nth weekday of a given month. Parameters are a date from a given month and the nth weekday I'm trying to obtain. It returns the Nth Weekday of the month if it exist and returns DateTime.MinValue othewise. For my purposes weekdays are M-F.Is there a more elegant or efficient way to implement this logic? My implementation feels crude, basically a while loop that counts weekdays until it finds the desired date or the end of the month. public static DateTime getNthWeekdayOfMonth(DateTime date, int nthWeekday) { //Valid inputs are greater than 0 but less than 24 if (nthWeekday > 23 || nthWeekday < 1) return DateTime.MinValue; //start with 1st day of month from date param DateTime currentDay = new DateTime(date.Year, date.Month, 1); int i = 0; while(i < nthWeekday && currentDay.Month == date.Month) { if (currentDay.DayOfWeek != DayOfWeek.Saturday && currentDay.DayOfWeek != DayOfWeek.Sunday) { i++; if(i == nthWeekday) return currentDay; } currentDay = currentDay.AddDays(1); } return DateTime.MinValue; }Usagevar date1 = getNthWeekdayOfMonth(new DateTime(2015, 8, 11), 22);//returns DateTime.MinValuevar date2 = getNthWeekdayOfMonth(new DateTime(2015, 8, 11), 21);//returns 8/31/2015var date3 = getNthWeekdayOfMonth(new DateTime(2015, 8, 11), 1);//returns 8/3/2015
Return Nth Weekday of Month
c#;.net;datetime
int i = 0; while(i < nthWeekday && currentDay.Month == date.Month) { if (currentDay.DayOfWeek != DayOfWeek.Saturday && currentDay.DayOfWeek != DayOfWeek.Sunday) { i++; if(i == nthWeekday) return currentDay; } currentDay = currentDay.AddDays(1); }Your while loop is a little messy let's clean that up first, and you should also have an early continue statement in there.Let me show you what I mean:int i = 1;while(i <= nthWeekday && currentDay.Month == date.Month){ bool isWeekendDay = currentDay.DayOfWeek == DayOfWeek.Saturday || currentDay.DayOfWeek == DayOfWeek.Sunday; if (isWeekendDay) { currentDay = currentDay.AddDays(1); continue; } if (i == nthWeekday) { return currentDay; } currentDay = currentDay.AddDays(1); i++;}This is a lot cleaner, and shows exactly what our intent is. It is much easier to read.You shouldn't nest if statements inside of other if statements if you don't have to, it can get very confusing.
_softwareengineering.190688
I have a WCF web service hosted in a load balanced environment. I do not need any WCF session related functionality in the service.QUESTION What are the scenarios in which performances will be best if keepAliveEnabled = falsekeepAliveEnabled = trueReferenceFrom Load BalancingBy default, the BasicHttpBinding sends a connection HTTP header in messages with a Keep-Alive value, which enables clients to establish persistent connections to the services that support them. This configuration offers enhanced throughput because previously established connections can be reused to send subsequent messages to the same server. However, connection reuse may cause clients to become strongly associated to a specific server within the load-balanced farm, which reduces the effectiveness of round-robin load balancing. If this behavior is undesirable, HTTP Keep-Alive can be disabled on the server using the KeepAliveEnabled property with a CustomBinding or user-defined Binding.
WCF Keep Alive: Whether to disable keepAliveEnabled
.net;wcf
null
_unix.138244
Is there a way I can use Putty and connect it to my machine in replacement of terminal on my laptop? I am currently using ubuntu but I like some of the features that putty has over using the terminal.
Replacement of using terminal
ubuntu;software installation;terminal emulator
Yes, you're looking for the pterm package.sudo apt-get install ptermAnd then run the pterm command to pop up a PuTTY terminal emulator.
_codereview.118996
This is my hangman game code for my GCSE computer science coursework. It has been submitted but I was wondering if there is anyway to improve it.import randomimport time#Variables holding different words for each difficultyEASYWORDS = open(Easy.txt,r+)words = []for item in EASYWORDS: words.append(item.strip('\n'))MEDWORDS = open(Med.txt,r+)words = []for item in MEDWORDS: words.append(item.strip('\n'))HARDWORDS = open(Hard.txt,r+)words = []for item in HARDWORDS: words.append(item.strip('\n'))INSANEWORDS = open(Insane.txt, r+)words = []for item in INSANEWORDS: words.append(item.strip('\n'))#Where the user picks a difficultydef difficulty(): print(easy\n) print(medium\n) print(hard\n) print(insane\n) menu=input(Welcome to Hangman, type in what difficulty you would like... ).lower() if menu == hard or menu == h: hard() elif menu == medium or menu == m or menu ==med: med() elif menu == easy or menu == e: easy() elif menu == insane or menu == i: insane() else: print(Please type in either hard, medium, easy or insane!) difficulty()def difficulty2(): print(Easy\n) print(Medium\n) print(Hard\n) print(Insane\n) print(Quit\n) menu=input(Welcome to Hangman, type in what difficulty you would like. Or would you like to quit the game?).lower() if menu == hard or menu == h: hard() elif menu == medium or menu == m or menu ==med: med() elif menu == easy or menu == e: easy() elif menu == insane or menu == i: insane() elif menu == quit or q: quit() else: print(Please type in either hard, medium, easy or insane!) difficulty()#if the user picked easy for their difficultydef easy(): global score print (\nStart guessing...) time.sleep(0.5) word = random.choice(words).lower() guesses = '' fails = 0 while fails >= 0 and fails < 10: failed = 0 for char in word: if char in guesses: print (char,) else: print (_), failed += 1 if failed == 0: print (\nYou won, WELL DONE!) score = score + 1 print (your score is,, score) print (the word was, , word) difficultyEASY() guess = input(\nGuess a letter:).lower() while len(guess)==0: guess = input(\nTry again you muppet:).lower() guess = guess[0] guesses += guess if guess not in word: fails += 1 print (\nWrong) if fails == 1: print (You have, + fails, fail....WATCH OUT! ) elif fails >= 2 and fails < 10: print (You have, + fails, fails....WATCH OUT! ) if fails == 10: print (You Lose\n) print (your score is, , score) print (the word was,, word) score = 0 difficultyEASY()#if the user picked medium for their difficultydef med(): global score print (\nStart guessing...) time.sleep(0.5) word = random.choice(words).lower() guesses = '' fails = 0 while fails >= 0 and fails < 10: failed = 0 for char in word: if char in guesses: print (char,) else: print (_), failed += 1 if failed == 0: print (\nYou won, WELL DONE!) score = score + 1 print (your score is,, score) difficultyMED() guess = input(\nGuess a letter:).lower() while len(guess)==0: guess = input(\nTry again you muppet:).lower() guess = guess[0] guesses += guess if guess not in word: fails += 1 print (\nWrong) if fails == 1: print (You have, + fails, fail....WATCH OUT! ) elif fails >= 2 and fails < 10: print (You have, + fails, fails....WATCH OUT! ) if fails == 10: print (You Lose\n) print (your score is, , score) print (the word was,, word) score = 0 difficultyMED() #if the user picked hard for their difficultydef hard(): global score print (\nStart guessing...) time.sleep(0.5) word = random.choice(words).lower() guesses = '' fails = 0 while fails >= 0 and fails < 10: #try to fix this failed = 0 for char in word: if char in guesses: print (char,) else: print (_), failed += 1 if failed == 0: print (\nYou won, WELL DONE!) score = score + 1 print (your score is,, score) difficultyHARD() guess = input(\nGuess a letter:).lower() while len(guess)==0: guess = input(\nTry again you muppet:).lower() guess = guess[0] guesses += guess if guess not in word: fails += 1 print (\nWrong) if fails == 1: print (You have, + fails, fail....WATCH OUT! ) elif fails >= 2 and fails < 10: print (You have, + fails, fails....WATCH OUT! ) if fails == 10: print (You Lose\n) print (your score is, , score) print (the word was,, word) score = 0 difficultyHARD()#if the user picked insane for their difficultydef insane(): global score print (This words may contain an apostrophe. \nStart guessing...) time.sleep(0.5) word = random.choice(words).lower() guesses = '' fails = 0 while fails >= 0 and fails < 10: #try to fix this failed = 0 for char in word: if char in guesses: print (char,) else: print (_), failed += 1 if failed == 0: print (\nYou won, WELL DONE!) score = score + 1 print (your score is,, score) difficultyINSANE() guess = input(\nGuess a letter:).lower() while len(guess)==0: guess = input(\nTry again you muppet:).lower() guess = guess[0] guesses += guess if guess not in word: fails += 1 print (\nWrong) if fails == 1: print (You have, + fails, fail....WATCH OUT! ) elif fails >= 2 and fails < 10: print (You have, + fails, fails....WATCH OUT! ) if fails == 10: print (You Lose\n) print (your score is, , score) print (the word was,, word) score = 0 difficultyINSANE()def start(): Continue = input(Do you want to play hangman?).lower() while Continue in [y, ye, yes, yeah]: name = input(What is your name? ) print (Hello, + name, Time to play hangman! You have ten guesses to win!) print (\n) time.sleep(1) difficulty() else: quit#whether they want to try a diffirent difficulty or stay on easydef difficultyEASY(): diff = input(Do you want to change the difficulty?. Or quit the game? ) if diff == yes or difficulty ==y: difficulty2() elif diff == no or diff ==n: easy()#whether they want to try a diffirent difficulty or stay on mediumdef difficultyMED(): diff = input(Do you want to change the difficulty?. Or quit the game? ) if diff == yes or difficulty ==y: difficulty2() elif diff == no or diff ==n: med()#whether they want to try a diffirent difficulty or stay on harddef difficultyHARD(): diff = input(Do you want to change the difficulty?. Or quit the game? ) if diff == yes or difficulty ==y: difficulty2() elif diff == no or diff ==n: hard()#whether they want to try a diffirent difficulty or stay on insanedef difficultyINSANE(): diff = input(Do you want to change the difficulty?. Or quit the game? ) if diff == yes or difficulty ==y: difficulty2() elif diff == no or diff ==n: insane()score = 0start()
Python Hangman Game
python;game;python 3.x;hangman
Input checkingThe way you're currently checking input is clunky, hard to write, and hard to read. For example, you have the following chunk of code:menu=input(Welcome to Hangman, type in what difficulty you would like... ).lower()if menu == hard or menu == h: hard()elif menu == medium or menu == m or menu ==med: med()elif menu == easy or menu == e: easy()elif menu == insane or menu == i: insane()else: print(Please type in either hard, medium, easy or insane!) difficulty()There are quite a few things that can be improved here, so let's start with the obvious. Rather than having multiple individual conditional expressions to check the value of a variable, simply create a list of all possible values and use the in operator to check the variable's value, like this, for example:if menu in [medium, med, m]: med()Next, I'd suggest that you add a .strip() call to the following line:menu=input(Welcome to Hangman, type in what difficulty you would like... ).lower()The .strip() function, when no arguments are specified, will remove leading and trailing whitespace. This means that a user can enter something like med without worrying that the program might reject their input. In addition, you could also consider using re.sub if you want to get rid of additional characters.Building word listsYou've got a lot of repetition in the following chunk of code:#Variables holding different words for each difficultyEASYWORDS = open(Easy.txt,r+)words = []for item in EASYWORDS: words.append(item.strip('\n'))MEDWORDS = open(Med.txt,r+)words = []for item in MEDWORDS: words.append(item.strip('\n'))HARDWORDS = open(Hard.txt,r+)words = []for item in HARDWORDS: words.append(item.strip('\n'))INSANEWORDS = open(Insane.txt, r+)words = []for item in INSANEWORDS: words.append(item.strip('\n'))The best way to do this would probably be to use generator expressions, and encapsulate it into a function, like this:def build_word_list(word_file): words = [item.strip(\n) for item in word_file] return wordsYou can then use it like this, assuming you've already defined build_word_list:EASYWORDS = open(Easy.txt,r+)MEDWORDS = open(Med.txt,r+)HARDWORDS = open(Hard.txt,r+)INSANEWORDS = open(Insane.txt, r+)easy_words = build_word_list(EASYWORDS)medium_words = build_word_list(MEDWORDS)hard_words = build_word_list(HARDWORDS)insane_words = build_word_list(INSANEWORDS)I've also fixed a pretty large bug. You were creating only one word list, which meant that regardless of what difficulty you chose, you'd have words from all difficulties. Now there are separate word lists for each separate difficulty.Creating a play functionThe functions easy, med, hard and insane are all identical. There is no reason that you should be repeating yourself over and over again. To help prevent the repetition, create one simple play function with an argument named word_list. The signature for the play function should look like this:def play(word_list): # Game logic goes hereYou'd simply pass a word list, like easy_words or insane_words as the word_list argument, and then use the word_list argument in the function.Misc. NitpicksThere are quite a few things I want to nitpick, so get ready.The difficulty2 function serves no purpose. It is identical in every way to difficulty. Any calls to difficulty2 in your code can just be changed to difficulty calls.Similarly to the above nitpick, your difficultyEASY, difficultyMED, etc. functions are also virtually identical. Simply create one function named change_difficulty and you're set.You need whitespace between your operators, and an introduction to PEP8, the official Python style guide.. Nobody wants to read code that looks like it was plucked straight out of a PPCG answer.
_webmaster.95653
I'm trying to fix 2 issues based on the report from Xenu's Link Sleuth.I have numerous 301 Redirects from Wordpress SQL based URLs despite using post name URLs.Despite using post name based URLs (ie. abc.com/my-post), when I run Xenu's Link Sleuth, it shows me a list of redirected URLs, all of which are SQL database related (ie. abc.com/?p=342). Is this normal or should I do something to remove/remedy this situation? There are broken page-local links on many of my pages with a format of abc.com/my-post/#text-5 Anchor occurs multiple times The #text-5 occurs in almost all of them, but how would I fix this? I have no typical anchor links on the page linking to a particular spot on the page. Is this just a theme or Wordpress glitch and should I even be concerned about this?
Using Xenu's Link Sleuth to remove bad 301's / broken page-local links
redirects;wordpress;cms;sql
null
_webapps.18262
If I use the secret email address to upload photos to my Facebook timeline, the photos will automatically be shown in one single post if I upload them within a certain timespan (after a day or so, Facebook will create a new post. Apparently the engine assumes that images uploaded one after the other somehow belong together).Is there a way to always make Facebook use one post per image, even if the images are part of one album, no matter how short the timespan between each upload?(I know I can use different albums, but I don't know how to do that using the email function. And sorry if I didn't get the terminology right - I'm a Facebook newbie AND German)
How does one prevent Facebook from automatically combining uploaded photos in the timeline?
facebook
If the photos are part of the same album, I do not see the need to clutter friend feeds with multiple posts. Facebook clumps events, they have even started clumping interests (friends talking about Harry Potter) to clear up the streams. So I do not think separate posts for the same event (i.e. adding photos to the same album) is possible.Using the personalized email address all photos will be sent to the Mobile Uploads album. You then need to access the non-mobile site from a browser and make your changes to the appropriate album. So edit the mobile uploads album and move the photos to the appropriate album. The events (posts) will then re-adjust themselves to the new events such as phwd added 3 new photos to the album Pancakesphwd added 2 new photos to the album Runninginstead of phwd added 5 new photos to the album Mobile Uploads
_codereview.121342
The following regex is meant to improve stringmatching by sanitizing the user -defined commandPrefix and checking for whitespace and line-endings after the specified text. command will generally be a single word, hence not escaped.var prefix = commandPrefix.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');return text.test(/^ + prefix + command + (?=\s|$)/);Can this be improved for code readability? And am I missing any regex special characters in the sanitation?
Regex to match strings safely
javascript;strings;regex
First, /pattern/ is the literal notation of a RegExp object and not a string, /pattern/ is a string and nothing more.If you want to concatenate several strings to build your pattern and then to obtain a RegExp object, you need to use the constructor:var re = new RegExp('^' + prefix + command + '(?!\\S)');return re.test(text);(Note that when you pass a string to the RegExp constructor, you need to escape the backslashes, since to figure a literal backslash in a string you need to escape it.)(test is a RegExp method, not a String method: RegExp.prototype.test())About special characters: -, } and ] are not special characters and don't need to be escaped. Note that { is read as a literal character too, but only if it isn't the start of a quantifier {n}, {m,n}, {m,}. Except for these special situations, you don't need to escape it when you write a pattern by hand, but here it's easier to escape it systematically instead of testing if it is or not the start of a quantifier. (if the escape is useless, it will be ignored)Since you will use the RegExp constructor with a string as first parameter (Since ECMAScript 6, this parameter can also be in literal notation), you no longer need to escape the delimiter / that is only used in the literal notation. You can remove it too:var prefix = commandPrefix.replace(/[.?*+\\|{()[^$]/g, '\\$&');About the readability, no need to make things more complicated than they are, a simple comment before the line should suffice.Since escaping special regex characters is a basic task, and if you project to use it several times, you can build a function:function regEscape(mystr) { return mystr.replace(/[.?*+\\|{()[^$]/g, '\\$&');}or, why not, adding it to the String methods:String.prototype.regEscape = function() { return this.replace(/[.?*+\\|{()[^$]/g, '\\$&');};...function ... (...) { ... var re = new RegExp('^' + commandPrefix.regEscape() + command + '(?!\\S)'); return re.test(text);}
_unix.370700
I am trying to check a port with lsof: lsof -i :443but it gives me an error message that says:/usr/local/bin/lsof[30]: 6226000 Memory fault(coredump)Why is this happening, and how can I solve this?
memory fault in lsof
aix;lsof;core dump
null
_datascience.16797
For detection, a common way to determine if one object proposal was right is Intersection over Union (IoU, IU). This takes the set $A$ of proposed object pixels and the set of true object pixels $B$ and calculates:$$IoU(A, B) = \frac{A \cap B}{A \cup B}$$Commonly, IoU > 0.5 means that it was a hit, otherwise it was a fail. For each class, one can calculate theTrue Positive ($TP(c)$): a proposal was made for class $c$ and there actually was an object of class $c$False Positive ($FP(c)$): a proposal was made for class $c$, but there is no object of class $c$Average Precision for class $c$: $\frac{\#TP(c)}{\#TP(c) + \#FP(c)}$The mAP (mean average precision) = $\frac{1}{|classes|}\sum_{c \in classes} \frac{\#TP(c)}{\#TP(c) + \#FP(c)}$If one wants better proposals, one does increase the IoU from 0.5 to a higher value (up to 1.0 which would be perfect). One can denote this with mAP@p, where $p \in (0, 1)$ is the IoU.But what does mAP@[.5:.95] (as found in this paper) mean?
What does the notation mAP@[.5:.95] mean?
computer vision
mAP@[.5:.95](someone denoted mAP@[.5,.95]) means average mAP over different IoU thresholds, from 0.5 to 0.95, step 0.05 (0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95).There is an associated MS COCO challenge with a new evaluation metric, that averages mAP over different IoU thresholds, from 0.5 to 0.95 (written as 0.5:0.95). [Ref]We evaluate the mAP averaged for IoU [0.5 : 0.05 : 0.95] (COCOs standard metric, simply denoted as mAP@[.5, .95]) and [email protected] (PASCAL VOCs metric). [Ref]To evaluate our final detections, we use the official COCO API [20], which measures mAP averaged over IOU thresholds in [0.5 : 0.05 : 0.95], amongst other metrics. [Ref]BTW, the source code of coco shows exactly what mAP@[.5:.95] is doing:self.iouThrs = np.linspace(.5, 0.95, np.round((0.95 - .5) / .05) + 1, endpoint=True)Referenceshttps://github.com/pdollar/cocohttp://mscoco.org/https://www.cs.cornell.edu/~sbell/pdf/cvpr2016-ion-bell.pdfhttps://arxiv.org/pdf/1506.01497.pdfhttps://arxiv.org/pdf/1611.10012.pdf
_cs.44412
Let's say I have a programming language that allows procedures, i.e., methods without return values, and immutable data-structures, so no sideeffecting inside a procedure. Is it possible to simulate a program written in a language with return values in our language?In other words, do return values allow for a more advanced model of computation? I guess it may be possible with Continuation-passing style, but i would appreciate other thoughts on this.
procedures and immutable data to simulate return values
programming languages;language design
null
_codereview.112786
I have this: public void InfoAssignment(){ //MessageBox.Show(firstName = firstNameBox.Text); firstName = firstNameBox.Text; lastName = lastNameBox.Text; phoneNumber = phoneBox.Text; address = addressBox.Text; //Check for text in firstNameBox if (!String.IsNullOrWhiteSpace(firstName)) { firstName = firstNameBox.Text; } else { MessageBox.Show(Please enter a first name); return; } if (!String.IsNullOrWhiteSpace(lastName)) { lastName = lastNameBox.Text; } else { MessageBox.Show(Please enter a last name); return; } if(!String.IsNullOrWhiteSpace(phoneNumber)) { phoneNumber = phoneBox.Text; } else { MessageBox.Show(Please enter a phone number); return; } if (!String.IsNullOrWhiteSpace(address)) { address = addressBox.Text; } else { MessageBox.Show(Please enter a phone number); return; } //firstName = firstNameBox.Text; //lastName = lastNameBox.Text;}It does what I need it to do but obviously this is basically repeating the same thing with only minor variations. I'm thinking there has to be a better way of which I'm unaware. Is there?
Extracting first name, last name, phone number, and address from a form
c#;validation;form
Here you go.Pass the variables by reference and let the method update them if the input is valid.Do processing if all the inputs are valid.EDIT: I needed to change the method name from ValidateInput to CopyToVariableWithValidation because the former fails to have a good name to represent it's function.private bool CopyToVariableWithValidation(TextBox textBox, string inputFriendlyName, ref string variableToCopyContent){ if (string.IsNullOrWhiteSpace(textBox.Text)) { MessageBox.Show(Please enter a + inputFriendlyName); return false; } variableToCopyContent = textBox.Text; return true;}public void InfoAssignment(){ if ( CopyToVariableWithValidation(firstNameBox, First Name, ref firstName) && CopyToVariableWithValidation(lastNameBox, Last Name, ref lastName) && CopyToVariableWithValidation(phoneBox, Phone Number, ref phoneNumber) && CopyToVariableWithValidation(addressBox, Address, ref address) ) { // Input is valid. Do more processing here. }}
_unix.237769
I just wrote a script that generated hundreds of files and stored them in a directory ~/foo. These files are ~/foo/X-file where X ranges from X=1 to X=900. My problem is that I would like to view these files in numerical order, but the files are not padded with zeros. Thus the directory contains 17-file and 544-file for example. Is there a way to pad these files with leading zeros?
How can I pad lots of file names with zeros in a directory?
files;rename
null
_unix.378402
I need to get UMTS modem working on Debian Wheezy.Modem details:SIERRA WIRELESS AirPrime, MC7304Linux Details: 'uname -a'Linux XXX 3.2.0-4-686-pae #1 SMP Debian 3.2.54-2 i686 GNU/LinuxWhat i found out is that i need cdc_wdm module installed on my system to get it to report under /dev/cdc-wdmX.cdc_wdm module is included in newer version of kernel but not in the one i have. How can I install cdc_wdm module into older version of kernel?Updating kernel is not acceptable at this point.I am new to kernel modules so sorry for my lack of understanding.
cdc_wdm module on Debian Wheezy
linux;kernel modules
null
_softwareengineering.221385
I'm currently working on a project that requires a complicated model structure and I'm struggling with picking the right architecture.First of all, there are several interdependent models. Change in one model can trigger changes in several other models. For example, user inputs a query, first model checks the database for type of the query and the second model requests its data depending on that query type.Secondly, each model can have several data sources. Data sources are used conditionally, dependent on system configuration.The app needs to function seamlessly, for example, if one data source doesn't return required information, model must try and use another one.An important thing also is that the codebase will eventually be expanded with other models. So models, data sources etc. must be very modular.Currently there are several ways I can organise the model layer:'Dumb' models re-created by factory objects when input data (or a related model) changes. Model dependencies are resolved in an operation object, encapsulating the whole update routine. Operation object is configured and run by a domain model. I don't know where to inject a data source though.'Smart' models with update logic encapsulated in them. Each model queries a sort of a mapper/data-source-manager, which works as a proxy for different data sources. Models report their updates to a domain model. Dependencies are resolved by a model-controller or dependency manager object.Which architecture is more appropriate here?I'm leaning towards the first one as it is (to my mind) better to work with immutable models, updating the whole tree on change of input. This approach gives several benefits: for example it is easier to serialize as the presence of model equals to a finite state. But I'm really unsure about data sources...
Several interdependent models, each with several data sources how to avoid hell and nightmare
design patterns;architecture;domain model;model
There are several interdependent models. Change in one model can trigger changes in several other models.This is exactly what you should avoid. Welcome to Hell.I'm getting a sense from your question that your head is in the technology more than in the business. I think the answer is for you to change your focus slightly...The key to minimizing dependencies is in how you divide a business problem in order to solve it. It sounds like the existing design is already facing some challenges. This makes your job harder as you not only have to understand and interface with business needs, but also with legacy systems that do not currently meet those needs.I would give the technical solution a rest and go back to the business and ask them 2 questions (again): What is the absolute minimum you need from the system on day 1? Where do you see the system capabilities going in the future? Any solution has limits and benefits. Communicate the relevant limits/benefits to the business (leaving out the technical details) and find out how well they fit with the business needs.With the business, design for the future, but then pick a subset of that design to implement for the present. That way you keep it as simple as possible, without completely walling yourself off from the changes you are most likely to have to make to it. Another little trick I sometimes play is to imagine that the system the business and I just designed is all implemented and then imagine how it will be used with the business. Often this teases out critical design considerations that were overlooked. Use cases anyone? How the business will use the system is super-critical...I don't know which of your proposed solutions you'll end up choosing, or if you'll come up with a new solution. No matter how smart I was, if I were to pick one for you, it would not be as helpful as for you to pick one in tandem with the business. The one that helps the business the most is the best way to go.I hope that helps. 24 views, 7 hours, no answers or comments... I thought I'd give it a stab.P.S. If you have to have fail-over from one data-source to another, that begs for a level of indirection somewhere. Ultimately, I'd want a layer in my code that I can ask for the data I need and if it's available at all, that layer will just return it. Then I can write relatively dumb clients that just say, Get me the data and not, Get me the data using SQL-flavor A from Source #1... then if that doesn't work, try using another query language from source #2... Maybe a JSON/XML/YAML service can encapsulate that complexity? Maybe it returns a little metadata footnote in addition to the data: From source C because A took too long to respond and B gave an error.I'm just latching onto the fail-over because it's the clearest requirement I got from your question.
_codereview.97076
I call these text updates Feeds. A Feed object has some basic attributes like its content string, how many lives it has and its priority in the queue. I haven't made a unittest for this one, but below I have added a small test function for the purpose of posting this question. I use this to update statusbar in GUI applications.import threadingimport queueimport timeLOW_PRIORITY = 0MEDIUM_PRIORITY = 1HIGH_PRIORITY = 2class Feed(object): def __init__(self, msg, life=1, priority=LOW_PRIORITY): self.msg = msg self.life = life self.priority = LOW_PRIORITY if life == -1 else priority def hit(self): if self.life > 0: self.life -= 1 elif not self.life: raise ValueError(Feed {} is already dead..format(self)) def __bool__(self): return True if self.life else False def __lt__(self, obj): if self.priority > obj.priority: return True return Falseclass FeedThread(threading.Thread): def __init__(self, globevent, handler, updateinterval=3): super(FeedThread, self).__init__() self.globevent = globevent self.handler = handler self.updateinterval = updateinterval self.feedqueue = queue.PriorityQueue() def PushFeed(self, feed): self.feedqueue.put(feed) def run(self): while not self.globevent.is_set(): try: feed = self.feedqueue.get(block=True, timeout=1) if feed: self.handler(feed.msg) feed.hit() self.PushFeed(feed) time.sleep(self.updateinterval) except queue.Empty: passdef test_feed(): newstime = threading.Event() def bullettin(news): print(\r{:^79}.format(news), end=) scroll = FeedThread(newstime, bullettin) scroll.start() sports_feed = Feed(Barclays Premier League - Man Utd V Tottenham - 12:45, life=2, priority=MEDIUM_PRIORITY) weather_feed = Feed(London - Cloudy, High 26C. Winds EDE at 15 to 30 km/h, life=-1) entertainment_feed = Feed(Upcoming movie - Pixels (2015), life=2) for feed in (sports_feed, weather_feed, entertainment_feed): scroll.PushFeed(feed) time.sleep(15) breaking_feed = Feed(BREAKING NEWS - Cats love lasers - pew pew pew!, priority=HIGH_PRIORITY) scroll.PushFeed(breaking_feed) time.sleep(15) newstime.set()if __name__ == __main__: test_feed()
A tiny module for handling text updates
python;multithreading;python 3.x
null
_scicomp.11829
I am using cvx to solve linear programs with constraints of the form $Ax=b,x\ge0$. However the matrix $A$ is rank deficient and cvx returns a warning and finally displays status as 'Infeasible'. Rank deficient systems can have a solution and my guess is that my system does have a solution. Is there a way to make cvx solve this system without making the matrix full rank?
Solving rank deficient systems with cvx
linear programming;cvx
It's known that CVX itself, and to an extent the solvers it uses, have issues with rank deficiency in the equation matrix. (Hence the warnings.) But what is your aversion to doing some sort of LU factorization here? Also, have you tried all of the solvers, or just one?Another approach is to solve a model that is guaranteed to be feasible. For instance:cvx_begin variables x(n) minimize(norm(A*x-b)) x >= 0cvx_endIf your original problem is feasible, this should have an optimal value that is near zero (to within roundoff error). If it has a non-negligible, positive optimal value, then your original model was infeasible.
_datascience.19637
I have a large file (~1GB) containing the names of birds and their population in the African subcontinent, sorted in ascending order of population. I want to plot this data into a graph to see if the distribution follows a (roughly) bell-shaped curve. How can I do that?
How do I get a bell-curve from a sorted list of data points?
visualization;distribution;plotting;excel
null
_codereview.111161
I am looking for some ways to make my code simpler for this currency converter.currencies = { BRL:(Brazilian Real), USD:(US Dollar), EUR:(Euro), GBP:(Great Britain Pound)}def real_to_dollar(): user_value = raw_input(How many reais? ) ammount = float(user_value) conversion = ammount * 0.26 print str(user_value) + reais is equal to + str(conversion) + dollars.def dollar_to_real(): passdef dollar_to_euro(): passdef euro_to_dollar(): passdef euro_to_pound(): passdef pound_to_euro(): passdef real_to_euro(): passdef euro_to_real(): passdef real_to_pound(): passdef pound_to_real(): passdef dollar_to_pound(): passdef pound_to_dollar(): passprint Welcome to currency converter.print Supported currencies:for currency in currencies: print currency + + currencies[currency]user_choice1 = raw_input(Convert: )user_choice2 = raw_input(To: )if user_choice1 == BRL and user_choice2 == USD: real_to_dollar()elif user_choice1 == USD and user_choice2 == BRL: dollar_to_real()
Currency converter in Python
python;converting;finance
null
_webmaster.35007
Getting many 404 errors on my website for the following URLs:/system/app/pages/admin/revisions*I was going to put Disallow in robots.txt, but it seems there is no way to edit robots.txt in google sites. Did I miss an option? If it's not there, is there a workaround using Webmaster tools?
Edit robots.txt on google sites
robots.txt;404;google sites
null
_codereview.80406
I mainly develop in PHP and every now and again I have to do stuff in JavaScript which I'm not really comfortable, so I would like a review of how I can improve my code and knowledge. This script takes data coming from JSON, does some basic checking on the data fro format and things like that and then displays the data. The code also calls a function in PHP that deals with updating the data in the JSON file, and then repeats the process.$(document).ready( function () { setInterval(function () { console.log(start); $.ajax({url: /QcT/bulk}) .done(function (data) { console.log(Done); $.getJSON(../../../UpdatedData/QC/QC.json, function (data) { var div = document.getElementById('Store'); div.innerHTML = ; var i = 0; for (var i = 0; i < data.length; i++) { var Machine = data[i]; //Correctley format the machine name if (Machine.MachineNo < 10) { MachineName = ZW0100 + Machine.MachineNo; } else { MachineName = ZW010 + Machine.MachineNo; } // Test to see if we have a first off. console.log(Machine + MachineName + override + Machine.FirstoffOverride + FirstOFfTime + Machine.FirstoffTime); if (Machine.FirstoffTime !== null) { Firstoff = <div class='col-md-1' style='border-color: black;padding-left: 0px;margin-right: 2px;border-style: solid;border-width: 2px;-webkit-border-radius: 27px;-moz-border-radius: 27px;border-radius: 27px;padding-right: 0px;background-color: greenyellow;font-size: 30px;text-align: center;width: 46px;margin-left: 10px;color:greenyellow;' > 1 </div>; } else { Firstoff = <div class='col-md-1' style='visibility: hidden; padding-left: 0px;margin-right: 2px;border-style: solid;border-width: 2px;-webkit-border-radius: 27px;-moz-border-radius: 27px;border-radius: 27px;padding-right: 0px;background-color: ##DFDFDF;font-size: 30px;text-align: center;width: 46px;margin-left: 10px;color:#DFDFDF;' > 1 </div>; } //Test to see if a comment is set if (Machine.comment !== null) { comment = Machine.comment; } else { comment = ; } var color = ; var time = ; content = <div class='panel panel-default' style='font-weight: 700;margin-bottom:0px;border-radius: 46px;background-color: #DFDFDF ;box-shadow: 3px 5px 14px #474747;height:63px;margin-bottom: 11px;' >; content += <div class='panel-body' style='padding: 10px;'>; content += <div class='col-md-8'>; content += <div class='col-md-2' style='font-size: 33px;color:black'> + MachineName + </div>; content += Firstoff; content += <div class='col-md-9 text-center' style='font-size: 28px;color:Black;'> + comment + </div></div>; content += <div class='col-md-4'>; $.each(Machine.PassFail, function (key, value) { //Check to see if it's pass or fail if (value.password === '0001') { color = greenyellow; time = value.ReaderTime; } else { color = red; time = value.ReaderTime; } content += <div class='col-md-1' style='padding-left:0px;margin-right: 2px;border-style: solid;border-width: 2px;-webkit-border-radius: 27px;-moz-border-radius: 27px;border-radius: 27px;padding-right:0px;background-color: + color + ;font-size: 30px;text-align: center;' > + time + </div>; }); content += </div></div></div></div>; $(content).appendTo(div); } ; console.log(refresh); }); }); }, 6000); });The data from the Ajax call runs the script that updates the JSON File. It doesn't directly interact with the data, but just updates the JSON file:/../../UpdatedData/QC/QC.json
Checking and displaying JSON data
javascript;jquery
Here are some tips based on pure code-style, including some jQuery tips, personal preferences and JavaScript best practices I am aware of:don't use anonymous functionsCode like this $(document).ready(function () { /* ... */ }); or this setInterval(function () { /* ... */ }, delay); use anonymous functions. I prefer to use function declaration (or at least named function) to help during code debugging, and to help reuse functions. Also, in a general way, I find that using named functions help you architecture your code in a better way and avoid the spaghetti code. What about something like this:function onDocReady () { setInterval(timerFired, delay); }function timerFired () { /* ... */ }$(document).ready(onDocReady);An hybrid solution could have been this:function timerFired () { /* ... */ }$(document).ready(function onDocReady () { // notice that this function has a name setInterval(timerFired, delay);});I find this much more readable than the code below, and it avoids callback-hell code:$(document).ready(function () { setInterval(function () { // ... }, delay);});You can read Angus Croll post about this: https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/don't use jQuery.ready when you don't need itIn most situations, jQuery ready event is not needed. I have explained it in another stackoverflow post so you can read it here: https://stackoverflow.com/questions/10649867/should-a-javascript-function-be-written-and-called-inside-jquery-document-ready. In your case, I assume you're in the situation FOUR and so you can almost safely switch to situation THREE and remove the jQuery.read call.avoid setIntervalsetInterval should be used with huge caution. Basically, setInterval ignores errors and network latency, so it might be harmful. Also, if the time of execution of the intervalled function is longer than the delay, your browser may have hard time handling this. The equivalent of this code setInterval(timerFired, delay); is the following, using safer setTimeout:function timerFired () { /* do work */ setTimeout(timerFired, delay);}timerFired();You can read more about this here, with some demos: http://zetafleet.com/blog/why-i-consider-setinterval-harmfulbe careful with relative pathIn this code $.getJSON(../../../UpdatedData/QC/QC.json, fn), be careful with relative path, maybe one day you'll want to change the location of your JavaScript file and it won't work anymore because of this. Maybe you can have all your config values like this grouped in the top of the file, something like this:var myConfig = { urlBulk: '/QcT/bulk', urlQC: '../../../UpdatedData/QC/QC.json'};$.ajax({url: myConfig.urlBulk}).done(function onBulkResultGot (data) { $.getJSON(myConfig.urlQC, onQCResultGot);});Cache length in loopsThe code for (var i = 0; i < data.length; i++) should be written like this for (var i = 0, len = data.length; i < len; i++). This avoid calculating the length property on each iteration loop. This advice does not apply in one situation although: when the length changes during the loop. But as far as I see, this is not your case here.Use consistent naming conventionIn your code, we can find this var div = document.getElementById('Store'); and this var Machine = data[i];. Both variable div and Machine doesn't follow the same naming convention. You should pick one and stick with it. In general, JavaScript developers like to use camelCase or snake_case for variable name, and PascalCase for class and sometimes functions names.Be careful with variable declarationsBoth Firstoff and content variables are not declared using var keyword. This can lead to some tricky bug so don't forget to use it. Also, your code can be read as follows:$.ajax({url: '/some/url'}).done(function (data) { $.getJSON('/another/url', function (data) { });});You have declared two variable with the same name, data.Also, both color and time variables are not used: only a value is affected but not used anywhere else.Use better variable namesYou have variable named data, div. What are they supposed to represent ? Those names are way too generic IMHO. What if you have to deal with a second div ? Will you name it div2 ? Try to find better name for them, which explains why they are variable, what do they refer too etc..jQuery.each may be overkillIn most cases, jQuery.each(element, fn) can be replace by a far more simple element.forEach(fn). This is true if element is not null and is a true array (not an object). So your code could be written as follow: Machine.PassFail.forEach(function forEachPassFail (value, key) { });. Notice parameters order is not the same as in jQuery.each method. Appart from IE 8 and below, Array.prototype.forEach is widely supported: http://kangax.github.io/compat-table/es5/#Array.prototype.forEach.Avoid multiple DOM callWhen we go one step above your code, we can see something like this:var div = document.getElementById('Store');div.innerHTML = ;var content = 'some content';content += 'whatever'; // multiple times$(content).appendTo(div);The variable div is only used twice, so the code could be written as follows:var content = 'some content';content += 'whatever'; // multiple timesvar div = document.getElementById('Store');div.innerHTML = ;$(content).appendTo(div);And even this could be simplified as:var content = 'some content';content += 'whatever'; // multiple timesvar div = document.getElementById('Store');div.innerHTML = content;This way, you have only one DOM modification, instead of two.Don't embed HTML into JavaScriptYou should not have code like this var Firstoff = <div class='someclass'>...</div>. Following preceding advice, you better use document.createDocumentFragment, or even better, a templating system.Don't embed CSS into HTMLYou should not embed CSS declaration into your HTML code. If you want to add style to an element, use CSS classname for that purpose. Have a look:From this:<div class=col-md-1 style=border-color: black;padding-left: 0px;margin-right: 2px;>...</div>To this:HTML<div class=col-md-1 my-style>...</div>CSS.my-style { border-color: black; padding-left: 0px; margin-right: 2px;}Be careful with indentation styleYour code looks like as follows:$(document).ready( function timerFired () { // indent += 8, why not ? But why use indentation here ? setInterval(function () { // indent += 4, uh ? $.ajax({url: /QcT/bulk}) // indent += 4, ok... .done(function (data) { // indent += 8, uh ?? // ... }); }, 6000); }); // can you guess what does this close ? timerFired (indent=8) & ready call (indent=0)This one looks like more readable IMHO (but others tips such as avoid spaghetti code still apply):$(document).ready(function onReady () { setInterval(function timerFired () { $.ajax({url: /QcT/bulk}) .done(function onBulkResultGot (bulkData) { // ... }); }, 6000);});JavaScript contains a capital SBut this points doesn't really matters anyway :)Also, if you're new to JavaScript world, you may have a look to this post: http://tobyho.com/2011/11/16/7-common-js-mistakes-or-confusions/. It explains 7 common mistakes we found in this world.Finally, and as a side note, I can't recommend you enough to check out and use JSHint.Hope that helps :)
_softwareengineering.284788
Aadit M Shah states in Benefits of prototypal inheritance over classical:One of the most important advantages of prototypal inheritance is that you can add new properties to prototypes after they are created. ... This is not possible in classical inheritance because once a class is created you can't modify it at runtime.But it seems to me that needing the ability to add new properties/methods to your classes at runtime would be indicative of the code author not fully anticipating the needs and responsibilities of the class when defining it.Is this the case?
Does needing the ability to extend a class at runtime imply poor design?
object oriented design;dynamic inheritance
First off, the premise is flawed. You most definitely can modify classes at runtime, e.g. in Ruby:class Foo; endfoo = Foo.newfoo.bar# NoMethodError: undefined method `bar' for #<Foo:0xdeadbeef4815162342>class Foo; def bar; 'Hello' end endfoo.bar# => 'Hello'Python:class Foo: passfoo = Foo()foo.bar()# Traceback (most recent call last):# File <stdin>, line 1, in <module># AttributeError: Foo instance has no attribute 'bar'Foo.bar = lambda self: Hellofoo.bar()# => HelloOn the other hand, there are prototype-based languages, which do not allow you to modify the prototype at runtime, most notably the statically typed prototype-based languages.Now, to answer your question:But it seems to me that needing the ability to add new properties/methods to your classes at runtime would be indicative of the code author not fully anticipating the needs and responsibilities of the class when defining it.Yes. Its Difficult to Make Predictions, Especially About the Future. Therefore, it is sometimes hard if not impossible to know what the shape of an object will be until runtime. Think, for example, of an XML deserializer, which creates objects described by an XML document, whose shape is described by an XML Schema, both of which are passed as command line arguments at runtime.Steve Yegge's classic rant about The Universal Design Pattern is another example, where being able to dynamically add and remove properties from objects is desirable. He gives several case studies, where people have re-invented prototypes and dynamic properties on top of languages that don't have them natively, including inside the Eclipse JDT written in Java and Steve Yegge's own multiplayer role-playing game Wyvern, also written in Java. In Wyvern, property bags with prototypes are being used to model more or less all game objects.
_unix.2639
I'm a long time Window user. Recently, I learned JavaScript/PHP/mySql and considered that Ubuntu Server will be the choice. I'll still work on Windows XP/7, though. Here's my ideaDevelopment Machine (XP/7): Where I do all the programming. The IDEs will be Spket (JavaScript) and Aptana (PHP). Along with other software like PhotoShop, Office...Server (Ubuntu Lucid): This is where I store my data, run my HTTP, email, FTP server... It will be a VPS.So simply put, I'll be working with Windows as a client (IDE, Client Email Software, FTP...) and Ubuntu as a server to manage my data (Mercurial, Apache, mySql...)I'm new, I wonder if there is already someone doing this and working with this mix of client/server. What are the possible downsides of this method? Is working over FTP with a VPS a good idea or not?I'm a solo-developer, I was thinking in the last few days of the best approach to work with the cloud. I do web development. Please reply with anything related and helpful, I would appreciate a lot developers that will write lengthy post about their working environment. I have exactly no specific idea in mind, just looking to make better.Thank you!
Setting up a development environment in Ubuntu
ubuntu;windows
Certainly many people have used Ubuntu Server with Windows clients. The Ubuntu Server Guide covers pretty much all of what you want to do.Here are a few comments on your proposed setup:Ditch FTP. Use SSH instead. Personally, I would also add that you should set up key-based authentication and disable password auth. See this page for some help.I don't see any sort of backup solution mentioned. Be sure to have regular backups.Consider Git. I would consider using Git rather than Mercurial, but that is a personal preference.Think about security from the start--especially if it is going to be facing the web. Again see (1). You don't need to be a security expert, but you should at least consider the following: Use a firewall. With Ubuntu Server this is easy to do using ufw and is talked about in the guide. Don't run services you don't need. Specifically, I would stay away from things like phpmyadmin.Don't provide access or privileges that isn't needed to others.Think about auditing and logging. A more general comment that I don't want to push too hard is that you might consider just moving your development process over to linux as well. In my experience, the tools available for linux make working with a remote server much smoother.
_codereview.19431
I want to store image (details) in my database, and want for each image the possibility to have from 1 to N versions.I want a single file (src) to be associated with a single version. There must not be more than one version for an single image with the same dimensions and format (no point having a version with 1920x1080 jpg and 1920x1080 jpg, whereas 1920x1080 jpg and 1920x1080 png would be ok).I have come out with the following tables :-- ----------------------------------------------------------------------------------- IMAGE TABLE-- ---------------------------------------------------------------------------------DROP TABLE IF EXISTS image_e;CREATE TABLE IF NOT EXISTS image_e( id int unsigned NOT NULL AUTO_INCREMENT, title varchar(32) NOT NULL, alt varchar(16) NOT NULL, PRIMARY KEY (id)) ENGINE = MyISAM DEFAULT CHARSET = utf8 COLLATE = utf8_bin;-- ----------------------------------------------------------------------------------- IMAGE VERSION TABLE-- ---------------------------------------------------------------------------------DROP TABLE IF EXISTS image_version_e;CREATE TABLE IF NOT EXISTS image_version_e( id int unsigned NOT NULL AUTO_INCREMENT, imageId int unsigned NOT NULL, format varchar(4) NOT NULL, size int unsigned NOT NULL, width int unsigned NOT NULL, height int unsigned NOT NULL, src varchar(64) NOT NULL, PRIMARY KEY (id)) ENGINE = MyISAM DEFAULT CHARSET = utf8 COLLATE = utf8_bin;ALTER TABLE image_version_e ADD UNIQUE KEY (imageId, format, width, height);ALTER TABLE image_version_e ADD UNIQUE KEY (src);image_version_e.imageId references image_e.idThis version is MyISAM, i will make a second version for InnoDB with this foreign key.I don't care about insert / update / delete speed, but i do care about select speed as i will use this for a wallpaper gallery with a search function.Are my unique keys done correctly ? Isn't it too much or not enough ? Is the schema well thought ? Is there a way to optimize it ?Thanks for reading and for your help :)
Are these tables concepted correctly?
mysql;sql
The unique keys will enforce the requirements you specified, but unless your data entry program either traps error codes returned by MySQL and prompts the user for correction or checks for uniqueness before saving the record, you will probably experience a lot of record rejections where you won't understand why.I would also use a much larger VARCHAR maximum length for the image_version_e.src column. Remember that VARCHAR columns only require as much storage space as needed for the actual data with trailing spaces stripped (usually). VARCHAR(255) or more is not unreasonable as it will accommodate those really long directory paths or URLs. Your data entry form field for it should be scrollable but much shorter... probably a multiline text field.See more details in the MySQL documentation of CHAR and VARCHAR.
_softwareengineering.189318
I was at an interview recently and although they knew that I was a beginner in javascript they asked me what selectors I used before? I didn't know what to say. I came back home and searched for it but can't find a clear definition. Isn't a selector something like a .class or #id?
What are some JavaScript selectors?
programming languages;javascript;interview
Yes, you were interviewed by morons. Consider that bullet dodged. They were probably thinking of jQuery, which you probably should learn, but it does in fact use CSS selectors and xpath... (whatever you call xpath statements/selector thingies) for syntax. The right answer if you should want to be hired by somebody who makes the same mistake again is JavaScript doesn't have selectors. Are you talking about jQuery? Or are you referring to the DOM API? The DOM API, btw, is something you should already know if you don't.Edit: Okay, maybe not total morons. They could have been thinking of the query selector API (see Dystroy's answer) but IMO, that still should have been clear.
_softwareengineering.214772
I am asking this question in continuation with http-session-or-database-approach.I am planning to follow this approach.When user add product to cart, create a Cart Model, add items to cart and save to DB.Convert Cart model to cart data and save it to HTTP session.Any update/ edit update underlying cart in DB and update data snap shot in Session.When user click on view cart page, just pick cart data from Session and display to customer.I have following queries regarding HTTP Session How good is it to store large data (Shopping Cart) in Session?How scalable this approach can be ? (With respect to Session)Won't my application going to eat and demand a lot of memory?Is my approach is fine or do i need to consider other points while designing this?Though, we can control what all cart data should be stored in the Session, but still we need to have certain information in cart data being stored in session?
Storing large data in HTTP Session (Java Application)
design;database;web applications;session
null
_unix.255867
Apparently NetworkManager recently gained support for macvlan interfaces. I notice it also supports macvtap, and the patch shows it already had some support for tun/tap devices.I thought tap interfaces are normally created by VM software. Then the interface can be joined to a bridge. Or either of tun/tap can have an IP address assigned, again often done by VM software like virt-manager/libvirt. For macvtap, there isn't even anything that NetworkManager could configure! I just can't make sense of it.Question: Can anyone think of a reason to create tun/tap/macvtap devices using NetworkManager?Glossarymacvlan is an alternative to bridging for networking Virtual Machines. Apparently it avoids some overhead. I haven't worked out the corresponding limitations.tun/tap network interfaces provide a corresponding character device, which allows virtual machine implementations to read/write network packets from the interface. tap works at layer 2 (ethernet); tun only works at layer 3 (IP).macvtap provides the same character device, but packets either come out a physical device the macvtap was bound to, or are bridged to a different macvtap/macvlan device on the same physical interface.It can be useful to create a macvlan interface for the host. It wouldn't make sense to create a macvtap interface for the host though.
Why does NetworkManager explicitly support tun/tap devices?
linux;virtual machine;networkmanager
null
_webapps.93472
Recently, twitch.tv videos have added a chat replay feature, where you can see the messages that were sent on chat at the time the video was being streamed live.The stream delay on twitch makes chat quite interesting. Typically most viewers see each other's chat messages in sync with the stream, because most viewers have the same delay. That is, if another viewer sends a chat message about the stream, it's about the same event that you can see on the stream. On the other hand, viewers see the streamer's chat messages some time before the event shows up in the video, while the streamer sees viewers' messages some time after the event really happened.When you're watching the video playback, are you getting the streamer's point of view (i.e. the streamer's messages are on-time but viewers' messages are about what happened 30 s ago), or a viewer's point of view (the streamer's messages are too early but viewers' messages are on-time)?
How is chat replay synchronized on twitch videos?
chat;twitch.tv
Chat replay works from the viewer's point of view, as if the Stream was being replayed live. That's because the stream delay is really Twitch's servers processing the video before broadcasting it back out on the streamer's channel page.You can most clearly see this when watching archives of streamers that include chat in their stream video, such as ProtonJon. Twitch's chat replay is typically 30 seconds ahead of the in-stream chat window.
_cs.69471
Let's say we have a universe $U$ of $n$ elements and a collection $S$ of $m$ subsets of $U$, i.e., $S=\{S_1,\ldots,S_m\}$, and a positive integer $k$. If I ask is there a set cover of $U$ of size $k$ or less, then this is NP-complete. Now suppose that I add the following: $|S_1| \gt |S_2| \gt \ldots \gt |S_m|$.Is this still NP-complete?I guess that, given 1., we know that the sets $S_i$ are all distinct and then the only cover for $U$ is $S$ but I am not sure about this.
Is this variant of set cover NP-complete?
np complete;set cover
As quicksort comments, you can convert any set cover instance to your special case by adding dummy elements. Take a large enough pool of dummy elements, and put all of it into a new set $S_1$. Then add subsets of $S_1$ to the other sets to satisfy your cardinality condition, taking care to leave some of them out. Every solution has to take $S_1$, and otherwise it just has to be a solution to the original problem.This is of course not a formal reduction - this is left to the reader.
_codereview.63237
I would like to know an alternative, more elegant way to write the following method. I am especially not enthusiastic of the nested if statement.hasUserSavedCredentials: function () { var userName = Storage.get(CONFIG.app.storageUserName), password = Storage.get(CONFIG.app.storagePassword), result = false; if (userName !== null && password !== null) { if (userName.length > 0 && password.length > 0) { result = true; // save in state for faster retrivial State.xx.isSaved = result; State.xx.userName = userName; State.xx.password = password; } else { result = false; State.xx.isSaved = false; } } return result; },
Null checks in user validation
javascript;validation
You can remove result = false;, as result is already false.And to get rid of the nested statements, you could use early returns:if (userName == null && password == null) { return false;}if (userName.length <= 0 && password.length <= 0) { State.xx.isSaved = false; return false;}State.xx.isSaved = true;State.xx.userName = userName;State.xx.password = password;return true;Is it correct that when username is null, isSaved = false should not be set? Because if not, then you could just combine the two if statements, either in my example, or in yours.
_unix.365759
When I connect with the Linux, I am under /root library.[root@localhost ~]# lsanaconda-ks.cfg packstack-answers-20170515-095857.txtkeystonerc_admin tmp-packstack-answers-20170515-095856.txtkeystonerc_demoThere is two questions:Why in /root there is ~ in the [root@localhost ~] but not the root?Because if I in /tmp, this is [root@localhost tmp]#.Why connected with linux, I am under the /root, but not the /, if there is something convenient for us to config, where is the benefits?
Why connected with linux we under the /root directory?
linux
First of all, you log in to your home directory which is defined in your password file (/etc/passwd).The ~ simply indicates that you are presently in your home directory and can also be used as a shortcut. If you want to go in your something directory which is inside your home, you can cd ~/something.You do not want to log in any public directory for security reasons because of your profile configuration and connection logs for example.It is not inconvenient to change directories (cd).
_softwareengineering.228848
As an assignment question, I am asked to answer the following:How are cycles handled? Where does the term graph come from? In the examples given, there does not appear to be any clear trick that was done to serialize a cyclic linked list, so I can't discern if anything special is being done on the part of the programmer, or if it's handled internally by the JVM. Moreover, a Google search does not appear to answer the question other than to say that the JVM handles cyclic serialization natively by not re-serializing objects. But I'm not satisfied that this actually answers the question of how. My best guess is that some form of spanning tree algorithm is run on the object graph to remove cycles, but again, this is unconfirmed...Where can I find information to help answer this question?
How does Java handle cyclic data references when serializing an object?
java;serialization
it caches the object and uses references so objects are not written out twice5. If the object has already been written to the stream, its handle is written to the stream and writeObject returns. 12. For regular objects, the ObjectStreamClass for the class of the object is written by recursively calling writeObject. It will appear in the stream only the first time it is referenced. A handle is assigned for the object.http://docs.oracle.com/javase/6/docs/platform/serialization/spec/output.htmlIn other words it checks a IdentityHashMap<Object,Handle> for each object it writes out. and if present will just write out the handle.this can be overridden by using writeUnshared(Object) to write out the object
_reverseengineering.1338
What is the largest program that has been analyzed by a semantics-based static binary analysis?By semantics-based, I mean an analysis that examines the meaning of the program, and does not simply perform a computation on the syntax of the program, such as computing an md5sum.
What is the scalability of state of the art static binary analysis techniques?
static analysis;binary analysis
null
_unix.236139
I have setup my linux system to generate Kernel Core Dump using KDump and kexec packages. I am using the crash tool to analyze the core dump. How do I find the call stack of the process which resulted in the kernel call that crashed? Also, is it possible to include all the running process Call Stack in the Kernel Core Dump? What other useful information could be extracted from Kernel Core Dump?
Finding the Process which resulted in Kernel Panic
linux;kernel;crash
null
_codereview.124825
This is my challenge using JavaScript -> Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.My code works, but I think that it can be better.function diffArray(arr1, arr2) { var newArr = []; arr1.map(function(val){ arr2.indexOf(val) < 0 ? newArr.push(val) : ''; }); arr2.map(function(val){ arr1.indexOf(val) < 0 ? newArr.push(val) : ''; }); return newArr;}diffArray([1, 2, 3, 5, 6, 7], [1, 2, 3, 4, 5]);What do you think?
Diff Two Arrays - return the symmetric difference of the two arrays
javascript;algorithm;array
null
_unix.269546
tl;dr ... found a script that uses ${1+$@} to forward command line arguments to another script. What exactly does this do? When do you use it instead of $@ and $@?There's a simple shell script called runhaskell that is distributed with ghc on Ubuntu 15.10 (and perhaps others). I am trying to figure out how to replace it with something that's aware of cabal sandboxes. The shell script looks like this. It appears to have some variables that aren't used and an unnecessary shebang-like comment (from an earlier version of the script?)#!/bin/bashexedir=/usr/lib/ghc/binexeprog=runghcexecutablename=$exedir/$exeprogdatadir=/usr/sharebindir=/usr/bintopdir=/usr/lib/ghc#!/bin/shexec $executablename -f $bindir/ghc ${1+$@}I'm having trouble understanding the last line. /usr/lib/ghc/bin/runghc is a native executable that runhaskell evidently delegates to, and one of the arguments it passes in is the location of the compiler. Okay, no problem.What does ${1+$@} do and when should you use it? My best guess is that 1 is just a test that always succeeds and that this construction is just being used just to pass in the arguments verbatim. I remember POSIX requires that $@ and $@ behave somewhat differently from what you'd expect, but I don't remember the exact details.
Bash when to use $@, $@, and ${1+$@}
bash
${var+foo} expands to foo if variable var is set (even if empty), and nothing otherwise. In this case the variable is the first positional parameter, $1. So, the ${1+$@} checks if $1 is set and expands to $@ accordingly, and is nothing otherwise.As for $@ and $@, $@ is subject to field splitting and filename expansion after it has expanded to the positional paramters, whereas $@ isn't:$ sh -c 'cd /usr; printf %s\n $@' _ 'a b' '*' abbininclude$ sh -c 'cd /usr; printf %s\n $@' _ 'a b' '*'a b*You almost always want to use $@ over [email protected] for ${1+$@} vs just $@, in POSIX-compliant shells, both would have the same effect. According to this Stack Overflow post:'Hysterical Raisins', aka Historical Reasons.Once upon 20 or so years ago, some broken minor variants of the Bourne Shell substituted an empty string for $@ if there were no arguments, instead of the correct, current behaviour of substituting nothing. Whether any such systems are still in use is open to debate.The autoconf manual section on Shell Substitutions also deals with this:There are also portability pitfalls with particular expansions:$@ One of the most famous shell-portability issues is related to $@. When there are no positional arguments, Posix says that $@ is supposed to be equivalent to nothing, but the original Unix version 7 Bourne shell treated it as equivalent to instead, and this behavior survives in later implementations like Digital Unix 5.0.Also see:Greg Bacon's answer to 'Explain the deviousness of the Perl preamble'
_unix.148141
Basically, its a game server (minecraft) and I have a situation where I am attempting to automate new world generation. Basically, I have a file that gets generated happily which has this snippet in it.file1.txtkeepSpawnInMemory: 'true'spawnLocation: ==: MVSpawnLocation yaw: 0.0 pitch: 0.0 z: 256.5 y: 62.0 x: -223.5autoLoad: 'true'bedRespawn: 'true'This works fine, but I need to extract the z: 256.5, y:62.0 and x: -223.5 respectively and then write a file called file2.txt with the following lines. world: mine x: -223.5 y: 62.0 z: 256.5 yaw: 0.0 pitch: 0.0 name: mineI assume I'll be using something like awk to extract the initial numbers, assigning them to variables then writing the file? I have never used awk before, and I am insanely confused. Appreciate any help in this guys. Im using Ubuntu linux, bash scripts. Can I extract text like that and make them into variables using awk and bash?EDIT:I did forget to mention that the file 1 has multiple instances of x,y and z. It can be accessed here: http://pastebin.com/TqaLcWzVIs there a way to start at a certain line? For example, z, y and x will always be on lines 183, 184 and 185 respectively.
Extracting text string from file, assigning them to variables then writing them to another file?
text processing;awk
Try this script:#!/bin/bashFILE1=/path/to/file1FILE2=/path/to/file2#extracting lines 183 to 185FILE1=$(awk 'FNR>=183&&FNR<=185' $FILE1)#extracting variables Z=$(echo $FILE1 | grep z: | awk '{print $2}')Y=$(echo $FILE1 | grep y: | awk '{print $2}')X=$(echo $FILE1 | grep x: | awk '{print $2}')#YAW=$(echo $FILE1 | grep yaw: | awk '{print $2}')#PITCH=$(echo $FILE1 | grep pitch: | awk '{print $2}')cat <<EOF > $FILE2 world: mine x: $X y: $Y z: $Z yaw: 0.0 pitch: 0.0 name: mineEOFIf you want it to also extract the YAW and PITCH:Change the awk line to extract from line 181:FILE1=$(awk 'FNR>=181&&FNR<=185' $FILE1)Uncomment the YAW and PITCH linesChange the yaw: and pitch: at the very bottom to be:yaw: $YAWpitch: $PITCH
_unix.265228
I'm a sysadmin intern for a web hosting company and I'm trying to figure out how to get this task accomplished so I'll be as descriptive as possible.We have /etc/blockedips and /etc/donotblockI want to create a script that I can eventually setup in cron that will run like once every hour that scans both files and compares them and either a) send an alert out (we use watchdog) or b) automatically removes the IP inside /blockedips that matches what it shouldnt be blocking inside /donotblock as we have a lot of other techs who always add IPs that shouldnt be blocked.The problem I'm having as I am new to scripting is that I can easily run a simple grep command for straight IP addresses (ie: 76.76.76.76 will easily match across both files) but I cant figure out how to do the following:Lets say our companies IP block is 99.10.10.0/24. I don't want to put in every single address inside /donotblock, I just want the script to match any IP that is 99.10.10.* and I am drawing a blank on how to accomplish this.Can someone point me in the right direction with this?Edit: SampleSo the files look like so:/etc/donotblockUs26.225.128.0/18 43.150.128.0/20 44.50.142.0/2473.16.32.0/20 Everyone Else184.123.20.10184.123.20.11and then /etc/blocked_ips76.45.23.1lets say some tech added into the /blocked_ips73.16.32.10, I just want the script to look for 73.16.32.* to make up for that whole subnet.Speaking to the lead engineer he prefers to just have the script automatically remove the IP inside blocked_ips that match whats in donotblockThanks
How to scan and compare two files that will match IP addresses? Script for web hosting company
linux
null
_unix.188727
I have created a script that smartd daemon (smartmontools) executes as per command below.DEVICESCAN -a -m email -M test -M exec /usr/share/smartmontools/my-script -n stand...Smartd appears to be running as root looking at the top command output but it fails to find a config file in /root. $USER, $HOME, whoami, export USER=$(id -u -n) commands do not echo anything, not even an empty line. When executed manually in terminal it prints the current username as expected. Script was chmod'ed to 700.Why is this happening?Edit: Here is the actual script that I want to run.#!/bin/shexport USER=$(id -u -n)echo $whoamiecho USER: echo $USERecho $HOMEEMAIL_EXEC=mailxEMAIL_ACCOUNT=gmailEMAIL_SUBJECT=simplifiedEMAIL_BODY=simplifiedecho $EMAIL_BODY | $EMAIL_EXEC -A $EMAIL_ACCOUNT -s $EMAIL_SUBJECT [email protected] restarting smartd errors are found in the log and no email is sent unlike if executed manually as root.sudo systemctl restart smartdjournalctl -u smartdHere is the output of journalctl log:Test of /etc/smartmontools/run.d/email to [email protected] produced unexpected output (69 bytes) to STDOUT/STDERR:USER:rootAccount `gmail' does not exist.No mail for rootexport USER=$(id -u -n) appears to have set the $USER variable as you mentioned. gmail is a profile in /root/.mailrc file. Same error is produced when running as non-root user because the .mailrc file is missing in users home.How can I set the $HOME variable like the $USER variable? That might give an idea why it's not finding the file.
Shell script printing blank $USER variable when executed by Smartd
shell;shell script;arch linux;root;smartctl
Your ultimate problem was that mailx, when called from a shell script run by smartd, started by systemd, on Arch Linux, was not reading the root user's $HOME/.mailrc file.This was caused by a few factors:The mailx on Arch Linux, s-nail, relies on the environment variable HOME when looking for the .mailrc file. If HOME isn't present, it uses the current working directory. if ((cp = getenv(HOME)) == NULL) cp = .; /* XXX User and Login objects; Login: pw->pw_dir */ homedir = savestr(cp); systemd sets HOME only when the unit configuration file contains the User option.From Environment variables in spawned processes:$USER, $LOGNAME, $HOME, $SHELLUser name (twice), home directory, and the login shell. The variables are set for the units that have User= set, which includes user systemd instances.Since there was no HOME variable in the environment provided to smartd, and it was likely started in the / directory, mailx didn't read the /root/.mailrc file.To fix: add the lineexport HOME=~orexport MAILRC=~/.mailrcto the shell script before it invokes mailxor (not tested by me) addUser=rootto the [Service] stanza of your smartd.service unit configuration file.
_unix.335091
i need a little help. I have bash script what connects to a remote server and copy a logfile to my local server with scp. On remote servers I can't copy keys or install. I have limited rights. I have some dump logs what I need to analyze so i want to copy them on local server. This a little bit tricky cause i use expect command for password. This script is called scp.sh and it looks like:#!/bin/bashexpect -c spawn scp [email protected]:~/path/dir/some.log /home/some.logexpect \Password\send \password\r\interact .Now i have 2 servers (TEST and LIVE) and 2 users and i want to make it like this to execute: ./scp.sh TEST or ./scp.sh LIVE
bash script to execute a command but with different data stored in file
linux;bash;scripting
null
_unix.240430
Linux Mint 17.x contains GTK+ 3.10.8, which is very old. So old, that Eclipse Mars has some serious bugs when running with it (the most serious one is the file names missing in the Git commit dialog https://bugs.eclipse.org/bugs/show_bug.cgi?id=480032).Is there any way to compile + install a newer version of GTK+ on Linux Mint 17? I tried manually installing the packages from Ubuntu Vivid, but that opens up a dependency hell.Alternatively, can I install a newer version of GTK+ in some other directory, and start Eclipse so that it uses that version instead?
How to run Eclipse Mars using a newer version of GTK+ on Linux Mint
linux mint;eclipse;gtk3
I was able to fix this issue by adding the following two lines to the eclipse.ini (simply put it under one of the other --launcher options):--launcher.GTK_version2This will tell eclipse to use GTK2 which is not affected by the bug. I added two images for reference.Before:After:
_softwareengineering.204673
I'm starting to introduce myself in CQRS concepts, but I get stucked with the following situation:Supouse you have an entity that must have an unique name. In order to verify that, prior to create the entity you must make a query, thus you are verifing against the query subsystem.But what happens if the syncronization has not been happened between the command system and the query system yet? Other client just had sent the same name before you.What happens in that case?
CQRS and validations
cqrs
Well, you should not use the query subsystem for validations - use the command subsystem for that. Look into the picture in Fowler's article here - validations are typically placed at the command model side. If, for example, you try to give an entity a unique name, your command subsystem should throw an exception if that name was already used before. The initiator of that command should expect that this may happen, even when he has used the query subsystem before to find a free name.That is, of course, for the case of eventual consistency between those different models, where there is a delay between the synchronisation. If you have a system where both models are strictly kept consistent, rules can be obviously different.
_softwareengineering.135546
Problem: I'm working on coding a few light-weight touch-tablet games and often get stuck with difficulties naming my user interaction/interface classes and their relationships with each other (architecture?). I'm rarely satisfied with any of my solutions, thus doubt and change them several times on down the line. For example, I have a board game with these components (among others):HUD - the HUD frames the view of the game world thus enabling user interactionboardOverlay - this is invisible and lies on top of the viewed game world. It receives and interprets touches, consequently calling methods in thinger.board - maintains all elements on the board.thinger - the class that gets things done, changes game state. I call it thinger since I dont know what it should be called. Better to have a non-descript name than one that will be misinterpreted.Searching for enlightenment: Now I would like to have general/abstract names/architecture for these components which will likely be used in many other games/apps. But I have difficulty coming up with satisfying ones. I have searched the net many a time for guidelines/advice but I find that all of the sources are language/technology/API specific and seldom like their approach. I don't know the name of this discipline/practice to search for for enlightenment. I have tried event driven framework, event driven naming conventions, GUI architecture, +oop +GUI +taxonomy... on and on .... .... with no luck.Question1: Can anyone provide a resource to enlighten me? A technology independent resource that philosophizes about this type of naming and architecture.Extra credit question: It would also be great with a reliable/concise resource discussing practices/disciplines of this context? There are too many different and overlapping usages/interpretations out there. Example: GUI framework, GUI architecture, GUI structure, GUI design - what should the proper usage of these terms be?
GUI architecture and class naming advice
architecture;coding standards;gui;class
null
_codereview.120523
Below is the code to a Message Service. Does anyone have any ideas on how to improve the methods. It doesn't feel clean to me.public enum MessagesType{ Standard, LocationTargeted, Scheduled, Expired}public class MessageService : GenericService<PushMessage>{ public MessageService(IGenericRepository<PushMessage> messages) : base(messages) { } public IQueryable<PushMessage> Get(AuthenticatedUser user, MessagesType type) { var messages = this.Get(); switch (type) { case MessagesType.Standard: messages = messages.Where(_ => string.IsNullOrEmpty(_.LocationLatitude) && _.ReleaseDate == null).IsNotExpired(); break; case MessagesType.LocationTargeted: messages = messages.Where(_ => !string.IsNullOrEmpty(_.LocationLatitude)).IsNotExpired(); break; case MessagesType.Scheduled: messages = messages.Where(_ => _.ReleaseDate > DateTime.MinValue); break; case MessagesType.Expired: messages = messages.Where(_ => _.ReleaseDate > DateTime.MinValue && _.ExpireDate < DateTime.Today); break; default: throw new NotSupportedException(); } return this.FilterMessagesForUser(user, messages); } private IQueryable<PushMessage> FilterMessagesForUser(AuthenticatedUser user, IQueryable<PushMessage> messages) { if (user.Role == Role.Administrator) return messages; if (user.Apps.Length > 0) { if (user.Locations.Length > 0) messages = messages.Where(_ => _.Locations.Select(l => l.Id).Intersect(user.Locations).Any()); else messages = messages.Where(_ => user.Apps.Contains(_.AppId)); } else { messages = messages.Where(_ => _.App.ClientId == user.ClientId); } return messages; }}public static class MessageExtensions{ public static IQueryable<PushMessage> IsNotExpired(this IQueryable<PushMessage> query) { return query.Where(_ => _.ExpireDate == null || _.ExpireDate == DateTime.MinValue || _.ExpireDate < DateTime.Today); }}
Message Service
c#;design patterns
Honestly, it looks fine to my eyes. There are a few things that jump out at me, but all fairly minor. This is the biggest red flag to me. default: throw new NotSupportedException(); }It's the wrong exception type. The msdn doc says:The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality.Which seems close at a glance, but really doesn't hit the nail on the head. An ArgumentException would be much more appropriate here. Even better, use an ArgumentOutOfRange exception to perfectly describe what went wrong. Personal Preference NitpicksUse braces. Save my eyes and yourself a headache later. This line is getting really long. Some new lines would help readability. messages = messages.Where(_ => _.Locations.Select(l => l.Id).Intersect(user.Locations).Any());
_cs.56460
In undergraduate CS, Dynamic Programming problems are often related to Overlapping Optimal Substructure (https://en.wikipedia.org/wiki/Optimal_substructure).Dynamic Programming is also often used in Convex Optimization. Under the context of Dynamic Programming or in general, does Optimal Substructure implies convexity?
Does Optimal Substructure implies Convexity and vice versa?
optimization;dynamic programming;convex hull
null
_unix.175580
I'm writing a setup script for a server, and I need to show the user the login details for the server. They can be automatically redirected to a web page and I don't know any other details.I want to make a temporary webpage that will have the login details in it, but when the user accesses it it will be deleted from disk and the webserver shuts down.I don't mind installing python or perl or something, but if it could be done in just sh that would be great.Any pointers?
How do I set up a self-destructing web page?
ubuntu;webserver
This is a solution that only needs bash and netcat (traditional version). It's probably really insecure, but for a trusted user it probably works ok.Put this script in webscript.sh.#!/bin/bashfile=wantedfile.htmlhost=localhostwhile [ true ]do read a a=`echo ${a} | sed 's/\r//'` if [ ${a} == ] then break fi command=`echo ${a} | grep Host:` if [ ${command} != ] then host=`echo ${a} | awk '{ print $2 }'` fidonelen=`ls -la ${file} | awk '{ print $5 }'`echo HTTP/1.1 200 OKecho Host: ${host}echo Content-Length: ${len}echo cat ${file}rm ${file}Then you just need to use netcat:nc.traditional -e 'webscript.sh' -l -p 80
_unix.67719
I've been using Linux for a while, but only since I started using recent distros (ie.: anything non-Debian) I have started having I/O problems with most of my USB devices. Basically when trying to write any nontrivial amount of data into them the lose connection and or reboot themselves. In the system log I observe these kinds of messages:kernel: usb 1-7: reset high speed USB device using ehci_hcd and address 2kernel: usb 2-1: device descriptor read/64, error -71kernel: usb 2-4: new high speed USB device using ehci_hcd and address 13This happens with both pendrives and USB-connected hard drives. I can not find any useful pattern to detecting which devices will bork and which won't except perhaps size - I've never had 1 or 2 GB pendrives bork with these messages (but then again, no one sells those anymore).When those errors happen, pending reads to drive get locked, also locking whatever program was doing the work until I physically unplug the drive. Of course, after I reconnect the drive, I find files or partitions corrupted, thus losing me a lot of work and forcing me to some other work.Researching around I've found links in places such as the ArchWiki or the SUSE Forums or even this very community indicating that the culprit is the default value of the USB tree attribute max_sectors which specifies how much can be read or written to a USB drive in one go. Any more than what the drive supports and the device resets or crashes. I've found mentions that the value is too high in Linux (240) compared to old kernels or Windows installs (128 or even 64) which of course don't face this problem.Since I value data integrity more than blinding speed (and I hope most people do!) I'd like to somehow change the max_sectors value for any USB storage device where the meaning of any could be ample enough that I can avoid having to write custom commands or rules for the most part. Unfortunately, look where I try I haven't been able to find any configuration line or kernel boot option that can change this value (unlike, say, USB autosuspend).What have I missed or what can I do next? I know that I can write something like the following in a more or less automatic using the udev system, something like this:SUBSYSTEMS==usb, DRIVERS==usb-storage, ATTRS{manufacturer}==Some Company, ATTRS{serial}==xxxxxxxxxx, ATTRS{max_sectors}==240, ATTRS{max_sectors}=128And then reload or reboot the service, but I have not been able to find a generic enough udev rule that would fit as many devices as possible (so long as they are connected via a USB plug). I have the understanding that I can write more specific rules for devices whose max_sectors I want to restore or preserve, but here I'm only interested in a sort of wildcard.I have tried wildcard in some attributes, such as ATTRS{manufacturer}==* to no avail.What is a generic udev rule that can match me as many USB-plugged devices as possible? Is this even the correct way of handling this issue via software? (unloading USB 2.0 modules -as eg.: Ubuntu Forums suggest- seems to be not an option, as at least Fedora seems to have them integrated to the kernel).EDIT: As suggested by frostschutz, I'm using RUN+= to set up the attribute, which actually works (unlike using ATTR=). That's half a solution. I've been able to create a udev rule that matches pretty much everything, but I fear it matches too much.SUBSYSTEMS==usb, DRIVERS==usb-storage, \ RUN+=/bin/sh -c 'echo 64 > /sys/block/%k/device/max_sectors'The problem with this rule is that it'll set max_sectors for everything, including devices that have a lower value than 64. I've tried to make it more specific:SUBSYSTEMS==usb, DRIVERS==usb-storage, ATTRS{max_sectors}==240, \ RUN+=/bin/sh -c 'echo 64 > /sys/block/%k/device/max_sectors'But this doesn't work. I think I'm using the correct scope for udev rules (use attributes from one part of the tree and from one parent). What am I doing wrong?EDIT2: Accepted the answer below. As it turns out, RUN+= does the trick, whereas using ATTRS{}= for some reason doesn't. Also, the reason why I couldn't get to make a generic rule work was because I had misunderstood from the udev manpage. A rule must have at most attribute from one parent - that means if I want to use two sections, the second one must be the actual dvice. These two work mostly perfectly:SUBSYSTEM==scsi, ATTRS{max_sectors}==240, \ RUN+=/bin/sh -c 'echo 64 > /sys/block/%k/device/max_sectors'(note the singular for the attribute, first attribute is from the actual USB device and second one from a singular ancestor at the device tree)SUBSYSTEMS==usb, DRIVERS==usb-storage, ATTRS{max_sectors}==240, \ RUN+=/bin/sh -c 'echo 64 > /sys/block/%k/device/max_sectors'(this one uses two attributes from the same ancestor at the device tree)Also You can do the following: (use == to check, and = to assign):SUBSYSTEM==scsi, ATTRS{max_sectors}==240, ATTRS{max_sectors}=64On my system (Mageia 4, 3.14.24 core i7) I had to do the opposite due terribly slow write speeds (2MB/sec) on Kingston DT101 G2 16GB:vi /usr/lib/udev/rules.d/81-udisks_maxsect.rules and add:SUBSYSTEMS==scsi, ATTR{max_sectors}==240, ATTR{max_sectors}=32678And the dd write speed went up 3x times :-) mc cp probably 10-20x up (after I had started first partition @8192'th sector and reformatted with 64k aligned clusters):mkfs.vfat /dev/sdh1 -n KINGSTON16G -s 128 -R 4592and use fsck.vfat -v /dev/sdh1to check alignmentDefault mas_sectors (240) seem to cause high write amplification on some of the cheap new drives. But be very careful with such high setting, the similar effect is achieved at 2048 sectors:SUBSYSTEMS==scsi, ATTR{max_sectors}==240, ATTR{max_sectors}=2048Test all yours old USB devices, that they still work well. Use vendor/model attributes in the rules files to be more specific.
Change value of USB max_sectors for an entire family of devices
usb;udev
Sounds like a hardware issue you should go and fix. Powered USB Hub (if it's a power supply related issue), different USB cables, no front panel, a different USB controller (addon card), ...If it stays unreliable, an option would be using the sync mount option for USB media. That way no caching is done whatsoever, but you will see a big impact on performance as a result. Also (for flash drives) a possibility of extra writes (like if you create a file and immediately delete it, with async it would never be written in the first place, whereas sync always writes everything immediately).
_codereview.83573
This macro is made to randomly draw specific number of civilization choices for a specific number of Civ V players. It is based on a list of 43 possibilities and the for loop in the while loop checks for already picked civilizations. Constant cell references point to values obtained with scroll-bars in the worksheet. The variable based cell references are made to structure the results in a two-column design.Are there any smart ways to make my code better from both an aesthetic as well as functional view?Sub CIV_draw()Range(K2:M50).ClearContentsDim x As Integerx = Cells(3, 3).ValueFor i = 1 To x Cells(3 + (Cells(3, 7).Value + 2) * (i - 1), 11).Value = Player & i For j = 1 To Cells(3, 7).Value Dim Rand_CIV As String Dim RandNum As Integer Dim checkVal As Boolean checkVal = False While checkVal = False RandNum = CInt(Int(43 * Rnd())) + 1 Rand_CIV = Cells(RandNum, 16).Value & ( & Cells(RandNum, 15).Value & ) For Z = 1 To 50 If Cells(Z, 12) = Rand_CIV Then Exit For End If If Z = 50 Then checkVal = True End If Next Z Wend Cells((Cells(3, 7).Value + 2) * (i - 1) + (j + 3), 12).Value = Rand_CIV Next jNext iEnd SubI know for example that my duplicate check isn't optimal, and I would like to get suggestions for alternative solutions.
Randomizing Civilization 5 team choice
vba;excel
null
_codereview.26155
I know that this is a complete mess and does not even come close to fitting PEP8. That's why I'm posting it here. I need help making it better.bookName = NoneauthorName = NonebookStartLine = NonebookEndLine = Nonedef New_book(object): def __init__(self, currentBookName, currentAuthorName, currentBookStartLine, currentBookEndLine): self.currentBookName = currentBookName self.currentAuthorName = currentAuthorName self.currentBookStartLine = currentBookStartLine self.currentBookEndLine = currentBookEndLineimport urllib.requestdef parser(currentUrl): #parses texts to extract their title, author, begginning line and end line global bookName global authorName global bookStartLine global bookEndLine global url url = 'http://www.gutenberg.org/cache/epub/1232/pg1232.txt' #machiaveli url = currentUrl book = urllib.request.urlopen(url) lines = book.readlines() book.close() finalLines = [line.decode()[:-2] for line in lines] for line in finalLines: if Title in line: currentBookName = line[7:len(line)] break for line in finalLines: if Author in line: currentAuthorName = line[8:len(line)] break currentBookStartLine,currentBookEndLine = False,False for index,line in enumerate(line,start=1): if *** START OF THE PROJECT in line: currentBookStartLine = index if *** END OF THE PROJECT in line: currentBookEndLine = index url = currentUrl bookName = currentBookName authorName = currentAuthorName bookStartLine = currentBookStartLine bookEndLine = currentBookEndLineparser('http://www.gutenberg.org/cache/epub/768/pg768.txt') #wuthering heightsprint(url)print(bookName)print(authorName)print(bookStartLine)print(bookEndLine)
New book parser
python;beginner;parsing
null
_unix.41739
Sometimes I misunderstand the syntax of a command:# mysql -d testmysql: unknown option '-d'# echo $?2I try again and get it right:# mysql --database testWelcome to the MySQL monitor.mysql >...How do I prevent the first command, with error code different than 0, to enter the history?
Keep only successful commands in BASH history
bash;command history
I don't think you really want that. My usual workflow goes like this:Type a commandRun itNotice it failingPress UP keyEdit the commandRun it againNow, if the failed command weren't saved into history I couldn't get it easily back to fix and run again.
_softwareengineering.264177
To put this in context, I have the following scenario. I am writing a Common Lisp program that works with strings and lists of characters.In a certain function foo, the value of a variable suff is a list of characters. Further on in the code, I forgot that suff was a list and treated it as a string, calling(subseq suff 0 1)I did not notice the mistake, because subseq works both on strings and lists:CL-USER> (subseq abc 0 1)aCL-USER> (subseq '(#\a #\b #\c) 0 1)(#\a)So in the subsequent code I assumed I was working with strings while in fact I was moving around lists of characters.These wrongly-typed results were finally formatted by the program's output function using (concatenate 'string .... I was lucky, because concatenate happily produces a string when given lists of characters as arguments.I only discovered this mistake when adding more tests (yes, I know, TDD, but that's another topic) and testing foo directly.Since my program was running properly - at the time my output function was the only piece of code that was using the corrupted data - I cannot say that the program as a whole contained a bug even though function foo, taken separately, was buggy.Is there a special name to describe such an incorrect internal behaviour that does not manifest externally as a bug?
Is there a name for an internal incorrect behaviour that does not manifest itself as a bug?
bug;errors
A bug is a bug even when no one has found it.According with this wikipedia article:A software bug is an error, flaw, failure, or fault in a computer program or system that causes it to produce an incorrect or unexpected result, or to behave in unintended ways.The behavior was not what you intended, so it's a bug. You may call it a latent bug, a dormant bug, etc.Some bugs have only a subtle effect on the program's functionality, and may thus lie undetected for a long time.According to that article, the bug you talk about could be classified as a resource bug, meaning:Using an otherwise valid instruction on the wrong data typeIn conclusion, what hasn't yet manifested itself externally, is really a dormant bug, waiting for an specific situation to manifest itself, usually in a production environment and during a weekend.
_unix.148303
I am trying to set up an apt repository.This repository is actually replacing one that already exists and is functioning fine. I can't manage to install a package from this repo.In my /etc/apt/sources.list, I have the line:deb http://mirror.cs50.net/appliance50/2014/debs/dists/trusty/main/binary-i386 /An apt-get update goes through perfectly fine.But then something like apt-get install appliance50 (a package in that repo) gives me:Err http://mirror.cs50.net/appliance50/2014/debs/dists/trusty/main/binary-i386/ appliance50 2014-0 404 Not FoundE: Failed to fetch http://mirror.cs50.net/appliance50/2014/debs/dists/trusty/main/binary-i386/./appliance50_2014-0_i386.deb 404 Not FoundE: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?But then copying that URL into a browser downloads the file just fine! Is there some fundamental step that I'm missing? Does it have to do something with the fact that this server is redirecting the request to S3?Edit:Here's the output of sudo apt-get -o Debug::Acquire::Http=true install appliance50, per the comment:root@ubuntu:~# sudo apt-get -o Debug::Acquire::Http=true install appliance50Reading package lists... DoneBuilding dependency treeReading state information... DoneThe following packages were automatically installed and are no longer required: apt-clone archdetect-deb cifs-utils dmraid dpkg-repack gir1.2-appindicator3-0.1 gir1.2-json-1.0 gir1.2-timezonemap-1.0 gir1.2-xkl-1.0 kpartx kpartx-boot libdebian-installer4 libdevmapper-event1.02.1 libdmraid1.0.0.rc16 libldb1 libntdb1 libtalloc2 libtevent0 libtimezonemap1 libwbclient0 localechooser-data lvm2 lzma python-crypto python-ldb python-ntdb python-samba python-talloc python-tdb python3-icu python3-pam rdate samba-common samba-common-bin samba-libs watershedUse 'apt-get autoremove' to remove them.The following packages will be upgraded: appliance501 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.Need to get 1,205 kB of archives.After this operation, 4,096 B of additional disk space will be used.0% [Working]GET /appliance50/2014/debs/dists/trusty/main/binary-i386/./appliance50_2014-0_i386.deb HTTP/1.1Host: mirror.cs50.netUser-Agent: Debian APT-HTTP/1.3 (1.0.1ubuntu2)HTTP/1.1 404 Not FoundCache-control: no-cache=set-cookieContent-Type: text/html; charset=UTF-8Date: Mon, 04 Aug 2014 14:23:53 GMTServer: ApacheSet-Cookie: AWSELB=27CBB9F102866AACDE415904FB505399868B9DB4E22AC5183099E4BEEC583EF1DFA3B6E45DCB1D708481F98DC786A644C763A900F7898475BA865AD219D4E4F1F157545837;PATH=/;MAX-AGE=3600Content-Length: 0Connection: keep-aliveErr http://mirror.cs50.net/appliance50/2014/debs/dists/trusty/main/binary-i386/ appliance50 2014-0 404 Not FoundE: Failed to fetch http://mirror.cs50.net/appliance50/2014/debs/dists/trusty/main/binary-i386/./appliance50_2014-0_i386.deb 404 Not FoundE: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?
apt-get install gives 404 not found, but URL works
apt
It's a bug on apt-get, that is not sending the correct GET headers, so the server answers with 404.For example, telnet to the server mirror.cs50.net at port 80 (HTTP), and enter the following (emulating an apt-get request):GET /appliance50/2014/debs/dists/trusty/main/binary-i386/./appliance50_2014-0_i386.deb HTTP/1.1User-Agent: Debian APT-HTTP/1.3 (1.0.1ubuntu2)Host: mirror.cs50.netAccept: */*Then you will see the following:telnet mirror.cs50.net 80Trying 54.84.6.206...Connected to mirror.cs50.net.Escape character is '^]'.GET /appliance50/2014/debs/dists/trusty/main/binary-i386/./appliance50_2014-0_i386.deb HTTP/1.1User-Agent: Debian APT-HTTP/1.3 (1.0.1ubuntu2)Host: mirror.cs50.netAccept: */*HTTP/1.1 404 Not FoundCache-control: no-cache=set-cookieContent-Type: text/html; charset=UTF-8Date: Mon, 04 Aug 2014 18:31:01 GMTServer: ApacheSet-Cookie: AWSELB=27CBB9F102866AACDE415904FB505399868B9DB4E22AC5183099E4BEEC583EF1DFA3B6E45DFCB95EFBFF7B8F8F555126DCFFF8A461898475BA865AD219D4E4F1F157545837;PATH=/;MAX-AGE=3600Content-Length: 0Connection: keep-aliveIf we leave out the dot (/./) in the GET request, then the request responds with a redirect, i.e. 302, which is correct.GET /appliance50/2014/debs/dists/trusty/main/binary-i386/appliance50_2014-0_i386.deb HTTP/1.1Host: mirror.cs50.netUser-Agent: Debian APT-HTTP/1.3 (1.0.1ubuntu2)HTTP/1.1 302 FoundCache-control: no-cache=set-cookieContent-Type: text/html; charset=UTF-8Date: Mon, 04 Aug 2014 19:03:27 GMTLocation: http://dkui3cmikz357.cloudfront.net/appliance50/2014/debs/dists/trusty/main/binary-i386/appliance50_2014-0_i386.debServer: ApacheSet-Cookie: AWSELB=27CBB9F102866AACDE415904FB505399868B9DB4E22AC5183099E4BEEC583EF1DFA3B6E45DFCB95EFBFF7B8F8F555126DCFFF8A461898475BA865AD219D4E4F1F157545837;PATH=/;MAX-AGE=3600Content-Length: 0Connection: keep-aliveI've checkd this out with other mirrors and they report the same:Trying 64.50.233.100...Connected to ftp-nyc.osuosl.org.Escape character is '^]'.GET /debian/pool/main/e/./efivar_0.10-5_i386.deb HTTP/1.1 Host: ftp-nyc.osuosl.orgUser-Agent: Debian APT-HTTP/1.3 (1.0.6)HTTP/1.1 404 Not FoundDate: Mon, 04 Aug 2014 18:47:03 GMTServer: ApacheContent-Length: 307Content-Type: text/html; charset=iso-8859-1<!DOCTYPE HTML PUBLIC -//IETF//DTD HTML 2.0//EN><html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL /debian/pool/main/e/efivar_0.10-5_i386.deb was not found on this server.</p><hr><address>Apache Server at ftp-nyc.osuosl.org Port 80</address></body></html>Connection closed by foreign host.You should include in your bug report that apt-get should strip the get headers of the dot-n-slash.