text:
Q: Checksum JPEG data (not the whole file) Are there end-of-exif / end-of-xmp / end-of-iptc / start-of-data markers that I could use to get a checksum of just the data part of a jpg / jpeg (and other image formats)?

A: I think this question is related to this one Compute hash of only the core image data (excluding metadata) for an image, https://stackoverflow.com/a/10075170/890106 gives an element of answer if you're looking for code.
It might not works with all JPG variants though : some of them can embed multiple images (MPF / CIPA Multi-Picture Format, more informations at http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/MPF.html) and you might still have some metadata. Also, some software put an UID in the form of --[0-9A-F]+-- at the end of the file and it shouldn't be read. Safest solution if probably to checksum pixels (though you can still have influence of orientation, color profile, ..).

A: One easy way to get a hash sum of just the pixel data would be to convert the JPEG into a 32Bit BMP or alternatively into PNG and to calculate a hashsum from that. This will strip all the associated information from the JPEGs and would even match JPEGs with differnt encodings that lead to the same pixel data. You could of course also use the in memory pixel data of the resulting BMPs directly if you have it (i.e. Windows has several API functions to get it from any supported image type).

A: You'll have to look at each format. For JPEG, it looks like the structure implies that you can just do a checksum of the sections that start with FFEn (e.g. 0xFFE1) and checksum the bytes specified after each marker (It looks like the length follows the marker and is 2 bytes in big-endian format). For more details, see here.

A: Yes to jpeg and exif, I don't know to the others.
The JPEG spec that I have is called JFIF (JPEG File Interchange Format) it comes from Annex B of ISO 10918-1 and like all ISO specs, it takes careful reading to figure out how to translate the spec into data structures.  I think this is much easier to follow
the EXIF format parses much like the TIFF format. each chunk has a type and a size, so you just walk the chunks until you get to the image data chunk. it has a pointer to the image data (actually pointers to strips, but I'm pretty sure that you can assume the everything after the first strip of image data to the end of the file is image data.
The exif format has its own website

A: Since you want to do this for various image formats, you should just use a general-purpose image decompression library and run your checksum on the uncompressed data. This will allow you to match identical images even if they are encoded differently on disk.
If you want to limit yourself to JPEG, you can checksum the data between SOI and EOI. This answer can be slightly adapted to do what you need.

A: MediaTags has checksum support for JPEG, MP3, M4A, etc


text:
Q: Save Objects to plist file I need to save a CGDDisplayModeRef to a plist file but none of the available types are good for storing CGDisplayModeRef. Is there a way around this?

A: You can implement an object wrapper / container for this class and implement NSCoding for an object by writing a code for coding / decoding an valuable params for CGDDisplayModeRef. Afterward use NSKeyedArchiver / NSKeyedUnarchiver for saving / loading of your wrapper object with CGDisplayModeRef inside of it.

A: Saved the height, width & pixel encoding to a plist file & then used the myBestMode method found in Quartz Display Services to find a mode for the saved attributes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use equivalence Theorems inside Greater Than Propositions in Coq I have the following operation definitions for Equivalence, Less Than and Addition in the context of natural numbers:
Require Import Setoid.

(* CNat Set *)
Parameter (CNat:Set) (O i:CNat).

(* CEq Equivalence *)
Parameter CEq: CNat->CNat->Prop.
Infix "¦" := CEq (at level 70, no associativity).
Axiom ceq_refl: forall x:CNat, x¦x.
Axiom ceq_sym: forall x y:CNat, x¦y->y¦x.
Axiom ceq_trans: forall x y z:CNat, x¦y->y¦z->x¦z.
Add Relation CNat CEq
  reflexivity proved by ceq_refl
  symmetry proved by ceq_sym
  transitivity proved by ceq_trans
  as ceq_rel.

(* CLe StrictOrder *)
Parameter CLe: CNat->CNat->Prop.
Infix "«" := CLe (at level 70).
Axiom cle_irrefl: forall x:CNat, ~x«x.
Axiom cle_trans: forall x y z:CNat, x«y->y«z->x«z.
Add Relation CNat CLe
  transitivity proved by cle_trans
  as cle_rel.

(* CAdd Operation *)
Parameter CAdd : CNat->CNat->CNat.
Infix "±" := CAdd (at level 50, left associativity).
Add Morphism CAdd with signature CEq ==> CEq ==> CEq
  as ceq_add_mor. Admitted.

Then I define Neutral Addition and Natural Induction and try to use them inside a Test Theorem:
(* CNat Axioms *)
Axiom cnat_add_neutral: forall x:CNat, x±O¦x.
Axiom cnat_induction: forall P: CNat->Prop, P O ->
    (forall x:CNat, P x->P (x±i)) -> forall x:CNat, P x.

(* CNat Test Theorem *)
Example cle_neutral_test: forall x:CNat, O«x -> O«x±O.
Proof.
  intros x CH.
  rewrite cant_add_neutral. (* Error *)
  apply CH.
Qed.

With the following error:
Error:
Tactic failure: setoid rewrite failed: Unable to satisfy the following constraints:
In environment:
x : CNat
CH : O « x
do_subrelation := Morphisms.do_subrelation : Morphisms.apply_subrelation

?p : "Morphisms.Proper (CEq ==> Basics.flip Basics.impl) (CLe O)"

What kind of previous definition or demonstration should I generate before being able making this Test work?

A: (Using more standard notation, I hope that's still clear to you. CEq is ==, CLe is < (it should probably be named CLt))
First, before even delving into rewriting, let's make sure you logically have enough facts to prove the theorem.
You want to prove x < y, and you know y == z. For that you would want the following lemma, to change the goal to x < z:
y == z -> x < z -> x < y

This is presently missing from the list of facts.
One way to present that fact suitably for generalized rewriting is as a Morphism declaration for CLe:
Add Morphism CLe with signature CEq ==> CEq ==> iff
  as ceq_cle_mor. Admitted.

The signature CEq ==> CEq ==> iff means:
forall x x',
  x == x' ->
  forall y y',
  y == y' ->
  (x < y) <-> (x' < y')

Which one can easily check is a generalization of the missing fact above. Having added it, and after fixing a typo in the cnat_add_neutral lemma (in the initial version of your question, now edited), the proof goes through.
Add Morphism CLe with signature CEq ==> CEq ==> iff
  as ceq_cle_mor. Admitted.

(* CNat Test Theorem *)
Example cle_neutral_test: forall x:CNat, O«x -> O«x±O.
Proof.
  intros x CH.
  rewrite cnat_add_neutral.
  apply CH.
Qed.


text:
Q: Testing redis key expiration I was wondering if anyone has a clever way of testing behavior after a redis key expires. I am essentially building a small redis backed cache for my application and would like to test what happens after a redis key is set to expire.
I am using rspec as my testing framework. I tried to use Timecop to change the time during testing but realized that it would only effect the testing frame work and not the external redis server.
I can set the TTL to 1 and then use a sleep(1) but I would rather not introduce sleeps into my tests.
Does anyone have a good way of testing this?

A: Why not use http://redis.io/commands/expire to expire the key right away?

A: The proper way to fix this for the testing environment is to mock out the redis client and have it return the expected value. I have confidence redis will do the right thing and is implemented correctly so mocking this interaction out is probably better than letting the test actually hit redis.
redis_client.should_receive(:ttl).with(key).then_return(-1)

or just mock out the request for the key
redis_client.should_receive(:get).with(key).then_return(nil)

With the newer RSpecs version,
expect(redis_client).to receive(:get).with(key).and_return(value)


text:
Q: Relationship between OLS estimates of slope coefficients of simple linear regression Y on X and X on Y Assume a model $y = \beta_0 + \beta_1x + u$. Given a sample $(x_i, y_i)_{i=1}^n$, we can find the OLS estimates of $\beta_1$, $\hat{\beta_1}$. Then suppose that we assume another model $x = \gamma_0 + \gamma_1y + \varepsilon$. Then we also can compute the OLS estimates of $\gamma_1, \hat{\gamma_1}$. And my question is whether $\frac{1}{\hat{\gamma_1}}$ is the unbiased estimator of $\beta_1$? Assuming the models satisfy Gauss - Markov assumptions, i.e.
1) $\mathbb{E}(u|x) = 0,\ \mathbb{E}(\varepsilon|y) = 0$
2) $(y_i, x_{i})_{i=1}^n$ are i.i.d.
3) $\mathbb{E}(y^4) < \infty,\ \mathbb{E}(x^4) < \infty$
4) $u, \varepsilon$ are homoskedastic
5) $u \sim \mathscr{N}(0, \sigma_u^2), \varepsilon \sim \mathscr{N}(0, \sigma_{\varepsilon}^2)$
What have I done:
$\hat{\gamma_1} = \frac{\sum(y_i - \bar{y})(x_i - \bar{x})}{\sum (y_i - \bar{y})^2} = \frac{s^2_{xy}}{s^2_{yy}}$ (where $s^2$ means sample covariance)
$\frac{1}{\hat{\gamma_1}} = \frac{s^2_{yy}}{s^2_{xy}} = \frac{\sum(y_i - \bar{y})(\beta_1x_i + u_i - \beta_1\bar{x} - \bar{u})}{s^2_{xy}} = \frac{\beta_1s^2_{xy} + s^2_{yu}}{s^2_{xy}} = \beta_1 + \frac{s^2_{yu}}{s^2_{xy}}$
And here I got stuck. I have no idea, how to calculate the expectation of the second term (or prove that it has zero, or non-zero expectation). Could you please give me any hints?
Thanks a lot in advance for any help!

A: There is some contradiction in your symbology: I am assuming that you estimated the betas through a regression $y,x$ and the gammas with a regression $x,y$.
That means that:
 - in the first case, you are assuming the "error" to be in the $y$ data (while the $x$ values are precise);
 - in the second, on the contrary, the "error" is on the $x$ data.
In any case the regression line is going to pass through $(x_{avg},y_{avg})$, so we are concerned only with determining the slope.
So $\beta_1$ is tied to the conditional probability that all the error be with $y$ and $1/\gamma_{1}$ that it be all with $x$.
The intermediate case in which we allow the error to be both on the $x$ and $y$ data is solved through Total Least Squares linear regression which would produce a different slope according to the presumed ratio of precision (or noise) between the two sets of data.
So a relation cannot be established, unless you state such an assumption.
-- addendum in reply to your comment  --
The "physical" and "engineering"  concept about regression is  what I described above.
If you have, e.g., a set of measurements of (volume, weight) of a certain substance, made with instruments of which you know the precision and excluding systematic errors, and you want to determine the density of the substance then you resort to the statistics property of levelling out the errors by using multiple samples. That is to least squares method.
The standard least square method is to minimize $(\Delta y)^2=(y_n-(\beta_0+ \beta_1 x_n))^2$ which is the same to say that the "precise" value of $y$ is $\beta_0+ \beta_1 x_n$ which in turn means that $x_n$ is precise and you are minimizing the vertical distances  $y_n$-line.
And that's acceptable if the expected r.m.s. error (the $\sigma$) on $x$ is much lower than that on $y$.
If it is the contrary, then you shall minimize the horizontal  deviations from the line ($x,y$ regression).
In the case in which the expected r.m.s. errors are comparable, you shall minimize the distances from the line taken along a direction inclined same as the ratio of the $\sigma$'s (in between the two extreme cases above).
So, physically it is known that the vertical and horizontal approach might provide two different slopes, and mathematically you cannot concile them if not making assumptions about the said ratio.
-- addendum upon expliciting Gauss-Markov conditions  --
Translated into the engineering approach described above, they read as:
 - the systematic error is null;
 - it is present on both $x$ and $y$, independently;
 - it is distributed as a double Normal, on the two independent variables $x,y$, thus as a product of two Normals;
 - the expected r.m.s. error is given and is respectively $\sigma_x , \, \sigma_y$.
