Create "client in server" for send request for server

Question: I want to create something like this:

And i didn't know, how to create "client in server" in Twisted, for send response to another server. I mean sheme:
for example, it was been write some file into fs1:
 Client -> Server -> FSClient(created into Server.onMessage()) -> Fileserver
and get response:
 Fileserver -> FSClient -> Server -> Client
client.py:
ADDRESS = '127.0.0.1'
PORT = 5000

import os
import time
from random import shuffle
from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS

class DFSClientProtocol(WebSocketClientProtocol):

    def onOpen(self):
        text_files = [f for f in os.listdir(".\\initial") if f.endswith('.txt')]

        # write data into DFS
        shuffle(text_files)
        for file_name in text_files:
            file_path = str(".\\initial\\"+file_name)
            f = open(file_path, 'r')
            message = '[W]['+file_name+']'+f.read()
            self.sendMessage(message)
            f.close()

        # read from DFS
        shuffle(text_files)
        for file_name in text_files:
           message = '[R]['+file_name+']'
           self.sendMessage(message)

    def onMessage(self, msg, binary):
        typeMsg = msg[:3]
        file_name = msg[4:16]
        if typeMsg == '[C]':
            message = msg[17:]
            file_path = str(".\\read\\"+file_name)
            f = open(file_path, 'w')
            f.write(message)
            f.close()

if __name__ == '__main__':
    factory = WebSocketClientFactory("ws://" + ADDRESS + ":" + str(PORT), debug = False)
    factory.protocol = DFSClientProtocol
    connectWS(factory)
    print 'connecting to %s port %s' % (ADDRESS, PORT)
    reactor.run()

server.py (and fileserver-client):
ADDRESS = '127.0.0.1'
PORT = 5000
OPERATION = ''
SERVERS = 0
FILES = {}
SERVERS_PORT = [5001, 5002, 5003, 5004]
SERVER_FILEDIRS = ('fs1', 'fs2', 'fs3', 'fs4')
BYTES = [0, 0, 0, 0]

import time
from socket import gethostbyaddr
from twisted.internet import reactor
from autobahn.websocket import WebSocketServerFactory, WebSocketServerProtocol, listenWS, WebSocketClientFactory, WebSocketClientProtocol, connectWS

class FSClient(WebSocketClientProtocol):

    def onOpen(self):
        # send request to Fileserver
        self.sendMessage(OPERATION)

    def onMessage(self, msg, binary):
        # get response from Fileserver and resend to Server
        self.sendMessage(msg)

class DFS(WebSocketServerProtocol):

    def onOpen(self):
        peer = self.transport.getPeer()
        print "[USER][%s] User with %s connected" % (time.strftime("%H:%M:%S"), peer)

    def connectionLost(self, reason):
        print '[USER][%s] Lost connection from %s' % (time.strftime("%H:%M:%S"), self.transport.getPeer())

    def onMessage(self, msg, binary):
        typeMsg = msg[:3]
        file_name = msg[4:16]
        if typeMsg == '[W]':
            print "[W][%s] Write %s file into DFS" % (time.strftime("%H:%M:%S"), file_name)
            # at this place i want to send request to FSClient and this object send request for Fileserver
            # Client -> Server -> FSClient -> Fileserver
            # and when fileserver doing somework, he send response by sheme:
            # Fileserver -> FSclient -> Server -> Client
        elif typeMsg == '[R]':
            print "[R][%s] Read %s file from DFS" % (time.strftime("%H:%M:%S"), file_name)

if __name__ == '__main__':
    import sys
    if len(sys.argv)<2:
        sys.exit("Using server.py [SERVERS]")
    factory = WebSocketServerFactory("ws://" + ADDRESS + ":" + str(PORT), debug = False)
    SERVERS = int(sys.argv[1])
    factory.protocol = DFS
    listenWS(factory)
    print 'Server starting up on %s port %s' % (ADDRESS, PORT)
    reactor.run()

fileserver.py:
ADDRESS = '127.0.0.1'
PORT = 5001
CATALOG_NAME = ''
FILES_PATH = ''

import time
from socket import gethostbyaddr
from twisted.internet import reactor
from autobahn.websocket import WebSocketServerFactory, WebSocketServerProtocol, listenWS

class FS(WebSocketServerProtocol):

    def onOpen(self):
        peer = self.transport.getPeer()
        print "[USER][%s] User with %s connected" % (time.strftime("%H:%M:%S"), peer)

    def connectionLost(self, reason):
        print '[USER][%s] Lost connection from %s' % (time.strftime("%H:%M:%S"), self.transport.getPeer())

    def onMessage(self, msg, binary):
        typeMsg = msg[:3]
        file_name = msg[4:16]
        if typeMsg == '[W]':
            print "[W][%s] Write %s file into %s" % (time.strftime("%H:%M:%S"), file_name, CATALOG_NAME)
            message = msg[17:]
            file_path = FILES_PATH + file_name
            f = open(file_path, 'w')
            f.write(message)
            f.close()
            print "File %s successfully writen..." % file_name
            self.sendMessage('[C]['+file_name+']OK')
        elif typeMsg == '[R]':
            print "[R][%s] Read %s file from %s" % (time.strftime("%H:%M:%S"), file_name, CATALOG_NAME)
            print "File %s successfully read..." % file_name
            file_path = FILES_PATH + file_name
            f = open(file_path, 'r')
            message = '[O]['+file_name+']' + f.read()
            f.close()
            self.sendMessage(message)

if __name__ == '__main__':
    import sys
    if len(sys.argv)<4:
        sys.exit("Using fileserver.py [IP] [PORT] [file_catalog_name]")
    ADDRESS = str(sys.argv[1])
    PORT = int(sys.argv[2])
    CATALOG_NAME = str(sys.argv[3])
    FILES_PATH = '.\\data\\' + CATALOG_NAME + '\\'
    factory = WebSocketServerFactory("ws://" + ADDRESS + ":" + str(PORT), debug = False)
    factory.protocol = FS
    listenWS(factory)
    print 'Server starting up on %s port %s' % (ADDRESS, PORT)
    reactor.run()

Answer: The short version, for the forwarding WebSocket in a WebSocket server to another server again over WebSocket: in DFS, create a new WebSocketClientFactory and call connectWs in DFS.onOpen. You probably don't want to establish a new forwarding WebSocket connection upon each and every WebSocket message coming in to DFS.
This is only if I get what you want to do: see, it's good that you posted code (otherwise I had been completely clueless), but it would be also good to better describe what you actually trying to achieve - high-level.
Comment: In this case, you probably should use Twisted `processProtocol`: http://twistedmatrix.com/documents/current/core/howto/process.html
Comment: Im find one of the solutions: using subprocess module. Create communication between FSclient and Server by PIPE, and get response with this. It's really works! - im checked


WePay Delayed Payment with auto_capture (WePay Payment Gateway)

Question: I am working on an application integrating wepay's delayed payment functionality into it. While accessing /checkout/create api call on stage.wepay.com, it takes to payment page and the final response always gives the state as authorized.
I had passed the auto_complete parameter as false and the expected return state was reserved but instead wepay is always returning the authorized state.
Answer: It seems wepay always sends the response as authorized state. It will be returned as reserved only if we make a second request. This is the response I got from the wepay team :

Ticket #149740: Delayed payment issue on stage.wepay.com
Your request (#149740) has been updated .
To review, comment and continue the discussion, follow the link below:
http://support.wepay.com/tickets/149740
Chris Chen, Sep 08 09:50 am (PDT):
Hi xxxx,
That's actually how it's supposed to work. Authorized will turn into reserved. Very rarely will >something fail after Authorized except for something like fraud. This is a very very small fraction >of transactions.
We recommend you consider Authorized as successful.
Thanks.
Chris


Rails Join Table Problem

Question: I am working on a rails project and am having some issues with the following join:
@page = Page.find(params[:id], :joins => "LEFT JOIN page_translations ON page_translations.page_id = pages.id")

For some reason its only pulling back everything from the Pages table.
Here is my model for Page
class Page < ActiveRecord::Base
  has_many :users_pages
  has_many :users, :through => :users_pages
  has_many :page_translations
  has_many :categories
  accepts_nested_attributes_for :page_translations
  accepts_nested_attributes_for :categories
end

Here is my model for PageTranslation
class PageTranslation < ActiveRecord::Base
  belongs_to :pages
end

Thanks in advance for all of the help!
Edit (@thenduks)
The log runs two separate queries:
Page Load (0.5ms)  SELECT `pages`.* FROM `pages` WHERE (`pages`.`id` = 1) LIMIT 1

PageTranslation Load (0.5ms) SELECT `page_translations`.* FROM `page_translations` WHERE (`page_translations`.page_id = 1)

Here is what my controller looks like:
@page = Page.find(params[:id], :include => :page_translations)

Comment: What are you expecting? What do you get when you do page.page_translations?
Comment: Dude. I just figured it out! I'll update my answer below...
Comment: Here's the same question with good answer: http://stackoverflow.com/questions/27523326/when-joining-table-rails-anyway-makes-additional-request-when-accessing-fields
Answer: I was stumped about this same thing and wasted a few hours trying to figure it out. It turns out that using the joins method of the query interface doesn't initialize the models related to the tables being joined. You can see this by watching the SQL statements in the server console, or by even redirecting ActiveRecord logging to STDOUT in your Rails console.
I was very disappointed by this. It just doesn't seem like how the joins method should work -- it certainly wasn't what I was expecting. I was expecting it to eager load, since it was in the eager load section of the Edge Guides.
Anyway, I couldn't waste any more time trying to figure it out, so what I did instead is use the fancy query interface to simply build my query, used to_sql to get the SQL for my query, and then passed the SQL to select_all, which returns an array of hashes, where each element in the array (each hash) represents a row.
Example:
query = Post.joins("LEFT JOIN categories ON post.category_id = categories.id")
query.select("posts.*, category.category_name")
con = ActiveRecord::Base.connection
results = con.select_all(query.to_sql)

Results:
[{"id": 1, "title": "joins, why have you forsaken me", "category_name": "frustration"},{"id": 2, "title": "pizza", "category_name": "food"}]

To be honest, I would still like to know for certain if it is possible to do it the way we think it should work, or the way it ought to work. Otherwise, I see no reason for having a joins method, other than to help us build the query. So if any Rails gurus out there know how to use joins to populate models related to those tables, PLEASE LET ME (US) KNOW!
Anyway, I hope this helps you move along for now.

UPDATE: So I think I just figured it out. I stumbled across this blog post. As it turns out, when using the joins method of the query interface, Rails will actually add the columns you selected from the joined tables as attribute methods of the model being joined against.
Using the same example above, I can actually access the category_name of each post by simply calling post.category_name. #$%! Unbelievably simple, but no documentation whatsoever on this!
Here it is once again:
query = Post.joins("LEFT JOIN categories ON post.category_id = categories.id")
query.select("posts.*, category.category_name")
posts = query.all

# access a post's category name
puts posts[0].category_name

# this is what I thought I would be able to do
# without Rails making another query to the database
puts posts[0].category.category_name

I hope this helps! :)
Comment: No prob. Glad I could help. =)
Comment: Added an update to the end of my original post. Check it out.
Answer: How about:
Page.find( params[:id], :include => :page_translations )

