text:
Q: How to change IconButton color? How can I change the color of icon in IconButton? The color of icon in the theme (using theme designer) is black however sometimes I need to show a iconbutton in white color. The code below doesn't seem to change the color of icon to white
const iconStyle = {
    root: {
        color: theme.palette.white
    }
};

return (

            <IconButton iconProps={{ iconName: 'Close' }} styles={iconStyle} title="Close" ariaLabel="Close" />

{title}

{narrative}

        {link}

);

A: Here is a codepen demo: https://codepen.io/vitalius1/pen/BgWmYZ
      <IconButton
        iconProps={{ iconName: 'Emoji2' }}
        styles={{
          icon: {color: 'white', fontSize: 72},
          root: {
            width: 100,
            height: 100,
            backgroundColor: 'black',
            selectors: {
              ':hover .ms-Button-icon': {
                color: 'red'
              },
              ':active .ms-Button-icon': {
                color: 'yellow'
              }
            }
          },
          rootHovered: {backgroundColor: 'black'},
          rootPressed: {backgroundColor: 'black'}
        }}
      />

A: Similar to Vitalie's answer you can do this to avoid using rootHovered: https://codepen.io/Jlovett1/pen/vYKEQQd
<IconButton
        iconProps={{ iconName: 'Emoji2' }}
        styles={{
          icon: {color: 'white', fontSize: 72},
          root: {
            width: 100,
            height: 100,
            backgroundColor: 'black',
            margin: 0,
            padding: 0,
            selectors: {
              '& .ms-Button-icon:hover, .ms-Button-flexContainer:hover': {
                backgroundColor: 'black',
                color: 'red'
              },
            }
          },
        }}
      />


text:
Q: Jasmine async tests inside loop are not working as expected I have written some unit tests for a node.js driven API I built using Jasmine.
The tests work fine, but now I would like to run a set of async tests with different inputs, but I cannot get it working.
My tests run some requests against the API with an "offset" and "limit" parameter in the URL and the API inserts links for pagination in the response (first, prev, next and last).
Here my Jasmine test:
describe('API with "limit" and "offset" parameters', function() {

    var offset = 0;
    var limit = 4;
    var url = baseUrl + '?limit=' + limit + '&offset=' + offset;

    beforeEach(function(done) {
        request.get(url, function(err, res, resBody) {
            response = res;
            body = JSON.parse(resBody);
            count = body.count;
            done();
        });
    });

    it('should respond with status code 200', function(done) {
        expect(response.statusCode).toEqual(200);
        done();
    });

    it('should have a response with [limit] results if count - offset >= limit, otherwise count - offset', function(done) {
        if(count - offset >= limit) expect(body.rows.length).toEqual(limit);
        else expect(body.rows.length).toEqual(count - offset);
        done();
    });

    it('should have navigation links', function(done) {
        expect(body.first).toBeDefined();
        expect(body.prev).toBeDefined();
        expect(body.next).toBeDefined();
        expect(body.last).toBeDefined();
        done();
    });

    it('should have "first" navigation link equal to url offset=0 and limit=limit', function(done) {
        expect(body.first).toEqual(baseUrl + '?limit=' + limit + '&offset=0');
        done();
    });

    it('should have "prev" navigation link equal to null if offset=0, otherwise offset = offset - limit', function(done) {
        if(offset ===0) expect(body.prev).toBeNull();
        else expect(body.prev).toEqual(baseUrl + '?limit=' + limit + '&offset=' + (offset - limit));
        done();
    });

    it('should have "next" navigation link equal to offset + limit, or null if offset+limit > count', function(done) {
        if(offset + limit <= count) expect(body.next).toEqual(baseUrl + '?limit=' + limit + '&offset=' + (offset + limit));
        else expect(body.next).toBeNull();
        done();
    });

    it('should have "last" navigation link equal to floor(count/limit)*limit', function(done) {
        expect(body.last).toEqual(baseUrl + '?limit=' + limit + '&offset=' + Math.floor(count/limit) * limit);
        done();
    });
});

This test runs fine but now I'd like to repeatedly run this test, in each run incrementing "offset" by "limit" until the last page is reached (i.e. offset + limit >= count), but I can not get this working.
What I have tried so far
My first idea was to put the tests inside a loop, enclosed in an IIFE but this doesn't work because "count" in the for-loop is undefined (I guess it's only available inside "it"):
for(var i=offset; i<count; i+=limit) {  // "count" is undefined here

        (function(offset, count, limit) {

            it('should have "first" navigation link equal to url offset=0 and limit=limit', function(done) {
                expect(body.first).toEqual(baseUrl + '?limit=' + limit + '&offset=0');
                done();
            });

            it('should have "prev" navigation link equal to null if offset=0, otherwise offset = offset - limit', function(done) {
                if(offset ===0) expect(body.prev).toBeNull();
                else expect(body.prev).toEqual(baseUrl + '?limit=' + limit + '&offset=' + (offset - limit));
                done();
            });

            it('should have "next" navigation link equal to offset + limit, or null if offset+limit > count', function(done) {
                if(offset + limit <= count) expect(body.next).toEqual(baseUrl + '?limit=' + limit + '&offset=' + (offset + limit));
                else expect(body.next).toBeNull();
                done();
            });

            it('should have "last" navigation link equal to floor(count/limit)*limit', function(done) {
                expect(body.last).toEqual(baseUrl + '?limit=' + limit + '&offset=' + Math.floor(count/limit) * limit);
                done();
            });
        })(offset, count, limit);
    }

My second idea was to do the incrementing inside "afterAll", again wrapping the tests in an IIFE.
It seems that afterAll does run runTests() again (I see the console.log appearing) but the tests itself are not run again:
(function runTests(offset, count, limit) {
        console.log('running tests');
        beforeEach(function(done) {
            request.get(url, function(err, res, resBody) {
                response = res;
                body = JSON.parse(resBody);
                count = body.count;
                done();
            });
        });

        it('should have "first" navigation link equal to url offset=0 and limit=limit', function(done) {
            expect(body.first).toEqual(baseUrl + '?limit=' + limit + '&offset=0');
            done();
        });

        it('should have "prev" navigation link equal to null if offset=0, otherwise offset = offset - limit', function(done) {
            if(offset ===0) expect(body.prev).toBeNull();
            else expect(body.prev).toEqual(baseUrl + '?limit=' + limit + '&offset=' + (offset - limit));
            done();
        });

        it('should have "next" navigation link equal to offset + limit, or null if offset+limit > count', function(done) {
            console.log('next', offset, limit, count);
            if(offset + limit <= count) expect(body.next).toEqual(baseUrl + '?limit=' + limit + '&offset=' + (offset + limit));
            else expect(body.next).toBeNull();
            done();
        });

        it('should have "last" navigation link equal to floor(count/limit)*limit', function(done) {
            expect(body.last).toEqual(baseUrl + '?limit=' + limit + '&offset=' + Math.floor(count/limit) * limit);
            done();
        });

        afterAll(function() {
            offset += limit;

            if(offset < count) runTests(offset, count, limit);
        });
    })(offset, count, limit);

What am I doing wrong here? Is there another way to get this working?
UPDATE: here's my full working code based on Zlatko's answer:
describe('API with "limit" and "offset" parameters', function() {

    var offset = 0;
    var limit = 4;
    var url = baseUrl + '?limit=' + limit + '&offset=' + offset;

    function testNavLinks(limit, offset, url) {

        describe('Check navigation links with offset = ' + offset, function() {

            var response;
            var count;
            var body;

            beforeEach(function(done) {
                request.get(url, function(err, res, resBody) {
                    response = res;
                    body = JSON.parse(resBody);
                    count = body.count;
                    done();
                });
            });

            it('should respond with status code 200', function(done) {
                expect(response.statusCode).toEqual(200);
                done();
            });

            it('should have a response with [limit] results if count - offset >= limit, otherwise count - offset', function(done) {
                if(count - offset >= limit) expect(body.rows.length).toEqual(limit);
                else expect(body.rows.length).toEqual(count - offset);
                done();
            });

            it('should have navigation links', function(done) {
                expect(body.first).toBeDefined();
                expect(body.prev).toBeDefined();
                expect(body.next).toBeDefined();
                expect(body.last).toBeDefined();
                done();
            });

            it('should have "first" navigation link equal to url offset=0 and limit=limit', function(done) {
                expect(body.first).toEqual(baseUrl + '?limit=' + limit + '&offset=0');
                done();
            });

            it('should have "prev" navigation link equal to null if offset=0, otherwise offset = offset - limit', function(done) {
                if(offset === 0) expect(body.prev).toBeNull();
                else expect(body.prev).toEqual(baseUrl + '?limit=' + limit + '&offset=' + (offset - limit));
                done();
            });

            it('should have "next" navigation link equal to offset + limit, or null if offset+limit > count', function(done) {
                if(offset + limit <= count) expect(body.next).toEqual(baseUrl + '?limit=' + limit + '&offset=' + (offset + limit));
                else expect(body.next).toBeNull();
                done();
            });

            it('should have "last" navigation link equal to floor(count/limit)*limit', function(done) {
                expect(body.last).toEqual(baseUrl + '?limit=' + limit + '&offset=' + Math.floor(count/limit) * limit);
                done();
            });
        });
    }
    // 13 is the actual number of results
    // I did not manage to get the actual number from the response, see my comment below
    for(var i=0; i<13; i+=limit) {
        url = baseUrl + '?limit=' + limit + '&offset=' + i;
        testNavLinks(limit, i, url);
    }
});

A: So you're trying to repeat a test multiple times, but there's no need to deal with an IIFE at all. Just make your test a function, then call it from the loop:
describe('Loop an async set of tests.', function() {

  var baseUrl = process.env.API_URL; // or whatever
  function loopMyApi(offset, limit) {

    // add a new suite
    describe('Calling at offset: ' + offset , function() {

      var response;
      var myUrl = baseUrl + '?limit=' + limit + '&offset=' + offset;
      beforeEach(function(done) {

        request(myUrl, function(err, res) {

          if (err) {throw err;}
          response = res;
          done();
        });
      });

      it('should have length', function() {

        // btw since response is already here, this test is now sync
        // no need for `done`.
        response.body.length.should.equal(limit);
      });
      it('should be ok', function() {
        response.statusCode.should.be.lessThan(399);
      });
    });
  }
  var limit = 10;
  // you can start like this, or just make a regular for
  // loop as you have in your examples.
  [0, 10, 20, 30].forEach(function(offset) {

    // if you want to modify limit for some reason, do it here.
    loopMyApi(offset, limit);
  });
});

Adjust as necessary to fit your scenario.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Log4net RollingFileAppender not writing when application runs as a service I have an C# application that can run on Windows 10 either as a console app or as a service, depending on a configuration parameter.  I am writing log messages using a log4net RollingFileAppender.  I'm using log4net version 4.5.  When the application runs as a console app, the rolling file gets written as expected.  When it is run as a service the file does not get written.  What can I do to get my log file?
Here's the configuration file:
<?xml version="1.0" encoding="utf-8"?>
<log4net>

  <appender name="TimedFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="c:/misc/HotspotControlService.log" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <datePattern value="yyyyMMdd.lo\g" />
      <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date - %message%newline" />
      </layout>
  </appender>

  <root>
    <level value="DEBUG" />
    <appender-ref ref="TimedFileAppender" />
  </root>