So what explained above is totally justified and the actual slope shall be computed by minimizing the sum of
the square errors = deviations taken along the line $\Delta y / \Delta x = \sigma_y / \sigma_x$.
Or, in other words, transform $x$ and $y$ into
$$
\xi _{\,n}  = {{x_{\,n}  - \bar x} \over {\sigma _{\,x} }},\quad \eta _{\,n}  = {{y_{\,n}  - \bar y} \over {\sigma _{\,y} }}
$$
and calculate the errors orthogonally to the line : Orthogonal Regression.

Now you expect to have the inversion of the slope if you invert the axes.

A: This is a biased estimator. If $\beta_1 = g(\gamma)=1/\gamma=$ and $\mathbb{E}[\hat{\gamma}] = \gamma=1/\beta_1$, then $\beta_1 = 1/\mathbb{E}[\hat{\gamma}]$. And due to the fact that $1/x$ is either convex (for $x > 0$) or concave (for $x<0$), $1/\hat{\gamma}$ will be biased upward and downward, respectively. This stems from Jensen inequality, i.e., for $\hat{\gamma}>0$ you have
$$
\mathbb{E}g(\hat{\gamma}) \ge g\left( \mathbb{E}\hat{\gamma} \right),
$$
and reversed inequality for $ \hat{\gamma}<0$.


text:
Q: Mod Rewrite duplicating query I am attempting to rewrite a page but I am getting a repeated query.
http://www.website.com/settings/index.php?page=account
Rewrites to this:
http://www.website.com/settings/account
So my issue is that when I use server validation on my page I redirect to settings/account?valid=failedbut unfortunately I am getting:
http://www.website.com/settings/account?valid=false&page=account
This is my rewrite code:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([A-Za-z0-9-]+)?$ index.php?page=$1 [L,QSA]

A: The error was in the php. The mod rewrite was not the problem.


text:
Q: Can we reuse WordPress drag drop media upload in plugins? I'm building a plugin in which I want to upload the media.
I'm using <input type="file" /> which works as expected. But I'm thinking to reuse the WordPress drag drop media uploader.

Note: I have a solution in which I upload the media from popup window.

But, I'm looking for image dropable placeholder in which user upload the image.


text:
Q: Microsoft 365 Rest API returns Operation is not valid due to the current state of the object when getting versions of a large(8GB) file I am using the endpoint _api/web/GetFileById('" + fileUniqueId + "')/Versions('versionId') and _api/web/GetFileByServerRelativePath(path)/Versions('versionId') to get FileVersion based on fileId/path and version id. Both works on small files, but it return Operation is not valid due to the current state of the object when file is large, in my case it is 8GB. Is this an existing issue in SharePoint or is there a fix for this?

A: Per my test, I could reproduce this issue on my end. And I find a same issue here: https://stackoverflow.com/questions/55835984/o365-rest-api-error-response-for-version-method
It seems that this is an existing issue that large files in Microsoft Office 365 SharePoint do not support Versions request.


text:
Q: How to fire an ActionListener when a page is loaded? Working with JSF 2.0 (and Primefaces), is there a way to fire an ActionListener when a page is loaded?
Thanks

A: Depends of your need, for example you can use f:event with preRenderView if you want to initliaze something in your bean:
Check this link :
http://www.mkyong.com/jsf2/jsf-2-prerenderviewevent-example/
But you should know that the event is call on every requests : ajax, validation fail .... You can check if it's new request like this:
public boolean isNewRequest() {
        final FacesContext fc = FacesContext.getCurrentInstance();
        final boolean getMethod = ((HttpServletRequest) fc.getExternalContext().getRequest()).getMethod().equals("GET");
        final boolean ajaxRequest = fc.getPartialViewContext().isAjaxRequest();
        final boolean validationFailed = fc.isValidationFailed();
        return getMethod && !ajaxRequest && !validationFailed;
    }


text:
Q: Check for cookie and log the result in React I want to check if a cookie exists and if not I want to give the cookie auth a false value. If the cookie is false I want to redirect to / and if the cookie is true it should redirect to /home. Because I can not seem to get it working I removed the redirect and changed it to console.log("value"); so that I can see if it is working.
checkLogin() {
    var AuthCookie = localStorage.getItem("auth");

    if (AuthCookie === null) {
        console.log("null");
        localStorage.setItem("auth", false);
    }

    if (AuthCookie === false) {
        console.log("false");
    }
    else if (AuthCookie === true) {
        console.log("true");
    }
    else {
        console.log("AuthCookie is neither false or true");
    }
}

There is no output in the console with this code and I do not know why.

I want to store data locally, in this case it is a login page, but this is just to test the storing of the data.
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import { Redirect, Router } from 'react-router-dom';
import * as serviceWorker from './serviceWorker';
import Routes from './inc/routes';
import Navbar from './components/parts/navbar';

class Loader extends Component {
  checkLogin() {
    var AuthCookie = localStorage.getItem("auth");
    if (AuthCookie === null) {
        console.log("null");
        localStorage.setItem("auth", false);
    }

    if (AuthCookie === false) {
        console.log("false");
    }
    else if (AuthCookie === true) {
        console.log("true");
    }
    else {
        console.log("AuthCookie is neither false or true");
    }
}

render() {
    this.checkLogin();
    return (
        <div>
            <Navbar />
            <Routes />
        </div>
    );
}
}
ReactDOM.render(<Loader />, document.getElementById('root'));

Console now gives me AuthCookie is neither false or true, but when I look at application and localstorage it says that auth is false. Console shows no other errors or warnings.

A: Are you sure AuthCookie is null, perhaps it is undefined, although we can not know without showing where it is assigned to localStorage initially.
Try to work backwards when debugging, so start by console logging AuthCookie when calling the function so you can be sure it is assigned the value you expect. Otherwise go further back to where it is being assigned to localStorage and check the value there. We can not know for sure with the code provided but id say the value is not what you think it is.

A: So I made 3 mistakes, first was if (AuthCookie === null), this should be undefined. The second mistake is that var AuthCookie is not updated after if (AuthCookie === undefined) so AuthCookie is not being updated to the new value. The last mistake is that the value should be in "" so (AuthCookie === "false").
The correct code working now:
var AuthCookie = localStorage.getItem("auth");
if (AuthCookie === undefined) {
   console.log("null");
   localStorage.setItem("auth", false);
}

var AuthCookie = localStorage.getItem("auth");

if (AuthCookie === "false") {
   console.log("false");
}
else if (AuthCookie === "true") {
   console.log("true");
}
else {
   console.log("The cookie is set, but can't be read or has a different value");
}


text:
Q: Angular error when trying to retrieve JSON I'm trying to retrieve a simple JSON list and inject it into a dropdown list.
However, I'm getting an error from the following JS.
var rac  =  angular.module('rac', ['angular.filter']);

rac.controller('prodCtrl', function($scope, $http, $sce, $filter){
  var dataURL =
$sce.trustAsResourceUrl('http://www.mocky.io/v2/5b1ef454310000fa163ffa45');
  $http({
    method: 'JSONP',
    url: dataURL
  }).then(function ($scope, response) {
    $scope.products.data = response;
    console.log($scope.products);
  }, function (response) {
    console.log("Mr. Data. Report! " + response);
  });
});

My HTML:

Leonard Zakoor - Rolled Alloys

Please choose a product

    <select>
      <option ng-repeat="product in products">{{product.name}}</option>
    </select>

The error I'm getting is:
TypeError: Cannot set property 'data' of undefined
On line 9
$scope.products.data = response;

A: You need to define $scope.products = [];
and then ng-repeat over,
 <option ng-repeat="product in products">{{product.name}}</option>

EDIT:
I have made few changes on the request as follows,
rac.controller('prodCtrl', function($scope, $http, $sce, $filter) {
  $http.jsonp($sce.trustAsResourceUrl("https://www.mocky.io/v2/5b1ef454310000fa163ffa45"), {
      jsonpCallbackParam: 'callback'
    })
    .then(function(data) {
        $scope.products = data.data.products;
      },
      function(error) {}
    );
});

WORKING DEMO


text:
Q: Linearization of Simulink nonlinear state space models with Linearize States of the system in Simulink Conttrol Design are identified at the output of the integrator blocks accross the system.
If a model is already developed in a state space form, and specifically, integrators are already implemented in, for example, forward Euler form, how can one "inform" linearize command on what the states of the system are?
In simple words, how to use linearize for a high order dynamics system that does not contain any Matlab integrator block?


text:
Q: grub install failing on SSD I have a very frustrating problem. I wanted to set up a USB stick with a full install of Linux (I have gone for Zorin OS 15.1 but also have tried this with Ubuntu 18.04), that I could boot from any computer. I tend to use Macs so important that the drive has the right boot.efi setup so that simply holding down alt will provide the option to boot into it.
I followed the instructions here: https://medium.com/@mmiglier/ubuntu-installation-on-usb-stick-with-pure-efi-boot-mac-compatible-469ad33645c9 on a SanDisk Extreme Go USB 3.1 128GB drive and it worked perfectly. Really exciting, I can now boot into Zorin from any Mac.
I then went the whole way and bought a SanDisk Extreme Pro Portable SSD 500GB as the read speeds go to about 1050MB/s rather than the USB 150MB/s. I followed exactly the same steps but can never install grub.
The exact command is sudo grub-install --target x86_64-efi --boot-directory=/boot --efi-directory=/boot/efi --bootloader-id="$(lsb_release -ds)".
Time after time I get the error grub-install: error: cannot find GRUB drive for /dev/sdb1. Check your device.map.
I've researched the issue but cannot find anything specific to my case. I have tried GPT and MBR formatting. I have tried copying files from the working USB to the SSD e.t.c. Any help much appreciated.

A: *

*Download the Boot Repair iso file.

*Make a bootable Boot Repair live USB flash drive with Rufus or UNetbootin. If you have a Debian-based distribution handy you can also use Startup Disk Creator to make a bootable Boot Repair live USB flash drive.

*Temporarily disconnect the cable(s) to the hard drive(s) on your host computer so that grub doesn't get installed on the wrong drive. You want grub to be installed on the SanDisk Extreme Pro portable SSD.

