tc qdisc with GRE in openwrt

Question: I'm trying to implement traffic control to GRE interface in an openwrt board.
For this i followed below steps,

Create GRE interface named gre1 in both tunnel end devices.
Tested reachability with ping, Success.
create qdisc using following command.
tc qdisc add dev gre1 root handle 1: default 2
Before creating tc classes i tired to ping the tunnel interface but this failed.
5.I tried to capture packet in gre1 but found 0 packets.
Monitored the statistics of qdisc using the command
tc -p -s -d qdisc show dev gre1
found that packet drop count is increasing.

I have tested this same in Ubuntu PC and found working. Also if i change the tunnel to VPN tunnel instead of GRE it working fine.
Is there any additional thing which I need to handle to implement tc in GRE ?
Any help will be appreciated.
Answer: Fixed !
Add class
tc class add dev eth0 parent 1:1 classid 1:2 htb rate 60kbps ceil 100kbps

then add sfq for the class
tc qdisc add dev eth0 parent 1:2 handle 20: sfq

tc qdisc with GRE in openwrt


How to fix my Rewriterule in .htaccess to transparently redirect any domain alias?

Question: I want to transparently redirect any domain alias in .htaccess of a Drupal 7 site.
However, the rewriterule I use, has no effect while it should work.
So something in the default drupal 7 .htaccess that comes out of the box, prevents this rewriterule from working:
This rewriterule should redirect the homepage for any alias domain example.com to /landingpage/example-com  except from the companysite.
  # Rewrite Request for parked domains '/' to landing page
  RewriteCond %{HTTP_HOST} !=companysite.com
  RewriteCond %{HTTP_HOST} (.+)\.(\w+)
  RewriteRule ^/?$ /landingpage/%1-%2  [L]

I am posting the whole .htaccess file including this rewriterule (between double white lines) here:
#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|install|make|module|profile|po|sh|.*sql|theme|twig|tpl(\.php)?|xtmpl|yml)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Tag|Template|composer\.(json|lock))$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig|\.save)$">
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
  <IfModule !mod_authz_core.c>
    Order allow,deny
  </IfModule>
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Add correct encoding for SVGZ.
AddType image/svg+xml svg svgz
AddEncoding gzip svgz

# Most of the following PHP settings cannot be changed at runtime. See
# sites/default/default.settings.php and
# Drupal\Core\DrupalKernel::bootEnvironment() for settings that can be
# changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_value assert.active                   0
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
  # PHP 5.6 has deprecated $HTTP_RAW_POST_DATA and produces warnings if this is
  # not set.
  php_value always_populate_raw_post_data   -1
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Set a fallback resource if mod_rewrite is not enabled. This allows Drupal to
# work without clean URLs. This requires Apache version >= 2.2.16. If Drupal is
# not accessed by the top level URL (i.e.: http://example.com/drupal/ instead of
# http://example.com/), the path to index.php will need to be adjusted.
<IfModule !mod_rewrite.c>
  FallbackResource /index.php
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\." - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/foo will be redirected to http://www.example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/foo will be redirected to http://example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  RewriteBase /

  # Redirect common PHP files to their new locations.
  RewriteCond %{REQUEST_URI} ^(.*)?/(install.php) [OR]
  RewriteCond %{REQUEST_URI} ^(.*)?/(rebuild.php)
  RewriteCond %{REQUEST_URI} !core
  RewriteRule ^ %1/core/%2 [L,QSA,R=301]

  # Rewrite install.php during installation to see if mod_rewrite is working
  RewriteRule ^core/install.php core/install.php?rewrite=ok [QSA,L]

  # Pass all requests not referring directly to files in the filesystem to
  # index.php.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # Rewrite Request for parked domains '/' to landing page
  RewriteCond %{HTTP_HOST} !=corvalan.domain.trade
  RewriteCond %{HTTP_HOST} (.+)\.(\w+)
  RewriteRule ^/?$ /landingpage/%1-%2  [L]

  # For security reasons, deny access to other PHP files on public sites.
  # Note: The following URI conditions are not anchored at the start (^),
  # because Drupal may be located in a subdirectory. To further improve
  # security, you can replace '!/' with '!^/'.
  # Allow access to PHP files in /core (like authorize.php or install.php):
  RewriteCond %{REQUEST_URI} !/core/[^/]*\.php$
  # Allow access to test-specific PHP files:
  RewriteCond %{REQUEST_URI} !/core/modules/system/tests/https?.php
  # Allow access to Statistics module's custom front controller.
  # Copy and adapt this rule to directly execute PHP files in contributed or
  # custom modules or to run another PHP application in the same directory.
  RewriteCond %{REQUEST_URI} !/core/modules/statistics/statistics.php$
  # Deny access to any other PHP files that do not match the rules above.
  # Specifically, disallow autoload.php from being served directly.
  RewriteRule "^(.+/.*|autoload)\.php($|/)" - [F]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

# Add headers to all responses.
<IfModule mod_headers.c>
  # Disable content sniffing, since it's an attack vector.
  Header always set X-Content-Type-Options nosniff
</IfModule>

Answer: This worked: I had to use the ?q= inside the last rewriterule like this:
RewriteRule ^/?$ ?q=landingpage/%1-%2 [L]


Acceptance-Rejection method to generate random numbers from Gamma

Question: How to use the Acceptance-Rejection (A-R) method to generate
random numbers from the following gamma distribution with density
$$f(x) = \frac1{4^3Γ(3)}x^2\exp^{-\frac x4}, \ x > 0,$$
where $\Gamma(·)$ is the gamma function. The proposal distribution of your choice has to be a distribution from which you can easily generate random numbers using probability integral transformation method. For the proposal distribution of your choice, find
the best possible constant C and the corresponding acceptance probability of the A-R method.
I'm not sure how to go about finding a proposal distribution or finding an C (or M depending on what text you read)
Answer: Here is a start. In order to use the A-R method to simulate a distribution
with density $f(x),$ you need a function
that is an appropriate constant multiple $C$ of the PDF $g(x)$ of an easily
simulated distribution, such that $Cg(x) \ge f(x)$ throughout the support of
$f(x).$
Here is a sketch of the density of $\mathsf{Gamma}(shape=3, rate=1/4)$
along with a sketch of double the density of $\mathsf{Exp}(rate=1/12).$

R code for the sketch:
<code>curve(dgamma(x, 3, 1/4), 0, 30, ylim=c(0,.2), lwd=2, col="blue")
curve(2*dexp(x,1/12), 0, 30, add=T, col="red", lwd=2)
abline(v=0, col="green2");  abline(h=0, col="green2")
</code>
The exponential distribution is easily simulated from the standard uniform
distribution via the quantile method. Below about $x=8,$ the red curve is
much higher than the blue one, but from there on the fit isn't bad.
Obviously, the red curve is a little higher than it needs to be, so
$C=2$ is not quite the optimal constant.
I am not saying this is the best possible choice, but it illustrates
the kind of thinking you need to do, and I hope the sketch is helpful.


Overriding template logic in TowerJS Views

Question: How do I override how templates are rendered in TowerJS? I know I can use Jade, but if I stuck with CoffeeKup, how could I, for instance have this code:
formFor @user, (form) ->
  form.fieldset "Profile", (fields) ->
    fields.field "firstName"
    fields.field "lastName"
    fields.field "email"
  form.fieldset "Address", (fields) ->
    fields.field "lat", as: hidden
    fields.field "lng", as: hidden
    fields.field "street"
    fields.field "city", as: "select", collection: ["CA"]

... generate this:
<form class='form' data-method='post' method='post' novalidate='true' role='form'>
  <fieldset class='fieldset' id='profile'>
    <legend class='legend'>
      Profile
    </legend>

          First Name

...instead of this:
<form class='form' data-method='post' method='post' novalidate='true' role='form'>
  <fieldset class='fieldset' id='profile'>
    <legend class='legend'>
      Profile
    </legend>

          First Name

I guess I'm nitpicking over the
 versus
, but I am just starting use Tower in evaluation to Railway and Derby. Is this a CoffeKup question or Mint question?
Answer: You can customize that tag by setting:
Tower.View.fieldListTag = 'ul' # or whatever

The configuration variables are here:

https://github.com/viatropos/tower/tree/master/packages/tower-view/shared/view.coffee#L16-92
Comment: Thanks! I see now that I can change that and other settings in `config/application`.


How do I apply Intermediate Value theorem correctly?

Question: Let $f\colon \mathbb R \to \mathbb R$ be a continuous $2\pi$-periodic function, i.e. for every
$t \in \mathbb R,$ we have $f(t) = f(t+ 2\pi)$. Which of the following statements are true?
a. There exists $t_0 \in \mathbb R$ such that $f(t_0) = f(−t_0).$
b. There exists $t_0 \in \mathbb R$ such that $f(t_0) = f(t_0+\pi/2).$
c. There exists $t_0 ∈ \mathbb R$ such that $f(t_0) = f(t_0 +\pi/4).$
My Try:-
(a) Let $f(-\pi+2\pi)=f(\pi)=f(-\pi)$
(b) let $g(t)=f(t+\pi/2)-f(t)$
$g(0)=f(\pi/2)-f(0)$
$g(3\pi/2)=f(2\pi)-f(3\pi/2)$
I am wishing to apply Intermediate Value Theorem, But not able to apply.
(c) $g(t)=f(t+\pi/4)-f(t)$
Please help me to apply IVT in a correct way.
Here also I wish to apply Intermediate value theorem.
Comment: In case b) we need to prove that function $g$ has a root. Suppose contrary. Note that $g$ is a continuous function, so from IVT we obtain that $g (t)>0$ or ($g (t)<0$) for all $t$. Try to conclude a contradiction now.
Answer: $$0=f(0)-f(2\pi)=(f(0)-f(\pi/2))+(f(\pi/2)-f(\pi)$$ $$+(f(\pi))-f(3\pi/2))+(f(3\pi/2)-f(2\pi)).$$ Hence at least one of the terms here has to be positive and at least one negative. It follows that the continuous function $f(x)-f(x+\pi/2)$ takes both positive and negative values. Hence it must vanish at some point. This proves  b) and c) is similar.


Not sure how to add image variance to php/sql population of HTML table