</log4net>

A: As usual, my own idiocy is the problem.  I specified the configuration file in my program by the bare file name, with no folder given.  The file exists in the same folder as my executable file.  But when running as a service, the working folder is not the folder in which the executable folder lives.  I used an absolute path for the configuration file name, and it worked.


text:
Q: No module named itk (Insighttolkit) in Python I am novice in python and Simple_ITK both to process .mha 3D image files. I have two problems:

*

*When ever I install ITK, I always get an error as shown below:
 and somehow I install ITK It doesn't work at all having no connectivity with python. And I also tried python-insighttoolkit3 package then it shows and error of

" Can't down load Python 2.8:i386" in Ubuntu software Center. I have tried various methods to install Insight Tool Kit in Ubuntu whatever I found but most of the time I get the same error as shown in picture above.
So can anybody guide me how to install and build ITK so that no error like no module named itk found.

*Now another problem is I have a .py file and it has a class in which I have to fed input externally otherwise it will consider as None. SO I tried to call the file as

import /path/to/file/xxx.py

but it gives an Syntax error: invalid syntax
so how to call class from a python file from python Console .
Now, I'm using Ubuntu 15.02. For any missing details please ask.
Thanks.

A: 1- For what I see in the image, I see that you are trying to install ITK instead  of SimpleITK. For SimpleITK it is very simple using a linux package installer, like pip or easy-install. in this link you have the instructions to install it correctly. Remember to execute the instructions as super user. Maybe it is the reason of your error ( I can't see the instruction you are writing in the console ).
2- I recommend you to read the Python tutorial for modules The fastest way is to be located first on the directory of your .py file. The sequence would be:

cd /path
import module.py


text:
Q: Issues solving Project Euler #4 The problem reads

A palindromic number reads the same both ways. The largest palindrome
  made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit
  numbers.

I don't understand. I double checked everything before trying to reverse the number, but after that I don't get anything in the console but 0s.
public class E4 {

public static void main(String[] args) {

    int product, rev = 0;

    for (int x = 0, y = 1; x <= 99 && y <= 99;) {
        product = x * y;                            //This for loop multiplies numbers from 0-99 * 1
        if (x == 99) {                              //Then numbers from 0-99 * 2, and so on, until 99*99
            y++;
            x = 0;
        }
        x++;

        while (product != 0) {
            rev = rev * 10;                        //This loop should reverse the products and then
            rev = rev + product % 10;              //The if loop should check if it is a palindrome number
            product = product / 10;                //But it doesn't work?

            if (rev == product) {
                System.out.println(rev);
            }

        }

      }
    }
   }

A: Here is code that should work for you.
public class E4 {

    public static void main(String[] args) {

        int product = 0;

        for (int x = 0; x < 100; x++) {
            for (int y = 0; y < 100; y++) {
                product = x * y;
                int rev = reverseInt(product);
                if (rev == product) {
                    System.out.println(rev);
                }

            }
        }
    }

    private static int reverseInt(int product) {
        int rev = 0;
        while (product != 0) {
            rev = rev * 10;
            rev += product % 10;
            product = product / 10;
        }
        return rev;
    }
}

Part of your problem is that your code always ended up with product being 0 at the end (since your while loop changed it and only exited when product == 0).  Also, you never reset rev to 0.


text:
Q: specify the type inside a class method What is the pythonic way to properly specify the type of the arguments of a method?
Checking How do Python functions handle the types of the parameters that you pass in? and How do I ensure parameter is correct type in Python? only works for primitive data types.
Consider the minimum following example, where I want to pass an object of same type to the method. This does not work because the method is defined inside the class.
class num:
    def __init__(self,val:int) -> None:
        self.x=val
    def print(self,other:num) -> None:
        pass

def main():
    n=num(3)
    n.print()

main()

A: You can use forward references:
class num:
    def __init__(self,val:int) -> None:
        self.x=val
    def print(self,other:'num') -> None:
        pass

This works because Python (and any checkers complying to PEP 484) will understand your hint and register it appropriately, this is a common scenario.


text:
Q: Heat diffusion in semi-infinite rod with piecewise I.C. I am trying to solve a specific heat diffusion problem with a semi-infinite, isolated rod, where the initial temperature distribution is $10^\circ$ C for $0 < x < 1$, and $0$ for $x > 1$. The problem is thus of the form
$$ \frac{\partial u}{\partial t} - \frac{\partial^2u}{\partial x^2} = 0 $$
$$ \frac{\partial u}{\partial x}(0,t) = 0 $$
$$ u(x,0) = \begin{cases} 10 & \mathrm{for} \:\: 0 < x < 1 \\
0 & \mathrm{for} \:\: x > 1 \end{cases}. $$
One-sided Laplace transform in $t$ and rearranging yields
$$ \frac{\partial^2 \bar{u}}{\partial x^2}(x,s) - s\bar{u}(x,s) = -u(x,0) =  \begin{cases} -10 & \mathrm{for} \:\: 0 < x < 1 \\
0 & \mathrm{for} \:\: x > 1 \end{cases}.$$
I'm not sure how to approach this, but I've tried solving for the first region,
$$ \frac{\partial^2 \bar{u}}{\partial x^2} - s\bar{u} = -10 \Rightarrow $$
$$ \bar{u} = \bar{u}_h + \bar{u}_p = a(s)e^{\sqrt{s}x} + b(s)e^{-\sqrt{s}x} + \frac{10}{s} $$
and then applying the boundary conditions,
$$ u \:\: \mathrm{bounded} \Rightarrow a(s) = 0$$
$$ \frac{\partial u}{\partial x}(0,t) = 0 \Rightarrow \frac{\partial \bar{u}}{\partial x}(0,s) = 0 \Rightarrow -\sqrt{s}b(s) = 0 \Rightarrow b(s) = 0. $$
But this means that
$$ \bar{u}(x,s) = \frac{10}{s} \Rightarrow u(x,t) = 10H(t) \:\:\:\: (0 < x < 1) $$
which does not seem to make much sense since this means that the temperature remains constant in the first region and one would expect it to decrease as $t \rightarrow \infty$. Maybe some kind soul could point out what I'm doing wrong and how to best approach this problem?
(A similar problem with a piecewise I.C. was posted here, but the solution is attempted using the Fourier transform, which doesn't seem to work.)

A: After some further research, I think I have found a solution. One can extend the problem to all $x$ by reflecting $u$ evenly into negative $x$. The even extension of $u$ is then
$$ u^+(x,t)  = \begin{cases} u(x,t) & \mathrm{for} \:\: x>0 \\ u(-x,t) & \mathrm{for} \:\: x < 0  \end{cases}.$$
It can then be shown that
$$ \bigg(\frac{\partial^2u}{\partial x^2}\bigg)^+ = \frac{\partial^2u^+}{\partial x^2} - 2\frac{\partial^2u}{\partial x^2}(0,t)\delta(x). $$
Using this gives a new problem
$$ \frac{\partial u^+}{\partial t} - \frac{\partial^2u^+}{\partial x^2} = 0$$
$$ u^+(x,0) = 10H(x+1) - 10H(x-1). $$
Fourier transform in $x$ yields
$$ \frac{\partial \widehat{u^+}}{\partial t}(\omega,t) + \omega^2\widehat{u^+}(\omega,t) = 0 \Rightarrow $$
$$ \widehat{u^+} = C(\omega)e^{-\omega^2t}. $$
Applying the transformed initial condition yields
$$ \widehat{u^+}(\omega,0) = 10\frac{2\sin{\omega}}{\omega} = C(\omega) $$
$$ \therefore \:\: \widehat{u^+}(\omega,t) = 10\frac{2\sin{\omega}}{\omega} e^{-\omega^2t}.$$
Inverse transform using the convolution theorem (in $x$) now gives the extended solution
$$ u^+(x,t) = 10\big[H(x+1) - H(x-1)\big] \:\: \ast \:\: \frac{1}{\sqrt{4\pi t}}e^{-x^2/4t} = $$
$$\frac{10}{\sqrt{4\pi t}} \int_{-\infty}^\infty \big[H(\tau+1) - H(\tau-1)\big]e^{-(x-\tau)^2/4t} \:d\tau = $$
$$ \frac{10}{\sqrt{4\pi t}} \int_{-1}^1 e^{-(x-\tau)^2/4t} \:d\tau = \Bigg[\mathrm{Sub.} \:\: y=\frac{x-\tau}{\sqrt{4t}}\Bigg] = $$
$$ -\frac{10}{\sqrt{\pi}} \int_{(x+1)/\sqrt{4t}}^{(x-1)/\sqrt{4t}} e^{-y^2} \:dy = -5 \,\mathrm{erf}(y)\Bigg|_{(x+1)/\sqrt{4t}}^{(x-1)/\sqrt{4t}} =$$
$$ 5\Bigg[\mathrm{erf}\bigg(\frac{x+1}{\sqrt{4t}}\bigg) - \mathrm{erf}\bigg(\frac{x-1}{\sqrt{4t}}\bigg) \Bigg].$$
This is also the solution to the original problem ($x>0$). Plotting it for a few different values of $t$ gives a result that looks sensible:

Further comments are still welcome.

A: The Laplace transform approach also works, but your conclusion $a(s) = 0$ is wrong, since $\mathrm{e}^{\sqrt{s} x}$ is bounded for $x < 1$ anyway. The boundedness of $u$ can only be used to discard the term with the positive exponent in the region where $x > 1$. The general solution then reads
$$\bar{u}(x,s) = \begin{cases} a(s) \mathrm{e}^{\sqrt{s} x} + b(s) \mathrm{e}^{-\sqrt{s} x} + \frac{10}{s} &, \, x<1 \\
c(s) \mathrm{e}^{-\sqrt{s} x} & , \, x>1 \end{cases} \, .$$
From the boundary conditions $\partial_1 \bar{u}(0,s) = 0$, $\bar{u}(1^+,s) = \bar{u}(1^-,s)$, $\partial_1 \bar{u}(1^+,s) = \partial_1 \bar{u}(1^-,s)$ we obtain
$$ a(s) = b(s) = - \frac{\mathrm{e}^{-\sqrt{s}}}{\mathrm{e}^{\sqrt{s}}-\mathrm{e}^{-\sqrt{s}}} c(s) = - 5\frac{\mathrm{e}^{-\sqrt{s}}}{s} \, ,$$
so
\begin{align}
\bar{u}(x,s) &= \frac{10}{s} \begin{cases} 1 - \frac{1}{2} \left[\mathrm{e}^{\sqrt{s} (x-1)} + \mathrm{e}^{-\sqrt{s} (x+1)}\right] &, \, x \leq 1 \\
\frac{1}{2} \left[\mathrm{e}^{-\sqrt{s} (x-1)} - \mathrm{e}^{-\sqrt{s} (x+1)}\right] & , \, x>1 \end{cases} \\
&= \frac{10}{s} \left[\operatorname{H}(1-x) - \frac{1}{2} \mathrm{e}^{-\sqrt{s} (x+1)} + \frac{\operatorname{sgn}(x-1)}{2} \mathrm{e}^{-\sqrt{s} \lvert x-1\rvert}\right].
\end{align}
Finally, since
$$ \operatorname{\mathcal{L}}^{-1} \left(s \mapsto \frac{\mathrm{e}^{-a \sqrt{s}}}{s}\right) (t) = \operatorname{erfc}\left(\frac{a}{2 \sqrt{t}}\right) = 1 - \operatorname{erf}\left(\frac{a}{2 \sqrt{t}}\right) $$
holds for $a, t \geq 0$, we recover the result you derived using the Fourier transform:
\begin{align}
u(x,t) &= 5 \left[\operatorname{erf}\left(\frac{x+1}{2 \sqrt{t}}\right) - \operatorname{erf}\left(\frac{x-1}{2 \sqrt{t}}\right)\right] + 10 \left[\operatorname{H}(1-x) - \frac{1 - \operatorname{sgn}(x-1)}{2}\right] \\
&= 5 \left[\operatorname{erf}\left(\frac{x+1}{2 \sqrt{t}}\right) - \operatorname{erf}\left(\frac{x-1}{2 \sqrt{t}}\right)\right] .
\end{align}


text:
Q: Translate Google Chrome's storage from policies/managed/*.json to Firefox Google Chrome's extensions can be configured as a user by creating a file in /etc/chromium-browser/policies/managed/ containing e.g.
{
    "3rdparty": {
        "extensions": {
            "fiopkogmohpinncfhneadmpkcikmgkgc": {
                "youtube": 1
            }
        }
    }
}

(in Linux, for Windows, you have to set a group policy with similar content)
How can this be translated to Firefox? How can Firefox's WebExtensions be configured (as a user, not as a developer) with storage.managed?

A: Perhaps more information is needed, but it seems to me that the question is answered
by your own link.
If you are the extension developer, you should include in the manifest file
manifest.json:
"type": "storage",
"data":
{
  "whitelist": "google",
  "starttime": "0800",
  "endtime": "1500"
}

The attribute whitelist is referenced in the code by the
StorageArea.get() function:
var storageItem = browser.storage.managed.get('whitelist');
storageItem.then((res) => {
  console.log(`Whitelist is: ${res.whitelist}`);
});

If you would like to change an existing extension, then you need to do it
from source-code, since not only the manifest needs to be changed,
but also the code itself that references the storage items.
Even if the extension uses a
Native manifest,
defined as
"specially formatted JSON files that are provisioned on the user's computer by some means outside the extension installation process", changing
the manifest is not enough.
The
storage.managed
page links to the example add-on of
favourite-colour, which is a complete example showing the definition,
access and setting of the managed data, and of creating the
manifest.json file.

A: These are the steps to customize the favorite-color extension provided by Mozilla:

*

*download favorite-color extension at https://github.com/mdn/webextensions-examples/tree/master/favourite-colour

*create file with manifest content at https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage/managed#Provisioning_managed_storage:
{
  "name": "favourite-colour-examples@mozilla.org",
  "description": "ignored",
  "type": "storage",
  "data":
  {
    "colour": "management thinks it should be blue!"
  }
}

*mkdir -p /usr/lib/mozilla/managed-storage (global install, can also save to ~/.mozilla/managed-storage for a user-based install)

*save file to /usr/lib/mozilla/managed-storage/favourite-colour-examples@mozilla.org.json

*start firefox (or ESR)

*load extension downloaded in step 1 in about:debugging


text:
Q: Why can the results be different from the database on laravel? I want to ask, why can the results be with other users like the table below for the score, each score must be different.

So id_student = 15 with id_student = 12 the score is 80 the same for all, it should be different from that in the database it should be id_student = 15 the score is 100 which is correct as in the database in the Assignment_details table below:
Table database in MySQL

Code:
Controller:
public function DataAssignment(){
        $userAssignments = Assignment::join('subjects', 'assignments.id_subject', '=', 'subjects.id_sub')
            ->join('class_infos', 'subjects.id_class', '=', 'class_infos.id')
            ->join('class_details', 'class_infos.id', '=', 'class_details.id_class')
            ->where('class_details.id_user', '=', Auth::user()->id)
            ->get();

        return view('student.index', compact('userAssignments'));
    }

Model:
protected $fillable = [
        'id_id',
        'title',
        'assign_date',
        'due_date',
        'file_asg',
        'id_subject',
    ];

    public function assignments(){
        return $this->belongsTo(AssignmentDetail::class, 'id_id','id_assignment');
    }

    public function nulls(){
        return $this->hasMany(AssignmentDetail::class, 'id_assignment', 'id_id')
                ->where('assignment_details.id_student', '=', Auth::user()->id)
                ->first() === null;
    }

Blade:
@forelse($userAssignments as $data)

                                    {{$data->subjects->name_subject}}

                                    {{$data->title}}

                                    {{ date('d M Y - H:m', strtotime($data->due_date)) }} WIB

                                    @if(!$data->nulls())
                                        {{date('d M Y - H:m' ,strtotime($data->assignments->updated_at))}}
                                    @else
                                        Not uploaded yet
                                    @endif

                                    @if(!$data->nulls())
                                        Submitted
                                    @else
                                        Waiting
                                    @endif

                                    @if(!$data->nulls())
                                        {{ (!empty($data->assignments->score)) ? ($data->assignments->score):'0' }}
                                    @else
                                        0
                                    @endif

                                    @if(!$data->nulls())
                                        assignments->file_assignment))? url('upload/assignment/students/'.$data->assignments->file_assignment):''}}" download>
                                            <svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10" viewBox="0 0 20 20" fill="currentColor">
                                                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z" clip-rule="evenodd"></path>
                                            </svg>

                                    @else

                                    @endif
                                    id_id)}}">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10" viewBox="0 0 20 20" fill="currentColor">
                                            <path fill-rule="evenodd" d="M6 2a2 2 0 00-2 2v12a2 2 0 002 2h8a2 2 0 002-2V7.414A2 2 0 0015.414 6L12 2.586A2 2 0 0010.586 2H6zm5 6a1 1 0 10-2 0v2H7a1 1 0 100 2h2v2a1 1 0 102 0v-2h2a1 1 0 100-2h-2V8z" clip-rule="evenodd"></path>
                                        </svg>

                                    file_asg))? url('upload/assignment/question/'.$data->file_asg):url('images/no_image.jpg') }}" download>
                                        <svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10" viewBox="0 0 20 20" fill="currentColor">
                                            <path fill-rule="evenodd" d="M6 2a2 2 0 00-2 2v12a2 2 0 002 2h8a2 2 0 002-2V7.414A2 2 0 0015.414 6L12 2.586A2 2 0 0010.586 2H6zm5 6a1 1 0 10-2 0v3.586l-1.293-1.293a1 1 0 10-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L11 11.586V8z" clip-rule="evenodd"></path>
                                        </svg>

                        @empty

                                    No Data

                        @endforelse