Edit:
Ok, so some time recently the behavior of ActiveRecord when it comes to joins/includes seems to have changed. The guides still refer to being able to do this though two associations, as in has_many :orders, :include => :line_items and similar... but as far as including records from a has_many... After consulting with a co-worker we came across some info on the subject. Seems that the single monolithic queries were just getting too complex and ugly and it was causing problems for some of the fancier niceties that ActiveRecord gives you and duplicate rows, that kind of thing.
TL;DR: It doesn't work like that anymore. 2 queries is expected.
Comment: Ah, it's probably because you've named the `belongs_to` in `PageTranslation` wrong. You probably need `belongs_to :page`.
Comment: Its still pulling everything back just from the pages table
Comment: @thenduks, my model contains belongs_to :page and I am still only not getting the expected results of everything coming back in the query. This has got me stumped beyond belief! I mean quite simply I could make two database calls, but thats not effective.
Comment: In your question it says `belongs_to :pages`... What does the log say the query is?
Comment: And I tried running the following query in MySQL directly and it works

Query:
SELECT * FROM pages LEFT JOIN page_translations on pages.id = page_translations.page_id

Rails Join Table Problem


How to determine if some Linear Transformation exists

Question: I have these vectors below:

And i have this question about this below:
Is there a linear transformation L such that L (u1) = u2 and L (u3) = u4?
If yes:
How many such L are there? Enter the default matrix for such an image
L. If the answer is no: Explain
I know that a Linear Transformation you can add them togheter and you can also multiply them by a scalar but i'don't know here?
And another thing is that i searched about this and they told me about Linear Independent vectors or something??
Answer: First of all, we could just define a transformation by saying $L(u_1) = u_2$ and $L(u_3)=u_4$. This is possible because $u_1$ and $u_3$ are linearly independent (which means the only way to obtain zero as a linear combination of $u_1$ and $u_3$ is by plugging in coefficients zero:
$$a u_1 + bu_3 = 0 \Rightarrow a=b=0)$$
Why is it possible to "just define the transformation as we want"? Because a system of linearly independent vectors is contained in a basis of the vector space in which we are working, that means we can add more vectors to $\{u_1, u_3\}$ (in this case exactly one more) to form a basis of $\mathbb R^3$. And a linear transformation is described by how it acts on the basis vectors because every vector $v \in \mathbb R^3$ is a unique linear combination of the three basis vectors.
So: yes, there is a transformation $L$ which satisfies your given conditions. And since we also have infinitely many choices for what the image of the third basis vector should be, there are infinitely many such transformations.


Can't upgrade to 17.04 due to full /boot, already cleaned old kernels

Question: I've a /boot partition with 232MiB inside. Of those, 102.2MiB are free.
I've already performed any possible necessary cleanup, have only 2 (two) kernels installed, with each taking around 50MiB:
$ sudo du * -h | sort -n
1.0K    lost+found
1.4M    abi-4.8.0-42-generic
1.4M    abi-4.8.0-46-generic
2.1M    grub.bak/i386-pc
2.1M    grub/i386-pc
2.3M    grub/fonts
2.4M    grub.bak/fonts
3.9M    System.map-4.8.0-42-generic
3.9M    System.map-4.8.0-46-generic
4.4M    grub.bak
6.8M    grub
7.2M    vmlinuz-4.8.0-42-generic
7.2M    vmlinuz-4.8.0-46-generic
41M     initrd.img-4.8.0-42-generic
41M     initrd.img-4.8.0-46-generic
126K    grub/locale
180K    memtest86+.bin
182K    memtest86+.elf
182K    memtest86+_multiboot.bin
196K    config-4.8.0-42-generic
196K    config-4.8.0-46-generic
726K    extlinux/themes/debian-wheezy
727K    extlinux/themes
781K    extlinux

I've now tried to upgrade from Ubuntu 16.10 to Ubuntu 17.04 via update-manager -d, and it fails complaining about lack of space on /boot. This seems unreasonable to me.
I could very well resize /boot, but since it is already over what nearly all sources recommend, I'm afraid this is going to turn into a regular thing (and it takes quite some time for me since /boot is currently squeezed between other partitions).
Should I just remove the /boot partition and merge it with /? What am I risking in doing so?
Comment: 232mb is quite low. I used to have mine set for that and was forever running out of space. I increased it to 500mb, it's not like I'll miss the space from elsewhere. Yes, some guides will tell you 250mb minimum, but that's MINIMUM. You've got that, and your system works, so technically it's accurate. But you need to constantly maintain /boot when it has so little space. Bump it up to 500mb or even 1gb and you'll never need to worry about running out of space. If it's in between partitions, steal the space from the one to the left if you can - it'll be quicker
Comment: @Will I'll shift everything over then. LVM partitions are a pain to shrink.
Answer: If you have performed a system update, reboot your machine and execute the following command:
dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d' | xargs sudo apt-get -y purge

This will remove all the old kernels and generate a new Grub menu for you which will contain only the current kernel that you are using. You can then try an upgrade and see if the error has gone. Source:
https://ubuntugenius.wordpress.com/2011/01/08/ubuntu-cleanup-how-to-remove-all-unused-linux-kernel-headers-images-and-modules/
Comment: I know I can remove the last remaining kernel, but I'd prefer not to, since as a solution it would be way too brittle. Also keeping at least a backup kernel seems reasonable in case something goes wrong.
Comment: Then maybe you should resize the boot partition using  GParted. First, decrease the size of a partition according to your settings, lets say /home and then increase your boot partition to the desired size. A livecd is recommended to make such changes.
Answer: FWIW, this is a known bug that's been fixed; but the fix won't help you, since the size is set when you install Ubuntu. See the bug report here:
https://bugs.launchpad.net/ubuntu/+source/ubiquity/+bug/1465050
You might be able to do the update by removing the kernel you're not currently using. (I'd use dpkg for this, so that the changes are tracked in the package manager.) This may free up just enough space for the upgrade. Be aware that you're likely to bump into the partition's size limits soon thereafter, though, so resizing /boot (or creating a new and larger /boot) is desirable in the long run.


What is the best format to capture addresses for a universal user-base?