Question: Situation
I am currently populating an HTML table using PHP, which is working just fine using this code:
<?php
while ($row = mysqli_fetch_array($result)) {

    $lineID             = $row['lineID'];
    $ediShipDate        = $row['ediShipDate'];
    $resolution         = $row['resolution'];
    $resolutionComments = $row['resolutionComments'];

?>

Issue
I am trying to make it so with each individual line, if ediShipDate equals one thing, I place one image there (instead of the text inside that variable), and if it equals another thing, to place a different image.  I'm trying using this code in the middle here:

          <?= $cost?>
          <value="<?= $cost?>">

          <?php
            if ($row['ediShipDate'] = "Before Debit Exp"){
              print("");
              print("one") ;
            }
            else if  ($row['ediShipDate'] = "AFTER DEBIT EXP!"){
              print("");
              print("two") ;
            }
            else {
            print $row['ediShipDate'] ;
            print("three") ;
            }
          ?>
          <value="<?= $ediShipDate ?>">

              <?= $cost?>
              <value="<?= $cost?>">

With my test data, I have 4 rows.  The first three's value is "Before Debit Exp" while the fourth's value is "AFTER DEBIT EXP!", however, in the debug code I have here print("one") etc..., all four rows are evaluating to the first statement, regardless of their value, and printing out check-yes.png  I've tried changing all of them to have the actual value of "AFTER DEBIT EXP!" to no avail.
Why is this?  There is nothing in the logs or the console.
Answer: In your IF statement you're assigning the value not comparing.
= vs == or ===
You need to switch them to == at the very least, but it would be better to use ===.
          <?php
            if ($row['ediShipDate'] === "Before Debit Exp"){
              print("");
              print("one") ;
            }
            else if  ($row['ediShipDate'] === "AFTER DEBIT EXP!"){
              print("");
              print("two") ;
            }
            else {
            print $row['ediShipDate'] ;
            print("three") ;
            }
          ?>
          <value="<?= $ediShipDate ?>">


How to I redirect read requests to replica in Postgres Cluster?

Question: I have a Postgres Cluster of 2 servers currently.
They are managed by Patroni with ETCD as my DCS.
I want to be able to redirect Read requests to the replica and Write requests to the master. I read that PGPOOL II could do this, but this looks to do the same job as Patroni so wondering if there are any alternatives?
Answer: I've Used PGPool II to do this and it worked quite well. You have to have some kind of middleware that is able to look at the SQL and determine if it's a read request and then do the routing. That's where Patroni and PGPool are different.
The only other option I'm aware of is to make changes to your application so that you have separate DBs for writes and reads. Then you can configure your writes to go to your master and reads to go to your slave.
As a side note, it appears that Patroni really wants to have three servers because it uses RAFT and you have to have an odd number of servers to reliably avoid split-brain problems. If you've only got two servers, PGPool may be a better choice anyway.
Comment: thanks qhartman. I'm looking to add further servers down the line. ETCD solves that problem as I have more than 3 nodes in that cluster. I was looking at this as well, https://github.com/CrunchyData/crunchy-proxy which good do the same thing as pgpool ii. I'll take a look at both and see which works best for my situation.


Flipping a card over with CSS/JS Firefox issue

Question: I've got an issue in Firefox.
This works in chrome, and safari and mobile.
When you click the card, it flips over, but you can still see the "click to flip" front facing part of the card when you click on it to flip it over. It shows up as upside-down text. I've tried targeting the css to hide/show when the card css has the class of "flipped", but it still won't disappear.
Again this is a Firefox issue. Any suggestions would be great.

$('.card').click(function(){
     $(this).toggleClass('flipped');
 });
.card-height2: {
 height: 281px;
}
.flip {
 -webkit-perspective: 800;
 perspective: 800;
 position: relative;
 cursor: pointer;
}

.flip .card.flipped {
 -webkit-transform: rotatex(-180deg);
 transform: rotatex(-180deg);
 background: transparent;
}

.flip .card {
 height: 195px;
 -webkit-transform-style: preserve-3d;
 -webkit-transition: 0.5s;
 transform-style: preserve-3d;
 transition: 0.5s;
}

.flip .card .face {
 -webkit-backface-visibility: hidden ;
 backface-visibility: hidden ;
 z-index: 2;

}

.flip .card .front {
 position: absolute;
 width: 100%;
 z-index: 1;
 background: #2B5168;
}

.flip .card .back {
 -webkit-transform: rotatex(-180deg);
 transform: rotatex(-180deg);
 padding-left: 5%;
}

.flip .card .back2 {
 -webkit-transform: rotatex(-180deg);
 transform: rotatex(-180deg);
 padding-left: 5%;
 padding-bottom: 13%;
}

.inner {
 margin:0px
 !important;
}

div.card.card-1 {
 height: 195px;
 background: transparent;
 background: #2B5168;
}

.s7-small {
 font-size: 14px;
}

.s7-percents {
 color: #80c3db;
 font-size: 51px;
 font-weight: 800;
 margin: 0px;
}

.s7-heading1 {
 font-size: 27px;
 text-align: left;
 margin-top: 55px;
 margin-left: 50px;
}

.s7-heading2 {
 font-size: 27px;
 margin: 0px;
}

.s7-para {
 font-size: 27px;
 color: #85B9CE;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

Click to flip

Flipped!

http://jsbin.com/yobeweseri/edit?html,css,js,output
Comment: Have you tried adding backface-visibility: hidden; to your .card class?
Comment: @Julian Espinosa That did it! Thank you. So simple.
Answer: Add transform: rotateX(0deg); to the .face.front container.
See this answer: Backface-Visibility Not Working Properly in Firefox (Works in Safari)


Azure web role project not creating MbUnit test project?

Question: We're creating an Azure cloud service project in VS 2010 with an ASP.Net MVC 2 web role.  When we create the MVC project we're asked if we want to create a test project.  Our choices are MbUnit3 (our preference) and MS Test.
When we select MbUnit, a test folder is created in the file system, but no project is created.  Choosing MS Test on the other hand does what you would expect and the test project appears in the solution explorer.
Does anyone know why the MbUnit test project isn't being created in this case?  If it's an Azure project hiccup vis-a-vis MbUnit, how can we create the project by hand and add it to the solution?
Thanks very much for the help.
Answer: If you want to do it yourself, you can just create a new MVC project and later right-click on the roles node and add a web role using that project.  Be sure to mark the MVC assembly as "copy local" so it can run in the cloud (where MVC isn't installed in the GAC).
Comment: So create the MVC project outside of Azure (along with the MbUnit test project), then add it as a web role?  Sounds like a good idea, thanks.


DefaultPCUAllocator: not enough memory

Question: I want to do some CNN with Pytorch, but I got this error:

RuntimeError: [enforce fail at C:\cb\pytorch_1000000000000\work\c10\core\impl\alloc_cpu.cpp:81] data. DefaultCPUAllocator: not enough memory: you tried to allocate 412876800 bytes.

The dataset I am using is 3410 images consists of 0-9, A-Z, and a-z. I assume the dataset is not that large to the point that I don't have enough RAM to process them.
I read about some possible solutions to reduce batch size, but when I reduce the batch_size to 16 and run the file, nothing happens. Does anyone have any idea how to solve this?
Here is my code:
<code>class WritingDataset(Dataset):
    def __init__(self, csv_file, root_dir, transform=None):
        self.annotations = pd.read_csv(csv_file)
        self.root_dir = root_dir
        self.transform = transform

    def __len__(self):
        return len(self.annotations)

    def __getitem__(self, index):
        img_path = os.path.join(self.root_dir, self.annotations.iloc[index, 0])
        image = io.imread(img_path)
        y_label = torch.tensor(int(self.annotations.iloc[index, 1]))

        if self.transform:
            image = self.transform(image)

        return (image, y_label)

# Set device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Hyperparameters
in_channel = 3
num_classes = 2
learning_rate = 1e-3
batch_size = 32
num_epochs = 5

# Load Data
dataset = WritingDataset(
    csv_file='english.csv',
    root_dir='Img',
    transform=transforms.ToTensor()
)

train_set, test_set = torch.utils.data.random_split(dataset, [3000, 410])
train_loader = DataLoader(dataset=train_set, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(dataset=test_set, batch_size=batch_size, shuffle=True)

# Model
model = torchvision.models.googlenet(pretrained=True)
model.to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# Train Network
for epoch in range(num_epochs):
    losses = []

    for batch_idx, (data, targets) in enumerate(train_loader):
        # Get data to cuda if possible
        data = data.to(device=device)
        targets = targets.to(device=device)

        # forward
        scores = model(data)
        loss = criterion(scores, targets)

        losses.append(loss.item())

        # backward
        optimizer.zero_grad()
        loss.backward()

        # gradient descent or adam step
        optimizer.step()

    print(f"Cost at epoch {epoch} is {sum(losses)/len(losses)}")

# Check accuracy on training & test
def check_accuracy(loader, model):
    num_correct = 0
    num_samples = 0
    model.eval()

    with torch.no_grad():
        for x, y in loader:
            x = x.to(device=device)
            y = y.to(device=device)

            scores = model(x)
            _, predictions = scores.max(1)
            num_correct += (predictions == y).sum()
            num_samples += predictions.size(0)

        print(
            f"Got {num_correct} / {num_samples} with accuracy {float(num_correct)/float(num_samples)*100:.2f}"
        )

    model.train()
</code>
Answer: If you have enough VRAM memory, try to increase the pagefile (virtual memory) size. The better option is to set 'System managed', or manually increase it to higher values.

DefaultPCUAllocator: not enough memory


Use @ngx-formly with custom radio component (internal UI components)

Question: I am working with a custom radio components and I'm having a hard time connecting the component to the form using formly v5.
This is how I would use the custom radio component
<custom-radio
  name="regular"
  value="1"
  label="Regular"
>
</custom-radio>

The above code renders the following HTML, which I am oversimplifying
<custom-radio>

    <input type="radio">

      Regular

</custom-radio>

My formly configuration is the following
Formly Module
FormlyModule.forRoot({
   types: [
    {
      name: "custom-radio",
      component: FormlyCustomRadio, // This is my new formly wrapper component
    }
   ],
}),

Component
@Component({
  selector: 'formly-custom-radio',
  template: `
     <custom-radio
        *ngFor="let option of to.options"
        [formControl]="formControl"
        [formlyAttributes]="field"
        [name]="to.name"
        [value]="option.key"
        [label]="option.label"
   >
   </custom-radio>
   `
})
export class FormlyCustomRadio extends FieldType<FieldTypeConfig> {}

FormlyFieldConfig data
const fields: FormlyFieldConfig[] = [
    {
      key: "dog",
      type: "custom-radio",
      templateOptions: {
        label: "Do you have a dog?",
        name: "dog",
        options: [
          { key: "1", label: "Yes" },
          { key: "2", label: "No" },
        ],
      },
    },
]

The form renders properly but there is a error in the console and the form model does not contain the value selected in the form's radio button
Error: No value accessor for form control with unspecified name attribute

My spider sense is telling me that is has to do with formControl and the inability to find an input within custom-radio component as it hides the input from fromly
I'd like to not go the native path to solve this, since I'd have to rewrite the component's styles, inputs, and events.
Answer: I'm not sure if this is the most adequate way to solve this, but with it I was able to get and set form control

ngDefaultControl - added Angular property to custom component
formControl - use this property provided by formly to get and set value

note the use of formControl.value and formControl.setValue()

[model] - custom component binding represents the current selection of the radio component
(select) - custom component output binding emits whenever the radio button is selected

The new template will look like this.
@Component({
  selector: 'formly-custom-radio',
  template: `
     <custom-radio
        *ngFor="let option of to.options"
        ngDefaultControl
        [label]="option.label"
        [model]="formControl.value"
        [name]="to.name"
        (select)="formControl.setValue($event)"
        [value]="option.key"

   >
   </custom-radio>
   `
})
export class FormlyCustomRadio extends FieldType<FieldTypeConfig> {}


Dynamically creating unique link or button for each result of a database query result

Question: Basically, a list of results from a database query is inserted into a ul. I want the user to be able to click the result they are looking for and then have one of two things happen:

A unique link is created (such as a php GET request) using the ID of
the selected result
A JS function is called via the onClick
attribute, and the ID of the clicked result is sent as an argument.

The code below is what I have done so far - minus the functionality that I listed above.
The list as it is in the HTML:

                    Donor
                    for
                    Honoree

                    common
                    on:
                    Date

                    Dedication

The javascript that edits the list, based on the results of the query which is stored in the myTrees array. This function is called via a XMLHttpRequest object.
function showTreeContent()
{
if (requestObj.readyState == 4) //Request completed
{
    //Retrieve the JSON encoded array, which is stored at index-key: media
    var text = requestObj.responseText;
    //alert(text);
    var myTrees = jQuery.parseJSON(text).media;
    $('#treesUL').text('');

    //Alert the number of rows, for testing purposes
    alert(myTrees.length + " results.");

    //Loop through the JSON array, and add each element to a
, which is then added to the

    for(var i = 0; i < myTrees.length; i++)
    {
        var tree = myTrees[i];
        var li =$('#treesLI').clone();
        li.removeAttr('id');
        li.appendTo('#treesUL');

        //li.find('.treeLink').setAttribute("href", "somelink url");
        li.find('.donorName').text(tree['donor']);
        li.find('.honoreeName').text(tree['honoree']);
        li.find('.dedicationText').text("'" + tree['dedication'] + "'");

        if (tree['common'] != '')
            li.find('.treeName').text(tree['common']);
        else
            li.find('.treeName').text("Unknown Species");

        li.find('.donationDate').text(tree['date']);
        li.data('treeID','tree'+i);
    }
}
}

I tried surrounding the contents of the li tag with an a tag, and then editing the href of the a tag, but I was unable to get that to work. I'm using jQuery Mobile for this project also. Let me know if you need any more information - any help is greatly appreciated!
Answer: First thing that I see strange is that you are calling $('#treesUL').text(''); that deletes the contents of the ul and than in the loop you request $('#treesLI') which was deleted above.
What i would do is create the HTML as a string and append it to the ul.
Example.
var html = '';

for(var i = 0, length = myTrees.length; i < length; ++i)
{
    var tree = myTrees[i];
    html += '
';
    html += '
' + tree.donor + '';
    html += 'for '+ tree.honoree + '
';
    html +='
';
    $('#treesUL').append(html);
}

As you can see i added an onClick handler that calls a function that receives a parameter.
You can use that onClick function to make a GET request with $.axaj()
If you don't want to use onClick you can do:
$('#treesUL li').click(function(event){

});

Some other observations:

You can access the properties of an object using the . like this tree.dedication.
You should do your for like this for(var i = 0, length = myTrees.length; i < length; ++i)
it is 2 times faster in IE8
Comment: I implemented it this way, and it works but it lost the styling that I have implemented. Any idea why?
Comment: Probably because in the example I set the `class` of the `li`, not the `id`. It is bad-practice to have multiple `id`'s. Change your style to use `class` instead of `id`


What is the Correct Time to Name a Variable after a Builtin?

Question: So I see this a lot.  People call their dictionaries dict, their lists list, and so on.  I know this is frowned upon because it overwrites the built-in value in Python.
The question is, why doesn't this raise an exception?  I see a lot of people say to never do this, but why isn't it an error?  The only conclusion I can come to is that there is a time when this sort of thing needs to happen.
So, in what situation could someone gain a programming advantage by overwriting a builtin?  Or, if my conclusion is wrong, why aren't there protections against such overwriting?
Answer: Let's say we do that. You'll then need to consider what happens when I redefine my own functions:
from mymodule import func

def func(): # is this allowed?
    pass

func() # should this now fail?

So then there would be a difference in how Python treats overwriting built-ins from your own functions. I think it's fair to redefine your own functions so why would it be different for built-ins?
It's probably better to allow people to redefine built-ins and your own functions alike. This keep Python simple and it gives the developer flexibility in writing code.
Answer: Builtins are just names in the global namespace, so the same rule applies to any other non-builtin imported into the namespace. Now consider what happens if a new name is added to the imported module, or a new builtin is added, that has a name that is already in use in your code.
With the current rule, your code still works, but if you want to modify it to use the new names, you are forced to explicitly write module.name or __builtin__.name.
If the rule was that it raised an exception, your code would immediately stop working until you changed all references to the name.
I think the first scenario is preferable.
And of course, it's not always a mistake. Being able to inject your own functions or objects into other parts of code is part of the design of dynamic languages like python.


Comparar string PANDAS Data Science

Question: Estou começando nesse mundo de data Science e minha duvida como posso compara duas string na mesma coluna.

Tenho uma coluna [Investigation Type] que tem 'Acidente' e 'Incidente' eu queria fazer comparação entre as duas com grafico e não estou conseguindo.
como eu poderia fazer essa comparação com pandas?
Comment: Não entendi bem a pergunta. Que comparação gostaria de fazer? Contar as ocorrências de `Acidente` e `Incidente`?
Answer: Se a comparação é ver o número de ocorrências de cada tipo, Acidente e Incidente, e plotar um gráfico de barras, é possível usar a função hist do próprio pandas:
df['Investigation Type'].hist()

Mas eu particularmente acho o gráfico do matplotlib mais bonito:
import matplotlib.pyplot as plt

x = df['Investigation_Type'].unique() #['Acidente', 'Incidente']
# Também é possível pegar valores específicos fazendo: x = ['Acidente', 'Incidente']
y = [df['Investigation_Type'].value_counts()[key] for key in x]

plt.bar(x, y)

Comparar string PANDAS Data Science


How can I "inject" pages into my existing page using buttons to select the page

Question: I am new to Razor pages and hope there is a simple answer.
Using this sketch as an example:

     Name        |   Page Chooser
                 |-----------------
     Chooser     |   Page Content
                 |

In a Razor page, I want to click on a name in the "Name Chooser" section, and have the "Page Content" populate based on the ID of that selection.  Then, if the user clicks a button in the "Page Chooser" section, have the "Page Content" section update using the same ID chosen in the name choose, but with the new page's controls.
In web forms, I would probably use nested Master Pages for this where the main page is the site navigation, header, and footer and the nested master page would have the Name Chooser and the Page Chooser.  The child pages would be the "Page Content" section.
How would this be accomplished using Razor?
Is there a faster way of doing this?  I really need to only render out the "Page Content" section and not everything else.
Note: The "Page Content" could be inputs, tables, forms, etc.
Answer: I found the answer.  First, I used nested layouts to get the layout I wanted. Then, I put in a
 to hold the place the page will inject.
<button id="btnTest" class="btn">Test</button>

This shows the area that will change

Then, in JavaScript:
$('#btnTest').click(function () { $('#content').load('/Test');});

It works with Razor pages which is what I wanted.  I can now replace the single test button with a button bar or something similar and just add more jQuery to change the loaded file in JavaScript.


CUDA thrust: copy from device to device

Question: I have a memory array allocated in CUDA using standard CUDA malloc and it is passed to a function as follows:
void MyClass::run(uchar4 * input_data)

I also have a class member which is a thrust device_ptr declared as:
thrust::device_ptr<uchar4> data = thrust::device_malloc<uchar4(num_pts);

Here num_pts is the number of values in the array and the input_data pointer is guaranteed to be num_pts long.
Now, I would like to copy the input array into the thrust_device_ptr. I have looked at the thrust documentation and a lot of it is talking about copying from device to host memory and vice versa. I was wondering what would be the most performance optimal way to do this device to device copy on thrust or should I just use cudaMemcpy?
Comment: Yes you can may use `cudaMemcpy` with `cudaMemcpyDeviceToDevice` flag by first extracting the raw pointer from `thrust::device_ptr` like this: `uchar4* data_ptr = thrust::raw_pointer_cast(data);`
Answer: The canonical way to do this is just to use thrust::copy. The thrust::device_ptr has standard pointer semantics and the API will seamlessly understand whether the source and destination pointers are on the host or device, viz:
#include <thrust/device_malloc.h>
#include <thrust/device_ptr.h>
#include <thrust/copy.h>
#include <iostream>

int main()
{
    // Initial host data
    int ivals[4] = { 1, 3, 6, 10 };

    // Allocate and copy to first device allocation
    thrust::device_ptr<int> dp1 = thrust::device_malloc<int>(4);
    thrust::copy(&ivals[0], &ivals[0]+4, dp1);

    // Allocate and copy to second device allocation
    thrust::device_ptr<int> dp2 = thrust::device_malloc<int>(4);
    thrust::copy(dp1, dp1+4, dp2);

    // Copy back to host
    int ovals[4] = {-1, -1, -1, -1};
    thrust::copy(dp2, dp2+4, &ovals[0]);

    for(int i=0; i<4; i++)
        std::cout << ovals[i] << std::endl;

    return 0;
}

which does this:
talonmies@box:~$ nvcc -arch=sm_30 thrust_dtod.cu
talonmies@box:~$ ./a.out
1
3
6
10

Comment: This got me on the correct path! I ended up using thrust vectors but wrapping the raw input pointer via device_ptr and then using copy did the trick!
Comment: Hello sir, I have tried to declare the device vector directly. The copy function will not work.

CUDA thrust: copy from device to device


Quotient set and cardinality

Question:
Let $R_A= \{\langle x, y\rangle\mid y-x\in A\}$ for $A\subseteq \mathbb{Z}$
Given $A$ is a finite set and $R_A$ is an equivalence relation, what $A$ consists of?
For $k\in\mathbb{N}_+$ what is $A$ such that $R_A$ is an equivalence relation and, for it, $|\mathbb{Z}/R_A|=k$?

My thoughts are that for $A$ a finite set, $A=\{0\}$, because given $R_A$ equivalence, $\langle x,x\rangle\in R_A$, which means $A$ has to have $0$. I also understand that if $z\in \mathbb{Z}$, $z\in A$, $A$ is not a finite set because for $k\in\mathbb{Z}$, $\langle kz, 0\rangle \in R_A$.
Are my thought right? How do I describe them mathemathically?
My thoughts are that if $|\mathbb{Z}/R_A|=k$, then $A$ contains the $k$ first prime numbers. I understand that for each $z\in A$ $kz\in A$, but how do I describe the quotient set and equivalence classes? For example, let's say that $5k\in A$, does this mean that all $5k$ is one quotient set, or each $5k$ is a quotient  set of itself?
Comment: Mathematics is case sensitive. The variables $x,X,\mathcal X,\mathscr X$ and even $\mathbb X$ are all entirely different variables.
Comment: I don't really think it matters that much..
Comment: can you show that if $a\in A$ then $a\mathbb Z\subset A$ ? what if $A$ contains $a$ and $b$, think about $\gcd(a,b)$. so $\mathbb Z/k\mathbb Z$ is not very far...
Answer: If $R_A$ is an equivalence relation on $\mathbb Z$ then it is reflexive so that e.g. $\langle 5,5\rangle\in R_A$.
That leads to $0=5-5\in A$.
If $R_A$ is an equivalence relation on $\mathbb Z$ then it is transitive.
Now if $n\in A$ and $n\neq0$ then $\langle k,k+n\rangle\in R_A$ for every $k\in\mathbb Z$. Then with transitivity we find that $\langle k,k+2n\rangle\in R_A$ which means that $2n\in A$. This can be repeated so shows that in situation $A$ is not finite. From this we conclude that $A=\{0\}$ is the only option under the condition that $A$ is finite.

Let it be that $R_A\subseteq\mathbb Z^2$ is an equivalence relation on $\mathbb Z$, and that the cardinality of $\mathbb Z/R_A$ is $k$ where $k$ is a positive integer.
If $A$ is finite then (as shown allready) $A=\{0\}$ so if $[n]$ is an equivalence class then $k\in[n]\iff n-k=0\iff n=k$ telling us that $[n]=\{n\}$. In that case the cardinality of $\mathbb Z/R_A$ is not a positive integer so we can exclude that $A=\{0\}$.
Let $[0]$ denote the equivalence class represented by $0$. Then by definition: $$n\in[0]\iff \langle 0,n\rangle\in R_A\iff n=n-0\in A$$ telling us that $[0]=A$.
Also by symmetry we have:$$n\in A\iff\langle0,n\rangle\in R_A\iff\langle n,0\rangle\in R_A\iff -n\in A$$
Now let $m$ be the smallest positive integer with $m\in[0]$.
Then the transitivity of $R_A$ allows us to prove by induction that $nm\in A$ for all $n\in\mathbb N_+$ and combining this with the former results we conclude that $m\mathbb Z:=\{mn\mid n\in\mathbb Z\}\subseteq A$.
If $r\in A$ then $r-m\lfloor\frac{r}{m}\rfloor\in A$ so it cannot happen that $r$ is not a multiple of $m$ (it would contradict the minimality of $m$).
Proved is now that $A=m\mathbb Z$.
If $r\in\mathbb Z$ with $0<r<m$ then $s\in[r]\iff s-r\in A=m\mathbb Z$ showing that $[r]=r+m\mathbb Z$.
Then in $[0],[1],\dots,[m-1]$ we have $m$ distinct equivalence classes that cover $\mathbb Z$ so $m=k$.
Our final conclusion is: $$A=k\mathbb Z$$

Quotient set and cardinality


How can I share session variables across sites?

Question: On my main Drupal site, users need to be able to select a display preference (e.g. 'high visibility'). This will be available to registered and anonymous users but only for their session, so I plan to store their preference in a session variable, for example with <code>$_SESSION['display'] = $my_preference;</code>.
Another Drupal site runs on a subdomain of the main site, and needs the same functionality. And if the user visits both sites, it would be great to remember their preference.
I think that if I uncomment this line in both site's settings.php, session variables can be accessed across sites on the same domain?
<code>$cookie_domain = 'maindomain.com';
</code>
So then I could set $_SESSION['display'] on one site, and retrieve $_SESSION['display'] on the other?
Also, one site runs on Drupal 6 and the other on Drupal 7. Will this be a problem? Is caching for anonymous users going to cause problems?
Am I on the right lines, or is this plan flawed?
Answer: There are two options to do this

Using session

Use a single session table for both the site using settings.php set up

Using Cookie

Use same cookie domain for both site and set cookie available in all pages.
Comment: ah of course - sessions (and probably users) table needs to be shared between the sites. Thanks for the reply.
Comment: Be careful sharing tables across different sites. That particular solution can have erratic side effects.


Inserindo índice e valor num array bidimensional

Question: Tenho um array bidimensional (nele estão contidos dados vindo do banco de dados).
Para percorrer esses dados, utilizo um foreach().
Eu preciso adicionar um índice e um valor nesse índice no final de cada iteração do foreach().
Imaginando como se fosse uma matriz (linha x coluna), eu preciso inserir uma coluna no final de cada linha.
Segue o código abaixo:
foreach($dados as $d) {
    if($d['direta'] == 1 && ($d['idEntidade_evento'] == 0 && $d['idSemana'] == 0)){
        $d['tipo'] =& 'Mensagem instantânea';
    } else if($d['direta'] && $d['idEntidade_evento'] > 0 && $d['idSemana'] == 0){
        $d['tipo'] =& 'Evento';
    } else{
        $d['tipo'] =& 'Avaliação';
    }
}

No final, eu preciso que $dados contenha tudo (o novo índice inserido no foreach() )
No final, $dados não possui esse índice (não existe $dados['tipo']). É como se não fosse inserido nada.
Comment: Atualizei o post.
Answer: Pode fazer isso, modificando o elemento atual da iteração com o & ele alterar/adiciona o valor da variável por referência ou seja não faz um cópia um do original.
foreach($dados as &$d) {
   $d['nova_chave'] = rand(1,99);
}

Comment: Funcionou! Obrigado.
Answer: Pelo o que eu entendi você só quer colocar uma nova coluna, então é bem simples:
foreach($dados as $indice => $d) {
    $dados[$indice]['nova_coluna'] = "Novo dado";
}


The behaviour of $\sum_{\mathcal{R}\leq x}\left\{\frac{x}{\mathcal{R}}\right\}$, where $\mathcal{R}$ denote Ramanujan primes

Question: Here we denote with $\left\{x\right\}$ the fractional part function, and being $R_n$ for $n\geq 1$ the sequence of Ramanujan primes, see this Wikipedia, with the notation  $\mathcal{R}\leq x$ we mean the subset of Ramanujan primes less than $x$.

Question. I would like to know how to deduce a statement about the asymptotic behaviour (to me is enough a simple statement using big oh notation) of
  $$\sum_{\mathcal{R}\leq x}\left\{\frac{x}{\mathcal{R}}\right\}.\tag{1}$$
  Thanks in advance.

Only is required to provide hints or those details more complicated being specific in the manipulation or technique for our exercise. If it is known from the literature, answer this as a reference request.
Answer: Let $\mathcal{R}$ denote the set of Ramanujan primes, $\pi_{\mathcal{R}}(x)$ the number of Ramanujan primes less than $x$, and $$\theta_{\mathcal{R}}(x)=\sum_{\begin{array}{c}
p\leq x\\
p\in \mathcal{R}
\end{array}}\log p.$$ Then, writing this as a Riemann-Stieltjes integral, this will be $$\sum_{\begin{array}{c}
p\leq x\\
p\in\mathcal{R}
\end{array}}\left\{ \frac{x}{p}\right\} =\int_{2}^{x}\frac{1}{\log t}\left\{ \frac{x}{t}\right\} d\theta_{\mathcal{R}}(t).$$ To understand this quantity, we need to understand the number of Ramanujan primes less than $x$. The $n^{th}$ Ramanujan prime is the smallest integer $R_{n}$ such that $\pi(x)-\pi(x/2)\geq n$ for all $x\geq R_{n}$. Now, since $\pi(x)=\frac{x}{\log x}+O\left(\frac{x}{\log^{2}x}\right),$ it follows that $$\pi(x)-\pi(x/2)=\frac{x}{2\log x}+O\left(\frac{x}{\log^{2}x}\right).$$ The number of Ramanujan primes less than $x$, $\pi_{\mathcal{R}}(x)$, is equal to the largest $n$ such that $\pi(y)-\pi(y/2)\geq n$ for all $y\geq x$. By the above asymptotics, it follows that $$n=\pi_{\mathcal{R}}(x)=\frac{x}{2\log x}+O\left(\frac{x}{\log^{2}x}\right),$$ and by partial summation, we have that $$\theta_{\mathcal{R}}(x)=\frac{x}{2}+O\left(\frac{x}{\log x}\right).$$ Hence, by using integration by parts and bounding error terms in the partial summation above, we have that $$\sum_{\begin{array}{c}
p\leq x\\
p\in\mathcal{R}
\end{array}}\left\{ \frac{x}{p}\right\} =\frac{1}{2}\int_{2}^{x}\frac{1}{\log t}\left\{ \frac{x}{t}\right\} dt+O\left(\frac{x}{\log^{2}x}\right).$$ In other words, $$\sum_{\begin{array}{c}
p\leq x\\
p\in\mathcal{R}
\end{array}}\left\{ \frac{x}{p}\right\} =\frac{1}{2}\sum_{p\leq x}\left\{ \frac{x}{p}\right\} +O\left(\frac{x}{\log^{2}x}\right).$$
Comment: Many thanks for sharing these amazing calculations, I've read one time and I am going to study in detail it more later. I know your great knowledges (and recently an user mentioned in MO your paper about the median largest prime factor) but I would like to emphasize that is surprising the harmony of the calculations in this your answer together with your didactics in the explanation. You should write a book of analytical number theory!


Likelihood ratio test for sex ratio

Question: I am trying to solve this problem:
Assume that each child is male with probability $p$ independently of all other children.
We observed 19711 male births out of a total of 38562 births in American families with two children each.
Use the likelihood ratio test statistic to test the hypothesis $H_0: p=1/2$ against a suitable alternative, which you should specify.
We also found 17703 males out of 35042 similar births in Finland. Use the generalised likelihood ratio test to test the hypothesis that $p$ has the same value in each country versus a suitable alternative.
For the first part we have $X_1,..X_{38562}$ I.I.D. r.v. with distribution $\mathrm{Ber}(p)$.
The alternative hypothesis should be $H_1 : p \in [0,1]$.
Now as we know that the sample mean is the MLE for Bernoulli distributions, we have likelihood ratio, with $n= 38562$:
$$
\displaystyle \lambda(X)= \frac{(1/2)^n}{\overline x^{\sum x_i} \cdot (1-\overline x)^{(n-\sum x_i)} }
$$
So the likelihood ratio statistic is:
$$
\Lambda(X) = -2 \log(\lambda(X))
$$
Hence our test is that we reject $H_0$ iff $\Lambda(x) \geq k$ for a constant $k$ such that
$$
P(\chi^2_1 \geq k) = \alpha.
$$
Where $\alpha$ is the required size. We can do that as $n$ is large and we know that the likelihood ratio statistic converges in distribution to the chi squared with 1 degree of freedom
(QUESTION: the degrees of freedom should be $\mathrm{Dim}([0,1])- \mathrm{Dim}({1/2})= \mathrm{Dim}([0,1])$ why do we assign dimension 1 to this? I think we do, because otherwise 0 degrees of freedom wouldn't make much sense...)
I thought a sensible choice of $\alpha$ would be 0.05 so I worked out $k= 3.841$.
How do I proceed now? Putting the values in the likelihood ratio statistic leads to impossible calculations...
Any advice on this last bit or on the following part would be really appreciated!!
Answer: What's "impossible"?  If you mean you're trying to calculate a numerical value for the likelihood & then take its logarithm, then the numbers involved will be stupidly big.  Work out an expression for the log-likelihood first - using $\log(x^y)=y\log(x)$ &c. - & then put the numbers in.
The degrees of freedom are 1 because under the alternative you have one free parameter ($p$), & under the null no free parameters - $p$ is constrained to be $\frac{1}{2}$.
Comment: Well, in a large sample you can detect very small differences from the null hypothesis.  That doesn't mean they're necessarily of any practical significance; or even that they're real, given that there will also be unknown systematic errors.
Comment: yeah I've been stupid thank you!
i calculated the value and i got 8.3, hence I should reject the null hypothesis... it is strange as the data were pretty close isn't it?
also my concern was about [0,1] not being a vector space!
Comment: ah ok, i understand now! for the second part, I Was thinking of considering p_1 - p_2 as the parameter and to test the null of it being zero against the alternative of it being free, do you think this is the right track?

Likelihood ratio test for sex ratio


Card Game - Guessing No. of Cards

Question: Suppose that I am in a casino. The dealer is known to deal cards from
a deck that is comprised of 5 standard card decks. This means that there are 20 of each rank
of card and 260 total cards. The dealer plays a game where he shuffles all 5 decks together
randomly, and then he starts turning over cards from the top of the deck. Once he turns over 5
kings, the game is over. You win the game if you are closest to how many cards total (including
the final king) the dealer turns over before the game ends. How many cards should you guess
are turned over if you want to maximize your winning chances?
My reasoning The 20 kings partition the deck into 21 slices - something like ccccKccccK...ccccKccccKccc, where c denotes an arbitrary card, and K denotes a king. Each slice has expected size 260/21, and so for 5 kings to occur, there must be 1300/21 cards expected. The correct answer is 1305/21, however. Where am I going wrong? Moreover, how can I be more rigorous here? Can we use the idea of spacings somehow?
Comment: Hint:  Working from the back of the deck,  this is equivalent to finding the expected place of the first King.
Comment: @lulu there are $20$ kings in the five decks.
Comment: @ThomasAndrews  Oh, right.
Comment: In that case,  use symmetry.  Suppose we add a single Joker.  Now imagine the cards arranged in a circle.  By Symmetry, we expect a constant gap between the $21$ cards (Kings and the Joker).  Compute that gap.  Now remove the Joker to define the first and last cards of the shuffle.
Answer: Partitioning the deck into slices is almost right idea, but you need to exclude the kings from the count. This is because only twenty of the twenty-one slices contain a king in your method, so the slices do not all have the same expected size in your counting scheme.
There are $240$ non-kings, so the expected number of non-kings in each slice is $240/21$. This means the expected number of cards dealt is $5\times (240/21)+5$, where the $+5$ accounts for the five kings which come after the first five slices.

By the way, the question asks for "maximizing your winning chances", but in your solution you compute the "expected number of cards dealt". I see no reason for these to be the same concept, and would expect that that you would actually maximize your chances by choosing the mode, not the mean.

Card Game - Guessing No. of Cards


Nginx: make subdomain to not accept ssl request at all

Question: Previously, when my site does not have SSL/https at all, trying to access it would fail. For example, curl would return:
curl: (7) couldn't connect to host

Now that I have implemented SSL in a subdomain, I would like to simulate the previous behavior in all other domains.
For example: my https://api.example.com works as expected. But now visting https://www.example.com to would return 403.
# HTTPS server
server {
  listen 443;
  server_name api.example.com:

  ssl                  on;
  ssl_certificate      server.crt;
  ssl_certificate_key  server.key;

  ssl_session_timeout  5m;

  ssl_protocols  SSLv2 SSLv3 TLSv1;
  ssl_ciphers  HIGH:!aNULL:!MD5;
  ssl_prefer_server_ciphers   on;

  location / {
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    proxy_pass http://app;
  }
}

server {
  listen 443 default_server;
  server_name _;

  ssl                  on;
  ssl_certificate      server.crt;
  ssl_certificate_key  server.key;

  ssl_session_timeout  5m;

  ssl_protocols  SSLv2 SSLv3 TLSv1;
  ssl_ciphers  HIGH:!aNULL:!MD5;
  ssl_prefer_server_ciphers   on;

  deny all;
}

How should I configure Nginx, so visit subdomains which should not have SSL (https://www.example.com), it would behave as if the host can not be connected?
Answer: Instead of deny all, use return 444 instead.


Product topology set is Borel

Question: I'm trying to solve the following exercise from Hjort's measure theory notes:
Let $X=2^{\mathbb{N}}$, the collection of all functions from $\mathbb{N}$ to $\{0,1\}$ in the product topology.
Show that for each $N$ and $r\in\mathbb{R}$, the collection $A_{N,r}$ of $f\in X$ with $\dfrac{1}{N}|\{n<N:f(n)=1\}|>r$ is Borel.
My problem is that i don't know how to approach it. Also I'm confused about the definition of $A_{N,r}$. Any help or hints are welcome.
Answer: By $A_{N,r}$ I think he means $\{f\in X: \frac{1}{N}|\{n<N:f(n)=1\}|>r\}$ which can be rewritten as $\{f\in X: |\{n<N:f(n)=1\}|>Nr\}$. As $r$ can be any number, the number $Nr$ could be anything so we might as well call it $K$. But, we can rewrite $\{f\in X: |\{n<N:f(n)=1\}|>K\}$ as $\bigcup\limits_{I\subset \{1, 2,\cdots,N\}: |I|>K}\{f\in X : f(n)=1 \text{ for }n\in I\}$. It should be pretty clear that these sets are measurable when $\{0,1\}^{\mathbb{N}}$ is equipped with the product $\sigma-$algebra of the discrete $\sigma-$algebra on $\{0, 1\}$ (or, what is equivalent, the Borel $\sigma-$algebra induced by the product topology on $\{0,1\}^{\mathbb{N}})$, since they consists of all $f$s that attain some specified value on a finite number of points. Moreover, we are only taking the union over finitely many sets, so the union is itself measurable.

Product topology set is Borel


Writing utf-8 string inside my python files

Question: This line in my .py file is giving me a: "UnicodeDecodeError: 'utf8' codec can't decode bytes in position 8-13: unsupported Unicode code range"
if line.startswith(u"Fußnote"):

The file is saved in utf-8 and has the encoding at the top:
# -- coding: utf-8 --
I've got a lot of other py files with utf-8 encoded chinese text in them in the comments and in arrays for example:  arr = [u"chinese text",] so I'm wondering why this case in particular doesn't work for me.
Comment: There are also `hexdump -C` on most GNU/Linux distros and `hd(1)` on FreeBSD.
Comment: How do you know for sure it's really utf-8. Can you look at the appropriate output of `od -t c` on the file (if Unix)?
Comment: Thanks guys for the great answers, I moved and am away from my windows box I was working on. I was tearing my hair out over this, but I think I finally understand unicode. When I get back to it I'll accept an answer.
Answer: Let's examine that error message very closely:
"UnicodeDecodeError: 'utf8' codec can't decode bytes in position 8-13: unsupported Unicode code range"
Note carefully that it says "bytes in position 8-13" -- that's a 6-byte UTF-8 sequence. That might have been valid in the dark ages, but since Unicode was frozen at 21 bits, the maximum is FOUR bytes. UTF-8 validations and error reporting were tightened up recently; as a matter of interest, exactly what version of Python are you running?
With 2.7.1 and 2.6.6 at least, that error becomes the more useful "... can't decode byte XXXX in position 8: invalid start byte" where XXXX can be only be 0xfc or 0xfd if the old message suggested a 6-byte sequence. In ISO-8859-1 or cp1252, 0xfc represents U+00FC LATIN SMALL LETTER U WITH DIAERESIS (aka u-umlaut, a likely suspect); 0xfd represents U+00FD LATIN SMALL LETTER Y WITH ACUTE (less likely).
The problem is NOT with the if line.startswith(u"Fußnote"): statement in your source file. You would have got a message at COMPILE time if it wasn't proper UTF-8, and the message would have started with "SyntaxError", not "UnicodeDecodeError". In any case the UTF-8 encoding of that string is only 8 bytes long, not 14.
The problem is (as @Mark Tolonen has pointed out) in whatever "line" is referring to. It can only be a str object.
To get further you need to answer Mark's questions (1) result of print repr(line) (2) site.py change.
At this stage it's a good idea to clear the air about mixing str and unicode objects (in many operations, not just a.startswith(b)).
Unless the operation is defined to produce a str object, it will NOT coerce the unicode object to str. This is not the case with a.startswith(b).It will attempt to decode the str object using the default (usually 'ascii') encoding.
Examples:
>>> "\xff".startswith(u"\xab")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)

>>> u"\xff".startswith("\xab")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xab in position 0: ordinal not in range(128)

Furthermore, it is NOT correct to say "Mix and you get UnicodeDecodeError". It is quite possible that the str object is validly encoded in the default encoding (usually 'ascii') -- no exception is raised.
Examples:
>>> "abc".startswith(u"\xff")
False
>>> u"\xff".startswith("abc")
False
>>>

Comment: Thanks for the updating python mention, and the full explanation.
Comment: Hi Mark ... thanks for the upvote and answer acceptance. Please note that we still don't know what caused the problem; it would be helpful to future readers if you were to answer @MarkTolonen's 2 questions (edit your question, please, don't do it in a comment).
Answer: I can reproduce the UnicodeDecodeError with this code:
#!/usr/bin/env python
# -- coding: utf-8 --

line='Fußnoteno'
if line.startswith(u"Fußnote"):
    print('Hi')

Note that line is a string object, but u"Fußnote" is a unicode object.
Since line is a string object, the unicode object is being converted to a string object in the call to startswith. In Python2, the default is to try to decode using the ascii codec.
Since u"ß" can't be decoded with the ascii codec, a UnicodeDecodeError is raised.
The error can be avoided if you first make line a unicode object:
line='Fußnoteno'.decode('utf-8')
if line.startswith(u"Fußnote"):
    print('Hi')

or if you first make u"Fußnote" a string object:
line='Fußnoteno'
if line.startswith(u"Fußnote".encode('utf-8')):
    print('Hi')

Comment: -1 for 2 reasons (1) you have NOT reproduced that (unusual) error message, you would have got the plain variety (2) the unicode object is **NOT** being converted to a string [you mean `str`] object in the call to startswith. See my answer.
Answer: The error indicates line is not a Unicode string.  In X.startswith(Y) both X and Y must be Unicode or byte string.  Mix and you get UnicodeDecodeError.  print repr(line) to inspect it.  Also have you altered site.py to change the default encoding from 'ascii' to 'utf8'?  Normally it is the 'ascii' codec that is the default for Python 2.x.
Answer: Without seeing your code, it's unclear if the problem is the code or the data file the code is reading.
When you open the file, are you doing:
file = open("essay.txt")

or:
import codecs
file = codecs.open("essay.txt", encoding="utf-8")

What does:
print file.encoding

say if you add it just below the open line?
Both of these ways work for me:
# -- coding: utf-8 --

file = open("essay.txt")

print file.encoding

for line in file:
    uline = line.decode("utf-8")
    print type(uline)
    if uline.startswith(u"Fußnote"):
        print "Footnote"
    else:
        print "Other"

and this way:
# -- coding: utf-8 --

import codecs
file = codecs.open("essay.txt", encoding="utf-8")

print file.encoding

for line in file:
    print type(line)
    if line.startswith(u"Fußnote"):
        print "Footnote"
    else:
        print "Other"

In the first one, I am letting Python default to opening the file as a byte stream, then converting each line from a byte stream to a Unicode string using uline = line.decode("utf-8").
In the second one, I am opening the file as a UTF-8 encoded file, so Python returns Unicode strings when I iterate over the file.

EDIT
Here's a trivial way you could use to find out if the file contained any non-utf8 data.
import codecs
file = open("baduni.txt")
try:
    for char in codecs.iterdecode(file, "utf-8"):
        print char
except UnicodeDecodeError as e:
    print "error:", e

And an example of it in use:
$ echo 'ABC\0200\0101DEF' > baduni.txt
$ od -c baduni.txt
0000000   A   B   C 200   A   D   E   F  \n
0000011
$ python testuni.py
error: 'utf8' codec can't decode byte 0x80 in position 3: invalid start byte

In the example, the 4th byte (position 3, counting from 0) is 200 octal/0x80 hexadecimal.
The Wikipedia UTF-8 article shows that that would only be valid as the second byte of a two-byte sequence.
Answer: Your file is saved in some other encoding, and not UTF-8. Figure out what encoding the file is in (possibly CP1252 or so), and declare that instead.


MultiLojas Checkouts Diferentes

Question: Tenho um cliente que possui 2 lojas físicas que estarão na mesma loja virtual.
Uma equipe cuida da parte de roupas fitness e outra a de suplemento.
O cliente gostaria de 2 lojas diferentes em uma mesma instalação magento
Mas ele quer checkouts diferentes porque uma loja trabalha com um tipo de parcelamento e a outra com outro tipo.
É possível ter multilojas com checkouts diferentes?
Answer: Possível é sim. O problema é que sempre que eu tentei isso, esbarrei em problemas relacionados aos gateways de pagamento, maioria deles não aceita um checkout múltiplo.
Imagine que a URL de resposta da transação seja diferente para cada loja, os gateways de pagamento não permitem que você tenha múltiplas URLs de retorno na mesma conta. Por isso tive que implementar uma fachada para o pagamento, tenho um site dedicado a pagamento, onde os callbacks de pagamento sempre apontam para a mesma URL, porém lá eu filtro eles e envio para a loja correta.
Answer: tem como sim!! O magento disponibiliza vários módulos de pagamento, por exemplo, voip, pague seguro , paypal e entre outros. Suponha que você queira usar o "pague seguro" para finalizar os pagamentos das duas lojas, você pode definir 2 checkouts com valores diferentes, ou criar duas contas do "pague seguro" se quiser manter as finalizações de forma mais organizadas, ou seja, uma finalização vai para conta do João e a outra para Maria...
Answer: Bom não sei como esta sendo tratado no Magento.
Mas o Magento permite ter 2 ou mais lojas na mesma instalação, para cadastrar uma nova loja acesse no admin aba Sistema/Gerenciar Lojas.
Se for ter os mesmo produtos em ambas as lojas compensa criar uma visão, a visão e como outro idioma, voce conseguiria alterar preços etc pois o mesmo produto estaria em ambas visão.
Agora se for produtos diferentes, com segmentos diferentes conforme você sitou o ideal é realmente criar lojas.
Após ter essa parte de loja ou visão criadas, acesse os meios de pagamentos.
Quando estiver em meios de pagamentos altere o escopo conforme imagem
para qual visão ou loja quer configurar as diferenças, assim você consegue dizer que ambas tem o mesmo meio de pagamento com diferenças.
Também é possível instalar checkouts diferenciados para cada visão ou loja dessa mesma maneira, em uma loja ou visão você ativa o novo checkout e na outra desativa, caso queira novos checkouts clique aqui

MultiLojas Checkouts Diferentes


Is there a duration or rest error in the last bar here?

Question: In this example - my understanding is that every bar has four quarter notes, in the third bar, we can see only two eighth notes connected to a half note - does that not make a total of 3 quarter notes? The left hand part has a whole note - so that is okay - correctly equal to four quarter notes for that bar. But in the treble clef part for that last bar, shouldn't there be a quarter rest? (or is that supposed to be optional if the rest is in the end?)
This notation is from a published source - https://krishnadasmusic.com/products/krishna-das-selected-sheet-music-vol-1-digital

This is the full piece -
Comment: More dots are missing, in the last bars of the fourth and fifth systems.
Answer: Yes, the last bar shown contains only three beats in the treble clef, and no, this is not okay, especially since the bass clef contains four beats.
Since there's a repeat sign, sometimes you might see a situation like this that would be okay: if the repeated section started with a pickup (anacrusis); for instance, if there had been one beat before the first full measure, then the last measure would contain three beats and a repeat sign, and the repeated pickup would be the "fourth beat." But that's not the case here.
We can only guess what the correct notation should be; perhaps there should be a rest, or perhaps the last note should be dotted. My guess is the latter, since that's an easier mistake to make. But the difference between sustaining the pitch and ending it "early" is minimal.
Comment: Put  a rest in: the poor singer needs to take a breath in somewhere!
Comment: I would instead say that the note duration literally does indicate how long the note lasts, but individual singers/players/directors can choose to override the score's information for practical purposes like breathing. As an experienced choral singer, I promise that I want all choral singers to default to "sing the note for the exact duration indicated unless explicitly told otherwise"  :)
Comment: @Tim (That's a good next-level point: notate it as a dotted half and a singer will probably take roughly the final beat as a breath anyway. I make this point often when talking about articulation, staccato, etc: The note duration doesn't really tell you "how long the note lasts." Not really, not most of the time. Instead, they tell you "how long *until the next note starts*." Sometimes choral directors will make a point about sustain, or infinite-sustain instruments like organ can care about cutoff. More often, though, we taper, we breathe, we articulate, and rhythm is composed of attacks.
Comment: That's a false frame. Experienced singers know there are lots of possible ways and places to breathe, and thus they also know that they need to follow the specific choices of the conductor so that the ensemble sings as one.
Comment: And my take on @phoog's point is that it's not so much that the pros don't care about togetherness—it's that, the more fluent they are in their convention and with each other, *the less they have to talk about it*. You hear less "but *how* swung are these 8ths? are they more or less than two triplets," and a lot more "You'll know it when you hear it"—and they do. From Duke Ellington to Jordi Savall. (But I guess if you *don't* yet, you just have to put in the time, and talk about it, until you do....)
Comment: @GregMartin I prefer to sing in groups where the singers are experienced enough to know where to breathe, so the conductor can concentrate on more interesting things such as phrasing, expression, articulation, and form.
Comment: @GregMartin in my experience the quality of a performance tends to be inversely proportional to the amount of time a conductor devotes to communicating note durations to the singers.
Comment: @phoog - so how would your conductor conduct those bars - as writ, or make them full 4/4? Your last comment may ring true for singers, but certainly not for ensemble sections in big bands. They need to be smart in execution, otherwise it all sounds sloppy and amateur.
Comment: @Tim I'm talking generally.  Of course it's necessary to make corrections when the score has errors -- though this should happen before the first rehearsal, not in rehearsal.  And of course the degree to which breaths and note durations must be specified depends on the skill and experience of the performers, the amount of rehearsal time available, and the familiarity of the ensemble with each other and with the conductor.  Groups I've been in that focus on precise duration of notes tend to sound clean and amateur.  I'm not saying _never,_ just that many give it too much weight.
Comment: @phoog - can't imagine barber shop quartets sounding anything but clean and *professional*, with regard to correct breathing! And scores having errors - that may well not be apparent for all parts till a couple of rehearsals have gone by - even for seasoned players. As I found at the last big band rehearsal. Rhythm section reverted to 'playing by ear', which actually worked quite well!
Comment: @Tim there is no lack of very precise, very amateur sounding barbershop quartets on YouTube.  There's more to sounding professional than precise timing of lyrics and breaths -- much more.  And for other kinds of ensembles, especially larger ones in larger rooms, small differences in the lengths of breaths are not going to make a perceptible difference in most cases.  I'd rather focus on giving a compelling dynamic shape to, for example, the imitative counterpoint opening Mozart's Requiem, and on precision of tuning, than on specifying precisely how long each breath must last.
Comment: @GregMartin et alia: 1) I probably shouldn't have gotten us off on a topic that doesn't really bear on the OP's needs, but 2) it's important to note that our understanding of "duration" and "sustain" is parsed along lines of genre. Specifically, the notion that a note is "good to the last drop" until specified otherwise is relatively modern. It goes hand in hand with default notions of sustain (a whole note, marked *f*, means crank out exactly four full beats of homogenous volume). In contrast, early music approaches would assume that a note "lives"—blooms, breathes—in ways that are...
Comment: ... informed by context (swell toward dissonance, relax on resolution, etc etc metric phrasing, text, etc etc). Don't get me wrong; of course you have to worry about ensemble togetherness in Palestrina, and Lully was quite a hardass about it. But that ensemble will often figure out articulations, phrasings, and shapings that may or may not give a whole note exactly 3.9999 beats of sound, often by following performance conventions that are not notated or even discussed, but understood within the micro-music-culture.
Answer: The third bar is wrong.  The upper stave contains three beats, the lower stave contains four.   There's no room here for wriggling, it's just plain wrong.
Probably just a misprint though.   Adding a dot to the final half note would make everything add up.
LATER
Now you've shared the whole piece, we can confirm it's a simple misprint.   There's either a dot or a quarter rest missing from all the short measures.
Answer: The recording on which the score is based (linked below) makes clear that each bar should have four beats. The bars in question should have been written either with an extra quarter note (first example below) or with a quarter rest at the end of the bar (second example below). Either one would reflect the musical result demonstrated in the recording: the first would demonstrate the melodic intent but without a breath; the second would demonstrate the breathing, but without the melodic intent.


Executar uma lista de executáveis

Question: Estou tentando implementar um programa que execute concorrentemente uma lista de executáveis especificados como argumentos da linha de comando , considerando os executáveis sem quaisquer argumentos próprios. O programa deverá esperar pelo fim da execução de todos processos por si criados.
Só poderei usar estas funções para executar :
int execl(const char*path, const char*arg0, ..., NULL);
int execlp(const char*file, const char*arg0, ..., NULL);
int execv(const char*path, char*const argv[]);
int execvp(const char*file, char*const argv[]);

Isto foi o que criei até agora :
void main (int args , char **s) {

   int  i , x , status;

   if (args >= 2) {

    x = fork ();

    for ( i = 1 ; i < args ; i++) {

         if (x == 0) {
            execvp (s[i],&s[i]);
            x = fork();
         }
         else
         {
            wait (&status);
            _exit(i);
         }
      }
  }
   _exit(0);
}

Mas o programa só executa o primeiro argumento da main.
Como posso alterar o código para que faça o que quero?
Comment: acho que a melhor forma de fazer um sistema com concorrência, é usar `threads` ao invés de `fork`, o `fork` cria um novo processo, e as variáveis só podem ser usadas em um processo(exceto se for uma variável compartilhada)
Comment: Foi o que pensei @BrumazziD.B. , no entanto só posso usar o fork e os execs respetivos.
Answer:          if (x == 0) {
            execvp (s[i],&s[i]);
            x = fork();          // <== nunca executa
         }

Este segundo fork() nunca executa.
Depois do execvp() o programa actual é substituido por outro e o fork() deixa de "existir".

Primeiro fazes o fork(). Depois, apenas no filho, fazes o exec(). Assim ficas com dois processos activos: o pai a correr o programa original e o filho a correr o programa do exec.
// basicamente (MUITO BASICAMENTE) é isto
if (fork() == 0) {
    exec();     // o filho passa a executar outro programa
}               // o pai continua a executar este programa

Há um artigo na Wikipedia (em inglês) sobre o fork-exec.
Comment: Muito bem observado @pmg . Portanto se usar qualquer exec ele nao faz o processo do fork? Como faço para que o exec seja executado de acordo com o fork?

Executar uma lista de executáveis


Onde criar macros em C?

Question: Em termos de boas práticas de programação, se eu quero criar uma macro, por exemplo, uma macro que tenha mais ou menos umas 30 linhas de códigos, devo implementar ela no arquivo .c ou no .h? Qual é a boa prática?
Answer: Em termos de boas práticas você deve fazer o que é certo para cada situação. Para isso você precisa adquirir experiência. E não tem nada pior para adquirir experiência que ler "manuais" que dizem o que é certo ou errado fazer porque eles dão receitas de bolo e não ensinam.
Dito isto, macros devem ser evitadas tanto quanto possível. Nos compiladores atuais raramente elas precisam ser criadas. E se uma macro tem 30 linhas certamente tem algo errado nela. Crie uma função e ponto. Hoje eu acho que tem pouco caso de uso de macro, mesmo para uma linha, o motivo que ainda dão eu não gosto.
Pra que a macro no lugar da função? Para ter mais performance? Pode ser que fique até pior. Os compiladores otimizam as funções e elas são "linearizadas" como ocorreria com a macro, se for realmente viável (e o compilador sabe disto melhor que o programador em quase todas situações), com inúmeras vantagens em relação à macro.
Mas se quer insistir no erro, em tese nada importa onde você coloca. Apenas o padrão é que você deve usar arquivos com extensão .h para incluir em outros arquivos. E como o fonte da macro precisa estar disponível quando o código que a usa é compilado, é melhor incluir um um arquivo header. Alias, esta é mais uma desvantagem da macro.
Em C++ macros são absolutamente desnecessárias, ainda que algumas pessoas usem. Em C ainda tem alguns raros casos onde elas são interessantes, mas não para substituir códigos complexos que deveriam estar em uma função.
No SO já foi mostrado alguns problemas da macro.
Coloquei no GitHub para referência futura.
Comment: Quase certamente não. E se for útil, o compilador saberá quando fazer isto melhor que você. Neste caso é quase certo que você aumentará o tamanho do código gerado à toa, isto pode trazer problemas de performance (apesar de pequeno) e o ganho será ínfimo... em teoria. Na prática o saldo pode ser negativo.
Comment: Se sua pergunta é para um caso real e você não está convencido com a explicação acima, sugiro que você faça um benchmark, comparando as duas soluções e poste aqui um comparativo. Dificilmente você encontrará alguma diferença significativa, já que como @bigown disse, o compilador já faz otimizações. Contexto é a palavra chave: se vc quer um código tão otimizado, para uma situação tão específica, você pode recorrer ao Assembly. Como isso é exceção, na minha opinião, deve-se sempre optar pelo código mais claro, mesmo que haja algum (muitas vezes não comprovado) prejuízo de desempenho.
Comment: Mas se eu tenho um bloco de código que vai ser chamado pelo sistema constantemente, não seria útil, neste caso usar macro?
Comment: Mas macro, é carregada juntamente com o programa, o que torna sua chamada mais rápida. Enfim, ainda não estou convencido que é melhor usar funções do que macros nestas situações rsrs, se puder dar um exemplo prático.
Comment: Então use, o problema será seu. Você está tentando fazer micro-otimização. o que quase sempre ou traz resultado contrário ou um resultado melhor tão pequeno que não compensa o esforço. http://pt.stackoverflow.com/q/29507/101
Answer: Primeiro ponto: evita o uso de macros como funções, faz funções reais.
Segundo ponto: em geral as macros devem ser criadas nos ficheiros de cabeçalho já que definem identificadores a serem usados por componentes externos.
Mas no teu caso não me parece que seja isso o pretendido. Apenas pretendes criar uma macro "interna", que não é para ser usada por outros ficheiros de código que fazem uso das tuas funções.
Podes meter a macro num ficheiro de extensão ".c", ou num ficheiro privado de extensão ".h".
#include "header.h"         // contem coisas publicas
#include "header-private.h" // contem coisas privadas

Se optares pela solução de funções reais e quiseres fazê-las privadas ... não metas o protótipo dessas funções no ficheiro de cabeçalho e define-as com static
static int private_big_function(int x) { return x + 42; }

Comment: Principalmente problemas de interpretação de código quando for preciso alterar a "função" mais tarde. Uma macro de 35 linhas é **muito** mais dificil de entender que uma função (com espaçamento apropriado, com comentários) com 100 linhas.
Comment: Porque devo evitar?
Comment: Porque as macros de funções trazem mais problemas do que os problemas que resolvem.
Comment: Que tipo de problemas?

Onde criar macros em C?


Can we classify all primes in the set of candidates at a certain iteration of the prime number sieve?

Question: Consider the group $U(p_1\dots p_n)$, where $p_i$ is the $i^{th}$ prime.  For any pair of primes $p,q>p_n$, say that $p\sim q$ if and only if $p\equiv q\pmod{p_1\dots p_n}$.  Does this define an equivalence relation on the set of all primes greater than $p_n$?  If so, how many equivalence classes are there?  What's the size of each class?  Does there exist $r\in U(p_1\dots p_n)$ such that the equivalence class of $r$ is empty?
I made this one up, so if it's a dumb question, I am to blame.
Answer: The answer to your first question is yes, this is an equivalence relation.
For the second question, it follows from Dirichlet Theorem on arithmetic progressions that for each  $r \in U(p1...p_n)$ there are infinitely many prime in its class.
Comment: Okay, and so the number of classes is $\phi(p_1\dots p_n)$, right?  Thanks for answering the question.  I had no idea about Dirichlet's Theorem.  Very interesting.  Clearly I know almost nothing about number theory.
Comment: So it would be interesting to consider the classes for $p_1\dots p_n+1$ and $p_1\dots p_n-1$ in connection with twin primes.
Comment: @SpencerParkin The problem is that it probably doesn't help. There are infinitely many primes of the form $k p_1...p_n \pm 1$ but there is no way of telling if you can find one pair for the same $k$.


Complex functions. Find the region of the plane

Question: Find the region of the plane onto which the function $e^z$ maps $\{z\in\mathbb{C}|\operatorname{Re}(z)\operatorname{Im}(z)=0\}$
I was told $e^z $ is periodic with period $2\pi i$ but I'm not sure if its relevant to the question or not.
Answer: First, what does the condition mean? $\mathrm{Im}(z)=0$ or $\mathrm{Re}(z)=0$, that it, the given set is the union of the real axis and the imaginary axis.
Now, the imaginary axis is mapped onto the curve $z=e^{it}$ with $t \in \mathbb{R}$, which is the unit circle.
And the real axis is mapped onto the half-line (or ray) $z=t$, for $t>0$.
Thus the image by $\exp$ is the union of the unit circle and this half-line.


'gcloud app deploy app.yaml' not deploying most recent version from Cloud Source Repositories

Question: So I am very new to using GCP. As of right now, I'm using it strictly for my personal website.
My website source is currently on Github and I've connected the repository with Cloud Source Repositories.
From what I've found online, simply re-deploying should incorporate the newly committed changes, but this isn't happening. What am I missing?

As a follow-up question, I would like to start using Jenkins to accomplish push-to-deploy while incurring the least amount of charge possible on my GCP account.
What would be the most lightweight CI/CD setup with GCP and Jenkins? I'm fairly certain I need Kubernetes as well (which I've never used).
Bottom line, I'm looking for a push-to-deploy setup that is as open-source as possible. The less Google APIs I'm using, the better.
I've done a fair amount of research, but given how new I am to containerization and CI/CD, I am a little clueless as to where I should begin reading.
ANY setup and/or reading material suggestions would be highly appreciated!
Thanks,
Mack
Answer: You can take a look at Cloud Build
You can look at a quickstart guide here
And on this doc you can find 3 specific examples of use cases
For GCP Jenkins you use Kubernetes which is open source - tutorial
You mentioned you connected your repo with Cloud Source, you can check the steps for that here to make sure you followed all the steps, After you set up mirroring, Cloud Source Repositories should automatically sync your repository with the mirrored repository when a user commits a change.
You can also consider setting Cloud Build to automatically build your code each time you push a new commit to GitHub


What is the fundamental reason for epsilon numbers?

Question: I'm trying to wrap my head around the genesis of the $\epsilon$ numbers. In particular, I don't understand what gives rise to $\epsilon_0$ as a necessary notation once we get to $\def\iddots{
  {\kern3mu\raise1mu{.}\kern3mu\raise6mu{.}\kern3mu\raise12mu{.}}} \omega^{\omega^{\omega^\iddots}}$. I've read that $\epsilon_0$ is a fixed point on an exponential map, and (what I think amounts to the same thing) that $\epsilon=\omega^\epsilon$. If this is the same meaning of "fixed point" as in the idea that $2$ is a fixed point of $f(x)=x^2-3x+4$ (such that $f(f(x))$, $f(f(f(x)))$, etc are pointless), then I'm taking this to mean that $\epsilon_0$ is the infinite ordinal at which further iterations of exponentiation can't yield new ordinals. This is the crux of my confusion: either I'm wrong about that meaning of "fixed point" or I'm missing something about why $\def\iddots{
  {\kern3mu\raise1mu{.}\kern3mu\raise6mu{.}\kern3mu\raise12mu{.}}} \omega^{\omega^{\omega^\iddots}}$ is an endpoint for meaningful iteration. If $\def\iddots{
  {\kern3mu\raise1mu{.}\kern3mu\raise6mu{.}\kern3mu\raise12mu{.}}} \omega^{\omega^{\omega^\iddots}}=\:^\omega\omega=\epsilon_0$ couldn't we keep iterating tetration until $\omega\uparrow\uparrow\omega$, and then $\omega\uparrow^{(3)}\omega$ and then $\omega\uparrow^{(\omega)}\omega$ and so on. Is something fundamental breaking down at the point of $\def\iddots{
  {\kern3mu\raise1mu{.}\kern3mu\raise6mu{.}\kern3mu\raise12mu{.}}} \omega^{\omega^{\omega^\iddots}}$ that necessitates the new symbol before meaningful extensions of the ordinals can continue?
Comment: $\alpha\uparrow^{(\beta)}\delta$ is not commonly defined. And when defined... the exponential map thing tends to cause problems... however, I explained a way to surpass this in [this answer](https://math.stackexchange.com/questions/2313576/ordinal-tetration-the-issue-of-epsilon-0-omega/2326234#2326234).
Comment: You are aware that exponentiation is not commutative? That $\omega^\epsilon=\epsilon$ while $\epsilon^\omega\gt\epsilon$? So what do you mean by "further iterations of exponentiation can't yield new ordinals"?
Comment: @bof I mean further iterations of exponentiation *without* using $\epsilon$, but it's not a great phrasing. What I mean is, it seems like we can continue to build new ordinals using only $\omega$ with further tetration, pentation, etc., and so I don't understand what's fundamentally new that necessitates the introduction of $\epsilon_0$.
Answer: First off, $\alpha\uparrow^\beta\delta$ has no common definition for transfinite ordinals. Secondly, it has the problem of fixed points, mainly,
$$\omega\uparrow^2(\omega+1)\stackrel?=\omega^{\omega\uparrow^2\omega}=\omega^{\epsilon_0}=\epsilon_0=\omega\uparrow^2\omega$$
Indeed, under a definition that has $\alpha\uparrow^2(\beta+1)=\alpha^{\alpha\uparrow^2\beta}$, you will find that
$$\epsilon_0=\omega\uparrow^2\beta\quad\forall\beta\ge\omega$$
Which is, simply put, useless. Which is why we don't use hyperoperations and ordinals together.
Unless you happen to cook up a definition that actually steps beyond this. As I previously defined, with some extension, for ordinals $\alpha\ge\omega$,
$$\alpha\uparrow^\beta\delta=\begin{cases}\alpha,&\delta=1\\\alpha^\delta,&\beta=1\\\sup\{(\alpha\uparrow^\beta\psi)\uparrow^\gamma(\alpha\uparrow^\beta\psi)|0<\gamma<\beta,0<\psi<\delta\},&\text{else}\end{cases}$$
This gives what you might expect, with
$$\omega\uparrow^24=\omega^{\omega^{\omega^\omega}}$$
$$\omega\uparrow^2\omega=\epsilon_0$$
But it does something different once you pass limit ordinals:
$$\omega\uparrow^2(\omega+4)=\epsilon_0\uparrow^24=\epsilon_0^{\epsilon_0^{\epsilon_0^{\epsilon_0}}}$$
Indeed, this is how it overcomes the fixed-point issue, and the values you mentioned in your question are given as
$$\omega\uparrow^3\omega=\zeta_0=\varphi_2(0)$$
$$\omega\uparrow^\omega\omega=\varphi_\omega(0)$$

So why do we avoid this? Because its a slightly convoluted definition. Instead, we ended up using epsilon numbers and the Veblen function.
Comment: You say $\omega\uparrow^2(\omega+4)=\epsilon_0\uparrow^24=\epsilon_0^{\epsilon_0^{\epsilon_0^{\epsilon_0}}}$. But should it not be equal to $\varepsilon_{0}\uparrow^{2}5$?
Answer: You can do what you propose, but "tetration" also introduces a new symbol ($\uparrow$) so either way you need a new symbol.
Incidentally, $\epsilon_0$ isn't the first time you need a new "symbol" for ordinals.
Finite ordinals can be described by "$1+1+\ldots+1$", but to get $\omega$ you need a new "symbol", $\omega$.
Now with $1, +, \omega$, you can describe all ordinals < $\omega^2$.  At that point, you need a new symbol for multiplication ($\omega^2 = \omega \cdot \omega$).
Now you can get all the way up to (but not including) $\omega^\omega$, and you need to introduce a new symbol for exponentiation.
Then you get all the way up to (but not including) $\epsilon_0$, so you introduce a new symbol for it.
Comment: Well, not really, because a single $\uparrow$ means exponentiation, so it's not new just because we now need $\uparrow \uparrow$ to indicate tetration...
Comment: Yes, it is.  Tetration is a new operation, so however you write it, it counts as a new symbol (in the sense of "symbol" that people mean when they make claims of the sort "When you get to $\epsilon_0$, you need a new symbol.")  Just because you reuse an existing symbol for a new purpose, it's still a new symbol.
Comment: Fair enough. So the shift to epsilon at that point is relatively arbitrary? It's just equivalent to higher-order operations on omega?
Comment: Don't know what you mean by "either-order" operations.
Comment: Oops, typo. I meant "higher-order"
Comment: Sure, but no less "arbitrary" than all the earlier points where new symbols were introduced. I added some additional lines to the answer that may help.


Como posso criar um streaming a partir de um video que esta no servidor?

Question: Como o próprio titulo já diz, eu preciso criar um streaming ao vivo de um vídeo do servidor, ou do youtube ou algo do tipo, alguém pode me dar uma dica de como posso iniciar?
Pesquisei muito, e em todo lugar que procurei só encontrei ajuda/tutoriais relacionas a lives stream dai já entra parte de webcam e audio... e não esse meu objetivo.
Qualquer link ou ajuda é bem vinda!
Comment: dá uma olhada, é stream de audio e é direto dá maquina do cliente para os demais usuarios do sistema, mas modificando esse sistema dá para alterar para video, mas não é direto do servidor!!! https://www.webrtc-experiment.com/RTCMultiConnection/stream-mp3-live.html
Comment: dá uma olhada no site dele tambem: http://www.rtcmulticonnection.org/
Comment: pow vou dar uma olhada aqui, valeu cara.
Comment: Talvez eu tenha me expressado de maneira errada, eu tenho um arquivo de vídeo, e quero que esse arquivo seja reproduzido em minha pagina ao vivo, exemplo, coloco as 13h e todo mundo que for acessar vai ver o vídeo sendo reproduzido.
Obrigado
Answer: Sim você pode!
existe um software que ajuda nisso, e torna o streaming compatível com dispositivos móveis também!!!!
servidor de streaming [wowza] --> http://wowza.com
e você precisará de um cliente de streaming capaz de pegar os dados vindos do servidor (wowza) e colocar em um player que seja amigavel com desktop e mobile:
player [JW Player] --> http://jwplayer.com
abraço!!
Comment: Desculpa, talvez esteja fazendo uma pergunta besta, mas é que sou novo nessa questão streaming e afins. Mas eu posso utilizar estas ferramentas que você citou e testando em um ambiente local? localhost?
Sou estudante e não tenho $$$
Comment: O Wowza você pode usa-lo por 30 dias gratuitos. o jwplayer tem uma versão free! se sua intenção é estudo será ideal
Comment: Agradeço as dicas Aloiso, de fato fiz o cadastro no wowza e consegui a versão free do JW Player, o grande problema é que não consegui utilizar as duas ferramentas em comunhão. Estou recorrendo ao html5 e ao websocket para tentar atingir meu objetivo. Grato pela ajuda!
Answer: Crie uma activity para abrir o layout com uma VideoView e outra para trabalhar com o streaming com um layout próprio também:
  private ProgressDialog carregando;
  private Context context;
  private VideoView mVideoView;

      public void onCreate(Bundle paramBundle)
      {
        super.onCreate(paramBundle);
        setContentView(R.layout.player);
        this.context = this;
        this.carregando = ProgressDialog.show(this.context, "", "Carregando...", true, true, new DialogInterface.OnCancelListener()
        {
          public void onCancel(DialogInterface paramAnonymousDialogInterface)
          {
            Player.this.carregando.dismiss();
            Player.this.mVideoView.stopPlayback();
            Player.this.mVideoView.setVisibility(8);
          }
        });
        this.carregando.setCancelable(true);
        this.mVideoView = ((VideoView)findViewById(R.layout.videoview));
        this.mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
        {
          public void onPrepared(MediaPlayer paramAnonymousMediaPlayer)
          {
            Player.this.carregando.dismiss();
          }
        });
        this.mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
        {
          public void onCompletion(MediaPlayer paramAnonymousMediaPlayer)
          {
            Player.this.mVideoView.setVisibility(8);
            Player.this.carregando.dismiss();
          }
        });
        this.mVideoView.setVisibility(0);
        this.mVideoView.setVideoURI(Uri.parse("linkdostreamingnoservidor"));
        MediaController localMediaController = new MediaController(this.context);
        this.mVideoView.setMediaController(localMediaController);
        Log.d("NSLog", "Talvez isso: " + this.context + " ou isso: " + localMediaController);
        this.mVideoView.requestFocus();
        this.mVideoView.start();
      }


Nuget package doesn't copy .dll.config files to output folder

Question: My nuget package is for a library that needs a configuration file (ClassLibrary1.dll.config). I've tried to bundle it like this:

This is the nuspec file:
<code><?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
  <metadata>
    <id>ClassLibrary1</id>
    <version>1.0.0</version>
    <authors>ClassLibrary1</authors>
    <owners></owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Package Description</description>
    <dependencies>
      <group targetFramework="net5.0" />
    </dependencies>
  </metadata>
  <files>
    <file src="lib\net5.0\ClassLibrary1.dll" target="lib\net5.0\ClassLibrary1.dll" />
    <file src="lib\net5.0\ClassLibrary1.dll.config" target="lib\net5.0\ClassLibrary1.dll.config" />
  </files>
</package>
</code>
I have an application that references this Nuget package. The assembly is correctly copied to the output folder, but the .dll.config is not.
This is the output folder:

What's wrong? What should I do to get the config copied to the output directory?
I'm using Nuget 5.10+
BTW, I've read the answers to this post and none of them worked:
How can i make dll.config to be part of Nuget package
Answer: See https://stackoverflow.com/a/70608349/487503 for what worked for me.
In short: add a .props and .targets file to the nuget package that get executed in the project that consumes the nuget package and copies the .config file to the output directory.


Solve the differential equation $ \dfrac{ d^2x }{ dt^2 } + 6 \dfrac{ dx }{ dt } + 9x = 4t^2 + 5 $ using variation of parameters

Question: Would solving $ \dfrac{ d^2x }{ dt^2 } + 6 \dfrac{ dx }{ dt } + 9x = 4t^2 + 5 $ using variation of parameters require integration by parts or can I solve it without knowing integration by parts?
I'm not sure if I'm just using the method wrong or if it requires integration by parts. I'm new to variation of parameters, and I haven't encountered integration by parts. Thanks.
The non homogeneous characteristic equation is $ r^2 + 6r + 9 = 4t^2 + 5 $
The characteristic homogeneous equation is $ r^2 + 6r + 9 = 0 $
$ \Rightarrow (r + 3)(r + 3) $
$ \Rightarrow r = -3 $
$ \therefore x(t) = C_1e^{-3t} + C_2te^{-3t}$ is the general solution for the homogeneous differential equation.
I now find the particular solution.
$-e^{-3t} \displaystyle\int \dfrac{te^{-3t}(4t^2 + 5)}{W(x_1, x_2)} dt + te^{-3t} \displaystyle\int \dfrac{e^{-3t}(4t^2 + 5)}{W(x_1, x_2)} dt$
The Wronskian $W(x_1, x_2) = e^{-6t} $
$-e^{-3t} \displaystyle\int \dfrac{te^{-3t}(4t^2 + 5)}{W(x_1, x_2)} dt + te^{-3t} \displaystyle\int \dfrac{e^{-3t}(4t^2 + 5)}{W(x_1, x_2)} dt $
$= -e^{-3t} \displaystyle\int \dfrac{te^{-3t}(4t^2 + 5)}{e^{-6t}} dt +
te^{-3t} \displaystyle\int \dfrac{e^{-3t}(4t^2 + 5)}{e^{-6t}} dt$
Comment: Could you type up some of your work?
Comment: Yes. You do need integration by parts.
Comment: I think you want "$\mathrm{e}^{-6t}$" in those last two denominators.
Comment: It should be $e^{-6t}$ on the last line. Other than that, everything seems okay.
Comment: Yes. Simplify your integrand then use integration by parts.
Comment: It seems weird to have an "$x$" in front of the second integral.
Comment: @JackyChong Yes but I'm not sure if I'm just using the method wrong or if it requires integration by parts. I'm new to variation of parameters, and I haven't encountered integration by parts.
Comment: @JackyChong Yes. I will do that now.
Comment: @JackyChong Are you sure I didn't just make a mistake?
Comment: My thanks to both of you. So everyone agrees that this requires integration by parts to solve?
Comment: @JackyChong Ok. Thank you.
Comment: @EricTowers That's another mistake on my part. Thanks.
Comment: So you want me to evaluate your last integrals?
Answer: Considering the general case of $$I_k=\int t^k e^{r t}\,dt$$ Using integration by parts $$u=t^k \implies du=k t^{k-1}\,dt$$ $$dv=e^{r t}\,dt\implies v=\frac{e^{r t}}{r}$$ makes $$I_k=\frac{t^k e^{r t}}{r}-\frac k r\int  t^{k-1} e^{r t}\,dt=\frac{t^k e^{r t}}{r}-\frac k r I_{k-1}$$ with $I_0=\frac{e^{r t}}{r}$.
If you already heard about the incomplete gamma function, almost from definition, you would have $$I_k=-\frac{t^{k+1}} {(-r t)^{k+1}} \Gamma (k+1,-r t)$$ which, in the case where $r<0$ reduces to $$I_k=-\frac{\Gamma (k+1,-r t)} {(-r )^{k+1}} $$
Answer: $$
\int e^{r t} \sum_{i=0}^na_it^i dt  = \frac{1}{D} e^{rt} \sum_{i=0}^na_it^i = e^{rt} \frac{1}{D+r}\sum_{i=0}^na_it^i = e^{rt}\sum_{i=0}^n \frac{a_i}{r}  \frac{1}{1+D/r}t^i =
$$
$$
e^{rt}\sum_{i=0}^n \frac{a_i}{r} \sum_{j=0}^{\infty} \left(-\frac{D}{r}\right)^j t^i = e^{rt}\sum_{i=0}^n \frac{a_i}{r} \sum_{j=0}^{i} \left(-\frac{D}{r}\right)^j t^i = e^{rt}\sum_{i=0}^n \frac{a_i}{r} \sum_{j=0}^{i} \frac{(-1)^j}{r^j} \frac{i!}{(i-j)!} t^{i-j}
$$