*Boot from the Zorin/Ubuntu USB stick and install the OS until you get to the grub-install: error message. Continue the installation anyway until it finishes.

*Reboot the computer with the bootable Boot Repair live USB flash drive selected as the first entry in the boot priority menu of the UEFI/BIOS.

*Click the Recommended repair button in the Boot Repair menu and run it. You don't need to click any of the Advanced options. Boot Repair will install grub on the SanDisk Extreme Pro portable SSD.

*Reboot to the Zorin/Ubuntu installer from its USB installation media.

*At the Installation type screen select the Replace ... with Ubuntu/Zorin option where ... is whatever Linux you installed on the SanDisk SSD the last time. The installer may identify this Linux as "generic Linux" instead of Ubuntu because it has a different bootloader which was installed there by Boot Repair. This time the installer will run all the way through until the end and replace the grub that Boot Repair installed on the SanDisk Extreme Pro portable SSD with the appropriate grub for your distribution.

*Reconnect the cable(s) to the hard drive(s) on your host computer.

A: I have finally found a work around to this:
The trick is to install refind BUT make sure that when you install it the usb / ssd onto which you installed linux is connected.
What was happening was that I was installing refind and it wasn't detecting available linux partitions with standard grub. However, when a linux (ext4) partition is available at the time of installation, refind will install extra drivers so that it can find linux partitions in the future.
Not quite the solution to the original issue but gets the job done.


text:
Q: casting de ponteiros Galera , Não  consigo  entender o porquê de fazer o casting entre ponteiros isso tem algum impacto no código ou e só para deixar o código legível como por exemplo essa linha de uma função:
 void* getPhysicalAddress (pdirectory* dir, uint32_t virt) {

   ...
   ...

   return (void*) ((uint32_t*) (pagedir[virt >> 22] & ~0xfff))[virt << 10 >> 10 >> 12];

}

O porque fazer (void*)((uint32_t*)(..)  por exemplo?
Gostaria de saber quando usar o cast de ponteiros?

A: Primeiramente você deve entender que os tipos (int, char, long, etc.) tem um tamanho definido pela plataforma, alguns mantém seu tamanho em todas as plataformas, como no caso do tipo char de 8 bits.
Os ponteiros apontam para endereço de memória, porém, você necessita dizer pra que tipo (tamanho) de região de memória você quer apontar, para que o compilador saiba como lidar com as informações que o ponteiro aponta (alocações, cálculos, etc).
O tipo void é uma exceção das regras de tipos. O tipo void tem tamanho de 1 byte, porém, ele não armazena nenhum dado. O ponteiro de tipo void só pode apontar pra outro ponteiro de mesmo tipo (essa regra serve para os todos os tipos), geralmente ele é usado para "generalizar" dados. É muito usado para quando você não sabe que tipo de dado irá receber, porém, ao recebe-lo é necessário fazer um cast para o tipo da variável que está recebendo esse dado, para que seja possível manipulá-lo (alocações, cálculos, atribuições, etc.).
O cast serve para forçar uma variável a ser um tipo diferente do que ela foi declara. Ele é usado para otimizar as operações e até mesmo tornar possível fazer operação entre duas ou mais variáveis sem que o resultado seja algo inesperado.
Referente a sua linha de código, vou dividi-la em quatro para fazer uma análise:
Primeira parte:
Nesse trecho é feita uma operação de de deslocamento do valor da variável virt, para pegar os 10 bits mais significativos do dado contido na variável e o valor resultante servirá de índice para o array pagedir. Do valor contido em pagedir de índice [virt >> 22] é feita mais duas operações, uma de negação (~) e uma AND (&) e resultará em um outro valor, que me parece ser um outro endereço:
pagedir[virt >> 22] & ~0xfff

Segunda parte:
O resultado da primeira parte, ao que me parece, retorna um endereço, então, nessa segunda parte está sendo indexado (apontada) outra região de memória a partir desse endereço:
(pagedir[virt >> 22] & ~0xfff))[virt << 10 >> 10 >> 12];

Os parênteses, em volta de pagedir e nas operações feitas com ela, querem dizer que o endereço resultante dessas operações será indexado pelos colchetes e dentro dos colchetes é feita uma indexação que equivale a uma aritmética de ponteiros: (...)[virt << 10 >> 10 >> 12]
Terceira parte:
Nessa momento o cast de (uint32_t*) está dizendo que a região de memória indexada (apontada), conforme dito na segunda parte, deverá ser tratada na base (tamanho) de uint32_t, então, qualquer operação (alocações, cálculos, atribuições, etc.) realizada será nessa base:
((uint32_t*) (pagedir[virt >> 22] & ~0xfff))[virt << 10 >> 10 >> 12];

Quarta parte:
Por fim, toda a operação é apontada por um tipo void, pois a função retorna um dado deste tipo e, ao meu ver, essa função está deixando para quem receber seu retorno definir como ele quer armazenar o valor retornado, dessa forma quem receber esse retorno terá que fazer um cast para algum tipo:
return (void*) ((uint32_t*) (pagedir[virt >> 22] & ~0xfff))[virt << 10 >> 10 >> 12];

Vou deixar um link para que vocÊ encontre mais informações sobre ponteiros: Programar em C/Ponteiros

A: O casting de um ponteiro para (void*) é necessário para algumas funções que utilizam um "ponteiro genérico" como argumento. Um ponteiro, além de apontar um endereço de uma variável, também guarda o tamanho em memória que aquela variável ocupa. Quando fazemos o casting, estamos alterando o tamanho da variável que o ponteiro armazena.


text:
Q: HTML heading unexpectedly calls for CSS class I cannot figure out why this header "RESEARCH AND DEVELOPMENT" inherits of the class .consult h3, when the html file is actually void of that class.
If I change the font-family inside .consult h2, h3 the title change accordingly.

What are the case scenarios for this to happen?