What is the solution for id_student = 15 and id_student = 12 so that they can be on the web according to the database?

A: I think in your model should have One To Many relationship that's mean hasMany, every user may have many score. if right then you must have:
public function assignments(){
    return $this->hasMany(AssignmentDetail::class, 'id_id','id_assignment');
}


text:
Q: Is it OK to use Django development server for single-user applications? I'm developing an application that controls some piece of complex hardware and exposes a front-end to the users using Django, mainly for cross-platform and remote access reasons. Currently using Django templates, but soon with a separate front-end through DRF calls. My main points of interest are:

*

*user management. Admin users have more access

*session management. Ideally, one cannot login from multiple IPs at the same time.

*web-socket support for asynchronous notifications and real-time monitoring.

*asynchronous background operations. e.g. with celery workers

Note that the users of these application are the hardware operators which are usually no more than 3-5 tops, and most of the times, only one of them is actively working on it so no real user concurrency, neither real need to scale.
So my question is: Is there a real reason I would want to distribute my application using a production server such as gunicorn instead of simply running manage.py runserver?

A: From django runserver documentation:

DO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone through security audits or performance tests. (And that's how it's gonna stay. We're in the business of making Web frameworks, not Web servers, so improving this server to be able to handle a production environment is outside the scope of Django.)

The development server is not intended for use in production. It is not designed to be particularly efficient, stable, or secure. It does not support all the possible features of an HTTP server.
In short, python manage.py runserver may work until it breaks!!


text:
Q: How do I retrieve the path of a route? Given the following Router setup:
App.Router.map(function() {
  this.resource('posts', function() {
    this.route('new');
    this.resource('post', { path: ':post_id' }, function() {
      this.route('edit');
    });
  });
});

Is it possible to obtain the path of a route?
Fictitious example:
App.Router.get('path', 'posts.new'); //=> "/posts/new"

Or with a model like:
App.Router.get('path', 'post.edit', model); //=> "/posts/1/edit"

A: Try this in your console/dev tools:
App.Router.router.generate(['posts.new']);

this should output:
/posts/new

And with a model:
App.Router.router.generate(['post.edit'], postModel);

will output
/posts/1/edit

Thanks to @MilkyWayJoe's reference! https://github.com/emberjs/ember.js/blob/master/packages/ember-routing/lib/helpers/link_to.js#L112-L117 :)


text:
Q: How to search for Shiny Apps - Rstudio I'm entering the world of Shiny Rstudio now. So this is a beginner question
One question I came up with is: how do I search for the Shiny Apps available/created? Are all created Apps available? Is there any way that, once I create my app, I prevent it from being viewed? Or during the creation I "block it"?
From so much searching I found this link via Rstudio's website: http://www.showmeshiny.com/
Would this be the search platform for all apps made?
But in the case of http://www.showmeshiny.com/ it seems that it is necessary to send it via "Submit App".

A: I am not sure if I understand your questions correctly but I might be able to give you some insights.

*

*Are all created Apps available?
No, some shiny Apps are hosted on private servers or/and are embedded in password-protected websites or Wordpress-pages for example. If you dont have those access rights, then you cannot see those Apps.

*How do I search for the Shiny Apps available/created?
There is no way of doing that, except on pages like Showmeshiny, the RStudio Shiny Gallery, this gallery of recent Shiny-Apps or pther similar pages. Those Apps are publicly available and you can submit your own App if you like sharing it. Shinyapps.io is a nice and easy way of deploying your App on a server with a few clicks. But you need at least the standard license to include authentication, otherwise they would be free and open for everyone.

*Is there any way that, once I create my app, I prevent it from being
viewed?
I am not quite sure, what you mean. If it should be blocked from being viewed at all, I dont see the reason of building a ShinyApp. If you just want to access it yourself, then there are ways of doing so. Either password-protect it where only you know the password or host it on a local server that only you can access.

*Or during the creation I "block it"?
If you create it on your computer and run it, it will run on your computer and only be accessible to yourself, except you explicitly configure it otherwise. So there is no need of "blocking it".


text:
Q: checkbox with javascript magic attached does not uncheck I have a script where I use checkboxes and javascript to display additional items if the checkboxes are checked.
This seems to be working just fine most of the time.
There is one checkbox however that is giving problems.
I assume because of the javascript magic associated with it.
When checking it and then unchecking it, the checkbox always returns isset after post.
Never checking the checkbox and submitting returns not set as it should.
Checking and submitting returns checked as it should
checking, unchecking and submitting returns ... checked!
I have set up an example on http://vampke.uphero.com/tst.php
Here is the code:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['se_currentitem'])) echo "CHECKBOX = ISSET";
else echo "CHECKBOX = NOT SET";
}