Question: What is the best and most usable format to capture address information from a universal user base? I was thinking to have the system detect the country by IP address and have that selected by default, and then state/province droplist would be populated accordingly. But the issue is some countries have states and provinces and some do not. Some have postal codes and some do not. Is there a universal standard to capture complete address info to ensure efficiency for most users?
FYI: I did research on here and while there are some questions that are close, none are about this exact same question (unless I missed something)
Comment: [Use a single field and verify the input.](http://mwholt.com/freeform-addresses)
Comment: Don't rely on autodetecting the country only. It will be wrong for some users (because of VPN and whatnot), and they will be *very* annoyed if they can't give you the real country. So use such a check as a suggestion, not to replace input.
Answer: It depends on whether or not you need to verify the address.
When validation matters
If you need to verify the input you need a database of validation rules. But even then, it will be hard to keep track of all possible valid formats and keep in mind that these things are not set in stone and may change at any time.
You could think about offering an option for the user to submit non-validating data which you can then get checked by a person. This prevents excluding valid addresses and it's also a great way to improve your validation ruleset.
When validation doesn't matter
One wild idea, in case validation doesn't matter at all, is to display an envelope and ask the user to enter her address directly on the envelope as if she received an letter (textarea supporting multi-line input). That's probably the most natural way for a user to enter an address and doesn't force her to enter the address in an (to her) uncommon flow of fields.
Further reading: international names
A related problem is how to accept international name input. The W3C has a done a very thorough article on this topic: http://www.w3.org/International/questions/qa-personal-names.


which is best practice? Redundant loop, or calling the same if statements?

Question: I'm in the process of learning how to write the most optimal and readable code. The first way I wrote this has redundant for-loops but only checks eviction policy once. While my second way doesn't have redundant for loops but checks the eviction policy every iteration. Is there a better way to write this code?
    if self.remainingSpace - content.size < 0:
        if evictionPolicy == 'lru':
            while self.remainingSpace - content.size < 0:
                self.lruEvict()
        else:
            while self.remainingSpace - content.size < 0:
                self.mruEvict()

or
    if self.remainingSpace - content.size < 0:
        while self.remainingSpace - content.size < 0:
            if evictionPolicy == 'lru':
                self.lruEvict()
            else:
                self.mruEvict()

Comment: In both cases, you don't need the top-level if
Comment: It's almost always better in higher level languages to keep evaluations/decisions outside of loops. @ShadowRanger has the winner.
Answer: Simplest and fastest version. Since evictionPolicy never changes, select the method up front, put it in a common name, then use a single common loop:
evict = self.lruEvict if evictionPolicy == 'lru' else self.mruEvict

while self.remainingSpace - content.size < 0:  # As noted on the other answer, self.remainingSpace < content.size would be slightly more efficient
    evict()

No doubling of code, no runtime repeated checks for which method to call on each loop.
Comment: I love your use of functionalism here.
Answer: As @olivier-melançon mentioned, you don't need the first if statmement, since the while loop only enters in that case anyway.
The first version is more efficient, but if either self.lruEvict() or self.mruEvict() are expensive, then the efficiency savings may be negligible:
    if evictionPolicy == 'lru':
        while self.remainingSpace < content.size:
            self.lruEvict()
    else:
        while self.remainingSpace < content.size:
            self.mruEvict()

The second is more readable IMO:
    while self.remainingSpace < content.size:
        if evictionPolicy == 'lru':
            self.lruEvict()
        else:
            self.mruEvict()

Another option which would be the same efficiency as the second option, more concise, but perhaps a bit more obscure:
    while self.remainingSpace < content.size:
        self.lruEvict() if evictionPolicy == 'lru' else self.mruEvict()

When you use the thing_if_true if condition else thing_if_false ternary operator in Python, the thing_if_true only gets calculated or run if condition is truthy, and thing_if_false only gets calculated or run if condition is falsey.
Edit: Removed the - operator by swapping content.size to the right side of the <, since if we're micro-optimizing, it uses unnecessary overhead, and moreover the code looks nicer w/o it.


mysql not starting after removing plasma-desktop

Question: I know there are many questions regarding mysql not starting. I've tried following things
Checking MySQL error log — error reading '/var/log/mysql': Is a directory
Check /var/log/dist-upgrade/apt.log file for broken packages again no such file or directory
Remove MySQL-server and reinstall it But it's not getting uninstalled at all
this problem occurred when I uninstalled "plasma-desktop". I used following commands to remove "plasma-desktop" and related packages.
sudo apt-get purge '^kde' '^kubuntu' '^plasma'

sudo apt-get remove plasma-desktop

sudo apt-get autoremove

There was no error produced by the above three commands.
Answer: You can try these commands:
sudo apt-get purge mysql\*
sudo rm -r /var/lib/mysql
sudo rm -r /etc/mysql
sudo updatedb
sudo apt-get remove --purge mysql-server mysql-common

Then reinstall MySQL
sudo apt-get -f install -o Dpkg::Options::="--force-overwrite" mysql-server

Comment: I guess the source of this answer was https://serverfault.com/a/526702/372359 ? Be sure to give proper attribution as mentioned [here in our Help Center](https://askubuntu.com/help/referencing)


Trying to understand the following proof of $f(x) = a^x \implies f'(x) = a^x \ln a$

Question: I was reading proof of how to obtain derivative of $a^x$ here (Click on the screenshot below to expand).

Although I comprehend the proof, I have several questions about the way the proof is constructed and communicated:

Why did he substitute $u$ for $x\cdot \ln a$? He could've just directly used the chain rule without doing any substitution. (My only guess would be that this step was for clarification purpose, yet I fail to see how this makes things clearer)
What does phrase "Cancel out $dx$ over $dx$" mean? I understand what he did right after saying this, but the phrase itself perplexes me.
Comment: I think the text is simply more confusing than it should. About 1. I agree that they tried to make it clearer, but if they achieved it is questionable. About 2., writing $dx/dx = 1$  is simply stating that the derivative of the identity function is identically $1$. Once again, it does not seem to make the application of the Chain rule clearer. If you already understand the Chain rule, I suggest you just ignore the proof above.
Comment: I would just go with the Chain Rule as you know how to use it, and you will be fine.
Answer: Before answering your questions, I'll just note the $\frac{\mathrm{d}}{\mathrm{d}x}e^u$ factor should read $\frac{\mathrm{d}}{\mathrm{d}u}e^u$.

It is just for clarification. We have $a^x=f(g(x))$ with $f(u)=e^u,\,g(x)=x\ln a$.
This means $$\frac{\mathrm{d}}{\mathrm{d}x}\left(x\ln a\right)=\left(\frac{\mathrm{d}}{\mathrm{d}x}x\right)\ln a=\frac{\mathrm{d}x}{\mathrm{d}x}\ln a=1\cdot\ln a=\ln a.$$
Answer: For 1, the issue is that the next formula is wrong. You have $\frac d{dx}e^u$. It should be instead $\frac d{du}e^u$. For 2, it takes $\frac d{dx}x\ln a$ and they write it as $\ln a\frac{dx}{dx}$. It's a bad way of saying that the derivative of $x$ with respect to $x$ is $1$.
Answer: There is no need at all to introduce a new variable $u = x \ln(a)$ if you know how to make use of the chain rule. All you're doing is writing things as a power of $e$. So, $f(x) = a^x = e^{x \ln(a)}$. Hence, by the rule for differentiating exponentials, and by the chain rule,
\begin{align}
f'(x) = \ln(a) \cdot e^{x \ln(a)} = \ln(a) \cdot a^x
\end{align}
Once you know how to apply the chain rule, there is no need at all to explicitly introduce new variables (or more strictly speaking, write out all the compositions involved).
For the second question, that is just a very weird, and I would even say misleading way of saying that $\dfrac{dx}{dx} = 1$, because you're not "cancelling" the $dx$'s. The most formal way to state it is that the derivative of the identity function $I:\Bbb{R} \to \Bbb{R}$, defined by $I(x) = x$, is the constant function $1$; i.e for every $x \in \Bbb{R}$, $I'(x)  = 1$.
It seems their "added" explanation just confused you more so, my suggestion is to simply ignore it, and phrase the argument in your own words so that you understand it better.


why is the color of table not applied to the right-bottom corner?

Question: I have this table on fiddle. But the colors are not applied to the bottom-right corner.
http://jsfiddle.net/5LrEJ/
http://i.hizliresim.com/eXDaY0.png
How can I Fix it? Thanks.

Rank	Player Name	% of Wins	Total Wins	Total Losses

Previous

1

2

3

4

5

Next

1	data	data	data	data

2	data	data	data	data

3	data	data	data	data

4	data	data	data	data

5	data	data	data	data

6	data	data	data	data

7	data	data	data	data

8	data	data	data	data

9	data	data	data	data

10	data	data	data	data

Answer: Change

To

Your table has 5 columns but your tfoot has 4. By changing colspan from 4 to 5 the bottom right cell is added.
This solves your problem.


Super-Simple Grouping In SQL

Question: This is probably dumb, but I can't seem to figure this out.
I've written this code:
SELECT CoID,
       Job,
       Sum(ActualCost) AS TotalCost
FROM   Database
WHERE  Job = RandomJob
GROUP BY CoID, Job, ActualCost
HAVING ActualCost <> 0

And so it spits out this:
CoID  Job        TotalCost
X     RandomJob  1
X     RandomJob  1
X     RandomJob  2
X     RandomJob  3
X     RandomJob  5
X     RandomJob  8

What I'm trying to get to is this:
CoID  Job        TotalCost
X     RandomJob  20

Laughing at me is totally fine, since this is probably stupid easy, but please help me figure this out.
Comment: Just do this: `GROUP BY CoID, Job` and `HAVING SUM(ActualCost) <> 0`
Answer: Just remove column ActualCost from the group by clause, since you want to sum() the values in this column over group of rows having the same CoID and Job.
If you are looking to filter the groups of rows on their total cost, you can use a having clause.
SELECT CoID,
       Job,
       Sum(ActualCost) AS TotalCost
FROM   Database
WHERE  Job = 'RandomJob'
GROUP BY CoID, Job
HAVING Sum(ActualCost) <> 0

Note that since you are filtering on Job already, you would as well remove this column from the SELECT and GROUP BY clauses (this value is fixed).
Comment: Thanks, I appreciate it!

Super-Simple Grouping In SQL


Can we safely hang a ceiling fan from our vaulted livingroom ceiling?

Question: We have a tiny 1920's bungalow that's changed shape over the years, and we'd like to add a high efficiency ceiling fan to our living room in to replace an existing (lightweight) chandelier. The ceiling in this room was vaulted by a previous owner, who apparently built a soffit directly on top of the sloped drywall presumably for the sole purpose of wiring and hanging said chandelier. The small metal electrical box is definitely not the fan-supporting variety, and I'd ultimately like to know if we can safely add one without major structural and drywall work.

The entire ceiling was vaulted to match the roof line, with the drywall presumably fastened directly to roof joists. (We can't confirm this without taking off the roof, but it seems like a sound assumption.) I liberated the little electrical box and stuck a cheap USB snake camera into the soffit, which is how I learned that it was built on top of (lowered from) the larger drywall section. More critically, it seems that the soffit is built off of 2x4's that were affixed (screwed/nailed?) to the ceiling as a base for hanging the drywall with a patchwork of small plywood pieces, screws+nails, and miscellaneous small trim pieces. If there's a code for this, it's unlikely that it was followed.
I wasn't able to confirm how and exactly where the long 2x4's are affixed to the drywall, but I assume it's nailed and screwed into joists at reasonable intervals given that the soffit continues to stay in place and doesn't show any signs of stress or cracking in the four years we would have noticed.
The entire house is filled with inaccessible mysteries like this, and we're wondering in this case what we'd need to safely hang a 15lb (with mount) ceiling fan that draws 1.95-21.14 watts depending on its speed. Fan boxes can apparently be retrofitted to studs, but I'm not sure that non-structural 2x4's attached to drywall qualify as studs.

Can we get away with opening the bottom-most (flat, horizontal) drywall around the electrical box and reinforcing the area with more 2x4 framing, only having to re-drywall one surface? Do we have to rip off and rebuild the entire soffit to do this properly?
Comment: 15 lbs. of fan??????   My laptop weighs more than that. Normally I'd say no problem, but I'm curious about this, "2x4's attached to drywall qualify as studs," comment. If the fan is going to be attached to a 2x4 that's screwed to drywall, then, no, that won't work. Why not attach the fan through the 2x4 and through the drywall and into the framing above?
Comment: It's lightweight and really efficient (and thusly kind of expensive), hence some of my concern :) The fan itself is only meant to be mounted to a standard(ish) fan-friendly electrical box, so can I assume you mean attach the fan _electrical box_ through the 2x4 and drywall into the framing above? That'd still involve taking out the dropped rectangular part of the soffit, no?
Comment: No. It appears there are 2 - 2x4s just to the side of the opening. I think the electrical junction box can be fastened to these 2x4s.
Answer: That's actually what I would suggest, but be aware of the problems in opening it up. Assuming the drywall was done correctly, there's going to be corner bead. Hopefully they didn't nail it together, or you might have to replace a lot more beading that you're planning to.
You might not need more framing, though, It's probably a full box already. Just take the old box out and put a solid fan box with brace in.
Comment: Ah, looked at it wrong. Yeah, drop the bottom and see what holds up the sides, If they gave you a plywood box you'll have to add some 2x4s
Comment: Thanks Machavity! How might one determine whether it's a "full box" already as you say?
Comment: You need two 2x4s to brace against. It looks (based on your newly edited picture) that it is indeed 2x4s. What you want is a box [with a top brace](http://www.homedepot.com/p/15-5-cu-in-Retrofit-Ceiling-Fan-Saf-T-Brace-0110000/204845572) that can attach to the 2x4s and support the fan weight properly
Comment: I'm not sure how you intuited 2x4s from my closeup photo, unless you're suggesting that the visible layers of fiber board and plywood (directly on top of the cut drywall) imply 2x4 framing elsewhere in the interior of that dropout. Even if I'm communicating poorly here, I imagine installing one of those boxes with top brace lengthwise, and that the extension arms would punch into drywall or plywood rather than the 2x4s it's designed for. From what I can see, the interior of that dropout section is just plywood and screws.
Comment: Okay, thanks for your patience and clarification!


How can I be sure to install the latest AMD/ATI graphics driver

Question: I currently have the graphic GPU as follows:
[url]http://us.toshiba.com/computers/laptops/satellite/P770/P775D-S7144[/url] no longer being sold but to help you determine the best driver for my system
PROCESSOR*
AMD Quad-Core A8-3520M Accelerated Processor
&
GRAPHICS ENGINE*
AMD Radeon™ HD 6620G
This processor is no slouch in Ubuntu 12.4. But I however want to keep my driver the best and newest possible since I'm now gaming with steam on Linux.Any help would be greatly appreciated.
and a shout out to Linus Torvalds for creating an awesome OS that makes computing fun again!
Answer: i recommend you to watch this page :
HOW TO ATI Drivers
or if you like a video tutorial more, then go here:
ati driver installation ubuntu 12.04


Moving Value of a pointer to a value in C++ inline assembly (window)

Question: Here is the situation:
I have the
char c1 = 'a'

and
char c2* = somePointer

Now I want to move the Value that c2 points at into the char c1 using assembly.
mov c1, c2

does not work.
Thanks in advance
Edit: The idea behind this is that assembly can access parts of the memory C++ can't reach. So I want assembly to copy some data from outside into a spot in my accessible memory section.
Comment: note that I am using Windows, like I _meant_ to say in the title
Comment: `mov eax, c2`, `mov al, byte ptr [eax]`, `mov c1, al`
Comment: @Zain You can edit your question after you asked it.
Answer: c2 contains an address to the first byte of target character(s) memory. c1 contains a character value.
To dereference, use [ ].
mov c1,BYTE PTR [c2]

Comment: You can't move memory to memory in x86 assembly. You'll have to use a register as an intermediate.
Comment: @Zain: In case you want to look how an assembly looks like you can also take a look at godbolt: http://goo.gl/g6APkW In this case with -O0
Comment: Right, memory->memory doesn't work, my code was just an example. His byte can be stored f.e. in `al` as intermediate.


Does the aura color in Grand Prix Story modify its effectiveness for different actions?

Question: In Grand Prix Story the drivers will at different times enter what is called "Aura Time", during which they are surrounded by a colored aura. Performing most any action (research, upgrade, train, parts install, etc) with that driver will trigger the aura and increase the effectiveness of the action. So far I have seen two colors of aura occur on the same driver (purple and white, and not at the same time).
I am curious as to whether or not the color of the aura affects different actions differently, (i.e. maybe white is more effective at training and purple is better for increasing your qualifier lap).
Answer: Yes. Auras give you a guaranteed amount, when performing an action (improving a part/car), and also help you when racing.
They are ranked in the following order:

blue
red
silver
gold

The values change depending on the action, but for improving a car, it should be 25 (or 30) for the best aura, and then -5 when using a worse aura, so silver would be 20, red 15...
Comment: If you can find a reference that'd be great.
Comment: @Xantec Rewritten, this should be much more precise.


SQL LocalDB SELECT statement with multiple conditions

Question: I created a stored procedure for my .NET project and it goes like this,
ALTER PROCEDURE [dbo].[Search_PM_SELECTED]
(
    @acID varchar(50),
    @pmCat varchar(50),
    @pmTitle varchar(50),
    @pmUsername varchar(50),
    @pmSiteURL varchar(100)
)
AS
    SELECT * FROM pmPassword
    WHERE acID  = @acID and
    pmCat like '%' + @pmCat + '%' or
    pmTitle like '%' + @pmTitle + '%' or
    pmUsername like '%' + @pmUsername + '%' or
    pmSiteURL like '%' + @pmSiteURL + '%';

What I'm trying to accomplish is to select all records that match those fields except that they must be within acID. To further explain please take a look below;
 acID    pmCat      pmTitle    pmUsername       pmSiteURL
 1      Windows     Google       MyName     www.somewhere.com
 2      Network     FTP          MyName     www.somewhere.com

Above should look like a table. I only want to show the items with acID = 1
Please take note that acID does auto increment whenever I add a record which is what I have accomplished in VB alone. acID is not a PK. My PK is pmID which is not included in the query because I have no use for it.
I am working with VB and SQL LocalDB (2012).
Answer: AND has higher precendence than OR. You need to add parentheses to get what you want:
SELECT *
FROM pmPassword
WHERE acID = @acID
AND
(
    pmCat LIKE '%' + @pmCat + '%'
    OR pmTitle LIKE '%' + @pmTitle + '%'
    OR pmUsername LIKE '%' + @pmUsername + '%'
    OR pmSiteURL LIKE '%' + @pmSiteURL + '%'
);

Your query is interpreted as follows:
SELECT *
FROM pmPassword
WHERE (acID = @acID AND pmCat LIKE '%' + @pmCat + '%')
OR pmTitle LIKE '%' + @pmTitle + '%'
OR pmUsername LIKE '%' + @pmUsername + '%'
OR pmSiteURL LIKE '%' + @pmSiteURL + '%'


Generate PDF from web app

Question: I need to generate a PDF from the current screen in my webapp. Some kind of screenshot, but I'm facing serious difficulties.
The main problem is that the view contains a grid made with jQuery Gridster; and some "widgets" contain complex elements like tables, highcharts, etc.
So plugins like jsPDF or html2canvas can't render my page in a prorper PDF. They always generate it blank.
This is how the page looks like. You can/move resize each element:
(Sorry for the CIA style, but there's business data in there)

Some ideas I came across but don't work are:

Using browser print-to-pdf feature programatically. (can't)
Use phantomjs. (but page state matters, so...)

I believe a solution to this poroblem may be widely adopted by anyone trying to generate a PDF of img from current screen in a web app. Quite an unresolved problem.
It's ok if only works on Google Chrome.
Many thanks.
EDIT:
One posible solution might be to find a way to represent the current layout status with an object and save it with and id.
Then retrieve that object via url param with the id and apply the stored layout to the inital page.
This way I might able to take a screenshot with phatomjs, but it seems quite complex to me. Any alternative?
Comment: This is very doable with server side code. I have had the most luck with wkhtmltopdf. There are wrappers written for it for several server side languages. http://wkhtmltopdf.org
Comment: @eskimo not, it's not behind a login screeen. However it's a dynamic page, using Angular. So that's the main problem, it's not static and depends on the status of the grid (positions, sizes, etc)
Comment: Is the screen you're wanting to get as a PDF behind a login or is it accessible by anyone?
Comment: I was working on something similar recently (Using jsPDF) and a combination of manually building a similar structure for the data and adding base64 images from my canvas based graphs seemed to work well. Does your PDF have to be an exact copy, or do you just want a passable representation of your data?
Comment: @DBS I need an exact copy, just like a screenshot. Or as much exact as posible. jsPDF did something for me, but not enough. Thanks.
Comment: I don't think this is easily doable. You can't take a screenshot with js.
Comment: @SlavaKnyazev I know. But somebody must have came across something similar. I just want to generate a PDF (or even a image) from the current screen.
Comment: Google has a ["hidden" API](https://www.googleapis.com/pagespeedonline/v1/runPagespeed?screenshot=true&strategy=desktop&url=http://resn.co.nz/) for capturing screenshots (used for webmaster tools), but it's limited to 320px wide images. It would also be incredibly convoluted to use since the content is behind a login. You would have to regenerate the page (temporarily) available to public and use the google api to generate the screenshot (then "destroy" the public page). It would work, but the image is probably too small to be useful
Comment: @eskimo thank you for your comment, but it seems it can only take an image from an specified url, so page status won't be respected. Thanks.
Answer: Based on the fact that you're struggling with capturing dynamic content, I think at this point you need to take a step back and see that you might need to alter your approach. The reason these plugins are failing is because they will only work with the HTML before interactions right?
Why not convert the HTML to <code>.pdf</code> format from the server side? But the key part here is, send the current HTML back. By sending it back, you're sending updated static HTML back to the server to be rendered into a PDF? I've used HTML to PDF from server side before and it works fine, so I can't see why it wouldn't be appropriate here.
See this answer for details about HTML to PDF server side.
Comment: I'm not sure highcharta will be properly rendered, but i'll try anyway. Thanks.

Generate PDF from web app


Create a site script using Get-SPOSiteScriptFromWeb cmdlet error

Question: I am trying to create a site script from an existing team site but when I run the script that I followed from this Microsoft document it asks me for the WebURL WebURL Prompt, even though it is in the script, then when I provide it at the prompt it gives me the error Error.
I am not new to site scripts but have not used them much.  I would like to create one from an existing site that I have created for the PM team.  Please advise. I am using the latest SharePoint Online Management Shell and I am logged in.  I am also a Global Admin.
Any assistance would be helpful as I have done everything I can think of to do and Googled my heart out but cannot figure out what is going on.
Answer: From the screenshot you posted, it looks like you did not include ` (back tick) at the end of each row in your command. Those are necessary in order for PowerShell to understand entirety of your command which spans across multiple rows, like in the following example:
Get-SPOSiteScriptFromWeb `
    -WebUrl https://contoso.sharepoint.com/sites/template `
    -IncludeBranding `
    -IncludeTheme `
    -IncludeRegionalSettings `
    -IncludeSiteExternalSharingCapability `
    -IncludeLinksToExportedItems `
    -IncludedLists ("Shared Documents", "Lists/Project Activities")

Alternative would be to enter entire command and all parameters in single row, like this:
Get-SPOSiteScriptFromWeb -WebUrl https://contoso.sharepoint.com/sites/template -IncludeBranding -IncludeTheme -IncludeRegionalSettings -IncludeSiteExternalSharingCapability -IncludeLinksToExportedItems -IncludedLists ("Shared Documents", "Lists/Project Activities")


Is setting up a fake repository for a fake web service proxy class a good idea?

Question: When setting up a web service, I can have it use a repository class to fetch the data to send back to clients.  If I need to unit test the logic being done by the service, I could inject in it a reference to a fake repository which returns a handful of hard-coded data objects to avoid calls to a database.
On the client side, however, let's say I have an MVC-based web application that calls this web service via a service proxy.  If I want to unit test the logic in the MVC app and feed it data that is representative of what the service would return, how can I fake the proxy reference?  My thoughts are thus, though I don't feel 100% confident about this and wonder if I might be missing a simpler solution:
I can set up a proxy interface (let's call it IProxy) and then set up two concrete implementations of it (let's say, Proxy and FakeProxy) and inject the one appropriate to the situation being executed (FakeProxy when running unit tests, and Proxy for the actual production application). In order to generate some sample data for the unit tests without making the actual service calls, should I then implement a fake repository (maybe the same one being used in the server scenario above) in the Fake Proxy?  I'm unsure of how to best set up a fake proxy class to assist with the testing of my client side code.
Update:
I agree with the answers posted so far, but I'd already considered their points, so let me provide some sample C# code that illustrates why I'm asking this.  If I leave a fake repository out of my proxy design, my fake proxy might look something like this very simple contrived example:
public class FakeCustomerProxy : ICustomerProxy
{
    private List<Customer> Customers;

    public FakeProxy()
    {
        Customers = new List<Customer>();

        Customers.Add(new Customer { Id = 1, Name = "Smith, John" });
        Customers.Add(new Customer { Id = 2, Name = "Johnson, Al" });
        Customers.Add(new Customer { Id = 3, Name = "Thomas, William" });
    }

    public Customer GetById(int customerId)
    {
        return Customers.Where(c => c.Id == customerId).FirstOrDefault();
    }
}

The GetById() method, instead of making a call to a web service to derive the desired customer information, simply returns it from the hardcoded customer list imbedded in this class.  This really starts to resemble what I might set up for a fake repository (I may even have very similar-looking code set up server-side to assist with testing the service logic), so I was curious if I should consider placing these hardcoded customer references into a dedicated fake repository class to be used in multiple places.  Am I maybe thinking through the design of this Fake Proxy completely wrong?
Answer: No, setting up fake repository for fake web service proxy does not seem to be a good idea for unit tests.
Actually, just one fake (proxy or repository) shoud be enough generally.
I'd suggest you to look at mocking frameworks (e.g. Moq or Rhino Mock).
Using mocks, you won't even need to have FakeProxy implementation. In each test you can easily setup separate mocked implementation of IProxy which will act exactly as you need: return predefined data, raise exceptions, verify passed parameters, etc.
So, you won't need to implement 1 or 2 fake classes for testing.
UPDATE:
So, I see 2 options here:

To have non-reusable simple test data, which is specific for each particular test. You might need to setup something like mini-repository (about 1-3 items)  per each test or group of tests;
To have large enough reusable fake repository, which is common for both server-side & client side code. Most likely you will need to support some additional harness to use this fake repository in client-side tests and in server-side tests. E.g. you need FakeProxy additionaly to test client-side code.

You should consider those options and choose what is more suitable in your case.
In my opinion, option 1 is suitable for unit tests, but option 2 might be useful for integration tests.
Comment: Thanks for the answer - please see my update above for extra context on what I'm asking.  Perhaps my thinking on the fake proxy class is backwards?
Comment: Please see my updated answer, hope it helps you to make a good decision for your case :).
Comment: I think I see what you're saying.  If I'm following you, I shouldn't need to create a fake repository _and_ a fake proxy at the same time, because I'm either going to be unit testing my client-side code, in which case I just need to feed it dummy data (via the fake repository), or I'll be unit testing my service proxy, which should be completely outside the scope of this web app.  If I need to fake a call to the proxy when unit testing my client app, a mocking framework is what I should be considering for that point.  Hopefully, I'm not misstating anything here.  Thanks a bunch!
Answer: No, you should not repeat your implementation of repository-proxy connection in tests. Sooner or later there will be some business logic between proxy facade and repository, and you will have to implement it twice - on server side, and on client side, in FakeProxy.
So your mock instance of FakeProxy should just return raw data from calls.
On the other hand, you could import real Proxy class in client tests, and mock repository for testing, but this would be an integration test, not a unit test, and would involve usage of server-side code in client tests, which is not always possible.


What features should a robust, scalable, ... and expandable PHP Framework be composed of?

Question: What are the features (e.g. cookie, session, template, database handling) should a ...

robust
scalable
flexible
OOP-compatible
MVC
expandable

... PHP Framework be composed of? and what other features would be great for any developer in a PHP framework?
I've been looking a lot at frameworks such as CakePHP, Symphony, and so on.. their features are pretty common.
Answer: Having a nice ORM makes a big difference. It makes your code much more easy to read and maintain by not having SQL queries strewn all over the place.
Another mandatory feature, as far as I'm concerned, is URL routing. It makes a big difference (especially for SEO) being able to write URLs any way you want. Cake supports that, and I haven't checked but I imagine the other popular ones do as well.
I've used CakePHP for several projects, and it's pretty nice, once you get used to it. I picked that over Symphony, CodeIgniter and Zend, but that was a while ago so those might have had substantial improvements.
Answer: Basically, the primary reasoning for creating your own framework would be that you are dissatisfied with the frameworks available.
However, I think that a PHP framework should have the following components:

A nice ORM - like Dan Breen said (I'd recommend Doctrine)
Good, dynamic, lightweight URL routing
Fine grained configuration with cascade (project, application, module, controller level)
I18n & L10n support (also ability to handle different languages in URLs)
Loosely coupled (I like symfony, but I really also like that I can use different components from Zend Framework. I see ZF as more of a 'toolbox' than a framework)

That's just some of the most important elements and the elements that I value the most in the frameworks that I use.
I would think twice before starting to develop my own web framework - especially before starting developing it as an open-source project.


DHCP is mangling my PTR records in DNS

Question: I originally posted this in LinuxQuestions http://www.linuxquestions.org/questions/linux-server-73/dhcp-is-mangling-my-ptr-records-in-dns-4175412344/ without much luck, so I'll try here.
DHCP is repeating the first three octets when it adds a PTR record. From my messages log:
dhcpd: added reverse map from 10.2.168.192.2.168.192.in-addr.arpa to FTIR.Adherent.lab

I'm sure it is something stupid like a missing period, but I haven't been able to figure it out.
This happens on both the 192.168.2.xyz and 192.168.4.xyz networks.
Notice that the FTIR computer is already in the hosts and ptr files but a new entry still gets added. Also, nowhere in my configuration files do I have Adherent with a capital A, but the capitalized version shows up in the mangled file.
My DHCP/BIND server is Ubuntu Linux but all of the network computers are Windows.
Here is my system info:
$ uname -a
Linux ATI-DHCP.adherent.lan 2.6.32-41-server #90-Ubuntu SMP Tue May 22 12:41:40 UTC 2012 x86_64 GNU/Linux
$ lsb_release -a
Distributor ID: Ubuntu
Description:    Ubuntu 10.04.4 LTS
Release:        10.04
Codename:       lucid
$ named -v
BIND 9.7.0-P1

Here are my various configuration files:
dhcpd.conf:
ddns-update-style interim;
ddns-updates on;
authoritative;

log-facility local1;

default-lease-time 86400;
max-lease-time 259200;

include "/etc/dhcp3/ddns.key";

# Adherent internal network with internet access
zone adherent.lan. {
    primary 192.168.1.201;
    key ddns;
    }

# Reverse zone for 192.168.1.xyz
zone 1.168.192.in-addr.arpa. {
    primary 192.168.1.201;
    key ddns;
    }

# Adherent insecure network-NO internet access
zone lab.adherent.lan. {
    primary 192.168.2.201;
    key ddns;
    }

# Reverse zone for 192.168.2.xyz
zone 2.168.192.in-addr.arpa. {
    primary 192.168.2.201;
    key ddns;
    }

# Guest-Internet only
zone guest.adherent.lan. {
    primary 192.168.4.201;
    key ddns;
    }

# Reverse zone for 192.168.4.xyz
zone 4.168.192.in-addr.arpa. {
    primary 192.168.4.201;
    key ddns;
    }

# ATI shared network:  Internal (192.168.1.xyz) and visitor (192.168.4.xyz) nets
shared-network ATIshared {

    # ATI internal
    subnet 192.168.1.0 netmask 255.255.255.0 {
        #range 192.168.1.10 192.168.1.19;
        deny unknown-clients;
        ddns-domainname "adherent.lan";
        ddns-rev-domainname "1.168.192.in-addr.arpa";
        option domain-name "adherent.lan";
        option routers 192.168.1.201;
        option domain-name-servers 192.168.1.201;
        }

    # Visitor subnet
    subnet 192.168.4.0 netmask 255.255.255.0 {
        default-lease-time 3600;
        range 192.168.4.40 192.168.4.49;
        allow unknown-clients;
        ddns-domainname "guest.adherent.lan";
        ddns-rev-domainname "4.168.192.in-addr.arpa";
        option domain-name "guest.adherent.lan";
        option routers 192.168.4.201;
        option domain-name-servers 192.168.4.201;
        }
    }

# Adherent insecure network-NO internet access (192.168.2.xyz)
subnet 192.168.2.0 netmask 255.255.255.0 {
    range 192.168.2.240 192.168.2.250;
    ddns-domainname "lab.adherent.lan";
    ddns-rev-domainname "2.168.192.in-addr.arpa";
    option domain-name "lab.adherent.lan";
    option routers 192.168.2.101;
    option domain-name-servers 192.168.2.201;
    }

include "/etc/dhcp3/hosts.dhcp3";

named.conf.local
include "/etc/bind/zones.rfc1918";

include "/etc/bind/ddns.key";

###########################################################
# Adherent main zone.
# All addresses are fixed and from 192.168.1.0/24
# If DHCP doesn't have an entry for a computer, it gets put in the guest zone.
#
zone "adherent.lan" {
    type master;
    file "/var/lib/bind/adherent.lan.hosts";
    allow-update { key ddns ;};
};

zone "1.168.192.in-addr.arpa" {
    type master;
    file "/var/lib/bind/192.168.1.rev";
    allow-update { key ddns ;};
};

###########################################################
# Adherent lab zone.
# All addresses are from 192.168.2.0/24
# Doesn't matter if DHCP has an entry for the computer.

zone "lab.adherent.lan" {
    type master;
    file "/var/lib/bind/adherent-lab.lan.hosts";
    allow-update { key ddns ;};
};

zone "2.168.192.in-addr.arpa" {
        type master;
        file "/var/lib/bind/192.168.2.rev";
        allow-update { key ddns ;};
};

###########################################################
# Adherent guest zone.
# All addresses are from 192.168.4.0/24
# If DHCP doesn't have an entry for a computer, it gets put in this zone.
#
zone "guest.adherent.lan" {
    type master;
    file "/var/lib/bind/adherent-guest.lan.hosts";
    allow-update { key ddns ;};
};

zone "4.168.192.in-addr.arpa" {
    type master;
    file "/var/lib/bind/192.168.4.rev";
    allow-update { key ddns ;};
};

file /var/lib/bind/adherent-lab.lan.hosts
$ttl 3h
@       IN      SOA     ATI-DHCP.adherent.lan. bgordon.adherent-tech.com. (
                        2012061801      ; serial
                        3h              ; Refresh
                        1h              ; Retry
                        1w              ; Expire
                        1h              ; Minimum
                        )
@       IN      NS      ATI-DHCP.adherent.lan.

FTIR        IN  A   192.168.2.10
GCMS        IN  A   192.168.2.12
datalogg    IN  A   192.168.2.13
TA      IN  A   192.168.2.14
instron     IN  A   192.168.2.20
instron2    IN  A   192.168.2.21

file /var/lib/bind/192.168.2.rev
$TTL 3h
@   IN SOA  ATI-DHCP.adherent.lan. bgordon.adherent-tech.com. (
                2012061801  ; serial
                3h      ; refresh (3 hours)
                1h      ; retry (1 hour)
                1w      ; expire (1 week)
                1h      ; minimum (1 hour)
                )
@           NS  ATI-DHCP.adherent.lan.
10          PTR FTIR.lab.adherent.lan.
12          PTR GCMS.lab.adherent.lan.
13          PTR datalogg.lab.adherent.lan.
14          PTR TA.lab.adherent.lan.
20          PTR instron.lab.adherent.lan.
21          PTR instron2.lab.adherent.lan.

Same file after mangling (all changes made by DHCP/BIND:
$ORIGIN .
$TTL 10800  ; 3 hours
2.168.192.in-addr.arpa  IN SOA  ATI-DHCP.adherent.lan. bgordon.adherent-tech.com. (
                2012061802 ; serial
                10800      ; refresh (3 hours)
                3600       ; retry (1 hour)
            604800     ; expire (1 week)
            3600       ; minimum (1 hour)
            )
            NS  ATI-DHCP.adherent.lan.
$ORIGIN 2.168.192.in-addr.arpa.
10          PTR FTIR.lab.adherent.lan.
12          PTR GCMS.lab.adherent.lan.
13          PTR datalogg.lab.adherent.lan.
14          PTR TA.lab.adherent.lan.
$TTL 43200  ; 12 hours
10.2.168.192        PTR FTIR.Adherent.lab.
$TTL 10800  ; 3 hours
20          PTR instron.lab.adherent.lan.
21          PTR instron2.lab.adherent.lan.

Answer: I got an answer over in my original posting on LinuxQuestions.  The lines in dhcp.conf, for each subnet definintion, like:
ddns-rev-domainname "1.168.192.in-addr.arpa";
ddns-rev-domainname "2.168.192.in-addr.arpa";
ddns-rev-domainname "4.168.192.in-addr.arpa";

should all be:
ddns-rev-domainname "in-addr.arpa.";

I'm not sure if the dot after arpa is required, but it works with it there.

DHCP is mangling my PTR records in DNS


Getting the target folder from inside a rust proc-macro

Question: As the title suggests, I'm trying to retrieve the target folder to hold some intermediate compilation products. I need the actual target folder as I would like to cache some values between compilations to speed them up significantly (otherwise I could just use a temporary directory).
My current approach is to parse the arguments of the rustc invocation (through std::env::args()) and find the --out-dir, the code looks something like this:
// First we get the arguments for the rustc invocation
let mut args = std::env::args();

// Then we loop through them all, and find the value of "out-dir"
let mut out_dir = None;
while let Some(arg) = args.next() {
    if arg == "--out-dir" {
        out_dir = args.next();
    }
}

// Finally we clean out_dir by removing all trailing directories, until it ends with target
let mut out_dir = PathBuf::from(out_dir.expect("Failed to find out_dir"));
while !out_dir.ends_with("target") {
    if !out_dir.pop() {
        // We ran out of directories...
        panic!("Failed to find out_dir");
    }
}

out_dir

Normally I would use something like an environment variable (think of OUT_DIR), but I couldn't find anything that could help me.
So is there a proper way of doing this? Or should I file an issue to the rust dev team?
Comment: [Cargo sets the environment variable `OUT_DIR` when running build scripts](https://doc.rust-lang.org/cargo/reference/environment-variables.html). I don't know if it is also set when running the compiler though…
Answer: Looking at OUT_DIR is the right way to go and I'm puzzled that it isn't always set. If you have control over the crates that use your macro, you can add a (trivial) build script, which leads to cargo setting the OUT_DIR variable.
I must admit that this is a bit hacky. I've created a feature request for cargo to always set OUT_DIR, which would make this question trivial.


wifi module keeps getting soft blocked after reboot

Question: I'm using an Odroid XU4 with their USB WiFi module 4 and the official Odroid distro of Ubuntu 16.04.
If I type sudo rfkill unblock wifi into a terminal, everything works fine, but I intend this machine to run headless and untethered, so that isn't a solution.
I have also already tried adding the unblock command both as a service and to /etc/rc.local. Neither worked.
Some suspicious lines from syslog:
NetworkManager[678]: <info>  [1525808228.9431] rfkill0: found WiFi radio killswitch (at /sys/devices/platform/soc/12110000.usb/usb1/1-1/1-1:1.0/ieee80211/phy0/rfkill0) (driver rt2800usb)
NetworkManager[759]: <info>  [1525809316.1008] (wlan0): using nl80211 for WiFi device control
NetworkManager[759]: <info>  [1525809321.7019] manager: WiFi hardware radio set disabled
NetworkManager[759]: <info>  [1525809321.7114] manager: WiFi now disabled by radio killswitch

As far as I know, the XU4 does not have a hardware switch to disable WiFi.
$ lsmod

Module                  Size  Used by
fuse                   86016  3
cpufreq_conservative    16384  0
cpufreq_userspace      16384  0
cpufreq_powersave      16384  0
rt2800usb              28672  0
rt2800lib              98304  1 rt2800usb
rt2x00usb              20480  1 rt2800usb
rt2x00lib              45056  3 rt2800lib,rt2800usb,rt2x00usb
mac80211              618496  3 rt2800lib,rt2x00lib,rt2x00usb
cfg80211              479232  2 rt2x00lib,mac80211
rfkill                 20480  3 cfg80211
spidev                 20480  0
input_leds             16384  0
evdev                  24576  4
spi_s3c64xx            20480  0
gpio_keys              20480  0
uio_pdrv_genirq        16384  0
extcon_usb_gpio        16384  0
uio                    16384  1 uio_pdrv_genirq
exynos_gpiomem         16384  0
ipv6                  380928  46
usbhid                 45056  0

$ sudo lshw -class network
USB

  *-network:0
       description: Ethernet interface
       physical id: 7
       logical name: eth0
       serial: 00:1e:06:32:7c:fd
       size: 1Gbit/s
       capacity: 1Gbit/s
       capabilities: ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=r8152 driverversion=v1.09.9 duplex=full ip=[snip] link=yes multicast=yes port=MII speed=1Gbit/s
  *-network:1 DISABLED
       description: Wireless interface
       physical id: 8
       bus info: usb@1:1
       logical name: wlan0
       serial: 70:f1:1c:03:b3:d1
       capabilities: ethernet physical wireless
       configuration: broadcast=yes driver=rt2800usb driverversion=4.14.35-128 firmware=0.29 ip=[snip] link=no multicast=yes wireless=IEEE 802.11

$ lsusb
Bus 006 Device 002: ID 0bda:8153 Realtek Semiconductor Corp.
Bus 006 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 005 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 002: ID 05e3:0616 Genesys Logic, Inc. hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 004: ID 046d:c05a Logitech, Inc. M90/M100 Optical Mouse
Bus 003 Device 003: ID 413c:2105 Dell Computer Corp. Model L100 Keyboard
Bus 003 Device 002: ID 05e3:0610 Genesys Logic, Inc. 4-port hub
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 002: ID 148f:5572 Ralink Technology, Corp. RT5572 Wireless Adapter
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Answer: I logged in with a monitor and keyboard and found that there was an "Enable WiFi" menu item unchecked in the GUI. Checking that menu item seems to have resolved the problem. It looks like I could have also done this on the command line with nmcli r wifi on, if anyone else stumbles upon this question in the future.


Will a collection with a total size exceeding 85kB be put on the large-object-heap?

Question: I have a question about about when objects get put into the small- vs large-object-heap.
I have two string with size smaller than 85kB which I add to a collection, such as a List. The combined size of the strings exceeds 85kB.
Will this collection be treated as part of the small-object-heap or as part of the large object-heap? I think it will be SOH but I'm not sure.
Answer: If the collection is a List<TReference> of any size then it is SOH. If the collection is a TReference[] with a size <= 20k elements at 32 bits, or 10k elements at 64 bits (the size of a reference at 32bits is 4 bytes, at 64bits is 8 bytes), the it is SOH.
The size of an object isn't calculate based on object X + all the objects referenced by object X, but simply by the "direct" size of X.
Why the difference between List<TReference> and TReference[]? Because arrays (technically single dimensional, 0-base indexed arrays) are the only variable length data type directly supported by the IL language. Nearly all the other collection types are simply a reference to a T[] array (or to a bunch of T[] arrays) plus some supporting numeric fields. So for example a List<T> is a reference to a T[] plus a int Length.
The point of SOH vs LOH is "how much fast would be to move it around memory"? Clearly:
public class MySmallClass
{
    public byte[] WithABigObject = new byte[1024*1024];
}

While moving the BigObject (the byte array) would be very slow, moving the MySmallClass (that is simply composed by a reference) is very fast, because it has the size of a reference :-)
Note that in C# creating objects that aren't arrays with a size >= 85k is quite difficult, because, as I've said, between the types that are directly supported by the IL language, only the array has a variable size. Every other type has a fixed size and is quite small. You would need to make a class with 22k int inside to make a LOH without an array :-)
An example of a LOH object without arrays: https://ideone.com/OuVkEs . It is based on multilevel KeyValuePair<,> (a struct) that at the lowest level use Guid (the biggest commonly used struct). The resulting BigGuid128k is a struct of 128k. By including it in your class, your class will become a LOH :-)
Comment: You can easily build a huge struct, but of course that's rarely a good idea.
Comment: @CodesInChaos Yes... by using `KeyValuePair<,>` recursively it is possible... But still it is a long way up to 85k :-) And it would be the most stupid idea I've ever seen.


How do I change the comment colors in android studio?

Question: I'm just trying to change the color of my comments so I can spot it faster. It's currently gray. I tried the settings but nothing that allows me to change the comment color.
Answer: Android Studio > Preferences > Editor > Colors & Fonts
Uncheck "use inherited attributes" on the right, and it will tell you what to do.
Comment: For **Android Studio 3.4.2**: _File > Settings > Editor > Color Scheme > Java > Comments > Line comment_. Then on the right uncheck the **Inherit values from** checkbox. Finally click the color on the right and choose the one you would like > Apply > OK.
Comment: In 2.3 it isin File=> settings => Editor
Comment: Thanks so much. This has been bugging me.
Answer: if you make two asterisk block comment, automatically android will turn that comment green. It's default doc comment and you don't have to change any settings.
<code>/**

green comment

*/
</code>
Comment: superb!! that's what i was looking for to highlight specific comments!! thanks!!!!
Answer: In new android studio version ( Android Studio Arctic Fox | 2020.3.1 Patch 4 ) go to -

Settings -> Editor -> Color Scheme -> Language Default

here can you customize all codes color including- comments, classes, Number
and etc.
Answer:
Default is grey and green you can use green color which hightlight more than grey color.


Finding possible key combination of a char regarding current keyboard layout

Question: How can I find a possible key combination of a char regarding to current keyboard layout
for example;
lets say my keyboard's caps lock is off
So in that case for char "A" key combination should be Shift + A
that was easy. how about non ascii chars or non visible chars on keyboard such as "@" char or "\"
for "@" I use Ctrl + Alt + Q
for "\" I use Ctrl + Alt + *
for "{" I use Ctrl + Alt + 7

So how could I know which key combination should I send to an application to make it handle "{" key assuming that application validates that combination to determine if I am bot or human.
Thanks in advance
Comment: The C++ standard library does not have functionality for raw keyboard handling. I don't think you will find any portable library for it either. So you're essentially stuck with OS API.
Answer: In Windows you can use VkKeyScan(char ch) function. It returns a short value which contains the virtual key code on low-order byte and modifier key flags on high-order byte.
You can call it in C# by declaring:
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern short VkKeyScan(char ch);

Here is the link to the documentation:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms646329%28v=vs.85%29.aspx
Comment: I think that can cover my requirements. Except the current virtual key code. So If I want to send '#' character over api VkKeyScan will return me Alt + Ctrl, but not Key.D3 . So How could I extract the Key.D3 then ?
Comment: You can mask the return value: `int virtualKeyCode = returnValue & 0xFF` to get the key.
Comment: GREAT. that works. except it says 'Shift' + 65 for  'A'  if caps lock is on. Do you have any idea ?
Comment: You must check the state of CapsLock key yourself. Fortunately you can use `GetKeyState(int nVirtKey)` function to get it.


Cannot Start Apache2?

Question: I'm trying to install apache2 (To set up a LAMP stack), but something appears to be using the HTTP port on 0.0.0.0:80.
There is also a text post about not being able to determine the server's fully qualified name.
Here is the full post:
invoke-rc.d: initscript apache2, action "start" failed.
● apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
  Drop-In: /lib/systemd/system/apache2.service.d
           └─apache2-systemd.conf
   Active: failed (Result: exit-code) since Wed 2019-05-22 15:57:55 UTC; 10ms ago
  Process: 28139 ExecStart=/usr/sbin/apachectl start (code=exited, status=1/FAILURE)

May 22 15:57:55 scilab_comp_0 apachectl[28139]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 192.168.1.222. Set the 'ServerName' directive globally to suppress this message
May 22 15:57:55 scilab_comp_0 apachectl[28139]: (98)Address already in use: AH00072: make_sock: could not bind to address [::]:80
May 22 15:57:55 scilab_comp_0 apachectl[28139]: (98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:80
May 22 15:57:55 scilab_comp_0 apachectl[28139]: no listening sockets available, shutting down
May 22 15:57:55 scilab_comp_0 apachectl[28139]: AH00015: Unable to open logs
May 22 15:57:55 scilab_comp_0 apachectl[28139]: Action 'start' failed.
May 22 15:57:55 scilab_comp_0 apachectl[28139]: The Apache error log may have more information.
May 22 15:57:55 scilab_comp_0 systemd[1]: apache2.service: Control process exited, code=exited status=1
May 22 15:57:55 scilab_comp_0 systemd[1]: apache2.service: Failed with result 'exit-code'.
May 22 15:57:55 scilab_comp_0 systemd[1]: Failed to start The Apache HTTP Server.
Processing triggers for ureadahead (0.100.0-21) ...
Processing triggers for systemd (237-3ubuntu10.21) ...
Processing triggers for man-db (2.8.3-2ubuntu0.1) ...
Processing triggers for ufw (0.36-0ubuntu0.18.04.1) ...
Rules updated for profile 'OpenSSH'

With regards to the server's domain name. I just created a domain name for it using my router's function for DDNS and have made this server a DMZ by forwarding all ports to it.
How should I go about resolving the issue and get Apache to start?
EDIT 0:
sarah@scilab_comp_0:~$ sudo netstat -tlpn | grep :80
tcp6       0      0 :::80            :::*              LISTEN      3034/httpd

Comment: It's more or less an duplicate of [this question](https://askubuntu.com/q/1144848/653515). Run `sudo netstat -tlpn | grep :80` and figure what is listening on port 80 today. Stop/disable that service, and start Apache.
Comment: `dpkg -l | grep httpd`
Comment: Within Ubuntu 16+ Apache2 (from the default repository) is named `apache2` and the binary is `/usr/sbin/apache2`, so apparently this service `httpd` probably is another HTTPD service, but not Apache2, so try to find which is it (by using `ps -aux | grep -i 'httpd'` or `which httpd`) and stop and disable it (if you do not need it) then restart Apache2. In order to suppress the message `AH00558:`  just add the directive `ServerName ` at the bottom of `/etc/apache2/apache2.conf`.
Comment: httpd is apache2...though that is how it is named on Red Hat flavors of linux.
Comment: @vidarlo It appears to be `httpd`. Hmm, no idea why/how the red hat version is present. How would I uninstall it? I ran `sudo purge apache2` already.
Comment: Can you run `uname -a` and post that here
Comment: @rtaft `Linux scilab_comp_0 4.15.0-50-generic #54-Ubuntu SMP Mon May 6 18:46:08 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux` I also purged apache* and attempted reinstall. This didn't help.
Comment: @rtaft Returns nothing
Comment: well for now, `sudo service httpd stop` should get you around the issue, and `sudo systemctl disable httpd` to disable it, figure out how to remove it later.
Comment: `httpd` is typically the name you'd end up with if you install from source or similar. Are you sure you haven't installed apache previously, via some other method?
Comment: What's the output of `which httpd`?
Comment: @vidarlo No output.
Comment: Looks like it's `nextcloud` from the output of `ps -aux | grep -i 'httpd'`. That doesn't make much sense to me though. Aren't they supposed to work in parallel? I followed a guide on it and they didn't mention anything about something like this.
Comment: @SarahSzabo How did you install nextcloud? You can't have two processes on listening to the same port, but Apache can host multiple websites, and act as a proxy for a server running on some other port, if needed.
Comment: @vidarlo I just ran `sudo snap install nextcloud` That was pretty much all aside for creating a user.
Comment: I would find how to change the listen port of `nextcloud`, then will setup my Apache, and as lat step will use proxy pass to access `nextcloud` via Apache's virtual host.
Comment: @SarahSzabo I don't touch snaps, but generally I'd recomend moving the snap's http server to a different port, and use `mod_proxy` in Apache to forward traffic, or set up nextcloud as a site in Apache.
Comment: After using `sudo snap disable` I reinstalled apache and it worked. I can't see the nextcloud page now when I type in the domain address, but that's a separate issue. I can see the Apache default page now.
Comment: Great! @vidarlo, could you write an answer?
Comment: @pa4080 Never touched a snap, and don't plan to :)
Answer: you can see all the processes that are using port 80 at the time you are starting apache2 :
sudo lsof -i TCP:80

and also I think the easiest way to resolve the problem you are facing is to change your port to something else ,
you can change them in this two files in your apache 2 configs:
/etc/apache2/ports.conf
/etc/apache2/sites-enabled/000-default.conf

after these you should restart the apache2 with this command :
 sudo /etc/init.d/apache2 restart

also for getting better result you can run this command to see whats missing or making problem in starting apache2:
 systemctl status apache2.service

Comment: Changing the port off of 80 won't negatively affect people wanting to connect to it? I'm still learning how this works. Thanks for the post!
Comment: @SarahSzabo I had this error yesterday and with all the searches I came up with this solution and that worked for me , hope it works for you too
Comment: @SarahSzabo Using a non-standard port will affect users, yes. If it's public-facing, you should *probably* look into using TLS as well...
Comment: @SarahSzabo you can also find which process is using (listening) port 80 so you can kill the process , this one worked for me too.

Cannot Start Apache2?


Error when run android app - ionic

Question: I have a problem when I run the app... I want to test the location with GPS in my android phone but I can`t, ... it´s only that.
this is my ionic info
cli packages: (/usr/local/lib/node_modules)

    @ionic/cli-utils  : 1.18.0
    ionic (Ionic CLI) : 3.18.0

global packages:

    cordova (Cordova CLI) : 7.1.0

local packages:

    @ionic/app-scripts : 3.1.2
    Cordova Platforms  : android 6.2.3
    Ionic Framework    : ionic-angular 3.9.2

System:

    Node  : v7.0.0
    npm   : 3.10.8
    OS    : macOS Sierra
    Xcode : Xcode 8.3.2 Build version 8E2002

Environment Variables:

    ANDROID_HOME : not set

Misc:

    backend : pro

l
ionic cordova run android --prod

This is the error:
Error:
./src/app/main.ts
Module not found: Error: Can't resolve './app.module.ngfactory' in '/Users/eliascanaza/Documents/www/ionic/yofood/src/app'
resolve './app.module.ngfactory' in '/Users/eliascanaza/Documents/www/ionic/yofood/src/app'
  using description file: /Users/eliascanaza/Documents/www/ionic/yofood/package.json (relative path: ./src/app)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /Users/eliascanaza/Documents/www/ionic/yofood/package.json (relative path: ./src/app)
    using description file: /Users/eliascanaza/Documents/www/ionic/yofood/package.json (relative path: ./src/app/app.module.ngfactory)
      no extension
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory doesn't exist
      .ts
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.ts doesn't exist
      .js
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.js doesn't exist
      .json
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.json doesn't exist
      as directory
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory doesn't exist
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.ts]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.js]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.json]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory]
 @ ./src/app/main.ts 2:0-60
    at new BuildError (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/@ionic/app-scripts/dist/util/errors.js:16:28)
    at callback (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/@ionic/app-scripts/dist/webpack.js:121:28)
    at emitRecords.err (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:269:13)
    at Compiler.emitRecords (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:375:38)
    at emitAssets.err (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:262:10)
    at applyPluginsAsyncSeries1.err (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:368:12)
    at next (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/tapable/lib/Tapable.js:218:11)
    at Compiler.compiler.plugin (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/performance/SizeLimitsPlugin.js:99:4)
    at Compiler.applyPluginsAsyncSeries1 (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/tapable/lib/Tapable.js:222:13)
    at Compiler.afterEmit (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:365:9)

app.module.ts, I want to test the location but I can`t, there is the library for location and the service to call the webservice
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { TestPage } from '../pages/test/test';

import { Geolocation } from '@ionic-native/geolocation';

import { MessageServiceProvider } from '../providers/message-service/message-service';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    TestPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    TestPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    MessageServiceProvider,
    Geolocation
  ]
})
export class AppModule {}

So, I need your help ... what is the wrong? thanks a lot!
Answer: Similiar issue is reported in angular CLI. Please try the following steps

Upgrade the angular CLI to latest version npm install @angular/cli and take the build
if it's still not working run npm i firstname.lastname@example.com
Comment: same error: Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.ts doesn't exist
Answer: It says that **Error: Can't resolve './app.module.ngfactory' **
1.check your main.ts file it should have import { AppModule } from './app.module'; not something like app.module.ngfactory.
2.Also make sure your app works without errors first using Ionic Serve and check console for any app specific errors.

Error when run android app - ionic


Issue with docker on mac terminal: ERROR: Cannot connect to the Docker daemon at unix:///var/run/docker.sock

Question: I am having this error message when running docker-compose or any docker command:
ERROR: Cannot connect to the Docker daemon at unix:///var/run/docker.sock
Answer: In my case, this issue is linked to the fact that I have changed my username to a new username. /var/run/docker.sockis a symlink to /Users/USERNAME/.docker/run/docker.sock
/var/run/docker.sock@ -> /Users/OLD USER NAME/.docker/run/docker.sock


CS:GO kick/ban in competitive match making

Question: I was kicked from a competitive match making earlier today right after the game ended, so I was wondering if it counted as a loss because I got kicked or if it just counted as a win because the game ended already?
Comment: Nope, you can now even kick on 15:x round.
Comment: You can't get kicked after the game ended. Round 13 is the last round where you can kick someone out.
Comment: @Conreuss Please specify: Do you want to know if you can lose your rank because of this or do you really want to know if it just affects your win/lose ratio? Then I can answer you on both. :)
Comment: @Noneofyourbusiness actually they changed it you can get at the end of the game when the score shows up, thats what happened to me
Answer: If you are kicked from a game, it counts as a loss on your rank, regardless of whether your team won or not.
Comment: Do you have a source for that ? After a quick source I didn't find any official reference. Only the same question, and people answering without providing any source.
Answer: Being kicked from a game does, in fact, count as a loss regardless of whether or not your team won. Here is a Steam Forum thread by someone who shows disdain regarding this condition along with others expressing their views on the kick process in general.


Unable to get into the chest with another character

Question: I already beat Binding of Isaac quite a lot of times and am trying to max out Samson. Unfortunately, after beating satan five times with that character I still get endgame video instead of entry to the chest. What character-specific requirements are there for the chest?
Comment: Beating Satan doesn't get you to the chest...?
Comment: @Dova nope it doesn't. I get an endgame video.
Answer: It sounds like you might be confusing the end levels. As per the wiki, you can access the chest in one of three ways:

Touching the large chest that drops after beating Isaac in the Cathedral while holding the Polaroid. (This is the normal method of accessing the chest.) The Polaroid is a guaranteed drop from Mom if you've beaten Isaac 5 times.
Somehow teleporting to the I AM ERROR room while on the Cathedral.
Finding a Black Market in the Cathedral.

If you've beaten Satan, then you're actually in Sheol, which is the "evil" equivalent of the Cathedral. Touching the chest in Sheol while holding the Negative (the "evil" equivalent of the Polaroid, which unlocks after beating Satan 5 times) will teleport you to the Dark Room.
If you mix these up at all (for example, taking the Negative to the Cathedral or the Polaroid to Sheol), you will not be able to progress to the next floor and the game will end when you beat Isaac/Satan.


How common are these Nuzlocke rules?

Question: I have Nuzlocked Pokemon Ruby and now I want to Hardcore Nuzlocke Pokemon Ruby. Now, the rule I am concerned about is:
You can only catch a first Pokemon per route.
This is a standard Pokemon rule, but I would twist what a route is. To be specific, I consider every floor of Dewford cave a route for itself. Why? Aron! If you would consider only Pokemon on your first entry as your Dewford cave encounter, there is no chance of you encountering Aron. On my first Nuzlocke, I solved this by picking that Repel after defeating Roxanne and then Repeling until I went down so my first encounter was Aron. Why am I now thinking otherwise? On first floor you have:

Makuhita, lvl 24 Hariyama same attack stat as Blaziken,

Zubat, just think about Crobat,

Abra, even though you don't get Kadabra, to Brawly it makes no difference

Geodude, the best possible encounter, Wattson - laughs in Ground. Flannery - laughs in quad resist plus super effective whatever. Norman - laughs in unable to set up Facade and tank monstrosity. Elite Four - laughs in Earthquake.

Also, I was playing on no repeat encounters. But I have not seen a single good use of Beautifly in game. While Dustox is a monstrosity that can just solo Brawly for you (and even Roxanne, lvl 15 destroys her with Confusion again and again).
How common are these rules in Nuzlocking?
Comment: It's very common to Nuzlocke with whatever rule modifications *you think are fun*. Nuzlocke isn't some strict thing you have to follow, it's for your fun. If you think this modification makes it more fun for you, do it. And if a rule *isn't fun*, don't do it.
Comment: What determines "common"?
Answer: In my opinion, the whole cave counts as one.
The definition of a route is when the area text changes. For example, you walk to a different route, it'll say on the screen "Route xx".
The name doesn't change throughout the cave area, so it's only one route.
But you can use a different strategy I found on Gamefaqs:

Each level of a cave is considered a different area but you can only catch one Pokemon in the entire cave. That way, if certain Pokemon only live near the bottom of the cave, you still have a chance of getting them.
The trade off is once you encounter a Pokemon on a floor and choose to not catch it, you can't change your mind should the other floors yield worse encounters.
Answer: On my nuzlockes I consider routes as separate areas with different names so for me Dewford cave floors wouldn't count as separate ones.
Although, the routes can be counted to be only routes if they have the name "Route" on it so caves, special zones and poke safaris don't count to get more consistency at knowing when to get pokemon.

How common are these Nuzlocke rules?


Simplification of Kampé de Fériet function

Question: I was dealing with a convolution type integral
$$
\int^z_0 t^m {}_0F_1(;1;-t) \: {}_2F_3\Big( 1,1;2,m,m+1 ; -a t\Big) \:\mathrm{d}t
$$
By applying one of the identities in Exton's book, the solution should be
$$\frac{\Gamma(m)}{\Gamma(m+1)}
z^m
\,
\mathrm{F}^{0:3;1}_{1:3;1}
\Bigg(
\begin{matrix}
  - &:& m,1,1 &;1& \\
 m+1&:& 2,m,m+1&;1&
\end{matrix}
\Bigg|
-az,z
\Bigg)
$$
any idea how to reduce this form of Kampé de Fériet function into :
(a) a product of hypergeometric functions
(b) any form of Appell or Humbert series.
Answer: Hint:
$\int_0^zt^m~_0F_1(;1;-t)~_2F_3(1,1;2,m,m+1;-at)~dt$
$=\int_0^zt^m\sum\limits_{n=0}^\infty\dfrac{(-1)^nt^n}{(n!)^2}\sum\limits_{k=0}^\infty\dfrac{(-1)^ka^kt^k}{(m)_k(m+1)_k(k+1)}dt$
$=\int_0^z\sum\limits_{n=0}^\infty\sum\limits_{k=0}^\infty\dfrac{(-1)^{n+k}a^kt^{n+k+m}}{(n!)^2(m)_k(m+1)_k(k+1)}dt$
$=\left[\sum\limits_{n=0}^\infty\sum\limits_{k=0}^\infty\dfrac{(-1)^{n+k}a^kt^{n+k+m+1}}{(n!)^2(m)_k(m+1)_k(k+1)(n+k+m+1)}\right]_0^z$
$=\sum\limits_{n=0}^\infty\sum\limits_{k=0}^\infty\dfrac{(-1)^{n+k}a^kz^{n+k+m+1}}{(n!)^2(m)_k(m+1)_k(k+1)(n+k+m+1)}$


Modifying lines

Question: I'm looking to load a file and modify several predefined lines to certain values.
The following is what I tried:
with open("test.txt",'w') as f:
                for i,line in f:
                    if (i == 2):
                        f.writelines(serial1)
                    if (i == 3):
                        f.writelines(serial2)
                    if (i == 4):
                        f.writelines(serial3)
                    else:
                        f.writelines(line)

However, when running the code I got the following error:
for i,line in f:
io.UnsupportedOperation: not readable

What am I doing wrong?
Comment: You're opening the file using `w`, *writing-only* mode. Even so, this won't do even if you changed that; you can't simply write into the middle of a file (at least without *overwriting* the rest).
Comment: I think you would want `for i, line in enumerate(f)` in any case.
Comment: See this answer: http://stackoverflow.com/a/2081880/11208
Answer: What you are doing is called editing in place. For that, Python standard library fileinput can help:
import fileinput

for line in fileinput.input('test.txt', inplace=True):
    if fileinput.lineno() == 2:
        print serial1
    elif fileinput.lineno() == 3:
        print serial2
    elif fileinput.lineno() == 4:
        print serial3
    else:
        print line

Update
As for "What I'm doing wrong?" there are a couple:

You opened the file for writing, how can you read from it? You might attempt to change the mode from "w" to "r+", which is read and write. That brings up another dilemma: After reading line 2, the file pointer is positioned at the beginning of line 3, anything you write will overwrite line 3, not to mention the length differences between the old and new lines. It is better to write to a new temp file, then copy it back to the original when done, or you can use fileinput as shown above.
for i, line in f does not work, I think you meant for i, line in enumerate(f, 1)
What's with the extremely deep indentation?
The if statement should be if ... elif ... else. Currently your else clause is attached only to the if i == 4 statement, not the other two.
Answer: You open the file for write-only (w mode) and try to read it - which is done by the for statement.
That is: iterating over a file with the for statement is done when you are reading the file.
If you plan to write to it, for on the fileitself can't help you - just use a normal counter with "range" and write to it.
with open("test.txt",'w') as f:
    for i in range(desired_lines):
        if (i == 2):
            f.write(serial1 + "\n")
        if (i == 3):
            f.write(serial2 + "\n")
        if (i == 4):
            f.write(serial3 + "\n")
        else:
            f.write(line + "\n")

Also, writelines should be used when you have a list of strings you want to write,
each ina  separate line - yu don't show the content of your vaiables, but given that you want the exact line numbers, it looks like writelines is not what you want.
(On a side note - beware of indentation - you should ident a fixed ammount foreach block you enter in Python - it will work with an arbitrry identation like you did, but is not usual in Python code)
update
It looks like you need to change just some lines of an already existing text file. The best approach for this  is by far to recreate another file, replacing the lines you want, and rename everything afterwards.
(Writing over a text file is barely feasible, since all text lines would have to be the same size as the previously existing lines - and still would gain nothing in low-level disk access).
import os

...

lines_to_change{
    2: serial1,
    3: serial2,
    4: serial3,
}

with open("test.txt",'rt') as input_file, open("newfile.txt", "wt") as output_file:
    for i, line in enumerate(input_file):
        if i in lines_to_change:
            output_file.write(lines_to_change[i] + '\n')
        else:
            output_file.write(line)

os.rename("test.txt", "test_old.txt")
os.rename("newfile.txt", "test.txt")
os.unlink("test_old.txt")

Comment: How I get the "current" line from the file?
Comment: There is no way to get the "current line" - if you are writting to it, you destroyed the previous file to start with. It is possible to open a file to read and write - but that is usually done with binary files, where you have fixed-size fields, not text.
Comment: If you want to generate a text file that just modifies some lines from another, already existing file the approach is to re-create another file with where you rewrite all the information, changing the needed information, and delete the old file and rename the new one when you are done  - I will update the answer with an example of this approach
Answer: As pointed out, your issue is that you try to read and write in the same file. The easiest way is to open a new file, and replace the first one when you have the desired output.
To get the file lines number, you can use enumerate:
with open("test.txt",'r') as f:
                for i,line in enumerate(f):
                    if (i == 2):
                        f.writelines(serial1)
                    if (i == 3):
                        f.writelines(serial2)
                    if (i == 4):
                        f.writelines(serial3)
                    else:
                        f.writelines(line)

Modifying lines


showing that a lie algebra is the direct sum of two ideals.

Question: I am trying to do an exercise(2.13) in Wildon and Erdmann's Intro to Lie Algebras and I'm stuck.  The meat of the question is to show that under the following conditions
i. the center, $Z(I)=0$
ii. if $D:I\to I$ is a derivation, then $D= \mathrm{ad}~x$ for some $x\in I$
a lie algebra, $L$ is the direct sum of an ideal $I$ of L and the centraliser $B$ of $I$ in $L$. That is, I'm required to show that $L=I\oplus B$.
With the help of the Jacobi identity, I've been able to show that $B$ is an ideal of $L$. My difficulty is in showing the direct sum. I know I have to show that $B\cap I = \{0\}$ and every element in $L$ can be written as a sum of elements in $B$ and $L$.
Answer: $Z(I) = \{0\}$ is equivalent to the intersection of the centralizer of $I$ and $I$ being trivial.  So $B \cap I = \{0\}$.  Now let $y \in L$.  By (ii) there exists $x \in I$ such that $\operatorname{ad} y\vert_I = \operatorname{ad} x\vert_I$.  Then $y - x \in B$ since $[y-x, z] = [y,z] - [x,z] = 0$ for all $z \in I$.  Thus $y = x + (y-x)$ with $x \in I$ and $y-x \in B$.
Comment: can u explain your first sentence a bit.
Comment: Suppose $x \in B \cap I$.  Then since $x \in B$, $[x,y] = 0$ for all $y \in I$.  Since $x \in I$, this implies $x\in Z(I) = \{0\}$.  So $B \cap I = \{0\}$.


How do I get gold stars?

Question: In Cooking Mama 4: Kitchen Magic, I've noticed that sometimes after completing a recipe I get a gold star, and if I get a total of three (over time, not all at once), I get a reward (usually a custom item for either Mama to wear, or something to change the look of my kitchen).
What can I do to make sure I get all the stars? Is it related to score, somehow?
Answer: Doing a recipe step perfectly in less than half the time earns you a bonus star.
Doing a recipe step perfectly within the allotted time unlocks recipes and sometimes unlocks a "Let's Help" mini-game.
With this new found knowledge, go make Mama proud!
Comment: Hurray! I shall make her proud (and keep her from making her scary burning eyes at me...)

How do I get gold stars?