A: The comma in a CSS selector separates entire selectors, so the CSS:
.consult h2, h3 {

is the same as
.consult h2 {
    ...
}
.h3 {
    ... same stuff ...
}

So the CSS is applied to every h3 element.
Note that .consult h2 selects all h2 elements inside an element with class consult. There is no equivalent to parentheses in CSS, so to select all h2 and h3 elements inside an element with class consult, you must do:
.consult h2, .consult h3 {

If you meant to select all h2 and h3 that have class consult, you need:
h2.consult, h3.consult {


text:
Q: Series $q^{2k}$ How to show that $\sum_{k=1}^{\infty} q^{2k} = \frac{q^{2}}{1 - q^{2}}$, where $0<q<1$?
I gather that this sum is the limit to which a sequence of partial sums $\left( \sum_{k=1}^{n} q^{2k}  \right)_{n=1}^{\infty}$ converges.
I verified numerically that $\frac{q^{2}}{1 - q^{2}}$ is indeed the answer here. How to show it?
I reckon it's a convergence type proof, where for any $\epsilon>0$ I must pick $N \in \mathbb{N}$ such that $n \geq N \implies \lvert \sum_{k=1}^{n} q^{2k} - \frac{q^{2}}{1 - q^{2}} \rvert < \epsilon$, but I fail to do it. I try to get there by fixing some $\epsilon$ and checking different $N$, but this isn't leading me to the solution.

A: Observe that $$\sum\limits_{k=1}^{n} q^{2k} = \frac {q^2 (1 - q^{2n} )} {1 - q^2},\ \text {for any}\ n \geq 1.$$ Also observe that $q^{2n} \to 0$ as $n \to \infty$ for $0 < q < 1.$

A: Prove by induction that $\frac{q^2}{1-q^2}-\sum_{k=1}^nq^{2k}=\frac{q^{2(n+1)}}{1-q^2}$. If $|q|<1$, this $\to0$ as $n\to\infty$.


text:
Q: Como pegar o retorno Task de uma função (MediaTR) - Asp.net Core MVC Como faço para pegar o valor inteiro retornado através de uma Task? Já tentei fazer de várias maneiras, conforme vi em fóruns na net, mas não consegui. Tentei usar var customerId = Bus.SendCommand(registerCommand).Result, mas não funciona...
Obrigado a todos :)
public class CustomerCommandHandler : CommandHandler,
    IRequestHandler<RegisterNewCustomerCommand, int>,
{
    private readonly ICustomerRepository _customerRepository;
    private readonly IMediatorHandler Bus;

    public CustomerCommandHandler(ICustomerRepository customerRepository,
                                  IUnitOfWork uow,
                                  IMediatorHandler bus,
                                  INotificationHandler<DomainNotification> notifications) :base(uow, bus, notifications)
    {
        _customerRepository = customerRepository;
        Bus = bus;
    }

    public Task<int> Handle(RegisterNewCustomerCommand message, CancellationToken cancellationToken)
    {
        if (!message.IsValid())
        {
            NotifyValidationErrors(message);
            return Task.FromResult(0);
        }

        var customer = new Customer(Guid.NewGuid(), message.Name, message.Email, message.BirthDate);

        if (_customerRepository.GetByEmail(customer.Email) != null)
        {
            Bus.RaiseEvent(new DomainNotification(message.MessageType, "The customer e-mail has already been taken."));
            return Task.FromResult(0);
        }

        _customerRepository.Add(customer);

        if (Commit())
        {
            Bus.RaiseEvent(new CustomerRegisteredEvent(customer.Id, customer.Name, customer.Email, customer.BirthDate));
        }

        return Task.FromResult(customer.Id);
    }

    public void Dispose()
    {
        _customerRepository.Dispose();
    }
}

Chamada:
 public void Register(CustomerViewModel customerViewModel)
{
    var registerCommand = _mapper.Map<RegisterNewCustomerCommand>(customerViewModel);
    var customerId = Bus.SendCommand(registerCommand); /////????????????????????
}


text:
Q: JSF page - Why no validations yet process attribute required? The command button's actionListener event of the following JSF based xhtml page does not work. I do not have any validations on the page. The event only works when I add attribute process="@this" to button tag. As there are no validations, so I do not even get any validation error. But with process attribute I get success message returned by java side handler method. So I am kind of stuck without unwanted process attribute.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:c="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:p="http://primefaces.org/ui">

<h:head>

</h:head>

<h:body style="margin:0 auto !important;width:80% !important;">
<h:form id="form1">
    <p:panel id="rootPanel"
        style="background-color:#E8E8E8 ;width=90%;padding:10px;margin:10px;border:2px solid black;">
        <p:panel id="logoHeaderPanel"
            style="background-color:#E8E8E8 ;width=70%;padding:30px;margin:30px;border:1px solid black;">
            <h:panelGrid columns="2">
                <h:graphicImage library="images" name="./headerImage.gif"  />
                <h:outputLabel style="font-size:2.1em;margin-left:30px"
                    value="Demo App" />
            </h:panelGrid>
        </p:panel>
          <p:messages id="messages" autoUpdate="true"/>
        <p:panel id="mainContentPanel"
            style="background-color:#E8E8E8 ;width=70%;padding:60px;margin:30px;border:1px solid black;">
            <h:panelGrid columns="4">
                <h:outputLabel for="a" value="State Search" style="margin:10px;" />
                <p:inputText id="a" value="" style="margin:10px;" />
                <h:outputLabel for="b" value="Value" style="margin:10px;" />
                <p:inputText id="b" value="" style="margin:10px;" />

                <h:outputLabel for="c" value="City Search" style="margin:10px;" />
                <p:inputText id="c" value="" style="margin:10px;" />
                <h:outputLabel for="d" value="Value" style="margin:10px;" />
                <p:inputText id="d" value="" style="margin:10px;" />
            </h:panelGrid>
            <h:panelGrid columns="2" style="float:right;">
                <p:commandButton style="height:80px;" value="Generate Report"
                            id="reporting" actionListener="#{sampleBean.handlerMethod}" update="a"/>
            </h:panelGrid>
        </p:panel>
    </p:panel>
    </h:form>
</h:body>
</html>

Java side code
public void handlerMethod(ActionEvent actionEvent) {
        System.out.println("Inside Listener");
        FacesContext.getCurrentInstance().addMessage(
                null,
                new FacesMessage("Success! Action called."));
}

A: You cannot use value="" in the p:inputText. If you do not want to specify value, you should remove attribute value="".
<p:inputText id="a" style="margin:10px;" />


text:
Q: Button for Creative Coding Asteroids project I'm an undergrad and in one of my classes, we have this assignment to make the Asteroids game (you know, the retro one!) on Processing (which is basically a simplified Javascript program). I have the code for a button:
void setup()
{
size(1280, 720);
}

void draw()
{
background(0,0,0);
drawButton();
}
Boolean pointIsInRectangle(int left, int top, int right, int bottom, int pointX, int pointY)
{
if (pointX >= left
&& pointX <= right
&& pointY <= bottom
&& pointY >= top
)
  return true;
else
  return false;
}
void drawButton()
{
int left = 350;
int top = 145;
int right = 860;
int bottom = 220;

rectMode(CORNERS);
color background = color(0,0,0);
if (pointIsInRectangle(left,top,right,bottom,mouseX,mouseY))
{
  background = color(255);
}

// draw outer rectangle
stroke(255);
fill(background);
rect(left,top,right,bottom);

// draw caption
fill(255);
textSize(100);
text(" ASTEROIDS", left,bottom);
}

and I have the preliminary code for the ship for the game, but I need the button to get to an "in between" page so that when the button is clicked, it leads to a new screen that says "click anywhere to play game" and when any point in the screen is clicked, the ship appears and asteroids begin appearing and the game begins. HOW DO I GET THE BUTTON TO LEAD TO A NEW PAGE, AND HOW DO I CREATE THAT PAGE? I really cannot figure it out. Crossing my fingers that someone will be able to give me some guidance!!!!!
The actual result I'm seeing is that nothing is happening when the button is clicked. This makes sense because I don't know how to add the next page that says Click to Play Game, so this is the issue I'm facing. The code I have so far can be found above.

A: This is not question about a button, but about a game engine with multiple scenes.
Your game is a collection of screens (scenes). Every scene have definition of visuals, definition of logic, and definition of switch for another scene.
Here is the minimal solution of Your problem.
1 - Define visuals of Your screens in .display() method,
2 - Define logic condition for next screen switch in stateCondition().
boolean mouseReleased;
GameScreen screen;
GameScreen splashScreen;
GameScreen inBetweenPage;

void setup() {
  size(1280, 720);
  GameScreen splashScreen = new SplashScreen();
  GameScreen inBetweenPage = new InBetweenPage();

  splashScreen.setNextScreen(inBetweenPage);
  inBetweenPage.setNextScreen(splashScreen);
  screen = splashScreen;
  mouseReleased = false;
}

void draw() {
  screen.display();
  if (screen.stateCondition()) {
    screen = screen.getNextScreen();
  }
}

interface GameScreen {
  /**
   **   screen visual definition
   **/
  void display();

  /**
   **   screen change state condition
   **/
  boolean stateCondition();

  void setNextScreen(GameScreen scr);
  GameScreen getNextScreen();
}

class SplashScreen implements GameScreen {
  GameScreen nextScreen;
  int left = 350;
  int top = 145;
  int right = 860;
  int bottom = 220;

  void display() {
    background(0, 0, 0);
    rectMode(CORNERS);
    color background = color(0, 0, 0);
    if (pointIsInRectangle(left, top, right, bottom, mouseX, mouseY)) {
      background = color(255, 255, 255, 160);
    }

    // draw outer rectangle
    stroke(255);
    fill(background);
    rect(left, top, right, bottom);

    // draw caption
    fill(255);
    textSize(100);
    textAlign(CENTER, CENTER);
    text("ASTEROIDS", (left+right)/2, (top+bottom)/2-16);
  }

  boolean stateCondition() {
    if (mouseReleased && (mouseButton == LEFT)) {
      mouseReleased = false;
      return pointIsInRectangle(left, top, right, bottom, mouseX, mouseY);
    }
    return false;
  }

  GameScreen getNextScreen() {
    return nextScreen;
  }

  void setNextScreen(GameScreen target) {
    this.nextScreen = target;
  }
}

class InBetweenPage implements GameScreen {
  GameScreen nextScreen;
  int left = 0;
  int top = 0;
  int right = width;
  int bottom = height;

  void display() {
    background(0, 0, 0);
    // draw caption
    fill(255);
    textSize(24);
    textAlign(CENTER, CENTER);
    text("< click anywhere to play game >", width/2, height/2);
  }

  boolean stateCondition() {
    if (mouseReleased && (mouseButton == LEFT)) {
      mouseReleased = false;
      return pointIsInRectangle(left, top, right, bottom, mouseX, mouseY);
    }
    return false;
  }

  GameScreen getNextScreen() {
    return nextScreen;
  }

  void setNextScreen(GameScreen target) {
    this.nextScreen = target;
  }
}

Boolean pointIsInRectangle(int left, int top, int right, int bottom, int pointX, int pointY) {
  if (pointX >= left && pointX <= right && pointY <= bottom && pointY >= top) {
    return true;
  } else
    return false;
}

void mouseReleased() {
  mouseReleased = true;
}

A: There is a relatively simple solution to this problem, which would be to make some space for a special "splashscreen" state in your code. It would almost be ninja coding to implement it, although in this case as you are learning it's not taking shortcuts but more like climbing a new step in the learning stairwell. Here's a proof of concept which shows what I'm speaking about:
// this boolean keeps track of the current game state: splashscreen or not
boolean splashScreen = true;

void setup() {
  size(600, 400);
}

void draw() {
  background(0);

  // if the game has yet to start, show the splashscreen
  if (splashScreen) {
    drawSplashScreen();
  } else {
    playGame();
  }
}

// this method draws the splashScreen
// it could be coded in the 'draw()' method, but it's easier to read this way
void drawSplashScreen() {
  textAlign(CENTER);
  textSize(30);
  fill(255);
  text("THIS IS THE SPLASHSCREEN \n click anywhere to play the game", width/2, height/2);
}

// this method contains everything your game loop needs to work
void playGame() {
  textAlign(CENTER);
  textSize(40);
  fill(200, 0, 200);
  text("YOU ARE CURRENTLY \n PLAYING THE GAME", width/2, height/2);
}

void mouseClicked() {
  if (splashScreen) {
    splashScreen = !splashScreen;
  }
}

Here you have 2 game states: the splash screen and the game itself, but you could implement more than just these two. There's a design pattern called Finite State Machine that would be just perfect for your needs. Although you already have everything you need to code your assignment, let me explain a little further:
A FSM let you determine the context which can lead to another context and limit some actions to it's own context. A good example of this is Mario in the original Super Mario Bros game: when he's small, getting a magic mushroom will transform him into Super Mario. When he's Super, getting a flower will transform him into Fire Mario. But while small, getting a flower will only make him into Super Mario, not Fire Mario (in the ooold first game at least). That's because each one of these states have rules, and he cannot just jump from one to the other without regard for these.
Your game's logic has it's own rules too: you have the first screen with the "start" button. When this button is clicked, there's a second state where it says "click anywhere to play the game". If the user clicks, then the game itself starts. That makes for 3 states (3 screens if you like) where every state has it's own set of rules - which we often call 'business rules'.
We could schematize this assignment like this:

And here's the skeleton code that would implement such a game, including a bonus rectangle collision detection method:
// the game states are as follow:
// 0 is welcome screen with button
// 1 is click anywhere screen
// 2 is the game itself
int gameState = 0;

void setup() {
  size(600, 400);
}

void draw() {
  background(0);

  // let's use the right game state here
  switch(gameState) {
  case 0:
    drawWelcomeScreen();
    break;
  case 1:
    drawClickAnywhereScreen();
    break;
  case 2:
    playGame();
    break;
  }
}

void drawWelcomeScreen() {
  fill(0, 0, 100);
  rect(100, 100, 400, 100);

  textAlign(CENTER);
  textSize(30);
  fill(255);
  text("Click here to play", 300, 150);
  text("THIS IS THE WELCOME SCREEN", width/2, 50);
}

void drawClickAnywhereScreen() {
  textAlign(CENTER);
  textSize(30);
  fill(255);
  text("Click anywhere to play the game", width/2, height/2);
}

void playGame() {
  textAlign(CENTER);
  textSize(40);
  fill(200, 0, 200);
  text("YOU ARE CURRENTLY \n PLAYING THE GAME \n click anywhere to go \n back to the welcome screen", width/2, height/2);
}

void mouseClicked() {
  // now this will be more complicated, because you'll want to deal with clicks differently depending on the game state
  // which kinda answers the question as how we'll deal with this issue: same as in the 'draw()' method

  switch(gameState) {
  case 0:
    // if the click's coordinates are in the rectangle's coordinates (use math here, or a collision method)
    // (in fact, use math pretty much everywhere)
    // (I hope you like math)
    // anyway here's an old collision method I paste everywhere on SO, feel free to steal it and improve on it!
    // I wrote it as a student to deal with pretty much the same stuff that you're going through
    if (intersect(100, 100, 400, 100, mouseX, mouseY, 1, 1)) {
      gameState = 1;
    }
    break;
  case 1:
    gameState = 2;
    break;
  case 2:
    gameState = 0;
    break;
  }
}

// enter the xy coordinates, the width and the heigh of 2 rectangle shapes and it'll return true if they intersect
boolean intersect(float x1, float y1, float w1, float h1, float x2, float y2, float w2, float h2) {
  boolean checkX = false;
  boolean checkY = false;

  if ( (x1<x2 && (x1+w1)>x2) || (x1<(x2+w2) && (x1+w1)>x2+w2) || (x1>x2 && (x1+w1)<(x2+w2)) ) {
    checkX = true;
  }
  if ( (y1<y2 && (y1+h1)>y2) || (y1<(y2+h2) && (y1+h1)>y2+h2) || (y1>y2 && (y1+h1)<(y2+h2)) ) {
    checkY = true;
  }

  return checkX && checkY;
}

I hope I'm not confusing you with all this material. I'll try and keep an eye out for any question you may have about these things.
Good luck and have fun!


text:
Q: unexpected tINTEGER, expecting $end I'm learning ruby and can't figure out what's the problem here.
formatter = "%s %s %s %s"
puts formatter = % [1, 2, 3, 4]

Result:
ex8.rb:3: syntax error, unexpected tINTEGER, expecting $end
puts formatter = % [1, 2, 3, 4]
                        ^

A: You either a) Don't need that = sign:
formatter = "%s %s %s %s"
puts formatter % [1, 2, 3, 4]

or b) need to assign the result to formatter differently:
formatter = "%s %s %s %s"
puts formatter = formatter % [1, 2, 3, 4]