echo <<< EOD

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<form action ="" method="post">
<input type="checkbox" id="se_currentitem" name="se_currentitem" value="1" onchange="toggle_currentitem()" />click the checkbox to activate the items

add item

<input type="submit" name="submit" value="submit" />
</form>

does anyone know what's going on?

A: The checkbox is named se_currentitem and the select menu is named se_currentitem[]. PHP's $_POST array treats these as the same.

*

*When you check the box, you create the select menu.

*When you uncheck the box, you hide the select menu, but it remains in the DOM, and is submitted by the browser. Notice in the Network inspector (or tcpflow, etc.). that the browser submits both se_currentitem and se_currentitem[].

You should rename the checkbox so it is not called se_currentitem (or rename the select menu so it is not called se_currentitem[]).


text:
Q: Why doesn't this released view controller cause a crash when messaged - (void)applicationDidFinishLaunching:(UIApplication *)application {

    // Create the navigation and view controllers
    RootViewController *rootViewController = [[RootViewController alloc]
                                              initWithStyle:UITableViewStylePlain];
    UINavigationController *aNavigationController = [[UINavigationController alloc]
                                             initWithRootViewController:rootViewController];
    self.navigationController = aNavigationController;
    [aNavigationController release];
    [rootViewController release];

    [rootViewController setRegions:[Region knownRegions]];

    // Configure and display the window
    [window addSubview:[navigationController view]];
    [window makeKeyAndVisible];
}

Here, in the above code the reference 'rootViewController' is used to send the message 'setRegions:', even after the object has been released in the previous line.
if it's wrong then how the simulator is running without any crash?
or
if it's right then, again how?, I couldn't see a difference between autorelease & release.
SOURCE:- http://developer.apple.com/iphone/library/samplecode/TableViewSuite/listing12.html
TO DOWNLOAD:- developer.apple.com/iphone/library/samplecode/TableViewSuite/index.html

A: The object held by rootViewController was retained by aNavigationController so its retain count is 2, and aNavigationController was retained when it is assigned to self.navigationController so its retain count is 2. So when you release rootViewController and aNavigationController, their retain counts drop to 1 each, so they are not collected, so you can still access them through their references.
Edit
Objects are only collected once their retain counts hit 0, and any reference to the objects is still valid, (even if the reference was released) until such time. Granted normally you don't want to rely on this and should make the call prior to releasing the object, but in this case it does work.


text:
Q: Call a method whenever a property is called Is there a way to add a attribute or something to a class that whenever a property of that class gets called that a method will be called?
Basically i have classes that contains a datarow and instead of accessing the individual column like:(DataRow["some_column_name"]) I want to access them using properties instead like: (MyClass.some_column_name).
My current work around is using reflection to dynamically pass the columns name as parameters like so:
public string some_column_name
    {
        get
        {

            return (string)GetValue(MethodBase.GetCurrentMethod().Name);
        }
        set
        {
            SetValue(MethodBase.GetCurrentMethod().Name, value);
        }
    }

The problem with the above mentioned way is if i have a class with 10 properties inside of it all these properties will have the above code snippet in them bloating the class.
Below code sample contains the get and set value method of the above code snippet these methods would be in the base class:
private DataRow some_table;

protected object GetValue(string columnName)
{
    return some_table[columnName.Substring(columnName.IndexOf('_') + 1)];
}

protected object SetValue(string columnName, object value)
{
    return  some_table[columnName.Substring(columnName.IndexOf('_') + 1)] = value;
}

A: You can use [CallerMemberName] attribute. If you decorate method parameter with this attribute like this:
protected object GetValue([CallerMemberName] string columnName = null)
{
    return some_table[columnName.Substring(columnName.IndexOf('_') + 1)];
}

protected object SetValue(object value, [CallerMemberName] string columnName = null)
{
    return  some_table[columnName.Substring(columnName.IndexOf('_') + 1)] = value;
}

Compiler will use, well, caller member (method) name instead of default null value. So your property becomes just:
public string some_column_name
{
    get
    {
        // current method name ("some_column_name") will be passed
        // as "column" parameter
        return (string)GetValue();
    }
    set
    {
        // same here
        SetValue(value);
    }
}

Another alternative might be to inherit from DynamicObject:
public class DynamicRow : DynamicObject {
    public override bool TryGetMember(GetMemberBinder binder, out object result) {
        // this will be called when you access dynamic property
        // like x.some_column_name
        result = GetValue(binder.Name);
        return true;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value) {
        // this will be called when you assign dynamic property
        // like x.some_column_name = "some value"
        SetValue(binder.Name, value);
        return true;
    }

    private DataRow some_table;

    protected object GetValue(string columnName) {
        return some_table[columnName.Substring(columnName.IndexOf('_') + 1)];
    }

    protected object SetValue(string columnName, object value) {
        return some_table[columnName.Substring(columnName.IndexOf('_') + 1)] = value;
    }
}

Then you can use it like this:
dynamic x = new DynamicRow();
object val = x.some_column_name;
x.some_column_name = "some value";

But I personally don't quite like it, because you are losing all type safety (any typo will only be caught at runtime), compared to using static list of properties like in the first approach.

A: Following is a simple working version of your code using PostSharp AOP. Result here would be TestProperty, as we trim get_ and set_. There's much more processing possible in the OnInvoke, the MethodInterceptionArgs can be used to make lot of modifications to the caller, then we can choose to return from PostSharp call itself or further execute the method. You can also plan to use AOP functions like OnMethodBoundaryAspect, which can execute on success or failure of a method
namespace TestAOP
{
    class Program
    {
        static void Main(string[] args)
        {
           var t = new Test();

           var x = t.TestProperty;

           Console.WriteLine(x);

           Console.Read();
        }
    }

    public class Test
    {
        private string _test = "InitialValue";

        [CustomProperty]
        public string TestProperty
        {
            get => _test;
            set => _test = value;
        }
    }

    [Serializable]
    public sealed class CustomPropertyAttribute : MethodInterceptionAspect
    {
        public override void OnInvoke(MethodInterceptionArgs args)
        {
           args.ReturnValue = args.Method.Name.Substring(args.Method.Name.IndexOf("_", StringComparison.Ordinal) + 1);

        }
    }
}


text:
Q: How to update database with Entity Framework and SQL Server on remote host I have a SQL Server database on a remote web host provider. I want to update the database (with add-migration and update-database commands for package manager) on the remote host.
But the host does not provide remote access.
How can I update the database?

A: You can use the MigrateDatabaseToLatestVersion database initializer to have the application update on startup.

Automatically Upgrading on Application Startup
If you are deploying your application you may want it to automatically
upgrade the database (by applying any pending migrations) when the
application launches. You can do this by registering the
MigrateDatabaseToLatestVersion database initializer

Entity Framework Code First Migrations
Or you can use update-database to generate a SQL script that will perform the upgrade. See Entity Framework Code First .  Then have your application somehow run that script.


text:
Q: How did he went from $b_{12}$ to $\tan 2\varphi=\cfrac{2a_{12}}{a_{11}-a_{22}}$? I'm reading Aarts': Plane and Solid Geometry. Here:

How did he go from $b_{12}$ to $\tan 2\varphi=\cfrac{2a_{12}}{a_{11}-a_{22}}$? I have tried a few things on paper but I throw it all away because there was no progress, but I basically used the formulas for double angles and $\sin^2(x)+\cos^2(x)=1$. I've even speculated that one must be high to understand it. The tag of the formula is $(4.20)$, perhaps this is no coincidence but I smoked some joints and nothing happened.

A: You have: $$b_{12} = -\frac{1}{2}a_{11}\sin 2\varphi + a_{12}\cos 2\varphi + \frac{1}{2}a_{22}\sin 2\varphi.$$
Division by $\cos 2\varphi$ gives: $$b_{12}\frac{1}{\cos 2\varphi} = -\frac{1}{2}a_{11}\tan 2\varphi + a_{12} + \frac{1}{2}a_{22}\tan 2\varphi.$$ From here: $$\tan 2\varphi =  \frac{2\left(a_{12} - \frac{b_{12}}{\cos 2\varphi}  \right)}{a_{11} - a_{22}}.$$ Surely you're not too high to conclude now?


text:
Q: Weak convergence of symmetries measures Consider a sequence of probability measure $\mu_1, \cdots, \mu_N$ with support on non-negative real numbers, $\mathbb{R}_{\geq 0}$. Now, let for each $1 \leq i \leq N$, $\hat{\mu}_i$ be the symmetrized measure of $\mu_i$, which is defined as:
$$
\hat{\mu} = \mu \, * \, \mu^\#
$$
with $\mu^\#(B) = \mu(-B)$ for each $B \in \mathfrak{B}(\mathbb{R})$.
Are the following two arguments equivalent?
$$
 \mu_i \to \mu \hspace{10 pt} \text{weakly}  \Longleftrightarrow \hat{\mu}_i \to \hat{\mu} \hspace{10 pt} \text{weakly}
$$

A: The notation $\hat{\mu}$ is typically reserved for the Fourier transform of $\mu$ (a.k.a. characteristic function of $\mu$) and thus, I would change the notation of the OP just a little.
Presumably, the symmetrization referred by the OP is the usual symmetrization $\tilde{\nu}$  of a measure $\nu$:
$$\tilde{\nu}:=\nu*\nu^\#$$
where $\nu^\#(B)=\nu(-B)$ for all $B\in\mathscr{B}(\mathbb{R})$.
Equivalently, in terms of random variables, if $X\sim \nu$ then the symmetrization $\tilde{\nu}$ of $\nu$ is the distribution of $Z=X-Y$ where $(X,Y)$ is an i.i.d. pair.
Notice that the characteristic function of the symmetrization $\tilde{\nu}$ of $\nu$ is
$$\widehat{\tilde{\nu}}(t)=|\hat{\nu}(t)|^2$$
Now, if $\mu_n\stackrel{n\rightarrow\infty}{\Longrightarrow}\mu$, then
$\hat{\mu}_n(t)\xrightarrow{n\rightarrow\infty}\hat{\mu}(t)$ for all $t$ and so, $|\hat{\mu}_n(t)|^2\xrightarrow{n\rightarrow\infty}|\hat{\mu}(t)|^2$ which means (Lévy-Bochner) that the symmetrization of $\mu_n$ also converges weakly; furthermore,  $\tilde{\mu}_n\stackrel{n\rightarrow\infty}{\Longrightarrow}\tilde{\mu}$.
The converse does not hold in general. Consider any real random variable $X$ (with values on $[0,\infty)$ to satisfy the conditions of the OP)) an define $X_n=X+n$. Let $\mu_n$ denote the law of $X_n$ and $\mu$ the law of $X$. Then
\begin{align}
\hat{\mu_n}(t)&=e^{int}\mu(t)\\
\hat{\tilde{\mu}}_n(t)&= |\mu(t)|^2
\end{align}
It follows that $\tilde{\mu_n}=\tilde{\mu}$ and so the sequence of symmetrizations $\tilde{\mu_n}$ converge weakly (in fact it is a constant sequence) to $\tilde{\mu}$; however, $\mu_n$ (or $X_n$) does not converge weakly.


text:
Q: "#include" a text file in a C program as a char[] Is there a way to include an entire text file as a string in a C program at compile-time?
something like:

*

*file.txt:
This is
a little
text file