or
formatter = "%s %s %s %s"
formatter = formatter % [1, 2, 3, 4]
puts formatter

The former answer for b will assign the result to formatter and then output the result of that assignment, which will be the right-hand side. I'd recommend the latter (and you could of course condense the top two lines into a single line) just because it's clearer.
Edit:
Also, if you check the code in Learn Ruby the Hard Way, they're not reassigning anything to formatter. The point is that you can supply any four-item array via formatter % and it will produce the text content of those four items. I see it's just dipping into Ruby methods (and you may be unfamiliar with printf), but the following are equivalent:
puts formatter % [1, 2, 3, 4]
puts formatter.%([1, 2, 3, 4])

# And the very retro
puts sprintf(formatter, 1, 2, 3, 4)

In other words, while there are a few nuances for operators -- just some sugar that you can actually use things like %= to assign the result and you don't need the . separating the object and its method -- these are just methods. You can look up % in Ruby's documentation like any other method.

A: It's not completely clear what is that you are trying to do. Maybe this?
formatter = "%s %s %s %s"
puts formatter % [1, 2, 3, 4]
# >> 1 2 3 4

A: Well these are called format specification with arguments,
"I got the following values: %s, %d, %d and %d" % ["Tom", 2, 3, 4]
 => "I got the following values: Tom, 2, 3 and 4"
"%05d" % 123
 => "00123"

More you can find at http://ruby-doc.org/core-1.9.3/String.html#method-i-25


text:
Q: sql query to get bi-weekly data enter image description hereI want to know the start bi-week date and end bi-week date.
means i want to get bi-weekly data from the below table structure.
create table #temp(
    EmployeeID int,
    TEDate datetime,
    EmpFNamenvarchar(100),
    EmpLName nvarchar(100)
)
go

insert into #temp (EmployeeID ,EmpFName,EmpLName,TEDate)
Select 2019,'roz','Ahmad','2019-04-23'
union all
Select 2019,'roz','Ahmad','2019-04-17'
union all
Select 2019,'roz','Ahmad','2019-04-29'

select * from #temp

How to do it? I have used below approach but still getting wrong results at the end.
Select *,
       DATEADD(WEEK, DATEPART(wk, TEDate),
       DATEADD(YEAR, year(TEDate) - 1900, 0)) - 4 - DATEPART(DW, DATEADD(WEEK, DATEPART(wk, TEDate),
       DATEADD(YEAR, year(TEDate) - 1900, 0)) - 4) + 1 AS [BiWEEK_START],
       DATEADD(WEEK, DATEPART(wk, TEDate),
       DATEADD(YEAR, year(TEDate) - 1900, 0)) - 4 - DATEPART(DW, DATEADD(WEEK, DATEPART(wk, TEDate),
       DATEADD(YEAR, year(TEDate) - 1900, 0)) - 4) + 14 AS [BiWEEK_END]
from #temp

Desired results:
4/17/2019
4/14/2019
4/27/2019
4/22/2019
4/14/2019
4/27/2019
4/23/2019
4/14/2019
4/27/2019
4/29/2019
4/28/2019
5/11/2019
5/3/2019
4/28/2019
5/11/2019
5/6/2019
4/28/2019
5/11/2019
5/8/2019
4/28/2019
5/11/2019
5/13/2019
5/12/2019
5/25/2019

A: Ok, here are two solutions. The problem is, you have to be able to tell which bi week a TEDate belongs to just by looking at the TEDate, otherwise you have to define either a list of the bi weeks or tell your query where to start. For the second query you should be able to put in any bi week start date and it should still work.
DECLARE @bi_weeks TABLE
(
StartDate DATE,
EndDate DATE
);

INSERT INTO @bi_weeks VALUES
('20190317','20190330'),
('20190331','20190413'),
('20190414','20190427'),
('20190428','20190511'),
('20190512','20190525');

DECLARE @emp_data TABLE
(
    EmployeeID INT,
    TEDate DATETIME,
    EmpFName NVARCHAR(100),
    EmpLName NVARCHAR(100)
);

INSERT INTO @emp_data (EmployeeID ,EmpFName,EmpLName,TEDate) VALUES
(2019,'roz','Ahmad','2019-03-20'),
(2019,'roz','Ahmad','2019-04-01'),
(2019,'roz','Ahmad','2019-04-13'),
(2019,'roz','Ahmad','2019-04-23'),
(2019,'roz','Ahmad','2019-04-17'),
(2019,'roz','Ahmad','2019-04-29');

--This is the first way where we join to a list of known bi week start and end dates
SELECT ed.*, bw.*
FROM @emp_data ed
LEFT JOIN @bi_weeks bw ON ed.TEDate BETWEEN bw.StartDate AND bw.EndDate
ORDER BY 2

--This is the second way where we tell our query a known start date and then use it to
--calculate the rest of the start and end dates.
DECLARE @initial_bi_week_start_date DATE = '20190414';

With empdataCTE AS
(
SELECT *,
[initial_bi_week_start_date] = @initial_bi_week_start_date ,
[bi_week_start] =
DATEADD(DAY,
            (DATEDIFF(DAY, @initial_bi_week_start_date, TEDate) / 14 +
                    IIF(TEDate < @initial_bi_week_start_date, 1, 0) * -1) * 14,
            @initial_bi_week_start_date)

FROM @emp_data ed
)

SELECT *, DATEADD(DAY, 13, [bi_week_start]) [bi_week_end]
FROM empdataCTE;


text:
Q: Toggle active class in ng-repeat How can I toggle a class in ng-repeat when onclick each item.My code does not work.Thank you,
This is my code.

Token ID :

                    Online :

Chat Duration:

in my controller:
 $scope.onClickTab= function(x){
      $scope.selectedIndex= x;
    };

A: You should use
onClickTab($index)

not the id.


text:
Q: Data GridView Multiple Combox I have a datagridview called GridView1 which has two column each are combobox's, I need to be able to change the items in one of the comboboxes based on the first one. The combobox are dynamically created and the values are bound with single dataset. Initially when i load the form every thing comes perfect but when i change the value of the first combobox the second combobox values do not change. I tried with EditingControlShowing event of the gridview and then applying SelectedIndexChanged to the combobox but still could not figure it out.
Grid view Combox
DataGridViewComboBoxColumn seccol = new DataGridViewComboBoxColumn();
                    seccol.DataSource = semch.Tables["secall"];
                    seccol.Name = "SSSS";
                    seccol.DisplayMember = "SSSSNAME";
                    seccol.ValueMember = "SSSSID";
                    seccol.HeaderText = "SSSS";
                    seccol.DataPropertyName = "SSSSID";
                    seccol.DefaultCellStyle.Font = new Font("Microsoft Sans Serif", 10, FontStyle.Bold);
                    studpromo_gv.Columns.Add(seccol);
                    studpromo_gv.Columns["SEC"].DisplayIndex = 14;
                    studpromo_gv.Columns[14].HeaderCell.Style.BackColor = Color.LightSeaGreen;

EditingControlShowing event
ComboBox cb = e.Control as ComboBox;
            if (cb != null)
            {
                cb.SelectedIndexChanged -= new EventHandler(cb_SelectedIndexChanged);
                cb.SelectedIndexChanged += new EventHandler(cb_SelectedIndexChanged);
            }

Updated Code
if (studpromo_gv.CurrentCell.ColumnIndex == 13)
            {
                ComboBox cmbBox = (ComboBox)sender;
                //int semx = Convert.ToInt32(cmbBox.SelectedValue);
                int semy = studpromo_gv.CurrentRow.Index;
                if (cmbBox != null)
                {
                    try
                    {
                        using (MySqlConnection conn = new MySqlConnection(MySQLconnection))
                        {
                            conn.Open();
                            MySqlDataAdapter secgvda = new MySqlDataAdapter("SELECT ID,NAME FROM STABLE WHERE SID='" + cmbBox.SelectedValue + "'", conn);
                            DataSet semch = new DataSet();
                            secgvda.Fill(semch, "secall");

                            (studpromo_gv[14, semy] as DataGridViewComboBoxCell).DataSource = semch.Tables["secall"];
                            (studpromo_gv[14, semy] as DataGridViewComboBoxCell).DisplayMember = "NAME";
                            (studpromo_gv[14, semy] as DataGridViewComboBoxCell).ValueMember = "ID";

                            conn.Close();
                            conn.Dispose();
                        }
                    }
                    catch (Exception)
                    {
                        //Some Statements
                    }

A: Since you want to assign a different DataSource you can choose to add it to the second DataGridViewComboBox column itself or to that specific cell,
Since you would know the RowIndex and ColumnIndex you could very well set a different DataSource based on the first value selected
(dataGridView1[0,0] as DataGridViewComboBoxCell).DataSource = list of states
EDIT
Since you need to select the first item you can add this which should work fine
(studpromo_gv[14, semy] as DataGridViewComboBoxCell).Value = (studpromo_gv[14, semy] as DataGridViewComboBoxCell).Items[0]


text:
Q: Why doesn't Stack Exchange's markdown support traditional code block syntax(``` ... ```)? In Stack Exchange, we need Ctrl + K to format code.
As we know, most Markdown editors support this syntax:
```c++
int main()
{
}
```

In Stack Exchange, it will be rendered to:
c++
int main()
{
}

While with Ctrl + K, it will be rendered to:
int main()
{
}

I cannot figure why it isn't supported by Stack Exchange.

A: As far as I can tell, Stack Exchange markdown is based on the original Markdown, defined in 2004.
Taking a look on their website, it does not define the "Fenced code blocks" syntax, which was added only much later to other markdown extensions.
That's why SE doesn't support it. There is a very popular feature request asking to support it.


text:
Q: SQL Column width from bytes to characters I'm trying to calculate the maximum number of characters allowed in an SQL field.
For example, I create a table like this:
CREATE TABLE bla (
  TEST TEXT,
  SHORTER TEXT(30),
  NUMBER INT,
  SHNUMBER INT(30)
)

Using the PHP function mysqli_fetch_fields, like this:
$finfo = mysqli_fetch_fields($res);
foreach($finfo as $value) {
    printf("Name:     %s\n", $value->name);
    printf("max. Len: %d\n", $value->length);
    printf("Type:     %d\n\n", $value->type);
}

I get the following output:
Name: TEST  max.Len: 65535  Type: 252
Name: SHORTER  max.Len: 255  Type: 252
Name: NUMBER  max.Len: 11  Type: 3
Name: SHNUMBER  max.Len: 30  Type: 3

My question is: how can I convert this max lenght (represented as number of bytes) back to a number of decimals, characters, ...?

A: Use show columns command to retreive the information about the columns in your table. See the documentation page.


text:
Q: Distribution of Y=|X|
X ~ f(x) = K|x|, -1<x<2. Derive the distribution of Y=|X| and find the value of K.

I have proceed the problem like this, but I don't know how to solve this problem. Please help me with this.
Y=|X| Let F(X) & F(Y) denote their respective CDFs and f(x) and f(y) their PDFs.
CDF of F(Y) evaluated at  y<0 is  0
And, CDF of F(Y) evaluated at  y≥0 is
F(Y)= P(Y≤y)
=P(−y≤X≤y)
=P(X≤y)−P(X<−y)
= FX(y)-FX(−y)
Therefore,
FY(y)= FX(y)−FX(−y) ;y≥0
= 0            ;y<0

A:
CDF of $F_Y$ evaluated at $y<0$ is $0$ And, CDF of $F_Y$ evaluated at $y≥0$ is $$F_Y(y)~{= P(Y≤y) \\=P(−y≤X≤y) \\=P(X≤y)−P(X<−y) \\= F_X(y)-F_X(−y)}$$
Therefore, $F_Y(y)= \begin{cases}F_X(y)−F_X(−y) &;&y≥0 \\ 0 &;&y<0\end{cases}$

Indeed, so far so good.
Then by derivation: $f_Y(y) ~{= \begin{cases}f_X(y)+f_X(-y) &:& 0\leq y\lt 2\\0&:&\text{otherwise} \end{cases}\\=\begin{cases} 2K y&:& 0\leq y\lt 1\\Ky &:& 1\leq y\lt 2\\0&:& \text{otherwise}\end{cases}}$
So therefore $~~\qquad F_Y(y) ~{=\begin{cases}0&:& \qquad y\lt 0\\ K y^2&:& 0\leq y\lt 1\\K(y^2/2+1) &:& 1\leq y\lt 2\\1&:& 2\leq y\end{cases}}$


text:
Q: Bootstrap DatePicker format not recogined by ASP.NET MVC validator I'm using bootstrap datepicker in my ASP.NET MVC application. When I try to post the form, I'm getting error saying "The field Start Date must be a date." I'm using "jquery.validate.js"to validate in client side. My date picker format, I have customized as "dd-MM-yyyy" (Eg: 12-May-2016).
This error is happening only in IE, it works fine in Chrome browser.
By googling, I tried different ways:
1) Setting up Data Annotations in Model
[Required]
[Display(Name = "Start Date")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]

2) Edited date function in jquery.validate.js
date: function (value, element) {
            return value.match("^\d{2}-[a-zA-Z]{3}-\d{4}$");
        },

But nothing seems to be working. Most of the questions are discussing around JQuery datepicker, but mine is bootstrap datepicker.
Any help would be appreciated.

A: There are  some fixes:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime BirthDate { get; set; }

2.
Go global asax and add:
protected void Application_BeginRequest(Object sender, EventArgs e)
    {

        CultureInfo newCulture = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
        newCulture.DateTimeFormat.ShortDatePattern = "dd/MMM/yyyy";
        newCulture.DateTimeFormat.DateSeparator = "/";
        Thread.CurrentThread.CurrentCulture = newCulture;
    }

*And Finaly try this in  your View
@Html.TextBoxFor(model => model.BirthDate, "{0:dd/MM/yyyy}", new {@class = "date-picker form-control"})


text:
Q: System.Web.HttpException File does not exist - Page loads just fine (ASP.NET) I'm using Log4Net and logging everytime my ASP.NET-Application throws an error:
    protected void Application_Error(object sender, EventArgs e)
    {
        Exception ex = Server.GetLastError();
        Log.Error("An error occurred", ex);
    }

Alas, everytime I visit a page on my application, a System.Web.HttpException is caught, "File does not exist".
Here's the Stack Trace:
bei System.Web.StaticFileHandler.GetFileInfo(String virtualPathWithPathInfo, String physicalPath, HttpResponse response)
bei System.Web.StaticFileHandler.ProcessRequestInternal(HttpContext context, String overrideVirtualPath)
bei System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state)
bei System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
bei System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

I don't have any clue how to debug this, this happens on my ASP.NET Development Server and on an IIS 7.5 I deploy it on.

A: I bet it's the favicon.ico that Google Chrome always requests and which you forgot to include. But to be sure you could trace the request url:
protected void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    Log.Error("An error occurred", ex);
    Log.Error("Requested url: ", Request.RawUrl);
}

Now in your log file you should see:
Requested url: /favicon.ico

or something else like robots.txt when for example web crawlers attempted to crawl your site.

A: I have same error:
There were some file references in CSS. That does not exist in directory. So it gave this error.
I created Image Files, so error disappeared.
So make sure that file reference that you have given is exists in your directory

A: Check your HTML output of your page in case of using url with tilda "~/"
You need to use @Url.Content() to fix it
http://clubmicrosoft.net/post/2014/02/28/File-does-not-exist.aspx


text:
Q: Multiple integrals in polar coordinates So, I was practicing some problems and found this:
$$\int_0^2 \int_0^{\sqrt{4-x^2}} e^{x^2+y^2} dydx.$$
While converting from Cartesian to polar coordinates, $\theta$ limits will be from $0$ to $\pi /2$ but what about the $r$ limits?
I am stuck on this.
Is it $0$ to $2cosec θ$?

A: The integration region corresponds to the part of a circle with radius $2$ centered at $(0,0)$ that lies in the first quadrant. So the distance to the origin, $r$, is between $0$ and $2$. the integral becomes
$$
\int_0^{\pi/2} \int_0^2 r e^{r^2} dr d \theta = \frac{\pi}{2} [\frac 12 e^{r^2}]_0^2 = \frac{\pi}{4}(e^4-1)
$$


text:
Q: Android: How to get Battery level status more accurately? I want to get android battery info with more accuracy.
I've found some code which gives battery level and scale but it isn't helping me out much.
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

I need more information that this. I need battery level with upto 2 places decimal accuracy.
P.S. I saw route '/sys/class/power_supply/battery/'. but i didn't find info which I want.

A: Try this its working for me
private void getBatteryPercentage() {
    BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            context.unregisterReceiver(this);
            int currentLevel = intent.getIntExtra(
                    BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            int level = -1;
            if (currentLevel >= 0 && scale > 0) {
                level = (currentLevel * 100) / scale;
            }
    Toast.makeText(getApplicationContext(), "Battery Level Remaining: " + level
                    + "%", Toast.LENGTH_LONG).show();

        }
    };
    IntentFilter batteryLevelFilter = new IntentFilter(
            Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}


text:
Q: Java 11 package is declared in module which does not export it I have created two modular programs. One is JavaFX modular project that contains module-info.java like:
module checker {
    requires javafx.fxml;
    requires javafx.controls;
    requires TextInputProgram; // Btw, IDEA shows me here "Ambiguous module reference"
    exports sample;
    opens sample;
}

Another Maven project that contains module-info.java like:
module TextInputProgram {
    requires selenium.api;
    requires selenium.chrome.driver;
}

So, I added modular maven project as external jar into JavaFX (via Project Structure in libs and in module-info via requires I specified jar). Also I added variable that contains external jar for compilation (in addition to PATH_TO_FX and PATH_TO_FX_MODS):
set EXTERNAL_JAR="...\out\artifacts\TextInputProgram_jar"

But when I'm trying to compile the project via command:
dir /s /b src\*.java > sources.txt & javac --module-path %EXTERNAL_JAR%;%PATH_TO_FX% -d mods/checker @sources.txt & del sources.txt

following this tutorial
I'm getting from JavaFX project class the error:
\src\sample\Controller.java:9: error: package project is not visible
import project.SeleniumProgram;
       ^
  (package project is declared in module TextInputProgram, which does not export it)
1 error

Package is declared in module which does not export it

import project.SeleniumProgram I imported in JavaFX project to use classes from external jar.
Updated:
If I add exports project; inside module-info.java of maven project then I see the error in JavaFX module-info.java:

If I delete requires TextInputProgram; then I have another error from import:

Am I missing something here? I'm trying to get executable Jar of these two programs.

A: As discussed throughout the comments, there are a few possible issues here:

*

*Module definition

*Local jars and dependencies
Based on the modular projects posted, I'll create a small demo multi-modular project to explain both problems.
Maven multi-modular project
Using your IDE, create a Maven project, then add two modules, TextInputProgram and checker, like:
Parent pom
<groupId>org.openjfx</groupId>
<artifactId>hellofx</artifactId>
<version>1.0-SNAPSHOT</version>
<modules>
    <module>TextInputProgram</module>
    <module>checker</module>
</modules>
<packaging>pom</packaging>

TextInputProgram pom
<parent>
    <groupId>org.openjfx</groupId>
    <artifactId>hellofx</artifactId>
    <version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>TextInputProgram</artifactId>

<properties>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.141.59</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <release>11</release>
            </configuration>
        </plugin>
    </plugins>
</build>

Module-info.java
module TextInputProgram {
    requires selenium.api;
    requires selenium.chrome.driver;

    exports project to checker;
}

Checker pom
<parent>
    <artifactId>testMods</artifactId>
    <groupId>org.openjfx</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>checker</artifactId>

<dependencies>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-controls</artifactId>
        <version>12.0.2</version>
    </dependency>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-fxml</artifactId>
        <version>12.0.2</version>
    </dependency>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>TextInputProgram</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <release>11</release>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-maven-plugin</artifactId>
            <version>0.0.3</version>
            <configuration>
                <mainClass>sample.Main</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>

Module-info.java
module checker {
    requires javafx.fxml;
    requires javafx.controls;
    requires TextInputProgram;

    opens sample to javafx.fxml;

    exports sample;
}

(Code of both modules is irrelevant at this point).
Solutions included
Now note that you have to add this in the TextInputProgram module descriptor:
exports project to checker;

if you want to let checker module to access TextInputProgram's project package.
This will solve this error:

package project is declared in module TextInputProgram, which does not export it

Also, note that I've included this dependency in the checker project:
<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>TextInputProgram</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

Even having two modules, under the same parent, you need to include the dependency from one module to the other. Otherwise this will fail (module not found):
requires TextInputProgram;

You can run mvn clean install in the TextInputProgram module, to install org.openjfx:TextInputProgram:1.0-SNAPSHOT in your local repository .m2.
Then you can run mvn clean javafx:run int the checker module, to run the GUI project.
It is worth mentioning that it is not a good idea to combine both maven dependencies with jar files. If you end up using both, you will get this error:

Module 'checker' reads 'project' from both 'TextInputProgram' and 'TextInputProgram'

This message means that there are two modules in the module path with the exact same name, one the maven dependency, the other one, the jar artifact.
In order to distribute your project and modules, it is better to use the maven approach, and avoid having jar files in lib folders. Later on your modules will be published as separated artifacts, and you won't need to modify your pom files (other than to update the version numbers).