*main.c:
#include <stdio.h>
int main(void) {
   #blackmagicinclude("file.txt", content)
   /*
   equiv: char[] content = "This is\na little\ntext file";
   */
   printf("%s", content);
}

obtaining a little program that prints on stdout "This is
a little
text file"
At the moment I used an hackish python script, but it's butt-ugly and limited to only one variable name, can you tell me another way to do it?

A: ok, inspired by Daemin's post i tested the following simple example :
a.data:
"this is test\n file\n"

test.c:
int main(void)
{
    char *test =
#include "a.data"
    ;
    return 0;
}

gcc -E test.c output:
# 1 "test.c"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "test.c"

int main(void)
{
    char *test =
# 1 "a.data" 1
"this is test\n file\n"
# 6 "test.c" 2
    ;
    return 0;
}

So it's working but require data surrounded with quotation marks.

A: If you're willing to resort to some dirty tricks you can get creative with raw string literals and #include for certain types of files.
For example, say I want to include some SQL scripts for SQLite in my project and I want to get syntax highlighting but don't want any special build infrastructure. I can have this file test.sql which is valid SQL for SQLite where -- starts a comment:
--x, R"(--
SELECT * from TestTable
WHERE field = 5
--)"

And then in my C++ code I can have:
int main()
{
    auto x = 0;
    const char* mysql = (
#include "test.sql"
    );

    cout << mysql << endl;
}

The output is:
--
SELECT * from TestTable
WHERE field = 5
--

Or to include some Python code from a file test.py which is a valid Python script (because # starts a comment in Python and pass is a no-op):
#define pass R"(
pass
def myfunc():
    print("Some Python code")

myfunc()
#undef pass
#define pass )"
pass

And then in the C++ code:
int main()
{
    const char* mypython = (
#include "test.py"
    );

    cout << mypython << endl;
}

Which will output:
pass
def myfunc():
    print("Some Python code")

myfunc()
#undef pass
#define pass

It should be possible to play similar tricks for various other types of code you might want to include as a string. Whether or not it is a good idea I'm not sure. It's kind of a neat hack but probably not something you'd want in real production code. Might be ok for a weekend hack project though.

A: I like kayahr's answer. If you don't want to touch the input files however, and if you are using CMake, you can add the delimeter character sequences on the file. The following CMake code, for instance, copies the input files and wraps their content accordingly:
function(make_includable input_file output_file)
    file(READ ${input_file} content)
    set(delim "for_c++_include")
    set(content "R\"${delim}(\n${content})${delim}\"")
    file(WRITE ${output_file} "${content}")
endfunction(make_includable)

# Use like
make_includable(external/shaders/cool.frag generated/cool.frag)

Then include in c++ like this:
constexpr char *test =
#include "generated/cool.frag"
;

A: You need my xtr utility but you can do it with a bash script. This is a script I call bin2inc. The first parameter is the name of the resulting char[] variable. The second parameter is the name of the file. The output is C include file with the file content encoded (in lowercase hex) as the variable name given. The char array is zero terminated, and the length of the data is stored in $variableName_length
#!/bin/bash

fileSize ()

{

    [ -e "$1" ]  && {

        set -- `ls -l "$1"`;

        echo $5;

    }

}

echo unsigned char $1'[] = {'
./xtr -fhex -p 0x -s ', ' < "$2";
echo '0x00'
echo '};';
echo '';
echo unsigned long int ${1}_length = $(fileSize "$2")';'

YOU CAN GET XTR HERE xtr (character eXTRapolator) is GPLV3

A: Why not link the text into the program and use it as a global variable! Here is an example. I'm considering using this to include Open GL shader files within an executable since GL shaders need to be compiled for the GPU at runtime.

A: I reimplemented xxd in python3, fixing all of xxd's annoyances:

*

*Const correctness

*string length datatype: int → size_t

*Null termination (in case you might want that)

*C string compatible: Drop unsigned on the array.

*Smaller, readable output, as you would have written it: Printable ascii is output as-is; other bytes are hex-encoded.

Here is the script, filtered by itself, so you can see what it does:
pyxxd.c
#include <stddef.h>

extern const char pyxxd[];
extern const size_t pyxxd_len;

const char pyxxd[] =
"#!/usr/bin/env python3\n"
"\n"
"import sys\n"
"import re\n"
"\n"
"def is_printable_ascii(byte):\n"
"    return byte >= ord(' ') and byte <= ord('~')\n"
"\n"
"def needs_escaping(byte):\n"
"    return byte == ord('\\\"') or byte == ord('\\\\')\n"
"\n"
"def stringify_nibble(nibble):\n"
"    if nibble < 10:\n"
"        return chr(nibble + ord('0'))\n"
"    return chr(nibble - 10 + ord('a'))\n"
"\n"
"def write_byte(of, byte):\n"
"    if is_printable_ascii(byte):\n"
"        if needs_escaping(byte):\n"
"            of.write('\\\\')\n"
"        of.write(chr(byte))\n"
"    elif byte == ord('\\n'):\n"
"        of.write('\\\\n\"\\n\"')\n"
"    else:\n"
"        of.write('\\\\x')\n"
"        of.write(stringify_nibble(byte >> 4))\n"
"        of.write(stringify_nibble(byte & 0xf))\n"
"\n"
"def mk_valid_identifier(s):\n"
"    s = re.sub('^[^_a-z]', '_', s)\n"
"    s = re.sub('[^_a-z0-9]', '_', s)\n"
"    return s\n"
"\n"
"def main():\n"
"    # `xxd -i` compatibility\n"
"    if len(sys.argv) != 4 or sys.argv[1] != \"-i\":\n"
"        print(\"Usage: xxd -i infile outfile\")\n"
"        exit(2)\n"
"\n"
"    with open(sys.argv[2], \"rb\") as infile:\n"
"        with open(sys.argv[3], \"w\") as outfile:\n"
"\n"
"            identifier = mk_valid_identifier(sys.argv[2]);\n"
"            outfile.write('#include <stddef.h>\\n\\n');\n"
"            outfile.write('extern const char {}[];\\n'.format(identifier));\n"
"            outfile.write('extern const size_t {}_len;\\n\\n'.format(identifier));\n"
"            outfile.write('const char {}[] =\\n\"'.format(identifier));\n"
"\n"
"            while True:\n"
"                byte = infile.read(1)\n"
"                if byte == b\"\":\n"
"                    break\n"
"                write_byte(outfile, ord(byte))\n"
"\n"
"            outfile.write('\";\\n\\n');\n"
"            outfile.write('const size_t {}_len = sizeof({}) - 1;\\n'.format(identifier, identifier));\n"
"\n"
"if __name__ == '__main__':\n"
"    main()\n"
"";

const size_t pyxxd_len = sizeof(pyxxd) - 1;

Usage (this extracts the script):
#include <stdio.h>

extern const char pyxxd[];
extern const size_t pyxxd_len;

int main()
{
    fwrite(pyxxd, 1, pyxxd_len, stdout);
}

A: I'd suggest using (unix util)xxd for this.
you can use it like so
$ echo hello world > a
$ xxd -i a

outputs:
unsigned char a[] = {
  0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0a
};
unsigned int a_len = 12;

A: You have two possibilities:

*

*Make use of compiler/linker extensions to convert a file into a binary file, with proper symbols pointing to the begin and end of the binary data. See this answer: Include binary file with GNU ld linker script.

*Convert your file into a sequence of character constants that can initialize an array. Note you can't just do "" and span multiple lines. You would need a line continuation character (\), escape " characters and others to make that work. Easier to just write a little program to convert the bytes into a sequence like '\xFF', '\xAB', ...., '\0' (or use the unix tool xxd described by another answer, if you have it available!):

Code:
#include <stdio.h>

int main() {
    int c;
    while((c = fgetc(stdin)) != EOF) {
        printf("'\\x%X',", (unsigned)c);
    }
    printf("'\\0'"); // put terminating zero
}

(not tested). Then do:
char my_file[] = {
#include "data.h"
};

Where data.h is generated by
cat file.bin | ./bin2c > data.h

A: The question was about C but in case someone tries to do it with C++11 then it can be done with only little changes to the included text file thanks to the new raw string literals:
In C++ do this:
const char *s =
#include "test.txt"
;

In the text file do this:
R"(Line 1
Line 2
Line 3
Line 4
Line 5
Line 6)"

So there must only be a prefix at the top of the file and a suffix at the end of it. Between it you can do what you want, no special escaping is necessary as long as you don't need the character sequence )". But even this can work if you specify your own custom delimiter:
R"=====(Line 1
Line 2
Line 3
Now you can use "( and )" in the text file, too.
Line 5
Line 6)====="

A: You can do this using objcopy:
objcopy --input binary --output elf64-x86-64 myfile.txt myfile.o

Now you have an object file you can link into your executable which contains symbols for the beginning, end, and size of the content from myfile.txt.

A: Here's a hack I use for Visual C++. I add the following Pre-Build Event (where file.txt is the input and file_txt.h is the output):
@(
  echo const char text[] = R"***(
  type file.txt
  echo ^^^)***";
) > file_txt.h

I then include file_txt.h where I need it.
This isn't perfect, as it adds \n at the start and \n^ at the end, but that's not a problem to handle and I like the simplicity of this solution. If anyone can refine is to get rid of the extra chars, that would be nice.

A: You can use assembly for this:
asm("fileData:    .incbin \"filename.ext\"");
asm("fileDataEnd: db 0x00");

extern char fileData[];
extern char fileDataEnd[];
const int fileDataSize = fileDataEnd - fileData + 1;