text:
Q: Creating a map from an array of arrays in Ruby I'm trying to write a function in Ruby which can take in a in an array of arrays, and convert it into a hash. This will be used to simulate sentences and create arbitrary word sequences. The resulting map will be helpful in generating all combination of sentences available with the current sentence rules.
How do I go about achieving this? I'm a bit lost as to where to start.

A: Try this:
arr = [ ["<start>", "The   <object>   <verb>   tonight."],
        ["<object>", "waves", "big    yellow       flowers", "slugs"],
        ["<verb>", "sigh <adverb>", "portend like <object>", "die <adverb>"],
        ["<adverb>", "warily", "grumpily"] ]

arr.map { |ar| [ar.shift, ar.map { |str| str.split }] }.to_h
#=>
#{ "<start>"  => [["The", "<object>", "<verb>", "tonight."]],
#  "<object>" => [["waves"], ["big", "yellow", "flowers"], ["slugs"]],
#  "<verb>"   => [["sigh", "<adverb>"], ["portend", "like", "<object>"], ["die", "<adverb>"]],
#  "<adverb>" => [["warily"], ["grumpily"]] }

ar.shift takes the first element of each subarray. The block used with ar.map splits (on whitespace) the remaining elements into arrays. Finally to_h converts the resulting array into a hash.


text:
Q: mat-menu: overlay which comes from mat-menu prevent below menu being done mouseenter Summary
I tried to create a side navigation which contains several menus by using mat-nav and mat-menu, then its menu open by mouseenter.
But, the second menu didn't open its submenu.
I don't know how to cope with this problem, want to get some advice.
Help...
What I checked
It seems that the first's submenu overlay prevent the second being done.
So, when I checked mouseenter from bottom to top,(The second to the first) then it worked.
Sample
I created a sample.
Here is my stackblitz.
(Please click a hamburger menu on header, then hover side menu from to bottom.)
https://stackblitz.com/edit/angular-g88bvg
Expectation
My Expectation is to open the second menu when I do hover side navigation from top to bottom.
And, I want the floating menu to stay until another menu is focused.

A: If the overlay overlapping the hovered mat-list-item is not an issue for you then just set it to true and it will trigger your openSubMenu method just fine, example :

    <mat-toolbar color="primary" class="example-toolbar">
        <button mat-icon-button (click)="sidenav.toggle()"><mat-icon>menu</mat-icon></button>

Responsive App

  </mat-toolbar>

<mat-sidenav-container (backdropClick)="clickBack()" >

    <mat-sidenav class="side-container" mode="over" [fixedInViewport]="true" [opened]="false" #sidenav>

        <mat-list>
            <mat-list-item [matMenuTriggerFor]="menus" #menuTrigger="matMenuTrigger">
                Apple
            </mat-list-item>
            <mat-menu #menus="matMenu" [overlapTrigger]="true" [hasBackdrop]="false" class="top-sub-menu">

aaa

aaa

aaa

            </mat-menu>
        </mat-list>

        <mat-list>
            <mat-list-item [matMenuTriggerFor]="menus2" #menuTrigger2="matMenuTrigger">
                Benjamine
            </mat-list-item>
            <mat-menu #menus2="matMenu" [overlapTrigger]="true" [hasBackdrop]="false" class="top-sub-menu">

bbb

bbb

bbb

            </mat-menu>
        </mat-list>

    </mat-sidenav>
  <mat-sidenav-content class="main-contents">
    Contents
  </mat-sidenav-content>
</mat-sidenav-container>

EDIT:
I found your problem, after looking on your css file I noticed that you added margin to both of your mat-menu's and it can be seen on your inspect element that the overlay would overlap your mat-list-item's, to fix this you add the style position absolute so that it still applies your margin style but doesn't overlap the mouse inspect of the child elements, like so :
::ng-deep .top-sub-menu {
    font-size: 14px;
    color: black;
    min-width: 80px;
    margin-left: 60px;
    text-align: center;
    position:absolute;
}

If you turn off [overlapTrigger] again you get the previous behavior of the overlay ( you can turn this on or to your liking )


text:
Q: How to calculate "gcd product" $\operatorname{gcdp}(n,m)=\gcd(n,1)\gcd(n,2)\cdots\gcd(n,m)$ Given two numbers $m$ and $n$ how can we calculate the gcd product of any two numbers i.e, $\operatorname{gcd p}(n,m)=\gcd(n,1)\gcd(n,2)\cdots\gcd(n,m)$ where gcd is the greatest common divisor?
Can this be solved using Euler Totient function?
My Approach:-
For any prime number $n$, $\operatorname{gcdp}(n,m)=n^{\operatorname{floor}(m/n)}$.
Is there any way to solve it for any non-prime $n$?

A: Let
$$f_m(n)=\gcd(n,1)\gcd(n,2)\gcd(n,3)\cdots \gcd(n,m).$$
To extend your computation of $f_m(n)$ beyond the primes, note that fox fixed $n$ the function $f_m$ is multiplicative: If $\gcd(a,b)=1$, then $f_m(ab)=f_m(a)f_m(b)$.
Thus it is enough to know $f$ at prime powers. In particular, since you know $f_m(p)$ for prime $p$, you know $f_m(n)$ for all square-free $n$.
Now let us get a handle on $f_m(p^2)$, where $p$ is prime. We will pick up a $p$ for every number $i\le m$ such that $i$ is divisible by $p$. We will pick up an extra $p$ for every number $i\le m$ which is divisible by $p^2$. Thus the total number of $p$'s that we pick up is $\left\lfloor\frac{m}{p}\right\rfloor+\left\lfloor\frac{m}{p^2}\right\rfloor$. That gives us the exponent of $p$ in $f_m(p^2)$.
Exactly the same reasoning can be used to find the exponent of $p$ in $f_m(p^3)$. We get $\left\lfloor\frac{m}{p}\right\rfloor+\left\lfloor\frac{m}{p^2}\right\rfloor+ \left\lfloor\frac{m}{p^3}\right\rfloor$. The idea readily generalizes to $f_m(p^k)$.
Thus we can get an explicit expression for $f_m(n)$, once we know the prime power factorization of $n$.


text:
Q: WkHtmlToPdf grey border around images I'm creating a PDF using the Wkhtmltopdf library.
Everything is working fine, except one little detail: I overlap two images with transparent background to another background image.
This is the result:
The background image is the one with the trees and the sky, each character is in a different image with transparent background. So the result is quite perfect except for the grey border around each person.
Is it possible to remove it?

A: Quick fix: Load image in gimp, go to layers -> transparency -> remove alpha layer. Re-export image as PNG and try the conversion again.


text:
Q: Laravel excel can't handle japanese heading properly I am using laravel excel to upload a excel file. The file contains heading at the very top. However, when the heading is in Japanese it is not being processed properly.
For example, if my file is like
+---------+--------+-------+
| bango   | name   | level |
+---------+--------+-------+
| nihongo | 日本語 | 8     |
+---------+--------+-------+
| test01  | test01 | 12    |
+---------+--------+-------+

It gives the following output,

This is the correct output.
However, when I change the heading to include Japanese then it doesn't work correctly.
My file is like,
+---------+--------+--------+
| 番号    | 名前   | ラベル |
+---------+--------+--------+
| nihongo | 日本語 | 8      |
+---------+--------+--------+
| test01  | test01 | 12     |
+---------+--------+--------+

The output becomes

I tested to mix this and put some headers in English and some in Japanese.
My file is like,
+---------+--------+--------+
| 番号    | name   | ラベル |
+---------+--------+--------+
| nihongo | 日本語 | 8      |
+---------+--------+--------+
| test01  | test01 | 12     |
+---------+--------+--------+

And my result becomes,

Although, the result gives name values correctly but the serial is incorrect. name values should be before level but it is not.
My controller function is like,
public function post($id)
    {
        $array  = (new DeliveryImport)->toArray(request('file'));
        dd($array);
    }

And my DeliveryImport.php is like,
class DeliveryImport implements ToModel, WithHeadingRow
{
    use Importable;
    public function model(array $row)
    {
    }
}

Please, note that, the code doesn't work only when there are Japanese on heading. If there is Japanese on other places then it works without a problem.

A: I have solved the problem. The solution is to change in config/excel.php.
In that file find imports' => 'heading_row'.
Then change the formatter from slug to none.
It worked flawlessly after that.

A: Or you can also put these above, outside your function
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
HeadingRowFormatter::default('none');


text:
Q: How do I remove the numbering at the end of each line? This code
\begin{align}
y'' & =\frac{-4[ \sin(2x)(3+2y)+\cos(2x)y']}{(3+2y)^2} \\
& = ... \\
& = \frac{-4[ \sin(2x)(3+2y)^2+2\cos^2(2x)]}{(3+2y)^3}=:f_x \\
\end{align}

produces this output

However, I do not want the numbers at the end of each line in the code to exist. How do I remove them? I'm guessing it has something to do with the packages I've used? Here are most of them if they're helpful (I've excluded some matlab formatting code because I don't think it influences)
\usepackage[utf8]{inputenc}
\usepackage[english, greek]{babel}
\usepackage[T1, T2A]{fontenc}
\usepackage{mathtools}
\usepackage{amsmath}
\usepackage{listings}
\usepackage{color} %red, green, blue, yellow, cyan, magenta, black, white
\definecolor{mygreen}{RGB}{28,172,0} % color values Red, Green, Blue
\definecolor{mylilas}{RGB}{170,55,241}
%matlab
\usepackage{bigfoot} % to allow verbatim in footnote
\usepackage[numbered,framed]{matlab-prettifier}

\usepackage{pdfpages}
\usepackage[final]{pdfpages}

\pagenumbering{gobble}

\setlength{\parindent}{4em}
\setlength{\parskip}{1em}
\renewcommand{\baselinestretch}{1.5}
\usepackage{natbib}
\usepackage{graphicx}
\usepackage{extarrows}


text:
Q: A suitable text editor for C that includes lint & cstyle? I'd like to use a nice C code-editor, that would have built-in support for:

*

*Code-colouring for C, Make, XML, Java, etc.

*Lint

*Cstyle

*Works under Ubuntu

*Possibly a nice visual debugger integrated, too?

I'd rather not use an IDE, as most of them seem to me somewhat clumsy with C.
I am a former Java dev, so I'm sorry if I sound boring to some.
Thanks guys!

A: You can try using VIM. VIM has a high learning curve in the beginning but it's excellent once you are highly acquainted with it. VIM also has many excellent plugins like NERD-Tree and Command-T which allows you to search for file names in your directory tree with just a couple keystrokes. VIM is also fast with many nice built in functionalities and it requires minimized computer resource so it's very fast on most computer (works real well for computers with limited resources). VIM also has syntax highlight and formatting for almost all the languages that you can name. It can be a standalone editor or you can equip it with enough plugins to make it the fastest IDE ever built. Good luck with your choices :)

A: Emacs will probably do, but it might be cumbersome to adjust everything to your needs and to get used to it.
Emacs comes bundled with C, Java, XML, Make, and support for other languages. Almost every language can be plugged in and is already plugged in by someone else.
Works of course under Ubuntu and integrates well with GDB.


text:
Q: Android: UI issue with custom dialog I need to show dialog in my app as shown:

Earlier I was using Popup window, so it appeared correctly. But, I changed it later to DialogFragment since, other dialogs similar to this one will have ListViews and Tabs. So, using DialogFragment would be more flexible.
After I changed it to DialogFragment, it appeared as follows:

This is my code for Dialog Fragment:
public class AddTransactionDialogFragment extends DialogFragment {

private final String TAG = "AddTransactionDialog";
private View anchorView; // Anchor view here in Dollar button

private int dialogHeight, dialogWidth; // Width and height are the size this
                                        // dialog should have

private View contentView;

public AddTransactionDialogFragment() {
}

public AddTransactionDialogFragment(View anchorView, int dialogHeight,
        int dialogWidth) {
    this.anchorView = anchorView;
    this.dialogHeight = dialogHeight;
    this.dialogWidth = dialogWidth;
    Log.e(TAG, "Dialog width: " + dialogWidth + " Dialog height: "
            + dialogHeight);
}

public static AddTransactionDialogFragment newInstance(
        FriendsDAO mFriendsDao) {
    AddTransactionDialogFragment fragment = new AddTransactionDialogFragment();

    Bundle args = new Bundle();
    args.putParcelable("friendsDao", mFriendsDao);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setStyle(STYLE_NO_FRAME, R.style.AddTransactionDialog);
}

@Override
public void onStart() {
    super.onStart();

    Window window = getDialog().getWindow();
    WindowManager.LayoutParams params = window.getAttributes();
    params.dimAmount = 0.2f;
    window.setAttributes(params);

    window.setBackgroundDrawableResource(android.R.color.transparent);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    contentView = inflater.inflate(R.layout.add_transaction_popup,
            container, false);
    setDialogPosition();
    return contentView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

private void setDialogPosition() {
    if (anchorView == null) {
        return;
    }
    int[] location = new int[2];
    anchorView.getLocationOnScreen(location);
    int anchorViewX = location[0];
    int anchorViewY = location[1];

    Log.e(TAG, "AnchorViewX: " + anchorViewX + " AnchorViewY: "
            + anchorViewY);
    Window window = getDialog().getWindow();

    window.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);

    window.setBackgroundDrawable(new ColorDrawable(
            android.graphics.Color.TRANSPARENT));

    WindowManager.LayoutParams params = window.getAttributes();
    params.copyFrom(window.getAttributes());

    Log.e("AddTransactionDialog",
            "Anchor view width: " + anchorView.getWidth());
    Log.e("AddTransactionDialog",
            "Anchor view height: " + anchorView.getHeight());

    params.x = anchorViewX - anchorView.getWidth();
    params.y = anchorViewY - anchorView.getHeight();
    params.height = dialogHeight;
    params.width = dialogWidth;
    window.setAttributes(params);
}

public int dpToPx(float valueInDp) {
    DisplayMetrics metrics = getActivity().getResources()
            .getDisplayMetrics();
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
            valueInDp, metrics);
}
}

add_transaction_popup.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/left_popup_bg"
android:orientation="vertical" >

<include
    android:id="@+id/header"
    android:layout_width="wrap_content"
    layout="@layout/transactionheader" />

<RelativeLayout
    android:id="@+id/relTransactionPanel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/header"
    android:layout_alignRight="@+id/header"
    android:layout_below="@+id/header"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="60dp" >

    <LinearLayout
        android:id="@+id/linButtonPanel"
        style="?android:attr/buttonBarStyle"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btnIOwe"
            style="?android:attr/buttonBarButtonStyle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="0.5"
            android:background="@drawable/btn_pink"
            android:text="@string/i_owe"
            android:textColor="@color/red_shade_2"
            android:textSize="18sp" />

        <Button
            android:id="@+id/btnTheyOwe"
            style="?android:attr/buttonBarButtonStyle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="0.5"
            android:background="@drawable/btn_green"
            android:text="@string/they_owe"
            android:textColor="@color/green_shade_2"
            android:textSize="18sp" />
    </LinearLayout>

    <EditText
        android:id="@+id/edtTransactionDesc"
        style="@style/transactioninputTextStyle"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_alignLeft="@+id/linButtonPanel"
        android:layout_alignRight="@+id/linButtonPanel"
        android:layout_below="@+id/linButtonPanel"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:background="@drawable/transaction_edittext_bg"
        android:hint="@string/description"
        android:paddingLeft="10dp" />

    <EditText
        android:id="@+id/edtTransactionAmt"
        style="@style/transactioninputTextStyle"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_alignLeft="@+id/linButtonPanel"
        android:layout_alignRight="@+id/linButtonPanel"
        android:layout_below="@+id/edtTransactionDesc"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:background="@drawable/transaction_edittext_bg"
        android:hint="@string/amount"
        android:inputType="number"
        android:paddingLeft="10dp" />

</RelativeLayout>

<RelativeLayout
    android:id="@+id/relAddTransaction"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/relTransactionPanel"
    android:layout_marginTop="100dp" >

    <View
        android:id="@+id/view1"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="18dp"
        android:background="@color/green_shade_3" />

    <TextView
        android:id="@+id/txtAddTransaction"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/add"
        android:textColor="@color/green_shade_3"
        android:textSize="18sp" />

    <ImageView
        android:id="@+id/imgPay"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/view1"
        android:layout_marginRight="18dp"
        android:contentDescription="@string/app_name"
        android:src="@drawable/pay_green" />

    <View
        android:id="@+id/view2"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_below="@+id/imgPay"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="18dp"
        android:background="@color/green_shade_3" />
</RelativeLayout>

transactionheader.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="65dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="18dp"
android:layout_marginTop="15dp"
android:orientation="vertical" >

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_toLeftOf="@+id/friendsImage"
    android:orientation="vertical" >

    <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="2dp"
        android:background="@color/bro_name_color" />

    <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="6dp"
        android:background="@color/bro_name_color" />

    <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_marginLeft="25dp"
        android:layout_marginRight="2dp"
        android:layout_marginTop="6dp"
        android:background="@color/bro_name_color" />
</LinearLayout>

<com.dzo.moneybro.ui.CircularImageView
    android:id="@+id/friendsImage"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:layout_centerInParent="true"
    android:src="@drawable/rotatetrans" />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_toRightOf="@+id/friendsImage"
    android:orientation="vertical" >

    <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="5dp"
        android:background="@color/bro_name_color" />

    <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="6dp"
        android:background="@color/bro_name_color" />

    <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="25dp"
        android:layout_marginTop="6dp"
        android:background="@color/bro_name_color" />
</LinearLayout>

How can I get the desired dialog(as shown in first image) using dialog fragment?

A: For the content view, you are setting for DialogFragment, have you tried to set the layout_height to wrap_content?
The problem here is the layout_height is match_parent.


text:
Q: How to keep one specific row while dropping all other unnecessary rows in scala spark dataframe? Just as the title, in scala spark, if I have a dataframe like below:
+-------------+----------+
| key         | Time     |
+-------------+----------+
|  1          |        1 |
|  1          |        2 |
|  1          |        4 |
|  2          |        2 |
|  2          |        3 |
+-------------+----------+

For same key, how can I only keep the key with the least time and drop all other unnecessary row? In this case, for key 1, it has 3 rows with different time, the least time is 1, so I only want to keep the key 1, time 1 row and drop other 2 rows for key 1. Same with key 2, I only want to keep key 2, time 2, so I drop the key 2, time 3 row. The format of key is LongType and the format of time is StringType. If there is some way to achieve this?
+-------------+----------+
| key         | Time     |
+-------------+----------+
|  1          |        1 |
|  2          |        2 |
+-------------+----------+

I tried to use drop or filter function, but I don't think they works.

A: Try something similar to this, my own data here of course:
%scala

import spark.implicits._
import org.apache.spark.sql.functions._

val df = sc.parallelize(Seq( (1,7), (1,8), (1,9), (2,2), (2,99) )).toDF("i", "c")
df.groupBy($"i").agg(min($"c")).show()

returns:
+---+------+
|  i|min(c)|
+---+------+
|  1|     7|
|  2|     2|
+---+------+


text:
Q: AngularJS - Dynamically Load Javascript Snippets When Model Changes I'm hoping to load and unload javascript snippets dynamically when a model changes using ngSanitize.
Here's a demo showing what I'm trying to do:
http://jsbin.com/wenoz/5/edit?html,output
The logic goes like this:
* Store multiple snippets of JS in a database or string variables
* Load the JS into the DOM dynamically when the user changes an Angular model
* Remove any existing snippet in the DOM an instantiate the new snippet

Ideas? Thanks!

A: You can't completely get rid of javascript run when changing, once it executes it becomes part of the environment.  You could use an iframe to create a separate environment that doesn't have direct access to your page if that's what you want.  If all you want to to is run the scripts consecutively, you could just put it in an array and use ng-repeat on your script so it creates a new tag each time (JSBIN):

A Demo to Dynamically Add/Remove Javascript with AngularJS

<button ng-click="setScript(one)">One</button>
<button ng-click="setScript(two)">Two</button>
<button ng-click="setScript(three)">Three</button>


text:
Q: A sequence $(1,2,3,4,5,6)$ while rolling a die We roll the dice infinitely many times. What is the probability that we get the sequence $(1,2,3,4,5,6)$ infinitely many times?
I thought about using Bernoulli trials, but I don't get any results.

A: $P=1$. Let's say a "trial" consists of rolling a die $6$ times. Say $p>0$ is the probability that any individual trial has outcome $(1,2,3,4,5,6)$. Call that a "good" trial; anything else is "bad".
The probability of $N$ bad trials in a row is $(1-p)^N$, which tends to $0$. So the probability of at least one good trial is $1$. Now start over after your first good trial; the probability of another good trial later is also $1$...

A: Are you rolling one infinite sequence $a_1, a_2, a_3, \dots$ and looking at subsequences, or rather rolling infinitely many sequences of length 6? Regardless, the probability will be 1. For fixed $k$, the probability $P(E_k)$ of the sequence occurring at most $k$ times in the first $n$ terms will tend to 0 as $n \to \infty$. Since $E_1 \subseteq E_2 \subseteq \dots$ we conclude $P(\bigcup_k E_k) = 0$, hence the complement of this union (sequence occurring infinitely many times) must have probability 1.

A: Now I'm no expert in probability, but wouldn't any given sequence of numbers appear an infinite amount of times? This seems related to the infinite monkey theorem, I think you should read up on that to get an answer to your question. I know that the probability of getting this sequence in 6 rolls is $\frac{1}{6^6}=\frac{1}{46656}$ so with an infinite number of rolls, we can expect this to happen an infinite number of times, with each occurrence happening approximately once for every 46656 trials.