A: Even if it can be done at compile time (I don't think it can in general), the text would likely be the preprocessed header rather than the files contents verbatim.  I expect you'll have to load the text from the file at runtime or do a nasty cut-n-paste job.

A: Hasturkun's answer using the xxd -i option is excellent.  If you want to incorporate the conversion process (text -> hex include file) directly into your build the hexdump.c tool/library recently added a capability similar to xxd's -i option (it doesn't give you the full header - you need to provide the char array definition - but that has the advantage of letting you pick the name of the char array):
http://25thandclement.com/~william/projects/hexdump.c.html
It's license is a lot more "standard" than xxd and is very liberal - an example of using it to embed an init file in a program can be seen in the CMakeLists.txt and scheme.c files here:
https://github.com/starseeker/tinyscheme-cmake
There are pros and cons both to including generated files in source trees and bundling utilities - how to handle it will depend on the specific goals and needs of your project.  hexdump.c opens up the bundling option for this application.

A: I think it is not possible with the compiler and preprocessor alone. gcc allows this:
#define _STRGF(x) # x
#define STRGF(x) _STRGF(x)

    printk ( MODULE_NAME " built " __DATE__ " at " __TIME__ " on host "
            STRGF(
#               define hostname my_dear_hostname
                hostname
            )
            "\n" );

But unfortunately not this:
#define _STRGF(x) # x
#define STRGF(x) _STRGF(x)

    printk ( MODULE_NAME " built " __DATE__ " at " __TIME__ " on host "
            STRGF(
#               include "/etc/hostname"
            )
            "\n" );

The error is:
/etc/hostname: In function 'init_module':
/etc/hostname:1:0: error: unterminated argument list invoking macro "STRGF"

A: I had similar issues, and for small files the aforementioned solution of Johannes Schaub worked like a charm for me.
However, for files that are a bit larger, it ran into issues with the character array limit of the compiler. Therefore, I wrote a small encoder application that converts file content into a 2D character array of equally sized chunks (and possibly padding zeros). It produces output textfiles with 2D array data like this:
const char main_js_file_data[8][4]= {
    {'\x69','\x73','\x20','\0'},
    {'\x69','\x73','\x20','\0'},
    {'\x61','\x20','\x74','\0'},
    {'\x65','\x73','\x74','\0'},
    {'\x20','\x66','\x6f','\0'},
    {'\x72','\x20','\x79','\0'},
    {'\x6f','\x75','\xd','\0'},
    {'\xa','\0','\0','\0'}};

where 4 is actually a variable MAX_CHARS_PER_ARRAY in the encoder. The file with the resulting C code, called, for example "main_js_file_data.h" can then easily be inlined into the C++ application, for example like this:
#include "main_js_file_data.h"

Here is the source code of the encoder:
#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>

#define MAX_CHARS_PER_ARRAY 2048

int main(int argc, char * argv[])
{
    // three parameters: input filename, output filename, variable name
    if (argc < 4)
    {
        return 1;
    }

    // buffer data, packaged into chunks
    std::vector<char> bufferedData;

    // open input file, in binary mode
    {
        std::ifstream fStr(argv[1], std::ios::binary);
        if (!fStr.is_open())
        {
            return 1;
        }

        bufferedData.assign(std::istreambuf_iterator<char>(fStr),
                            std::istreambuf_iterator<char>()     );
    }

    // write output text file, containing a variable declaration,
    // which will be a fixed-size two-dimensional plain array
    {
        std::ofstream fStr(argv[2]);
        if (!fStr.is_open())
        {
            return 1;
        }
        const std::size_t numChunks = std::size_t(std::ceil(double(bufferedData.size()) / (MAX_CHARS_PER_ARRAY - 1)));
        fStr << "const char " << argv[3] << "[" << numChunks           << "]"    <<
                                            "[" << MAX_CHARS_PER_ARRAY << "]= {" << std::endl;
        std::size_t count = 0;
        fStr << std::hex;
        while (count < bufferedData.size())
        {
            std::size_t n = 0;
            fStr << "{";
            for (; n < MAX_CHARS_PER_ARRAY - 1 && count < bufferedData.size(); ++n)
            {
                fStr << "'\\x" << int(unsigned char(bufferedData[count++])) << "',";
            }
            // fill missing part to reach fixed chunk size with zero entries
            for (std::size_t j = 0; j < (MAX_CHARS_PER_ARRAY - 1) - n; ++j)
            {
                fStr << "'\\0',";
            }
            fStr << "'\\0'}";
            if (count < bufferedData.size())
            {
                fStr << ",\n";
            }
        }
        fStr << "};\n";
    }

    return 0;
}

A: This problem was irritating me and xxd doesn't work for my use case because it made the variable called something like __home_myname_build_prog_cmakelists_src_autogen when I tried to script it in, so I made a utility to solve this exact problem:
https://github.com/Exaeta/brcc
It generates a source and header file and allows you to explicitly set the name of each variable so then you can use them via std::begin(arrayname) and std::end(arrayname).
I incorporated it into my cmake project like so:
add_custom_command(
  OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/binary_resources.hpp ${CMAKE_CURRENT_BINARY_DIR}/binary_resources.cpp
  COMMAND brcc ${CMAKE_CURRENT_BINARY_DIR}/binary_resources RGAME_BINARY_RESOURCES_HH txt_vertex_shader ${CMAKE_CURRENT_BINARY_DIR}/src/vertex_shader1.glsl
  DEPENDS src/vertex_shader1.glsl)

With small tweaks I suppose it could be made to work for C as well.

A: If you are using CMake, you probably may be interested in writing CMake preprocessing script like the following:
cmake/ConvertLayout.cmake
function(convert_layout file include_dir)
    get_filename_component(name ${file} NAME_WE)
    get_filename_component(directory ${file} DIRECTORY)
    get_filename_component(directory ${directory} NAME)
    string(TOUPPER ${name} NAME)
    string(TOUPPER ${directory} DIRECTORY)

    set(new_file ${include_dir}/${directory}/${name}.h)

    if (${file} IS_NEWER_THAN  ${new_file})
        file(READ ${file} content)

        string(REGEX REPLACE "\"" "\\\\\"" content "${content}")
        string(REGEX REPLACE "[\r\n]" "\\\\n\"\\\\\n\"" content "${content}")
        set(content "\"${content}\"")
        set(content "#ifndef ${DIRECTORY}_${NAME}\n#define ${DIRECTORY}_${NAME} ${content} \n#endif")
        message(STATUS "${content}")

        file(WRITE ${new_file} "${content}")

        message(STATUS "Generated layout include file ${new_file} from ${file}")
    endif()
endfunction()

function(convert_layout_directory layout_dir include_dir)
    file(GLOB layouts ${layout_dir}/*)
    foreach(layout ${layouts})
        convert_layout(${layout} ${include_dir})
    endforeach()
endfunction()

your CMakeLists.txt
include(cmake/ConvertLayout.cmake)
convert_layout_directory(layout ${CMAKE_BINARY_DIR}/include)
include_directories(${CMAKE_BINARY_DIR}/include)

somewhere in c++
#include "layout/menu.h"
Glib::ustring ui_info = LAYOUT_MENU;

A: I like @Martin R.'s answer because, as it says, it doesn't touch the input file and automates the process. To improve on this, I added the capability to automatically split up large files that exceed compiler limits. The output file is written as an array of smaller strings which can then be reassembled in code. The resulting script, based on @Martin R.'s version, and an example is included here:
https://github.com/skillcheck/cmaketools.git
The relevant CMake setup is:
make_includable( LargeFile.h
    ${CMAKE_CURRENT_BINARY_DIR}/generated/LargeFile.h
    "c++-include" "L" LINE_COUNT FILE_SIZE
)

The source code is then:
static std::vector<std::wstring> const chunks = {
#include "generated/LargeFile.h"
};

std::string contents =
    std::accumulate( chunks.begin(), chunks.end(), std::wstring() );

A: What might work is if you do something like:
int main()
{
    const char* text = "
#include "file.txt"
";
    printf("%s", text);
    return 0;
}

Of course you'll have to be careful with what is actually in the file, making sure there are no double quotes, that all appropriate characters are escaped, etc.
Therefore it might be easier if you just load the text from a file at runtime, or embed the text directly into the code.
If you still wanted the text in another file you could have it in there, but it would have to be represented there as a string. You would use the code as above but without the double quotes in it. For example:
file.txt
"Something evil\n"\
"this way comes!"

main.cpp
int main()
{
    const char* text =
#include "file.txt"
;
    printf("%s", text);
    return 0;
}

So basically having a C or C++ style string in a text file that you include. It would make the code neater because there isn't this huge lot of text at the start of the file.

A: in x.h
"this is a "
"buncha text"

in main.c
#include <stdio.h>
int main(void)
{
    char *textFileContents =
#include "x.h"
    ;

    printf("%s\n", textFileContents);

    return 0
}

ought to do the job.


text:
Q: "On" or "upon" execution of the script? To be specific, I want to write something like:

*

*Afterwards, on execution of the script, the solver is compiled and new dependency list files are generated.

*Afterwards, upon execution of the script, the solver is compiled and new dependency list files are generated.

Which is correct? Are both correct?
Is one more formal than the other? Or is there no difference at all?

A: It is true that the word "Afterwards" may be omitted from your sentence without it losing the intended meaning. If you prefer to use the word "Afterwards", you may still use the word "upon" while keeping the sentence grammatically correct. The word "on", however, is grammatically incorrect.
The word "on" is sometimes confused for a synonym of "upon" because in some cases, "upon" may be used in its stead to formalize a sentence. An example of such cases would be the sentence "I insist on paying for your dinner". A more formal version of this sentence would be "I insist upon paying for your dinner".
Alas, in your case, the word "upon" means "immediately after". The word "on" cannot take this meaning, and can therefore not be used in your sentence.
If the usage of the word "upon" still troubles you, you could omit it by using a sentence like:

Afterwards, the script is executed, the solver is compiled, and new dependency list files are generated.

This sentence can be a little bit clunky as well due to the excess of commas, so I would like to suggest the usage of the word "upon", but this sentence is perfectly correct as well.
I hope this helps you in wording your sentence!

A: on and upon are synonymous in the sense of after, and in your example redundant, for you already have afterwards. For better precision, however, I suggest that you remove the latter:

Upon completion of the script, the solver is compiled and new dependency lists are generated.

If you must keep the sequence of adjectives, then at least be so kind as to write the compound adjective with a hyphen: new dependecy-list files.
I would also advise you against using the passive voice here—surely it is not dwarfs that compile the solver and not elves that generate dependency lists. The readers of your manual will be grateful if you write clearly which component does what.


text:
Q: What is platform string for iPhone 5S & 5C? I know that someone was able to dig out iphone6,1 platform string from IOS 7 code. However, I don't know what it maps to iPhone 5S or 5C.
If anyone has early access to iPhone 5S/5C, please post platform string for everyone.
For more info on platform string, see these links theiphonewiki, stackoverflow and stackoverflow

A: *

*iPhone6,1 = iPhone 5S GSM

*iPhone6,2 = iPhone 5S Global

*iPhone5,3 = iPhone 5C GSM

*iPhone5,4 = iPhone 5C Global

Code:
if ([platform hasPrefix:@"iPhone5,3"])            return @"iPhone 5C (GSM)";
if ([platform hasPrefix:@"iPhone5,4"])            return @"iPhone 5C (Global)";
if ([platform hasPrefix:@"iPhone6,1"])            return @"iPhone 5S (GSM)";
if ([platform hasPrefix:@"iPhone6,2"])            return @"iPhone 5S (Global)";


text:
Q: Difference between iTextSharp 4.1.6 and 5.x versions We are developing a Pdf parser to be used along with our system.
The requirement is such that, we store all the information on any pdf documents and should be able to reproduce the document as such (with minimal changes from original document).
We did some googling and found iTextSharp be the best mate for our purpose.
We are developing our project using .net.
You might have guessed as i mentioned in my title requiring comparisons for specific versions of iTextSharp (4.1.6 vs 5.x). We know that 4.1.6 is the last version of iTextSharp with the LGPL/MPL license . The 5.x versions are AGPL.
We would like to have a good comparison between the versions before choosing the LGPL version or we buy the license for AGPL (we dont like to publish our code).
I did some browsing through the revision changes in the iTextSharp but i would like to know if any content exist, making a good comparison between the versions.
Thanks in advance!

A: I'm the CTO of iText Software, so just like Michaël who already answered in the comment section, I'm at the same time the most authoritative source as well as a biased source.
There's a very simple comparison chart on the iText web site.
This chart doesn't cover text extraction, so allow me to list the relevant improvements since iText 5.
You've probably also found this page.
In case you wonder about the bug fixes and the performance improvements regarding text parsing, this is a more exhaustive list:

*

*5.0.0: Text extraction: major overhaul to perform calculations in user space. This allows the parser to correctly determine line breaks, even if the text or page is rotated.

*5.0.1: Refactored callback so method signature won't need to change as render callback API evolves.

*5.0.1: Refactoring to make it easier for outside users to interact with the content stream processor. Also refactored render listener so text and image event listening occurs in the same interface (reduces a lot of non-value-add complexity)

*5.0.1: New filtering functionality for text renderers.

*5.0.1: Additional utility method for previewing PDF content.

*5.0.1: Added a much more advanced text renderer listener that can reconstruct page content based on physical location of text on the page

*5.0.1: Added support for XObject Form processing (text added via PdfTemplate can now be parsed)

*5.0.1: Added rudimentary support for XObject Image callbacks

*5.0.1: Bug fix - text extraction wasn't correct for certain page orientations

*5.0.1: Bug fix - matrices were being concatenated in the wrong order.

*5.0.1: PdfTextExtractor: changed the default render listener (new location aware strategy)

*5.0.1: Getters for GraphicsState

*5.0.2: Major refactoring of interface to text extraction functionality: for instance introduction of class PdfReaderContentParser

*5.0.2: CMapAwareDocumentFont: Tweaks to make processing quasi-invalid PDF files more robust

*5.0.2: PdfContentReaderTool: null pointer handling, plus a few well placed flush calls

*5.0.2: PdfContentReaderTool: Show details on resource entries

*5.0.2: PdfContentStreamProcessor: Adjustment so embedded images don't cause parsing problems and improvements to EI detection

*5.0.2: LocationTextExtractionStrategy: Fixed anti-parallel algorithm, plus accounting for negative inter-character offsets. Change to text extraction strategy that builds out the text model first, then computes concatenation requirements.

*5.0.2: Adjustments to linesegment implementation; optimalization of changes made by Bruno to text extraction; for example: introduction of the class MarkedContentInfo.

*5.0.2: Major refactoring of interface to text extraction functionality: for instance introduction of class PdfReaderContentParser

*5.0.3: added method to get area of image in user units

*5.0.3: better parsing of inline images

*5.0.3: Adding an extra check for begin/end sequences when parsing a ToUnicode stream.

*5.0.4: Content streams in arrays should be parsed as if they were separated by whitespace

*5.0.4: Expose CTM

*5.0.4: Refactor to pull inline image processing into it's own class. Added parsing of image data if there is no filter applied (there are some PDFs where there is no white space between the end of the image data and the EI operator). Ultimately, it will be best to actually parse the image data, but this will require a pretty big refactoring of the iText decoders (to work from streams instead of byte[] of known lengths).

*5.0.4: Handle multi-stage filters; Correct bug that pulled whitespace as first byte of inline image stream.

*5.0.4: Applying stream filters to inline images.

*5.0.4: PdfReader: Expose filter decoder for arbitrary byte arrays (instead of only streams)

*5.0.6: CMapParser: Fix to read broken ToUnicode cmaps.

*5.0.6: handle slightly malformed embedded images

*5.0.6: CMapAwareDocumentFont: Some PDFs have a diff map bigger than 256 characters.

*5.0.6: performance: Cache the fonts used in text extraction

*5.1.2: PRTokeniser: Made the algorithm to find startxref more memory efficient.

*5.1.2: RandomAccessFileOrArray: Improved handling for huge files that can't be mapped

*5.1.2: CMapAwareDocumentFont: fix NPE if mapping doesn't get initialized (I'd rather wind up with junk characters than throw an unexpected exception down the road)

*5.1.3: refactoring of how filters are applied to streams, adjust parser so it can handle multi-stage filters

*5.1.3: images: allow correct decoding of 1bpc bitmask images

*5.1.3: images: add jbig2 streams to pass through

*5.1.3: images: handle null and indirect references in decode parameters, throw exception if unable to decode an image

*5.2.0: Better error messages and better handling zero sized files and attempts to read past the end of the file.

*5.2.0: Removed restriction that using memory mapping requires the file be smaller than ~2GB.

*5.2.0: Avoid NullPointerException in RandomAccessFileOrArray

*5.2.0: Made a utility method in pdfContentStreamProcessor private and clarified the stateful nature of the class

*5.2.0: LocationTextExtractionStrategy: bounds checking on string lengths and refactoring to make code easier to read.

*5.2.0: Better handling of color space dictionaries in images.

*5.2.0: improve handling of quasi improper inline image content.

*5.2.0: don't decode inline image streams until we absolutely need them.

*5.2.0: avoid NullPointerException of resource dictionary isn't provided.

*5.3.0: LocationTextExtractionStrategy: old comparison approach caused runtime exceptions in Java 7

*5.3.3: incorporate the text-rise parameter

*5.3.3: expose glyph-by-glyph information

*5.3.3: Bugfix: text to user space transformation was being applied multiple times for sub-textrenderinfo objects

*5.3.3: Bugfix: Correct baseline calculation so it doesn't include final character spacing

*5.3.4: Added low-level filtering hook to LocationTextExtractionStrategy.

*5.3.5: Fixed bug in PRTokeniser: handle case where number is at end of stream.

*5.3.5: Replaced StringBuffer with StringBuilder in PRTokeniser for performance reasons.

*5.4.2: Added an isChunkAtWordBoundary() method to LocationTextExtractionStrategy to check if a space character should be inserted between a previous chunk and the current one.

*5.4.2: Added a getCharSpaceWidth() method to LocationTextExtractionStrategy to get the width of a space character.

*5.4.2: Added a getText() method to LocationTextExtractionStrategy to get the text of the current Chunk.

*5.4.2: Added an appendTextChunk(() method to SimpleTextExtractionStrategy to expose the append process so that subclasses can add text from outside the text parse operation.

*5.4.5: Added MultiFilteredRenderListener class for PDF parser.

*5.4.5: Added GlyphRenderListener and GlyphTextRenderListener classes for processing each glyph rather than processing chunks of text.

*5.4.5: Added method getMcid() in TextRenderInfo.

*5.4.5: fixed resource leak when many inline images were in content stream

*5.5.0: CMapAwareDocumentFont: if font space width isn't defined, use the default width for the font.

*5.5.0: PdfContentReader: avoid exception when displaying an empty dictionary.

There are some things that you won't be able to do if you don't upgrade. For instance, you won't be able to do the things described in these slides.
If you look at the roadmap for iText, you'll see that we'll invest even more time on text extraction in the future.
In all honesty: using the 5 year old version wouldn't only be like reinventing the wheel, it would also be like falling in every pitfall we've fallen in in the last 5 years. I can assure you that buying a license will be less expensive.


text:
Q: Circuit behaves poorly in timing simulation but alright in behavioral - new to verilog I'm new to verilog development and am having trouble seeing where I'm going wrong on a relatively simple counter and trigger output type design.
Here's the verilog code
Note the code returns the same result whether or not the reg is declared on the output_signal without the internal_output_buffer
    `timescale 1ns / 1ps

module testcounter(
        input wire clk,
        input wire resetn,
        input wire [31:0] num_to_count,
        output reg [7:0] output_signal
    );

    reg [31:0] counter;

    initial begin
        output_signal = 0;
    end

    always@(negedge resetn) begin
        counter = 0;
    end

    always@(posedge clk) begin
        if (counter == num_to_count) begin
            counter = 0;
            if (output_signal == 0) begin
                output_signal = 8'hff;
            end
            else begin
                output_signal = 8'h00;
            end
        end
        else begin
            counter = counter + 1;
        end

    end
    assign output_signal = internal_output_buffer;

endmodule

And the code is tested by
 `timescale 1ns / 1ps

module testcounter_testbench(

    );
    reg clk;
    reg resetn;
    reg [31:0] num_to_count;
    wire [7:0] output_signal;

    initial begin
        clk = 0;
        forever #1 clk = ~clk;
    end

    initial begin
        num_to_count = 20;
    end

    initial begin
        #7 resetn = 1;
        #35 resetn = 0;
    end

    testcounter A1(.clk(clk),.resetn(resetn),.num_to_count(num_to_count),.output_signal(output_signal));
endmodule

Behavioral simulation looks as I expected

But the timing simulation explodes

And for good measure: the actual probed execution blows up and looks like

Any tips would be appreciated. Thanks all.

A: The difference between the timing and functional simulations is that a timing simulation models the actual delay of logic gates while the functional simulation just checks if values are correct.
For e.g. if you have a simple combinational adder with two inputs a and b, and output c. A functional simulation will tell you that c=a+b. and c will change in the exact microsecond that a or b changes.
However, a timing simulation for the same circuit will only show you the result (a+b) on c after some time t, where t is the delay of the adder.
What is your platform? If you are using an FPGA it is very difficult to hit 500 MHz. Your clock statement:
    forever #1 clk = ~clk;

shows that you toggle the clock every 1ns, meaning that your period is 2ns and your frequency is 500MHz.
The combinational delay through FPGA resources such as lookup tables, multiplexers and wire segments is probably more than 2ns. So your circuit violates timing constraints and gives wrong behaviour.
The first thing I would try is to use a much lower clock frequency, for example 100 MHz and test the circuit again. I expect it to produce the correct results.
    forever #5 clk = ~clk;

Then to know the maximum safe frequency you can run at, look at your compilation reports in your design tools by running timing analysis. It is available in any FPGA CAD tool.

A: Your code seems working fine using Xilinx Vivado 14.2 but there is only one error which is the following line
assign output_signal = internal_output_buffer;

You can't assign registers by using "assign" and also "internal_output_buffer" is not defined.
I also personally recommend to set all registers to some values at initial. Your variables "resetn" and "counter" are not assigned initially. Basicly change your code like this for example
reg [31:0] counter = 32'b0;

Here is my result with your code:

A: Your verilog code in the testcounter looks broken: (a) you're having multiple drivers, and (b) like @StrayPointer notices, you're using blocking assignments for assigning Register (Flip-Flop) values.
I'm guessing your intent was the following, which could fix a lot of simulation mismatches:
module testcounter
(
    input wire clk,
    input wire resetn,
    input wire [31:0] num_to_count,
    output reg [7:0] output_signal
);

reg [31:0] counter;

always@(posedge clk or negedge resetn) begin
    if (!resetn) begin
        counter <= 0;
    end else begin
        if (counter == num_to_count) begin
            counter <= 0;
        end else begin
            counter <= counter + 1;
        end
    end
end
assign output_signal = (counter == num_to_count) ? 8'hff : 8'h00;

endmodule


text:
Q: How to log custom messages from code using gunicorn I have a gunicorn application running locally, and it does log requests to a text file. What I don't understand is how to log messages to the gunicorn log file from my gunicorn application. To start my app, I use a command like % gunicorn --workers=2 test:app --reload --log-file log.txt --log-level 'debug'
I'd like to have code like this:
def app(environ, start_response):

    path = environ.get("PATH_INFO")

    if path == "/abc":
        logging.info(f'user requested {path}')

And have gunicorn write an info log entry if that's appropriate to the level.
I checked the documentation, and I see that gunicorn uses a class gunicorn.glogging.Logger to log, but I don't see any documentation on how to instantiate that class or use it to log my own messages.

A: To log to the gunicorn log file, you must import logging and get a logger using the string "gunicorn.error"
import logging

gunicorn_logger = logging.getLogger('gunicorn.error')

and then you can do
gunicorn_logger.warning(f'returned 404 for: {path}')

Source
How to use the logging module in Python with gunicorn


text:
Q: AvaloniaUI: Logic in xaml Can I use logic in xaml e.g.
IsVisible="{Binding OnlyTraverseSelectedSection != null ? true : false}"

in some way?

A: You can't currently use expressions in bindings - I would love for that to be the case but we're not there yet!
Having said that, there is one kind-of expression you can use in binding - the negation operator:
https://github.com/AvaloniaUI/Avalonia/blob/master/docs/spec/binding-from-xaml.md#negating-bindings
An example:
<TextBox IsEnabled="{Binding !HasErrors}"/>


text:
Q: use of goto versus runtime code evaluation Recently for a programming class, we were given the assignment to write a program in any language that, given n, will produce all the possible derangements for an array p of size n such that p[i] != i for all i:  0 <= i < n.  We had to use iterators, e.g. yield.
Example: n=3, [0, 1, 2] is not a derangement, but [2, 0, 1] is as well as [1, 2, 0].
I came up with a pseudocode solution that would work, but the problem was that it required power loops (that is, n nested loops where n is only known at runtime).  To do this, I generated n nested loops in Ruby code in a string, then eval-ed the string.  My solution worked, however my professor thought that using a few gotos would have been better solution (easier to read, at least) than dynamic code generation.
I was under the impression that goto was always a bad choice.  Why might runtime evaluation of dynamically generated code be a worse choice than goto?  The generated code is clean and simple, and seems fairly efficient for the given problem.  The only user input upon which the code generation depends is n, which is checked to ensure it's an integer value beforehand.  It yields only unique derangements, as it should.
I'm not asking for a solution to my programming assignment, I just want to know reasons behind the use of goto over dynamic code evaluation, or vice versa.
Edit:  to clarify, the assignment included writing a program using iterators and another using recursion, so the iterative version wasn't necessarily meant to be efficient.

A: Both GOTO and code generation are inelegant solutions to this problem IMO. There is a recursive algorithm that is probably the right answer here.

A: Without seeing your code, I would tend to side with the prof. If it's a choice between GoTo and dynamic code, I would lean towards the former. GoTo are not always a bad choice.

A: You can solve almost all problems without the use of GoTos. Specifically with loops you can use the break and continue statements to implitly use gotos while code standard are still maintained.
n nested loops sound like a bad plan, and I suggest that you instead look into a recursive functions. Every single time you need to do a n-loops you should always be thinking recursion.

A: Dynamic code is not compile time checkable, which means any errors will go undetected until run time.  Potentially making them harder to find.  For ruby, this would mean that syntax errors would not be found by the IDE or editor, whichever you happen to be using. That is a plus for choosing goto.
I think I would have to see both to make a decision in this case.  I haven't seen the code, but I'm willing to bet there is a good solution that doesn't use dynamic code, or goto's.  goto is not always bad, but if you are thinking of using it you probably have not made the best design decisions up to this point and probably want to revisit your solution.

A: That's a really interesting question - I'm not sure that there's a definitive answer.
The problem with goto is its use in an unstructured fashion - a goto is a "massive random leap" so in the general instance, after the jump, you don't know where you came from which causes all kinds of issues both in terms of debugging and maintainability and - in a more formal sense with proving "correctness" of the code. Of course there are languages (I've been around a while) where you don't have an option at which point you impose structure on the code. The bottom line is that its not that GOTO is bad so much as the way that goto is used (and abused) that is bad and that makes its a dangerous construct to have available.
Using code generation and then evaluating the result is clever :) However "clever" is not always a good thing and I suspect that in part the issue with using that as a solution is that its not actually addressing the problem as intended. That may be "cheating" in a sense - at least so far as your professor is concerned - doesn't invalidate your solution but may render it "inelegant". The debugging and maintainance issues also arise in respect of the code.
A recursive solution - especially as I vaguely remember being taught (some 25 years ago) that one can usually unwind recursion into loops - would probably be the most elegant.
Definitely an interesting question!

A: In one of my assignement in college, I once had to do something that was relatively similar
My solution was to use a recursive function, passing the array, the size of the array and the nesting level as argument. The function then call itself with nesting level +1, until the nesting level is equal to the size of the array. No Goto, no code evaluation, only clean code!
Example
function computeDerangement(yourArray, loopLevel, arraySize)
{
    //We check to see if the loop level is the same as the array size
    //if true, then we have executed exactly n loop
    if (loopLevel == arraySize) {
         display(yourArray); //Display being some kind of function that show the array,
                             //you get the idea
    } else {
        while(something) {
            //Here you put the logic that you execute at one level of the loop

            //Then you call yourself with one more level of nesting
            computeDerangement(yourArray, loopLevel + 1, arraySize);
        }
    }
}

Hope that help!
I have never used goto in my life, so I'm pretty sure there is always a way to avoid them

A: The main reason people avoid goto statements is that they can make your program more difficult to understand.
Without having seen your code, I'd guess it's more difficult to understand than the equivalent program using goto...

A: GOTO Solution -- a goto is convenient when simulating a function call. Here's a non-recurisve solution that simply simulates the recursive solution using a stack and a goto label to return to the point where the function call would have occurred.
See the recursive procedure (I have posted this as a separate answer) for comparison.
Option Strict On
Option Explicit On
Module Module1
    Dim x As Stack
Private Sub printGeneratedList(ByVal generatedList As List(Of Integer))
    For Each el In generatedList
        Console.Write(el & " ")
    Next
    Console.WriteLine()
End Sub
Private Sub generateAux(ByVal i As Integer, ByVal n As Integer, _
                        ByVal generatedList As List(Of Integer))
    Dim stackI As Stack(Of Integer) = New Stack(Of Integer)
    Dim stackJ As Stack(Of Integer) = New Stack(Of Integer)

    Dim j As Integer

StartLabel:
    j = 0

    If i >= n Then
        printGeneratedList(generatedList)
        If stackI.Count = 0 Then
            Return
        Else
            GoTo ReturnLabel
        End If
    End If

     While j < n
        If Not j = i Then
            If Not generatedList.Contains(j) Then
                generatedList.Add(j)
                stackI.Push(i)
                stackJ.Push(j)
                i = i + 1
                GoTo StartLabel

ReturnLabel:
                i = stackI.Pop()
                j = stackJ.Pop()
                generatedList.Remove(j)
            End If
        End If
        j = j + 1
    End While
    If stackI.Count = 0 Then
        Return
    Else
        GoTo ReturnLabel
    End If
End Sub

Private Sub generate(ByVal n As Integer)
    Console.WriteLine("Generating for n = " & n.ToString())
    Dim l As List(Of Integer) = New List(Of Integer)
    If n < 0 Then
        Throw New Exception("n must be >= 0")
    End If
    generateAux(0, n, l)
End Sub

Sub Main()
    generate(0)
    Console.ReadLine()
    generate(1)
    Console.ReadLine()
    generate(2)
    Console.ReadLine()
    generate(3)
    Console.ReadLine()
    generate(4)
    Console.ReadLine()
End Sub

End Module

A: goto's are not clean. but if high performance is required, you need to break some of those coding rules sometimes...
if speed is really an important matter, for example if you want to write a library or code you have big exigeance on, you might consider using goto. for sure you have to pay attention that everything goes well.
Comment: At the end, the executing CPU does nothing else than simple jumps. Just only that the programming language / the compiler creates them. use with caution and don't mess with it.

A: Both the goto solution and dynamic code generation ideas are bad. This is easily solved with a recursive solution as mentioned by others. You simply recursively generate all permutations (standard recursive solution) and when generation is complete (ie at the leaf of the recursion) simply skip returning permutations that are not derangements.

A: Recursive solution -- here's a solution with early pruning. My only question is regarding enumerations: did he want you to create an enumerator that on each successful call would generate the next item in the list? This would probably be easiest implemented by creating a lambda version of this program - I used to do this in lisp all the time when writing query generators that would generate the next answer to a question when doing prolog-interpreter style queries.
Option Strict On
Option Explicit On
Module Module1
Private Sub printGeneratedList(ByVal generatedList As List(Of Integer))
    For Each el In generatedList
        Console.Write(el & " ")
    Next
    Console.WriteLine()
End Sub

Private Sub generateAux(ByVal i As Integer, ByVal n As Integer, _
                    ByVal generatedList As List(Of Integer))
    If i >= n Then
        printGeneratedList(generatedList)
        Return
    End If
    For j As Integer = 0 To n - 1
        If Not j = i Then
            If Not generatedList.Contains(j) Then
                generatedList.Add(j)
                generateAux(i + 1, n, generatedList)
                generatedList.Remove(j)
            End If
        End If
    Next
End Sub

Private Sub generate(ByVal n As Integer)
    Console.WriteLine("Generating for n = " & n.ToString())
    Dim l As List(Of Integer) = New List(Of Integer)
    If n < 0 Then
        Throw New Exception("n must be >= 0")
    End If
    generateAux(0, n, l)
End Sub

Sub Main()
     generate(0)

    Console.ReadLine()
    generate(1)

    Console.ReadLine()
    generate(2)

    Console.ReadLine()
    generate(3)

    Console.ReadLine()
    generate(4)

    Console.ReadLine()

End Sub

End Module


text:
Q: POST http://localhost:3000/sort net::ERR_ABORTED 500 (Internal Server Error) I am trying to upload a file to the API, sort the numbers and then return the result in another text file that is available to download. I upload the file, and when I start the calculation I get the Internal Server Error. The API is running on port 3000 and I start the React App.js on port 3001.
Is there something I'm doing wrong?
This is the API's app.js:
const express = require('express');
const multer = require('multer');
const bodyParser = require('body-parser');
const fs = require('fs');
const app = express();

const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

app.use(bodyParser.text({ type: 'text/plain' }));

app.post('/sort', upload.single('inputFile'), (req, res) => {
    console.log(req.file)
    const input = req.file.buffer.toString().split('\n').map(Number);
    const result = input.sort((a, b) => b - a);
    const resultText = result.join('\n');
    fs.writeFile('result.txt', resultText, (err) => {
        if(err) throw err;
        res.send('File succesfully sorted!');
    });
    res.set('Content-Type', 'text/plain');
    res.send(resultText);
});

app.listen(3000, () => {
    console.log('API is listening on port 3000');
});

This is the React App.js:
 const [inputFile, setInputFile] = useState(null);
  const [result, setResult] = useState(null);
  const [processingTime, setProcessingTime] = useState(null);

  const handleFileUpload = (event) => {
    setInputFile(event.target.files[0]);
  };

  const startCalculation = async (event) => {
    event.preventDefault();
    const startTime = performance.now();
    const formData = new FormData();
    formData.append('inputFile', inputFile);
    console.log(inputFile)

    const response = await fetch("http://localhost:3000/sort", {
      method: 'POST',
      body: formData,
      mode: 'no-cors',
    });

    const data = await response.text();
    console.log(data);
    setResult(data);
    setProcessingTime(performance.now() - startTime);

  };

  const handleDownload = (event) => {
    event.preventDefault();
    const file = new Blob([result], {
      type: 'text/plain'
    });
    const fileURL = URL.createObjectURL(file);
    const link = document.createElement('a');
    link.href = fileURL;
    link.download = 'result.txt';
    link.click();
  };

A: The issue is on the client you are setting the input name to inputFile, however, on the backend you are telling Multer that the input name is myFile.
Change from this:
upload.single("myFile")
To this:
upload.single("inputFile")