SwiftUI actionSheet into .tabItem

Question: I'm trying to insert a actionSheet into action button into .tabItem. I only see a View with the text "Test 1". Can't make it display a menu with different options?. Thanks in advance.
@State var showActionSheet = false

...
var actionSheet : ActionSheet{

    ActionSheet(title: Text("Crear"), message: Text("Selecciona opción"), buttons: [
        .default(Text("Opción 1")),
        .default(Text("Opción 2")),
        .destructive(Text("Cancel"))
    ])
}

...
        }.tag(1)

            Text("Test 1")

            .tabItem {
                VStack {
                    Image(systemName: "1.circle")

                    Button(action: {
                        self.showActionSheet.toggle()
                    }) {
                        Text("Display Action Sheet")
                    }
                    .actionSheet(isPresented: $showActionSheet, content: {
                        self.actionSheet  })

                }

Comment: This is not possible. TabItem only takes an Image and a Text and it's sole function is to switch views.
Answer: As Apple says:

Tab views only support tab items of type Text, Image, or an image followed by text. Passing any other type of view results in a visible but empty tab item.

You can use solution, which I described here. Shortly: you make empty tabItem (Text(" ")), set Image at needed position and use .onTapGesture. There I also made example with ActionSheet

SwiftUI actionSheet into .tabItem


Python - pilha - - balanceamento

Question: Não estou conseguindo encontrar o erro nesse codigo:
Uma sequencia de parenteses "(" ")", colchetes "[" "]" e chaves "{" "}"
é dita balanceada se cada simbolo "aberto" é "fechado"
em um momento apropriado
Por exemplo
'([])' é uma sequencia balanceada
'([)]' não é balanceada
'([]' não é balanceada
')' não é balanceada
'' é balanceada
 * Se vier alguma letra/numero (ou qualquer outra coisa que nao seja (){}[]<> a funcao deve ignorar em vez de dar erro.
o meu código:
def balanceada(string):
    pilha = []
    for i in string:
        if i != '(' or i != '[' or i != '{' or i != '<' or i != ')' or i != ']' or i != '}' or i != '>':
            pass
        else:
            if i == '(' or i == '[' or i == '{' or i == "<":
                pilha.append(i)
            else:
                topo = pilha[-1]
                if (i == ")" and topo == "(") or (i == "]" and topo == "[") or (i == "}" and topo == "{") or (i == ">" and topo == "<"):
                    pilha.pop()
                else:
                    return False
    if len(pilha) == 0:
        return True
    else:
        return False

quando rodo o teste:
self.assertEqual(balanceada('([}[])'),False)
AssertionError: True != False
Answer: Você tem um problema no primeiro "if" já - "se i for diferente de "(" OU diferente de "[" ..." - ra, I não pode ser IGUAL a "(" E "[" ao mesmo tempo - portanto a condição sempre vai ser verdadeira  - e você cai no caso em que não faz nada (pass).
O correto seria pergunta "se i for diferente de ... E diferente de ... então..."  - com and em vez de or.
No entanto não é a melhor forma - já que o operador in em Python pode verificar se uma substring é parte de outra em uma única comparação, é possível escrever, para esse primeiro "if" apenas:
if i not in "()[]{}<>":
    pass

Uma outra dica é não usar "else: " e colocar outro "if" dentro - em Python existe a palavra chave elif que já faz uma segunda comparação caso o primeiro ifseja falso, e evita justamente a escadinha que o seu código vai virando.
Acertando essas comparações, a sua lógica parece estar ok - deve funcionar.

Python - pilha - - balanceamento


Zooming out dispositiong image with custom imageView

Question: I am using following code to add a custom ImagView in a ViewPager to set Zooming system. On double Tap, You zoom in, and then on double tap again you zoom out. Now suppsoe you swipe and zoomed in a little bit, now I want the feature that if you now double tap it should zoom you out.
If i call function minZoomed() it zooms out but it does not centers the position now. However it does center the image if I first zoomed In fully and then double tap to zoom out. But when i zoom in a little using swipe and then try to zoom out, it displaces the image to some random places.I want the image to get centered in the screen after Zoom out
So
Firstly Total Zoom out(Centered)> Double Tap> Full Zoomed In (Centered) > Double Tap > Full zoomed out (centered)
But
Firstly Total Zoom out(Centered)> SWIPE TO ZOOM> Little Zoom (Centered) > Double Tap > Full zoomed out (Displaced)
How can I fix this issue?
<code>public class ZoomImageView extends ImageView
{
    Matrix matrix = new Matrix();

    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    int mode = NONE;

    boolean isMaxed = false;
    boolean zoomOut = false;

    PointF last = new PointF();
    PointF start = new PointF();
    float minScale = 1f;
    float maxScale = 3f;
    float[] m;

    float redundantXSpace, redundantYSpace;

    float width, height;
    static final int CLICK = 3;
    float saveScale = 1f;
    float right, bottom, origWidth, origHeight, bmWidth, bmHeight;

    ScaleGestureDetector mScaleDetector;
    GestureDetector mDoubleDetector;
    Context context;

    private CustomViewPager pager;

    public ZoomImageView(Context context)
    {
        super(context);
        super.setClickable(true);
        this.context = context;
        mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
        mDoubleDetector = new GestureDetector(context, new DoubleTapGestureDetector());
        matrix.setTranslate(1f, 1f);
        m = new float[9];
        setImageMatrix(matrix);
        setScaleType(ScaleType.MATRIX);

        setOnTouchListener(new OnTouchListener()
        {
            public boolean onTouch(View v, MotionEvent event)
            {
                mScaleDetector.onTouchEvent(event);
                mDoubleDetector.onTouchEvent(event);

                matrix.getValues(m);
                float x = m[Matrix.MTRANS_X];
                float y = m[Matrix.MTRANS_Y];
                PointF curr = new PointF(event.getX(), event.getY());

                switch (event.getAction())
                {
                    case MotionEvent.ACTION_DOWN:
                        last.set(event.getX(), event.getY());
                        start.set(last);
                        mode = DRAG;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (mode == DRAG)
                        {
                            float deltaX = curr.x - last.x;
                            float deltaY = curr.y - last.y;
                            float scaleWidth = Math.round(origWidth * saveScale);
                            float scaleHeight = Math.round(origHeight * saveScale);
                            if (scaleWidth < width)
                            {
                                deltaX = 0;
                                if (y + deltaY > 0)
                                    deltaY = -y;
                                else if (y + deltaY < -bottom)
                                    deltaY = -(y + bottom);
                            }
                            else if (scaleHeight < height)
                            {
                                deltaY = 0;
                                if (x + deltaX > 0)
                                    deltaX = -x;
                                else if (x + deltaX < -right)
                                    deltaX = -(x + right);
                            }
                            else
                            {
                                if (x + deltaX > 0)
                                    deltaX = -x;
                                else if (x + deltaX < -right)
                                    deltaX = -(x + right);

                                if (y + deltaY > 0)
                                    deltaY = -y;
                                else if (y + deltaY < -bottom)
                                    deltaY = -(y + bottom);
                            }
                            matrix.postTranslate(deltaX, deltaY);
                            last.set(curr.x, curr.y);
                        }
                        break;

                    case MotionEvent.ACTION_UP:
                        mode = NONE;
                        int xDiff = (int) Math.abs(curr.x - start.x);
                        int yDiff = (int) Math.abs(curr.y - start.y);
                        if (xDiff < CLICK && yDiff < CLICK)
                            performClick();
                        break;

                    case MotionEvent.ACTION_POINTER_UP:
                        mode = NONE;

                        break;
                }
                setImageMatrix(matrix);
                if (saveScale == minScale)
                {
                    pager.setPagingEnabled(true);
                }
                else
                {
                    pager.setPagingEnabled(false);
                }
                return true;
            }

        });
    }

    public void setPager(CustomViewPager pager)
    {
        this.pager = pager;
    }

    @Override
    public void setImageBitmap(Bitmap bm)
    {
        super.setImageBitmap(bm);
        bmWidth = bm.getWidth();
        bmHeight = bm.getHeight();
    }

    public void minZoomed()
    {
        matrix.setScale(minScale,minScale);
        setImageMatrix(matrix);
        invalidate();
        redundantYSpace = (float)height - (minScale * (float)bmHeight) ;
        redundantXSpace = (float)width - (minScale * (float)bmWidth);
        redundantYSpace /= (float)2;
        redundantXSpace /= (float)2;
        saveScale = minScale;
        matrix.postTranslate(redundantXSpace, redundantYSpace);
        origWidth = width - 2 * redundantXSpace;
        origHeight = height - 2 * redundantYSpace;
        right = width * saveScale - width - (2 * redundantXSpace * saveScale);
        bottom = height * saveScale - height - (2 * redundantYSpace * saveScale);
        setImageMatrix(matrix);
        invalidate();
    }

    public void maxZoomed()
    {
        matrix.setScale(maxScale,maxScale);
        setImageMatrix(matrix);
        redundantYSpace = (float)height - (maxScale * (float)bmHeight) ;
        redundantXSpace = (float)width - (maxScale * (float)bmWidth);
        redundantYSpace /= (float)2;
        redundantXSpace /= (float)2;

        matrix.postTranslate(redundantXSpace, redundantYSpace);
        origWidth = width - 2 * redundantXSpace;
        origHeight = height - 2 * redundantYSpace;
        right = width * saveScale - width - (2 * redundantXSpace * saveScale);
        bottom = height * saveScale - height - (2 * redundantYSpace * saveScale);
        setImageMatrix(matrix);
        invalidate();
        saveScale = maxScale;

    }
    public void setMaxZoom(float x)
    {
        maxScale = x;
    }

    public void setMinZoom(float x)
    {
        minScale = x;
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
    {
        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector)
        {
            mode = ZOOM;
            return true;
        }

        @Override
        public boolean onScale(ScaleGestureDetector detector)
        {
            float mScaleFactor = (float)Math.min(Math.max(.95f, detector.getScaleFactor()), 1.05);
            float origScale = saveScale;
            saveScale *= mScaleFactor;
            if (saveScale > maxScale)
            {
                saveScale = maxScale;
                mScaleFactor = maxScale / origScale;
            }
            else if (saveScale < minScale)
            {
                saveScale = minScale;
                mScaleFactor = minScale / origScale;
            }
            right = width * saveScale - width - (2 * redundantXSpace * saveScale);
            bottom = height * saveScale - height - (2 * redundantYSpace * saveScale);
            if (origWidth * saveScale <= width || origHeight * saveScale <= height)
            {
                matrix.postScale(mScaleFactor, mScaleFactor, width / 2, height / 2);
                if (mScaleFactor < 1)
                {
                    matrix.getValues(m);
                    float x = m[Matrix.MTRANS_X];
                    float y = m[Matrix.MTRANS_Y];
                    if (mScaleFactor < 1)
                    {
                        if (Math.round(origWidth * saveScale) < width)
                        {
                            if (y < -bottom)
                                matrix.postTranslate(0, -(y + bottom));
                            else if (y > 0)
                                matrix.postTranslate(0, -y);
                        }
                        else
                        {
                            if (x < -right)
                                matrix.postTranslate(-(x + right), 0);
                            else if (x > 0)
                                matrix.postTranslate(-x, 0);
                        }
                    }
                }
            }
            else
            {
                matrix.postScale(mScaleFactor, mScaleFactor, detector.getFocusX(), detector.getFocusY());
                matrix.getValues(m);
                float x = m[Matrix.MTRANS_X];
                float y = m[Matrix.MTRANS_Y];
                if (mScaleFactor < 1)
                {
                    if (x < -right)
                        matrix.postTranslate(-(x + right), 0);
                    else if (x > 0)
                        matrix.postTranslate(-x, 0);
                    if (y < -bottom)
                        matrix.postTranslate(0, -(y + bottom));
                    else if (y > 0)
                        matrix.postTranslate(0, -y);
                }
            }
            return true;
        }
    }

    @Override
    protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = MeasureSpec.getSize(widthMeasureSpec);
        height = MeasureSpec.getSize(heightMeasureSpec);
        //Fit to screen.
        float scale;
        float scaleX =  (float)width / (float)bmWidth;
        float scaleY = (float)height / (float)bmHeight;
        scale = Math.min(scaleX, scaleY);
        matrix.setScale(scale, scale);
        setImageMatrix(matrix);
        saveScale = 1f;

        // Center the image
        redundantYSpace = (float)height - (scale * (float)bmHeight) ;
        redundantXSpace = (float)width - (scale * (float)bmWidth);
        redundantYSpace /= (float)2;
        redundantXSpace /= (float)2;

        matrix.postTranslate(redundantXSpace, redundantYSpace);

        origWidth = width - 2 * redundantXSpace;
        origHeight = height - 2 * redundantYSpace;
        right = width * saveScale - width - (2 * redundantXSpace * saveScale);
        bottom = height * saveScale - height - (2 * redundantYSpace * saveScale);
        setImageMatrix(matrix);
    }

    private class DoubleTapGestureDetector extends GestureDetector.SimpleOnGestureListener
    {
        @Override
        public boolean onDown(MotionEvent e)
        {
            return true;
        }

        @Override
        public boolean onDoubleTap(MotionEvent e)
        {

            if( isMaxed == false)
            {
                isMaxed = true;
                maxZoomed();
                pager.setPagingEnabled(false);
            }
            else
            {
                isMaxed = false;
                minZoomed();
                pager.setPagingEnabled(true);
            }

            return true;
        }
    }

}
</code>
Answer: You can look at this project : https://github.com/sephiroth74/ImageViewZoom
It has pinch-to-zoom & double tap support and is very easy to implement (I've used it myself)
All credits go to sephiroth74
Answer: Follow this link : http://math.hws.edu/javanotes/c13/s5.html
(but not custom image view)
The program ( MandelbrotViewer.java) has zooming in/out features on tap.
(no external library needed)
zoom in :

More zoom :

zoom out:


Recovering an analytic function

Question: How can one recover an analytic function $L(\gamma)$ in real line, knowing its values only on two infinite sequences
$\{\lambda_n\}_{n \in \mathbb{Z}}$ and $\{\mu_n\}_{n \in \mathbb{Z}}$?
$\lambda_n = \pi n, \mu_n=\cfrac{\pi}{2} + \pi n, \; n \in \mathbb{Z}$
$L(\lambda_n)=a_n$, $\; L(\mu_n)=b_n$, $n=0, 1, 2, \ldots$ .
Comment: I don't see what it helps to have two such sequences.
Comment: Indeed...for instance, picking $\mu_i = \lambda_i$ shows that if it's possible, then having ONE sequence is enough.
Comment: I don't think it's possible, since you could just add $\sin(-\alpha_1 + \pi n)\sin(-\alpha_2 + \pi n)$ however many times you want to get a new function.
Comment: If the sequence $\lambda_n$ tended to some limit in $U$, where the analytic function is defined on domain $U$, then by the Identity Theorem, you know the value of the analytic function on all of $U$.
Comment: Unfortunately, here $\lambda_n \to \infty$ and, thus, the Identity Theorem doesn't work.
@PatrickStevens
Answer: As has been noted, there is no uniqueness here.  But you can get an analytic function with these values.  For convenience, put the two sequences together into one sequence of distinct complex numbers $\alpha_n$, $n = 0, 1, 2, \ldots$, where you want
$L(\alpha_n) = \beta_n$, such that $|\alpha_n| \to \infty$ as $n \to \infty$.
Let $f_n$ be a polynomial such that
$$\eqalign{f_n(\alpha_n) &= \beta_n - \sum_{j=0}^{n-1} f_j(\alpha_n)\cr
f_n(\alpha_j) &= 0 \ \text{for}\ j < n\cr
|f_n(z)| &< 2^{-n}\ \text{for}\ |z| < |\alpha_n|/2 \cr}$$
and take
$$ f(z) = \sum_{n=0}^\infty f_n(z) $$
a series that converges absolutely, uniformly on compact sets, so the
sum is analytic on all of $\mathbb C$.
For example, you could take $f_n$ of the form
$$f_n(z) = \left(\frac{z}{\alpha_n}\right)^M \left(\beta_n - \sum_{j=0}^{n-1} f_j(\alpha_n)\right)  \prod_{j=0}^{n-1} \dfrac{z - \alpha_j}{\alpha_n - \alpha_j}$$
where the factor $(z/\alpha_n)^M$ is omitted if $\alpha_n$ happens to be $0$; otherwise $M$ is an integer with
$$M > n + \log_2 \left| \beta_n - \sum_{j=0}^{n-1} f_j(\alpha_n)\right| + \sum_{j=0}^{n-1} \log_2 \left(\frac{|\alpha_j| + |\alpha_n|/2}{|\alpha_n - \alpha_j|}\right)$$
Comment: I've found a book related to this question.
If you are interested take a look:
Levin B.Ya. - "Lectures on entire functions" (AMS, 1996)(T)(ISBN 0821802828)(242s)
Lectures 20-22.

Recovering an analytic function


TempData perde propriedade ao usar Response.Redirect?

Question: Estou com o seguinte código nas páginas que, para serem acessadas, é necessário realizar o login:
if (Session["Login"] == null)
{
    TempData["msg"] = "É necessário realizar o login para acessar esta página!";
    Response.Redirect("/Login/Index");
}

Esta TempData["msg"] está da seguinte forma na tela de login:
@if (TempData["msg"] != null)
{

       @TempData["msg"]

}

Entretanto a mensagem não está aparecendo, como se o TempData estivesse se anulando. O que tenho que fazer para que a mensagem seja passada para a tela de login?
Comment: Para referência: https://pt.stackoverflow.com/questions/149665/passagem-de-par%C3%A2metros-com-asp-net-mvc/149674#149674
Answer: Utilize a ViewBag pois ela existe até o final da execução do response.
No controller:
if (Session["Login"] == null)
{
    ViewBag.msg = "É necessário realizar o login para acessar esta página!";
    Response.Redirect("/Login/Index");
}

Na view:
@if (TempData["msg"] != null)
{

       @ViewBag.msg

}


likelihood ratio test with constrained null hypothesis

Question: I am trying to understand a fundamental property of the Likelihood Ratio Test (LRT).
For simplicity, the following example is framed as binomial data, which of course could be solved using a simple hypothesis test (the binomial test).  But for the sake of the argument, please consider it from the LRT perspective, since it is a nice simplification of more complicated scenarios.
Let $X$ ~ binomial$(n,p)$.  Let $p_0 = 0.2$.
I would like to test that $H_0:  p \in (0 , p_0)$ vs. $H_1: p \in (p_0 , 1)$.
Then my LRT test statistic is, as usual:
$\Lambda = - 2 \cdot \log \frac{sup \{L(\theta | x) : \theta \in (0 , p_0) \}}{sup \{L(\theta | x) : \theta \in (0,1)\}}  $
I have read that the likelihood ratio test is not universal.  I've read that it fails when:

the parameter is constrained to be on the boundary (e.g. $N_2( [\mu_1 , \mu_2 ] , \Sigma)$ where $\mu_1, \mu_2 \ge 0$ and $H_0: \mu_1 = \mu_2 = 0$  ).
The parameters must be  on the "interior" of the parameter space.

In these cases, the LRT statistic $\Lambda$ is not asympotitcally $\chi^2$ distributed.
In the topological sense, my  $H_0$  constrained parameter space $(0,p_0)$ is indeed an interior set to $(0,1)$.  Further, I am not constraining $p$ to be on the boundary of $(0,1)$.  Seems like I should be OK, right?
Is the LRT statistic above still valid ?  i.e. is $\Lambda$ above still asymptotically ~ $\chi^2$ ?
Based on my reasoning about the interior point/constraints above, I believe the answer is yes.
Lastly:  what is the degrees of Freedom of my LRT test?
I believe it is 1, intuitively.
Comment: >$H_1: p \in (p_0 , 1)$ you meant $H_1: p \in (0 , 1)$ right ?
Comment: Sure.  This is a moot point.  The form of the LRT statistic $\Lambda$ as I wrote in the question does not change.  Conventionally, you state $H_0$ and $H_1$ as disjoint.  So you state $H_1$ as $(p_0,1)$.  But for the LRT, you want $H_0$ nested in $H_1$, so you "use" $(0,1)$.
Answer: The chi-squared limiting distribution is valid only for a special type of composite hypotheses. $H_0: \theta_1=\theta_1^0,\ldots,\theta_r=\theta_r^0,\theta_{r+1},\ldots,\theta_k$, that is when the first $r$ parameters are specified and the rest are not, versus $H_a: \theta_1,\ldots,\theta_k$ that leaves all of them unspecified.
Your null hypothesis does not have that form, and it is easy to see that the limiting distribution is not chi-squared under the null hypothesis. Suppose $p$ is small (less than 0.2), and $n$ is large. Then the maximum likelihood estimate will be almost always less than 0.2 either under the null or the without restriction. Then your test statistic will be almost always 0! In fact, its limiting distribution is degenerate.
In general, likelihood-ratio tests are not convenient for one-sided alternatives, because the direction of the difference is obliterated by the squaring. However the correct way for developing a one-sided likelihood-ratio test is to note that $p=0.2$ is closest to the alternative, so we test $H_0: p=0.2$ versus $H_a: p\geq 0.2$. In this case, however, the value of interest is on the edge of the parameter space, so the limiting distribution is not chi-squared. In fact, for this case it is a mixture distribution of $0.5 I({0}) + 0.5\chi^2_1$.
Comment: I understand.  What hypothesis test is sufficient to test $H_0: p \le p_0$  vs $H_1: p > p_0 $ ?


Symfony 4 with Hateoas: Relations with Child class

Question: I have a parent class MapItem, and a child class, MapExhibit. My MapExhibit class has a property, $builiding, which ties the exhibit to a particular MapBuilding entity. When the API calls for the JSON, the $building should not appear for MapExhibit entities in particular.
Note I am using the willdurand/Hateoas bundle
Here is my current setup:
/**
 * @ORM\Entity(repositoryClass="App\Repository\Map\MapItemRepository")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap({"item" = "MapItem", "bathroom" = "MapBathroom", "building" = "MapBuilding", "bus" = "MapBus", "emergency" = "MapEmergency", "exhibit" = "MapExhibit", "parking" = "MapParking"})
 * @Serializer\XmlRoot("mapItem")
 * @Hateoas\Relation("self", href = "expr('/api/mapitems/' ~ object.getId())")
 */
abstract class MapItem
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @Serializer\XmlAttribute
    */
    private $id;

    ...
}

/**
 * @ORM\Entity(repositoryClass="App\Repository\Map\MapExhibitRepository")
 *
 * @Hateoas\Relation(
 *    "building",
 *    exclusion = @Hateoas\Exclusion()
 * )
 */
class MapExhibit extends MapItem
{
   ...

   /**
    * Many emergency devices can belong to one building.
    * @ORM\ManyToOne(targetEntity="MapBuilding", inversedBy="emergencyDevices")
    * @ORM\JoinColumn(name="building_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
    */
   private $building;

   ...

   public function getBuilding(): ?MapBuilding
   {
       return $this->building;
   }
}

The result is a JSON object that includes the relation from the parent MapItem
"_links":{"self":{"href":"\/api\/mapitems\/29"}}}]

But also includes the data from the exhibit's building. This part should be ignored.
Answer: Take a look on exclusion strategies in documentation.

If you would like to always expose, or exclude certain properties. Then, you can do this with the annotations @ExclusionPolicy, @Exclude, and @Expose.
The default exclusion policy is to exclude nothing. That is, all properties of the object will be serialized. If you only want to expose a few of the properties, then it is easier to change the exclusion policy, and only mark these few properties: (...)

So basically, put @Serializer\Exclude() above private $builidng. Don't forget to add use JMS\Serializer\Annotation as Serializer; on top.


AD users that have specific word in the description field via Powershell

Question: I am new to PowerShell and I am trying to extract username and name of users that contain a word or specific words in the description field of an AD user.
In the description field we have added user job titles and I am trying to search for specific job titles to display full names and usernames.
What I have gathered from my quick googling is this:
Get-ADUser -Filter * -Properties Description | Select Name,SamAccountName
This displays all AD users with name and username details.
I believe this area I need to change is the -Filter but when I try something like this the command fails
Get-ADUser -Filter -like "developer" -Properties Description | Select Name,SamAccountName
This is probably going to be pretty straightforward for a powershell guy but I am struggling here.
Update to the command
Get-ADUser -Properties Description -Filter 'Description -like "developer"' | Select Name,SamAccountName
Nothing is getting outputted after I enter the command.
Further update the command that worked for me was:
Get-ADUser -Properties Description -Filter 'Description -like "*developer*"' | Select Name,SamAccountName
Comment: `Get-ADUser -Filter "Description -Like '*developer*'" -Properties Description`; this also may take a while depending on how many users you have, so I'd recommend narrowing down the search to an OU.
Comment: Thanks your comment helped my fix it.
Answer: Using -Filter Parameter:
Get-ADUser -Properties Description -Filter {Description -like "developer"}
OR
Get-ADUser -Properties Description -Filter 'Description -like "*developer*"'

Using Where-Object
Get-ADUser -Properties Description -Filter * | ? Description -match "developer"

Add your Final Select at the end of the pipeline if you just need this specific properties:
| Select Name,SamAccountName,Description

Comment: Hi thanks for your help I tried the -filter parameter: Get-ADUser -Properties Description -Filter 'Description -like "developer"' | Select Name,SamAccountName nothing gets outputted so I tried the where-object parameter  Get-ADUser -Properties Description * | ? Description -match "developer" this fails cannot find an object with identity '*'
Comment: Update your select... add description.. check in the answer
Comment: Sorry I was my fault I was missing the additional * after developer so I entered * developer not * developer * thanks for your help on this it fixed the command.


Isn't a smooth map having rank 2 injective by the corollary of inverse function theorem?

Question: In the book of E. Bloch, at page 171, it is stated that

Corollary:
Let $U\subseteq \mathbb{R}^2$ be an open subset, and let $f: U \to
 \mathbb{R}^3$ be a smooth map. If for $p \in U$, $Df(p)$ has rank 2,
  then there is an open subset $W$ of $U$ s.t $f|_W$ is injective, and
  $Df(q)$ for all $q\in W$ has rank 2.

However, when we define a coordinate patch in page 203,

Definition:
Let $U\subseteq \mathbb{R}^2$ be an open set. A smooth map $x: U\to \mathbb{R}^3$ is a coordinate path if it is injective and $x_1 \times x_2 \not = 0$ for all $p\in U$.
Equivalently to the above conditions are that $x_1 $ and $x_2$ are
  linearly independent, or that $Dx$ has rank 2 for all $q\in U$.

But by the corollary, if $x$ has rank 2, by choosing a "smaller" neighbourhood of $p$, we can make it an injective map, so isn't the condition for $x$ to be injective redundant in here ? or Am I missing something ?
Answer: It isn't redundant because being locally injective doesn't mean that you are injective. If you start with a map $x \colon U \rightarrow \mathbb{R}^3$ defined on $U$ such that $Dx(p)$ has rank two for any $p \in U$, then, give a $p \in U$ you can find a neighborhood $W$ of $p$ such that $x|_{W} \colon W \rightarrow \mathbb{R}^3$ is injective. It doesn't mean that $x$ itself is injective as it is possible to have $q' \in W, q'' \in U$ such that $x(q') = x(q'')$. The point $q''$ can't also be in $W$ because $x|_{W}$ is injective but nothing forbids the existence of a point in $U \setminus W$ which has the same image as a point in $W$.
For a concrete example, consider $x(\theta,z) = (\cos \theta, \sin \theta, z)$ defined on $\mathbb{R}^2$, whose image is an infinite cylinder. The differential has rank two anywhere, but it is only locally injective and not injective. If you drop the condition of being injective, you are left with a useful notion in differential geometry which is called immersion but it is not the same as being a coordinate patch.
Comment: Yes, but bu just defining $U := W$, we can make it injective map since $x$ is just a local coordinate patch, and as long as we can cover the manifold with $W$s (which we can since we are taking $W$ around $p$ for every $p \in M$)
Comment: @onurcanbektas: You didn't mention anywhere in your question a global manifold $M$. In general, a chart of a (embedded submanifold) $M$ is required to be a homeomorphism onto an open subset of $M$ (with the subspace topology), and in particular, it must be injective. If you remove from the requirement of a chart that the charts are homeomorphisms and leave only the requirement that they have constant rank, then the restriction $x|_{W}$, while being injective, won't necessarily be a homeomorphism onto an open neighborhood in $M$.
Comment: I didn't get what your point is.


Can't mount disk (VFS: Can't find ext4 filesystem)

Question: Tried to mount a disk (hardware raid) but failed.
#mount -t ext4 /dev/sda /data

mount: wrong fs type, bad option, bad superblock on /dev/sda,
       missing codepage or helper program, or other error
       In some cases useful info is found in syslog - try
       dmesg | tail  or so

#dmesg | tail -1
       EXT4-fs (sda): VFS: Can't find ext4 filesystem

what am I doing wrong?
I saw that many posters with similar problem were request to post the content of fstab so here it is:
#cat /etc/fstab

#
# /etc/fstab
# Created by anaconda on Wed Aug  6 11:29:15 2014
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
UUID=276c97cc-9c5f-496f-a56f-ac3a45c58a26           /           ext4    defaults,usrquota,grpquota  1 1
UUID=3978f122-03d4-48db-adeb-6fc8a2c624c4 /boot                   ext2    defaults        1 2
UUID=1251c6d8-c417-48df-9cf4-2f56e3a823a6 /tmp                    ext4    defaults        1 2
UUID=95fd67df-7172-4ac9-9264-0b50819a203a swap                    swap    defaults        0 0
tmpfs                   /dev/shm                tmpfs   defaults        0 0
devpts                  /dev/pts                devpts  gid=5,mode=620  0 0
sysfs                   /sys                    sysfs   defaults        0 0
proc                    /proc                   proc    defaults        0 0

CentOs 6
Updates:
# cat /proc/partitions
major minor  #blocks  name

   8       32  244198584 sdc
   8       33     102400 sdc1
   8       34    4194304 sdc2
   8       35    2097152 sdc3
   8       36          1 sdc4
   8       37  237802496 sdc5
   8       48  244198584 sdd
   8       49     102400 sdd1
   8       50    4194304 sdd2
   8       51    2097152 sdd3
   8       52          1 sdd4
   8       53  237802496 sdd5
   8        0 21484255232 sda
   8       16 21484255232 sdb
   9        1    4192192 md1
   9        3  237671232 md3
   9        2    2096064 md2
   9        0     102336 md0

#fdisk -l | grep sda
Disk /dev/sda: 21999.9 GB, 21999877357568 bytes

Comment: What does `cat /proc/partitions` say?
Comment: I've added the output to the question
Comment: Try commands `pvscan`, `vgscan`, `lvscan` ... perhaps your ext4 resides in LVM volume?
Comment: all of these command don't exist on my machine, should I install them? it's a hardware raid 5
Comment: Is that two separate RAID-5 arrays? Is there any data on the RAID-5? It would be interesting to see the output of `hexdump -C </dev/sda | head -40` and likewise with `sdb`.
Answer: When using mount you have to mount the partition not the drive itself eg mount -t ext4 /dev/sda1 /data
Comment: I doesn't look like you have created any partitions on that raid.  Create a primary partition with fdisk eg `fdisk /dev/sda/`.  When the menu comes up `n` for a new partition select the defaults if you only want one partition. Select `t` to change the type of partition you want I believe 83 is Linux then `w` to write the changes. Then run `mkfs.ext4 /dev/sda1` to format the newly created partition.  Or if you are not to savvy with command line a GUI utility like gparted will do the trick.
Comment: # mount -t ext4 /dev/sda1 /data

mount: special device /dev/sda1 does not exist
Comment: /dev/sda1 was just an example.  I would suggest running an `fdisk -l` to see what drives/partitions are available and then try mounting the one you want from there.
Comment: in fdisk -l I can see /dav/sda (I've updated my post with the data from fdisk)
Comment: Thanks! it did the trick but it appears that fdisk doesn't allow more than 2TB partition and I needed 22TB parition. After some googling I could find this [excellent post](http://unix.stackexchange.com/questions/29078/how-to-partition-22tb-disk) which solved my problem.
Comment: Glad to hear it!
Comment: If you could please mark this as answered so people don't keep posing answers in an old thread.
Comment: I created a ext4 partition using `parted` and was mounting with the correct command, but it was giving the same error. Using `mkfs.ext4` as suggested by @joeg1ff worked fine.
Answer: You can get that error in the dmesg when you are creating a new Logical Volume but you forget to run the mkfs command which actually builds the file system. What I am trying to say here is that in order to be able to mount a partition you should make sure first that you ran mkfs after you created the Logical Volume or else it will complain same as in your example.

Create a Logical Volume from the Volume group vg:
 lvcreate -L 2G --name lv_data vg
Make the file system an ext4 type:
mkfs.ext4 /dev/mapper/vg-lv_data
Mount it:
mount -t ext4 /dev/mapper/vg-lv_data /data

Jumping/missing step 2 it will complain with the error: VFS: Can't find ext4 filesystem.
Answer: It clearly says wrong file system type, give below command and check which file system it is.
file -sL /dev/mapper/datavg-datalv

output:

/dev/mapper/datavg-datalv: SGI XFS filesystem data

Cross check the fs type in /etc/fstab, if it is other than xfs, change it to xfs and in /etc/fstab and then try mounting


C# e Sql Server, inserindo com proc usando BEGIN TRAN

Question: Boa noite!
Estou inserindo um registro usando o C# e Windows forms, estou usando uma proc que insere em duas tabelas ao mesmo tempo, o código está funcionando, mas, criei uma regra que a loja só pode ter apenas 1 gerente, joguei um select na proc para poder usar como retorno e usar o cmd.ExecuteEscalar (c#), porem, ele insere na tabela e ainda me joga um erro na tela

( Erro Violação da restrição UNIQUE KEY 'UQ_TblPessoa_Cpf'. Não é
  possível inserir a chave duplicada no objeto 'dbo.TblPessoa'. O valor
  de chave duplicada é (22$%#@).

Não é possível inserir o valor NULL na coluna Id_Pessoa, tabela 'DB_BANCO_DE_HORAS.dbo.TblFuncionario'; a coluna não permite nulos. Falha em INSERT.) mas se eu olha no banco o registro consta , inclusive com o idGerente. espero que tenha ficado claro :-)
código da proc;
  ALTER PROC PR_INSERIR_PESSOA_E_FUNCIONARIO
    --pessoas
    @Cpf varchar(11),
    @Nome varchar(60),
    @sexo char(1),
    --Funcionario
    @funcao varchar(30),
    @IdGerente int,
    @idLoja int
    as
        DECLARE @X TABLE (IdPessoa INT)
        DECLARE @CONT INT = 0

        --VALIDANDO SE TEM GERENTE CADASTRADO NA LOJA
        IF(@funcao = 'GERENTE')
            SET @CONT = (SELECT COUNT(*) FROM TblFuncionario WHERE Id_Loja = @idLoja)

        IF(@CONT <= 0)
        BEGIN

            BEGIN TRAN

            INSERT INTO TblPessoa (Cpf,Nome,Sexo)
            --essa linha vai pegar o idPessoa que é gerado pelo identity e seta na table @x, no campo da tabela idPessoa
            output inserted.Id_Pessoa into @X
            VALUES
            (@Cpf,@Nome,@sexo)

            if(@IdGerente = '')
                set @IdGerente = null;

            INSERT INTO TblFuncionario (Id_Pessoa,Funcao,Id_Gerente,Ativo,Id_Loja, DataContrato)
            VALUES
            ( (SELECT IdPessoa FROM @X),@funcao,@IdGerente,1,@idLoja,GETDATE())

            IF @@ERROR = 0
                COMMIT
            ELSE
                ROLLBACK

            select IdPessoa from @X
        END

    GO

C#
public bool InserirFuncionario (Funcionario funcionario)
        {
            int idpessoa = 0;
            bool cadastro = false;
            cmd = new SqlCommand();
            cmd.Connection = ConexaoBancoSQLServer.Conectar();

            cmd.CommandText = "PR_INSERIR_PESSOA_E_FUNCIONARIO";

            cmd.Parameters.AddWithValue("@Cpf", funcionario.cpf);
            cmd.Parameters.AddWithValue("@Nome", funcionario.nome);
            cmd.Parameters.AddWithValue("@sexo", funcionario.sexo);
            cmd.Parameters.AddWithValue("@funcao", funcionario.funcao);

            if(funcionario.id_Gerente.ToString() != "")
                cmd.Parameters.AddWithValue("@IdGerente", funcionario.id_Gerente);

            cmd.Parameters.AddWithValue("@idLoja", funcionario.id_Loja);

            cmd.CommandType = CommandType.StoredProcedure;

            cmd.ExecuteNonQuery();

            try
            {
                idpessoa = int.Parse(cmd.ExecuteScalar().ToString());
                cadastro = true;
            }
            catch (Exception ex)
            {

                Console.WriteLine("Erro " + ex.Message);
            }
            cmd.Parameters.Clear();
            cmd.Connection.Close();

            return cadastro;

        }

private void btnSalvar_Click(object sender, EventArgs e)
        {
            try
            {
                Funcionario funcionario = new Funcionario();

                funcionario.nome = txtNome.Text;
                funcionario.cpf = txtCpf.Text;
                funcionario.funcao = cmbFuncao.Text;
                funcionario.id_Loja = Convert.ToInt32(cmbLoja.SelectedValue);

                if(cmbGerente.Text != "")
                    funcionario.id_Gerente = FuncionarioGerenteCombo.func.id_Func;

                if (rdtFeminino.Checked == true || rdtMasculino.Checked == true)
                {
                    if (rdtFeminino.Checked == true)
                        funcionario.sexo = "F";
                    else
                        funcionario.sexo = "M";
                }

                if (funcionarioNegocio.InserirFuncionario(funcionario))
                {
                    MessageBox.Show("Funcionário cadastrado com sucesso!");

                    DialogResult resultado = MessageBox.Show("Deseja Cadastrar outro funcionário?", "Pergunta", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (resultado == DialogResult.No)
                        LimparCampos();
                }
                else
                    MessageBox.Show("Erro");

            }
            catch (Exception erro)
            {

                MessageBox.Show("Erro: " + erro.Message);
            }

        }

namespace ObjetoTransferencia
{
    public class Pessoa
    {
        public int id_Pessoa { get; set; }
        public string cpf { get; set; }
        public string nome { get; set; }
        public string sexo { get; set; }

    }
}

namespace ObjetoTransferencia
{
    public class Funcionario : Pessoa
    {
        public int id_Func { get; set; }
        public string funcao { get; set; }
        public int id_Gerente { get; set; }
        public bool ativo { get; set; }
        public int id_Loja { get; set; }

    }
}

Comment: a linha do erro está no NegocioFuncionario
idpessoa = int.Parse(cmd.ExecuteScalar().ToString());
Comment: o erro acontece no ExecuteScalar porque é erro do banco de dados, apenas erro de violação de chave, verifique a sua procedure e os dados que estão sendo ou tentando inserir
Answer: Existe algo muito mais fácil para recuperar o ultimo registro inserido do que criar uma tabela de depois inserir o registro nela chamado SCOPE_IDENTITY() já respondi isso aqui;
Dei uma melhorada na sua proc tinha umas coisas desnecessárias.
 ALTER PROC PR_INSERIR_PESSOA_E_FUNCIONARIO
    --pessoas
    @Cpf varchar(11),
    @Nome varchar(60),
    @sexo char(1),
    --Funcionario
    @funcao varchar(30),
    @IdGerente int,
    @idLoja int
    as

        --VALIDANDO SE TEM GERENTE CADASTRADO NA LOJA
        IF(@funcao = 'GERENTE')
        BEGIN
            DECLARE @CONT INT = (SELECT COUNT(*) FROM TblFuncionario WHERE Id_Loja = @idLoja)

        IF(@CONT <= 0)
            BEGIN

                BEGIN TRAN

                INSERT INTO TblPessoa (Cpf,Nome,Sexo)VALUES (@Cpf,@Nome,@sexo)
                 DECLARE @PessoaId int = SCOPE_IDENTITY();

                if(@IdGerente = '')
                    set @IdGerente = null;

                INSERT INTO TblFuncionario (Id_Pessoa,Funcao,Id_Gerente,Ativo,Id_Loja, DataContrato)
                VALUES (@PessoaId ,@funcao,@IdGerente,1,@idLoja,GETDATE())

                IF @@ERROR = 0
                    COMMIT
                ELSE
                    ROLLBACK

                select @PessoaId
            END
        END
    GO

Por fim, você tem que rever 3 coisas no seu C#
1º, não execute 3 vezes o mesmo CMD.
cmd.ExecuteNonQuery();

é
    try
    {
        idpessoa = int.Parse(cmd.ExecuteScalar().ToString());

2º, não a necessidade de você fazer cmd.Parameters.Clear().
3º encerre sua conexão use o Using por exemplo.
Answer: Olá, consegui resolver essa regra implantando uma trigger e alterando a proc
CREATE TRIGGER TR_VALIDAR_GERENTE

ON TblFuncionario

FOR INSERT, UPDATE

AS

DECLARE @FUNC VARCHAR(20) = (SELECT Funcao FROM inserted)

DECLARE @COUNT int = (SELECT COUNT(*) FROM TblFuncionario WHERE Funcao = 'GERENTE' and Id_Loja = (select Id_Loja from inserted))

IF(@FUNC = 'GERENTE' AND @COUNT > 1)
    ROLLBACK

CREATE PROC PR_INSERIR_PESSOA_E_FUNCIONARIO

--pessoas

@Cpf varchar(11),
@Nome varchar(60),
@sexo char(1),

--Funcionario

@funcao varchar(30),
@IdGerente int,
@idLoja int
as
DECLARE @X TABLE (IdPessoa INT)

BEGIN TRAN

    INSERT INTO TblPessoa (Cpf,Nome,Sexo)
    --essa linha vai pegar o idPessoa que é gerado pelo identity e seta na table @x, no campo da tabela idPessoa
    output inserted.Id_Pessoa into @X
    VALUES
    (@Cpf,@Nome,@sexo)

    if(@IdGerente = '')
        set @IdGerente = null;

    INSERT INTO TblFuncionario (Id_Pessoa,Funcao,Id_Gerente,Ativo,Id_Loja, DataContrato)
    VALUES
    ( (SELECT IdPessoa FROM @X),@funcao,@IdGerente,1,@idLoja,GETDATE())

IF @@ERROR = 0
    COMMIT
ELSE
    ROLLBACK

E pequenas alterações no C#
public void InserirFuncionario (Funcionario funcionario)
    {

        cmd = new SqlCommand();
        cmd.Connection = ConexaoBancoSQLServer.Conectar();

        cmd.CommandText = "PR_INSERIR_PESSOA_E_FUNCIONARIO";

        cmd.Parameters.AddWithValue("@Cpf", funcionario.cpf);
        cmd.Parameters.AddWithValue("@Nome", funcionario.nome);
        cmd.Parameters.AddWithValue("@sexo", funcionario.sexo);
        cmd.Parameters.AddWithValue("@funcao", funcionario.funcao);

        if(funcionario.id_Gerente.ToString() != "")
            cmd.Parameters.AddWithValue("@IdGerente", funcionario.id_Gerente);

        cmd.Parameters.AddWithValue("@idLoja", funcionario.id_Loja);

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.ExecuteNonQuery();

        cmd.Parameters.Clear();
        cmd.Connection.Close();

    }

private void btnSalvar_Click(object sender, EventArgs e)

    {

        try
        {
            Funcionario funcionario = new Funcionario();

            funcionario.nome = txtNome.Text;
            funcionario.cpf = txtCpf.Text;
            funcionario.funcao = cmbFuncao.Text;
            funcionario.id_Loja = Convert.ToInt32(cmbLoja.SelectedValue);

            if(cmbGerente.Text != "")
                funcionario.id_Gerente = FuncionarioGerenteCombo.func.id_Func;

            if (rdtFeminino.Checked == true || rdtMasculino.Checked == true)
            {
                if (rdtFeminino.Checked == true)
                    funcionario.sexo = "F";
                else
                    funcionario.sexo = "M";
            }

            funcionarioNegocio.InserirFuncionario(funcionario);

            MessageBox.Show("Funcionário cadastrado com sucesso!");

            DialogResult resultado = MessageBox.Show("Deseja Cadastrar outro funcionário?", "Pergunta", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (resultado == DialogResult.No)
                LimparCampos();

        }
        catch (Exception erro)
        {

            MessageBox.Show("Erro: " + erro.Message);
        }

    }


Topologically simple compact topological groups

Question: In a lecture note, there is the following sentence without any reference or proofs:

Is there any reference or proofs for it?
Comment: This should follow from Peter-Weyl plus a bit of Lie theory to show that a topologically simple Lie group is algebraically simple.
Comment: I suppose you want to assume that your group is also Hausdorff. Then indeed the statement will follow from linearity of compact Hausdorff groups as Eric said.
Comment: @studiosus  there is not such assumption in the context.
Comment: Without Hausdorfness the statement you quoted is  false. For instance any group equipped with trivial topology is compact and topologically simple.
Comment: What is the definition of a *topologically simple group*? If it means there are no proper nontrivial normal subgroups, this is wrong: there are compact connected simple (algebraic) Lie group with nontrivial centre (which is a closed proper nontrivial subgroup).

Sometimes *topologically simple* means there are no *connected* normal subgroup, but in this case the theorem still is incorrect: every profinite group is a compact topological group with no connected normal subgroup.
Comment: @Cronus a topological group is "topologically simple" if it has exactly two closed normal subgroups.
Comment: I realise now I was also trying to prove the other direction... whoops.
Answer: First you should prove, using the Peter-Weyl theorem (a proof of which is in Chapter 4 of Lie Groups: Beyond an Introduction by Knapp), that
Lemma. Every compact topological group which is topologically simple is isomorphic to a compact Lie group, and is algebraic.
Sketch of Proof.  I will just explain how to obtain an injective homomorphism into a matrix group. It is not too hard to see from the theorem that every compact topological group is isomorphic to a subgroup of a (possibly infinite) product of compact Lie groups. (This can be seen by first proving every element $x$ in the group admits a finite-dimensional complex unitary representation $\rho_x$ such that $x$ is not in its kernel; then $\bigoplus_x \rho_x$ is an injective map into a product of compact Lie groups of the form $U_n$ for some $n$).
Now, let $G$ be a compact topological group which is topologically simple; embedding it in a product of compact Lie groups, we see that the projection onto each coordinate is either trivial or injective (since its kernel is a closed normal subgroup). At least one must be injective, and therefore $G$ must be isomorphic to a compact Lie group. $\square$
Thus, we just need to prove a compact Lie group $G$ which is topologically simple is either finite or connected.
For this you need to use the fact the connected component of the identity is an open-closed normal subgroup. Therefore, it is either trivial or everything. If it is trivial our group is discrete (since the trivial group is open), and compact, hence finite. If it is everything, our group is connected.
Observe this is not a necessary conditions: there are compact topologically simple groups which are neither finite nor connected algebraic.
Answer: First of all, by a compact topological group one usually understands a topological group which, is a compact Hausdorff topological space. I think, Hausdorffness assumption here is due to Bourbaki who always assume  compact topological spaces to be Hausdorff (without Hausdorffness assumption they use the terminology quasicompact). With this in mind, you can find a proof of the fact that every topologically simple compact group is abstractly simple, for instance, in Theorem 9.90 of
Karl H. Hofmann, Sidney A. Morris,
The Structure of Compact Groups.
A Primer for the Student – A Handbook for the Expert,
de Gruyter Studies in Mathematics, Volume 25, 1998.
Without Hausdorffness, the claim is clearly false since every group can be equipped with the trivial topology which makes it compact. Such a group will be topologically simple (since it contains only two closed subsets) but not necessarily algebraically simple. Consider, for instance, the additive group of integers.
Edit. One can replace Hausdorff by T1 since a topological group is Hausdorff if and only if it is T1.
Comment: The cofinite topology is not a group topology. Every $T_1$ (in fact, $T_0$) topological group is Hausdorff.


Checking independence of A/B/C/... test results using Python

Question: Assume I collected the following results from an A/B/C/D/E test:
        Result 1    Result 2    Result 3
Control 21          7           32
VAR1    65          25          64
VAR2    107         50          94
VAR3    15          8           15
VAR4    189         6           2

The null hypothesis is that the results are independent and I want to use Chi-Squared Test of Independence [1]. To that end, I would like to use scipy.stats.chi2_contingency.
However, in order to better understand the happenings, I reproduce the computations manually, as described in [1].
When taking the whole results set, everything works as expected; the chi2 test statistic and the p-value computed manually or using  scipy.stats.chi2_contingency are identical. This is also the case when taking subsets of the results (e.g. only two columns OR only two variations). I get puzzled once taking a 2x2 subset of the results (equivalent to a binary A/B test). Once doing so, the numbers that I get manually are no longer the same as those returned by scipy.stats.chi2_contingency.
Here is a summary of the code behind my exercise:
import pandas as pd
import numpy as np
from scipy import  stats

def comp_expected(df):
    """
    Compute the expected matrix
    """
    return pd.DataFrame(
        np.outer(df.sum(axis=1), df.sum(axis=0)) / df.sum().sum(),
        columns=df.columns,
        index=df.index
    )

chi_squared_stat = lambda observed, expected: (((observed-expected)**2)/expected).sum().sum()
p_value = lambda observed, chi_squared_stat: 1 - stats.chi2.cdf(
    x=chi_squared_stat,
    df=(observed.shape[0]-1)*(observed.shape[1]-1))

def compare_computations(observed):
    print(observed)
    chi2_stat = chi_squared_stat(observed, comp_expected(observed))
    pval = p_value(observed, chi_squared_stat(observed, comp_expected(observed)))
    chi2_contingency = stats.chi2_contingency(observed)
    print('chi2_stat = {}\npval = {}\nchi2_contingency output = {}'.format(
        chi2_stat,
        pval,
        chi2_contingency
    ))
    print("chi2_stat identical - {}".format(np.isclose(chi2_stat, chi2_contingency[0])))
    print("pval      identical - {}".format(np.isclose(pval, chi2_contingency[1])))

# Observed data
observed_base = pd.DataFrame(
    {
        "Result 1": [21, 65, 107, 15, 189],
        "Result 2": [7, 25, 50, 8, 6],
        "Result 3": [32, 64, 94, 15, 2]
    },
    index=["Control",
           "VAR1",
           "VAR2",
           "VAR3",
           "VAR4"]
)

Now you can compare the results of compare_computations(observed_base) and compare_computations(observed_base.iloc[0:2][observed_base.columns[0:2]]). The full example can be found here [2].
Question(s):

Why in the latter case the "manual" computation does not yield the same results as the one provided by scipy.stats.chi2_contingency?
As far as I understand, if the returned p-value is smaller then 0.05, it means that the null hypothesis can be rejected with 95% certainty. Is that correct?
What about the statistical power of the results? How can I compute it?
Answer: The answer to the first question is in the documentation of scipy.stats.chi2_contingency. In particular, in case the number of degrees of freedom is 1, then "Yates' correction for continuity" is applied.
By replacing stats.chi2_contingency(observed) with stats.chi2_contingency(observed, correction=False) the results of the manual computation and the ones provided by chi2_contingency are always consistent.
I am still not sure about the other two questions. Now, in addition, I have to investigate what Yates' correction is.


Breadcrumbs for a view page with arguments

Question: How do I set the breadcrumbs for a view page with arguments? I've used the "User: username" argument, and the following PHP Code as default argument, but it doesn't work:
<code>$breadcrumb[] = l('Home', NULL);
$breadcrumb[] .= l('Our Team', 'team');
drupal_set_breadcrumb($breadcrumb);
</code>
Comment: please tag your question with the version of drupal you are using (and also views)
Answer: I believe when you are creating a view that has an argument you can the opportunity to set a breadcrumb from within views itself.
Substitutions will also be available based on the arguments present.
For example, if you view is
<code>/blogs/2011
</code>
Where blogs is the path to the page, and 2011 is the argument, you could set the breadcrumb of the page with the argument to be:
<code>%1
</code>
This would leave breadcrumbs that would look like:
<code>Blogs > 2011
</code>
Comment: I already did that, but it returns no breadcrumbs at all :(
Comment: Don't suppose you are messing with hook_breadcrumb()? You will be able to do this without touching that hook
Comment: I only use this in template.php:

function phptemplate_breadcrumb($breadcrumb) {
  if (!empty($breadcrumb)) {
    return ''. implode(' → ', $breadcrumb) .'';
  }
}

does it interfere with views arguments?
Comment: You may want to check the menu settings for the views display at "/blogs".
Comment: Also, I think views only builds a breadcrumb from all but the last item. E.g. if you visit the page /blogs/2011/05/22, then the breadcrumb will only be Blogs > 2011 > 05, without the last item. See https://drupal.org/node/1919456#comment-7439094
Comment: (seeing this issue is 2 years old, but it may still have visitors from search)


Azure VNET Gateway - Firewall Traffic - Intra-subnet - port 10001, 20000, 54321

Question: I have a Hub VNET and a VNET Gateway linked to an ExpressRoute.
I added a route table on my Gateway subnet to route all traffic to my Azure Firewall.
When I inspect the FW logs, I see some intra-subnet traffic in the Gateway Subnet. Somethings in this subnet are trying to call each other on port 10001, 20000 and 54321. It's denied because I don't have any specific rule for that, but what is this traffic and do I have to allow it in my FW?
Answer: •   I tried to replicate your environment to understand this scenario of intra subnet traffic between the ports 10001, 20000 and 54321. Based on this, the port '54321' is used by SQL Analysis Services instance listening as the resources in the spoke virtual network might have been deployed with SQL Analysis Services and configured this port for the same.
•   Similarly, with regards to ports 10001 and 20000, they are used for 'Network Data Management Protocol' (NDMP) used primarily for backup of network-attached storage (NAS) devices, such as your storage systems or storage resources configured in the spoke virtual networks while port 20000 is used by 'Distributed Network Protocol' which is used SCADA systems operating as well as web-based Unix/Linux user administration tool. Thus, accordingly, you will have to check the used case scenarios of these ports in the spoke virtual networks based on the purpose of the applications deployed in them.
•   Thus, would suggest you to please check the resources accordingly in the spoke network by temporarily allowing the traffic over these ports and checking the source of these ports for any purposeful applications deployed on the resources in the spoke virtual network.
Therefore, for checking the above ports from the spoke and hub virtual networks, please try to execute the below commands to and from the resources in hub as well as the spoke virtual network: -
  telnet <IP address of the resource> <port no.>

  Test-NetConnection -ComputerName <IP address of the resource> -Port <port>

Also, ensure that you have enabled the hub virtual network as a gateway as shown below as well as configured the firewall policy rules for allowing traffic over these ports within the hub and spoke network as below: -

For more detailed information regarding this, kindly refer to the below link: -
https://learn.microsoft.com/en-us/azure/firewall-manager/secure-hybrid-network


Using Non-numeric Features

Question: I'm just starting out with machine learning. The example I was shown during a mini course I took was the predicting of the sale price of a house given features like:

size of house
number of floors
age of house
number of rooms

Given those features, it's trivial to train an algorithm to minimize some cost function, which in the course I took, was the sum of the differences between the value in the training set and the function used to fit it.
My question: how would I work with a feature that is not represented as a number?
For example, what if one of the features was, say, the name of the closest high school?
Answer: In most cases, you find a way to turn the non-numeric feature in a numeric one, and then go from there.
The simplest solution is to generate a set of indicator variables. For example, if you have $n$ different schools, you might add a set of $n$ variables $S_1, S_2, \ldots S_n$ to each data point. To indicate that $i$th school on your list is the closest, set $S_i = 1$ and set the rest of the variables to zero. This works well when 1) the identity of the closest school matters and 2) you can enumerate the schools present in your data set.
You might also think that the school identity per se doesn't actually carry much information; it's just a proxy for information about school size, test scores, student:teacher ratio, etc. You could join your data set with another data source that has that sort of information. The features would now be something like "size of the nearest high school", "Average SAT score at the nearest high school", etc.
It's also possible that the name of the school has a little bit of signal in it. For example, a good school system might have magnet and/or lab schools in it. You could design features to extract these from a string containing the school name. These would then be added, as indicator variables, to your feature set. This process, often called feature engineering, may require some domain knowledge.
However, in some cases, you can work directly on the non-numeric data. This is particularly true when building a discriminative classifier (or anything else using distances). For example, there are special kernels for support vector machines that allow you directly operate on strings (e.g., http://www.jmlr.org/papers/volume2/lodhi02a/lodhi02a.pdf), without turning them into something like a bag-of-words vector or something like that.
Answer: There could be many categorical variables that affect the sales price - for example,  Ready_for_immediate_occupancy (Yes/No).  I will not worry about your specific variable - closest high school - and just address using categorical variables in regression.
As @Matt Krause said, certainly it is not uncommon to use indicator variables and simply treat them as numeric variables.  But there are other methods as well. One of my favorites is to use decision trees.  Many people learn about decision trees as a means of classification - predicting a nominal value.  Your question is about regression - predicting a numeric value. But decision trees work just fine for regression and have no problems with categorical variables. One of the most popular methods is CART - Classification and Regression Trees. Other decision tree algorithms handle this too. Try googling  decision trees regression and you should find lots on the topic.

Using Non-numeric Features


Prove that cosine is norm decreasing

Question: Prove that:
$|\cos(y) - \cos(x)| <|x-y| ,\forall (x,y)\in(\mathbb{R} \times \mathbb{R}) /\triangle(\mathbb{R})$
My attempt
It looks like we need to prove that the cosine function is norm decreasing.So the goal is to show that $$d(f(x),f(y))<d(x,y),\forall x\neq y$$
By the mean value theorem, Let $f(x)=\cos(x)$ then $f'(x)=-\sin(x)$. So $$-\sin(c)= \frac{\cos(y)-\cos(x)}{y-x}$$
$$\Rightarrow (y-x)(- \sin(c))=\cos(y)-\cos(x) $$
I am not sure, but can we conclude anything about cosine being bounded here? Why or why not?
By some trig identities we know that:
$$i) \sin(A+B)=\sin(A)cos(B) +\cos(A) \sin (B)$$
$$ii) cos(A+B)= \cos(A) \cos(B) - \sin(A) \sin(B) $$
$$iii) \cos(x)-\cos(y)= -2\sin(\frac{x-y}{2})(\sin\frac{x+y}{2})$$
Plugging $iii$) in $d(f(x)-f(y))<d(x,y)$:
$$|-2\sin(\frac{x-y}{2})(\sin\frac{x+y}{2})|<|x-y|$$
$$= 2|\sin(\frac{x-y}{2})(\sin\frac{x+y}{2})|<|x-y|$$
Don't really know where to go from here
Oh and another thing... why is the domain $\forall (x,y)\in(\mathbb{R} \times \mathbb{R}) /\triangle(\mathbb{R})$, what does this even mean?
Comment: As for your last question, the forward slash seems to mean what is more usually denoted by the backslash $\setminus$, set difference:  the expression refers to $(x,y)$ with $x\ne y$, since obviously $\cos(x)-\cos(x)=x-x=0$.  $\triangle(\Bbb{R})$ looks like an unusual notation for the diagonal in $\Bbb{R}\times \Bbb{R}$. General advice:  do it first for $0\le x < y\le \pi/2$.
Answer: The set on which this is true should be written as
$$ \mathbb{R} \times \mathbb{R} \setminus \Delta(\mathbb{R}), $$
I believe: this is the set of pairs of real numbers without the diagonal: elements of the form $(x,x)$. $\Delta(\mathbb{R}) = \{(x,y):x=y \} $. This is obviously necessary since both sides are zero if $x=y$, so not unequal.

Pursuing your trigonometric identity idea, you have that
$$ \cos{(A+B)} = \cos{A}\cos{B}-\sin{A}\sin{B} \\
\cos{(A-B)} = \cos{A}\cos{B}+\sin{A}\sin{B}, $$
so subtracting gives
$$ \cos{(A+B)}-\cos{(A-B)} = - 2\sin{A}\sin{B} . $$
Replacing $A$ and $B$ by $(x\pm y)/2$ then gives
$$ \cos{x}-\cos{y} = -2\sin{\left( \frac{x+y}{2} \right)}\sin{\left( \frac{x-y}{2} \right)}. $$
Now, we want to show that the right-hand side is less in absolute value than $\lvert x-y \rvert$. Obviously $\left|\sin{\left( \frac{x+y}{2} \right)}\right|\leq 1$, so it suffices to show that $2\left|\sin{\left( \frac{x-y}{2} \right)}\right|<\lvert x-y \rvert$ for $\lvert x-y \rvert \neq 0$, which can be rewritten as
$$ \lvert\sin{u}\rvert<\lvert u \rvert $$
for $u \in \mathbb{R} \setminus \{0\}$. This is obviously true for $\lvert u\rvert>1$ since $\sin{u}$ is bounded between $1$ and $-1$. Moreover, it suffices to check for $u>0$ since $\sin{u}$ is odd. A simple geometrical argument can now be used: draw a circle with centre $O$, and draw two lines through $O$ that contain an angle $u$, meeting the circle at $A$ and $B$ respectively. Then $\triangle AOB$ has area $\frac{1}{2}R^2\sin{u}$, while the sector $OAB$ has area $\frac{1}{2}R^2u$, and is obviously larger than the triangle. The result follows.
Comment: Thank you, you wrote: $$ \cos{(A+B)} = \cos{A}\cos{B}-\sin{A}\sin{B} \\
\cos{(A+B)} = \cos{A}\cos{B}+\sin{A}\sin{B}, $$ which is a typo?
Comment: Of course. Careless copy-and-paste costs lives. Thanks, fixed.
Answer: Hint: Suppose $y>x$. By fundamental theorem of calculus, $\cos(y)-\cos(x)=\int_x^y -\sin(t)\, \textrm{d}t$. It is enough to notice that $ \int_x^y \lvert\sin(t)\rvert \,\textrm{d}t<\int_x^y 1\,\textrm{d}t$.

Prove that cosine is norm decreasing


Como deletar objetos dentro de uma lista?

Question: Tenho o seguinte código:
using (Context contexto = new Context())
{
    List<Cliente> listCliente = contexto.Cliente.Where(x => x.Status == 0).ToList();
}

Como faço para deletar do banco esse resultado? Lembrando que tenho inúmeros relacionamentos que também gostaria de deletar.
Algo do tipo:
using (Context contexto = new Context())
{
    List<Cliente> listCliente = contexto.Cliente.Where(x => x.Status == 0).ToList();

    foreach(Cliente objCliente in lilstCliente)
    {
        contexto.Cliente.Remove(objCliente);
    }
    contexto.SaveChanges();
}

Ao rodar dá o seguinte erro:

The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

Ao invés do:
contexto.Cliente.Remove(objCliente);

Tentei também:
System.Data.Entity.Infrastructure.DbEntityEntry deb = contexto.Entry(entity);
deb.State = EntityState.Deleted;

E deu o mesmo erro.
Atualizando o caso:
Bom, como ainda não descobri como fazer de forma genérica essa exclusão em cascata e preciso colocar isso em produção, por enquanto estou tratando objeto por objeto, e como provavelmente não previ todos os relacionamentos possíveis, fiz de forma que quando dê algum erro de chave estrangeira, grave esse erro e sei que preciso fazer um tratamento a mais, basta atualizar o serviço em questão.
O objeto que quero excluir pode ter vários relacionamentos, e esses relacionamentos podem ter outros relacionamentos, todos dependendo do objeto que quero excluir. Ex: quero excluir cliente, o cliente tem um processo, o processo tem histórico. Ou seja, se eu excluir o cliente, quero que tanto o processo quanto o histórico do processo sejam excluídos também.
Comment: Tente entender isso aqui : https://stackoverflow.com/questions/5538974/the-relationship-could-not-be-changed-because-one-or-more-of-the-foreign-key-pro.

Estou sem tempo agora, se não tentava te ajudar melhor, mas parece que isto ali resolve. Abraço
Comment: Você precisa mostrar os models que fazem relação com clientes.
Comment: @Bruno No caso do link que você passou, ele precisa fazer um tratamento em cada objeto que depende do objeto principal, certo? Então, eu gostaria de saber se tem como fazer tipo um delete cascade. Todos objetos que dependem do objeto principal precisariam ser deletados.
Comment: @LINQ Preciso dar um include em todos os objetos que dependem do objeto cliente? Não entendi muito bem o comentário.
Comment: Ah, você quer configurar um cascade delete para os dependentes de `Cliente`?
Comment: @LINQ Mais ou menos isso, mas pelo c# ou alguma funcionalidade do entity framework, tem como? Não pelo banco ou edmx, entende?
Comment: Tem como sim, perai
Comment: Como esta configurado seu DbContext ?  veja seu método OnModelCreating se esta configurado para não fazer delete em Cascade. modelBuilder.Conventions.Remove();
Comment: @MarconcilioSouza Não tem nada nele, além do padrão "throw new UnintentionalCodeFirstException()".
Answer: Por padrão o EntityFramework já faz o deletecascade por default, apenas se você desligar ele com o seguinte comando ele não o fará:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
}

No seu caso você tem um relacionamento 1-0:1 assim o Entityframework não sabe o que fazer quando tem um valor null, ele não consegue fazer o delete. Esse é um limite do EntityFramework < 6 e não tem o que fazer
Sugestão:

Como informado, delete os registros-filhos manualmente.
Existem diversas bibliotecas que estendem o EntityFramework como o http://entityframework-plus.net/ tente encontrar algo que faça isso.

Sobre os 2 comandos que você executou
Na entidade 6.0 há uma diferença entre:
context.Cliente.Remove(entity);

e
context.Entry(Cliente).State = EntityState.Deleted;

Ao usar o primeiro, cascata estão habilitados, a EF executará internamente as eliminações necessárias para os registros-filho. Ao usar a segunda opção, a EF não irá lidar com as eliminações necessárias.


Adjusting clarinet or saxophone reeds

Question: How do various techniques and equipments for adjusting reeds compare? e.g.

 (blade perpendicular strokes)

 (Tom Ridenour's Tools + DVD)

 (David Bourque's Instructions)

 (Ben Armato's Machine)

Reeds bought from stores, even of the same brand from the same batch rated with the same number, do not work equally well. Reeds also change their character as time goes by. What (physical adjustments) can I do to shape the reeds to make them / keep them sounding the best they can? Any techniques or equipments you personally have used / invented that works consistently well enough and cost a reasonable amount?
Comment: I haven't watched these videos just yet, but do you have anything specific you are trying to accomplish?  Any specific problem(s) you are trying to solve regarding your reeds?
Comment: As Andrew said - it would be helpful if your question asked "what techniques work well to accomplish xxxx"
Answer: I am assuming for this answer that you are wanting to adjust commercial reeds made from cane (not synthetic materials), and that you are not trying to make your own reeds from blanks or from stalks of cane.
I have always felt that my time with the saxophone was too limited as it was.  So, I always wanted to keep the reed work as simple and quick as possible while getting the desired results.  It so happens that I also have spent relatively little money doing so.
Also, it is important to store reeds well so that they last.  Doing so is, in my opinion, at least as important as adjusting the reeds correctly.
With all that in mind, here is a list of what I use to deal with reeds.  It's really not as extensive as it may seem at first glance.
Materials and tools

Good reeds to begin with.  "Good" depends on what you like, of course.  As a classical saxophonist, I've never found anything I like better than the standard Vandoren traditional "blue box" reeds, but the techniques apply no matter which brand you are using.
Proper containers for the reeds themselves once they are used.  The plastic cases that the Vandoren reeds come in are not good for storing them (explanation below).  I still use the old La Voz (now just Rico, I think) ReedGard-style cases, but there are lots of other products out there that I presume would be just fine.  Some people prefer the type that have ridges under the reed to let air in.  I have some of both type and honestly haven't noticed a difference in the reeds stored in each.
Some kind of container for the reed containers.  The idea here is to manage humidity.  (There are products that combine this function with the reed cases themselves, though I have found the present solution to be more cost-effective.)  I've had decent luck with just a plastic Tupperware-style box-shaped container.  The lid can seal or be left a little open, depending what I need to do with the humidity.
Some kind of humidity regulation for the container.  A ball of rock salt (maybe an inch or so in diameter) held together by a nylon can work nicely for this.  You don't want the container to be too dry (which causes problems with how the reeds play, see below) or too wet (which can allow the reeds to decay and mold).  Some of the commercial case/container combinations use charcoal.  I've never tried charcoal.
Wet/dry sandpaper, 320 or 400 grit.  This is one example that should work.  I used to be able to get something like this from the automotive section at Wal-Mart for about $4 for a package, but I haven't bought any in some time.  You can cut the sheets into smaller pieces for convenience.
A truly flat surface on which to work.  Some people like plexiglass.  I've always been fine just using a table.
Optionally, a reed knife.  You can get by without it if you have the sandpaper, and I did exactly that for a long time.  It is quicker to have one, though, for the balancing adjustment I describe below.  For single reeds, I don't think it matters what shape of reed knife you have, though I suppose it should be comfortable for you to use.  I think I bought mine for under $20, but that was a few years ago.

Reed warp
At least in the American Midwest, especially in the winter months, the biggest problem with reeds is warping due to uneven drying.  I'm not referring to the wrinkling at the tip of the reed, but rather a more "baseline" change in the reed such that the table (flat side) of the reed is no longer flat.  A warped reed will not seal against the mouthpiece and, therefore, will be harder to play than a flat reed, and it may be tough even to get a sound from the reed.  You can check for warp in two ways.  If you are playing, try taking the mouthpiece off the instrument while keeping the reed on.  Cover the round hole of the mouthpiece with your palm, then suck the air out of the mouthpiece.  If you can remove your mouth from the mouthpiece while the reed stays closed on the mouthpiece, eventually producing a "pop" sound as the reed comes away from the mouthpiece, you have a good seal.  If you cannot make that happen, or the pop happens immediately and is very weak, you probably have a warped reed.  The other way you can tell is to take the reed off the mouthpiece and put it on a flat surface.  Try rocking the reed from side to side.  If the reed rocks that way, it is warped.  The farther it rocks, the more warped it is.
Now, when you play, you want the reed to be wet.  We hope that getting the reed wet cures at least some of the warp issue, and in fact, that is your best bet: if a reed is warped, try soaking it in water for fifteen minutes.  I use something to hold the reed underwater in a cup of water.  (Specifically, I use the plastic holder that the Vandoren reeds ship in.)
If that does not work, you can try sanding the warp out.  Put your sandpaper on the flat surface and rub the reed back and forth across the sandpaper, taking care not to sand the area anywhere near the tip.  This may work, but it is really difficult to get the back of the reed truly flat this way.
One other method is similar to something described in the first video in the question.  Use the reed knife to try to get the reed table flat again.  Again, this is difficult to do well.  The factory will usually do a much better job at getting the reed table flat than I can, so I usually try to avoid working on the table unless the reed is otherwise a lost cause.
Balancing and strength adjustment
If the reed seems too hard, or you have problems playing is a certain range, the reed may be out of balance rather than specifically too hard.  The second video above shows a test on clarinet for balance, though it is not quite clear from the video itself what he is doing to check.  What I typically do on saxophone (alto or lower) is to turn the mouthpiece on the neck so that my lip is holding one rail of the reed shut, then try to play in the low range down to the lowest note.  I turn the mouthpiece the other direction and check the same thing.  If I can play without difficulty on each rail, the reed is probably good in this range.  If the rails play differently, the reed is probably out of balance.  If the rails play the same but are both too hard, the reed is too hard.
If the reed is out of balance, you need to remove material from the side that is harder.  Remember which side was left open to vibrate during your balance test when you had more trouble playing.  Using the knife if you have it or the sandpaper if you don't, remove material from the "low-register" area.  The following diagram shows an approximation.

You will want to remove a little material, then test again.  Especially with the knife, material comes off faster than you might expect.  If you are using a knife, it is important to have the knife moving in a back-and-forth scraping motion prior to contacting the reed; otherwise, you risk gouging the reed.
If the reed was just too hard, you can use sandpaper over the area of the vamp (on the non-flat side of the reed).  Use just a few strokes, avoiding the reed tip.  Then, check again.
Once you have both rails playing the same in the low register, balance the middle register and high register using the same procedure, removing material from the approximate area you need.
Note that if the reed is too soft, there is little you can do to adjust it.  You can try a reed trimmer if you want, but you will not get a lot of extra life out of the reed that way.  You can also make the reed seem a little harder by positioning the reed closer to the tip of the mouthpiece.
While there are certainly more reed adjustments available, some requiring more specialized equipment, I have found that procedures above solve nearly all my reed issues.
Evaluation of the videos
You asked about the Youtube videos, so I will say a few words about each.

The knife technique for flattening reeds is one I also use, but rarely, because I find it very hard to do as well as the factory in getting the reed table flat.  I do not use the knife on the reed table for any other purpose.
Seriously, what's with the hood?  Anyway, I am skeptical of the device being advertised for reasons similar to those I give in #4 below.  Maybe it would work, but I do not feel like spending the money to try it, and I certainly wouldn't try it with any kind of blindfold.
The rest of this DVD may or may not have something useful.  It looks like it's going the right direction, but without seeing the rest of the DVD, it is hard to comment.
This device has three problems that I see.  First, it is possible that your mouthpiece is not exactly symmetrical, so a reed that is exactly symmetrical will not play as a balanced reed on your mouthpiece.  Second, cane is not an internally consistent material.  Just looking at the reed, you can see that there are thicker and thinner fibers.  They are not guaranteed to be in any equal proportion through the reed.  So, there is no guarantee that a "perfectly"-shaped reed will actually have uniform resistance throughout the reed.  Third, I have no way of knowing what shape the device actually produces, but the first two problems are sufficient that I would steer clear of this device.  On the other hand, maybe someone else would have good luck with it.

In conclusion
I would be happy to attempt to answer any questions.  It is very difficult to explain some of these ideas in a web forum, and I may have been less than clear in some of my prose.
Answer: A long time ago I used to be a saxophonist, and later picked up bassoon and carried that into becoming a professional bassoonist.  (However I've undertaken a career change long since.)  In the course of my musical career, I learned to make my own bassoon reeds, and adjust them with knife and sandpaper (other implements required, of course.)
While I was doing this, I figured that similar adjustments could be made to sax reeds.  While I wasn't playing sax any longer, I had friends who still were.  Anecdotally, a box of reeds would have 10-20% of "good" reeds, most were passable but nothing special, and a few that were poor.  After very little experimentation, I discovered that it was very possible to take a "bad" sax reed and make it play much better; Often I could take a throw-away reed and make it play better than the best of the out-of-box reeds.
The simplest thing to do is adjust the reed so that it has longitudinal symmetry; if the left and right sides are asymmetric, it will not play well.
From there, it gets much more tricky (and my memory on specifics is hazy, as it's been many years).  Basically, you want to create a gentle-curving slope from the heart of the reed to the lateral edges, as well as from the center to the tip.  Different locations with different thicknesses/slopes will yield different tonal characteristics regarding tone and responsiveness, and this can be made to vary widely.
For me, I would get a gauge on the progress by holding the reed up to a light to see the variance in brightness/thickness.  After awhile (with single-reeds), I found that great improvements could be made before any play-testing was required (and then usually just response or tonal adjustments to specific sound ranges).
I greatly enjoyed doing this work, but it requires some amount of trial-and-error to get the feel for it.

Looking at the above videos, the jig-and-blade solution looks novel, and will help you get a balanced reed more easily, but if you are not happy with the result that it produces, you will of course need to make more adjustments.
The David Borque instructional set looks like it would be similar to the techniques that I used.

Adjusting clarinet or saxophone reeds


Propositional logic : $¬A \land (A \lor B) \vdash B$

Question: First time posting here. I'm going through some examples and stumbled upon $¬A \land (A \lor B) \vdash B$.
I'm hoping someone can help me with understanding it. This is what I've done so far, mostly I don't know how to continue from line 9 onwards taking into consideration the first part is correct.
TIA
$¬A \land (A \lor B) \vdash B$
1.  ¬A ^ (A v B)        hyp
2.      |¬B     ass
3.      |¬A     1, ^E1
4.  ¬B => ¬A        2-3, =>I
5.      |¬B     ass
6.      |   |¬A sub ass
7.      |   |¬B copy 5.
8.      |¬A => ¬B   6-7, =>I
9.      |   |¬A sub ass
.
.
.
.
.
.
a.      |¬A => B
b.      |¬¬A        8,a, ¬I
c.      |A      b, ¬E
d.  ¬B => A         5-c, =>I
e.  B           4,d ¬I

Update. Tried it like this. Does it make sense? The only issue I have is with line 8 ...
1.  ¬A ^ (A v B)        hyp
2.      |¬B             ass
3.      |A v B          1, ^E2
4.  ¬B => A v B         2-3, =>I
5.      |¬B             ass
6.      |¬A             1, ^E1
7.      |¬A v ¬B        6, vI1
8.      |¬(A v B)       (Taking not common)
9.  ¬B => ¬(A v B)      5-8, =>I
10. ¬¬B                 4,9 ¬I
11. B                   10, ¬E

Comment: How you derive 8 from 7 ?
Answer: First step: we have to "unpack" the premise : $\lnot A \land (A \lor B)$ using $\land$-elim.
Thus, the derivation must start with :
1) $\lnot A \land (A \lor B)$ --- premise
2) $\lnot A$ --- from 1)  by $\land$-elim
3) $(A \lor B)$ --- from 1)  by $\land$-elim.
Then we have to apply $\lor$-elim to 3) :
4) $A$ --- assumed from 3) for $\lor$-elim
5) $B$ --- form the contradiction of 2) with 4) by Ex falso
6) $B$ --- assumed from 3) for $\lor$-elim
Having derived $B$ under both assumptions 4) and 6), we have

7) $B$ --- from 3) and 4)-5) and 6) by $\lor$-elim, discharging temporary assumptions 4) and 6).
Comment: Thanks for your reply! I don't know however what I should do with 3... doesn't make sense. what should A and B imply to satisfy the rule? i.e what should C be?
Comment: I have tried a different approach. Does it make sense?
Comment: I'm unsure how you did 4-6 ... so far I only know the very basic rules i.e. we can't use any lemmas. Could you please explain.
Comment: *Ex falso quodlibet*  is a basic rule of inference.  (It is also known as the Principle of Explosion, or *sometimes* Falsum Elimination ($\bot E$)).


If an API only provides POST requests functions, is it RESTful?

Question: I'm not sure I understand correctly the notion of RESTful API. If I understand correctly, such an API should provide functions you can trigger with GET, POST, PUT & DELETE requests. My question is: if an API only provides POST requests functions, is it still RESTful?
Comment: Yes - it is still RESTul
Comment: I wonder, why there is vote to close the topic? It is not opinion based question and it is directly related to programming!
Comment: It is an *architecture* question, not a *programming* question @SaidbakR
Comment: @JayBlanchard However, it is still meant by programming. The `restful` tag is suffixed with `architecture` too. i.e there is a tag that allows talking about it.
Comment: I think others may be reading this as *"if an API only provides this method is it still this architecture?"* @SaidbakR Just because the tag exists doesn't mean you can ask non-programming questions about it. The OP did not provide [a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve), for example.
Comment: I'd say that this question seems _not concrete_ enough (?), generating possible discussion (as already in the comments of the answers). Like those old locked questions with this text: _"This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here."_, we do have locked questions that are good, but they still are not evidence to ask more questions like them.
Answer: You should probably watch this lecture and read this article.
REST a such has nothing to do with how much of available HTTP methods you use. So, the quick answer is: yes, it could be considered "restful" (whatever that actually means).
Buuut ... it most likely - isn't. And it has nothing to do with the abuse of POST calls.
The main indicator for this magical "RESTfulness" has nothing really to do with how you make the HTTP request (methods and pretty URLs are pointless worthless as a determining factor).
What matters is the returned data and whether, by looking at this data, you can learn about other resources and actions, that are related the resource in any given endpoint. It's basically about the discover-ability.
Comment: @Martin I think you mis-read what I wrote. Or you have no understanding of what REST is.
Comment: Not at all. You clearly dont know the subject. Read this if you mind http://www.restapitutorial.com/lessons/restfulresourcenaming.html
As someone already said, Restful is an architecture, and it has some guidelines. I wouldn't expect a Restful API to have a GET that deletes something when I call it. It has a lot of aspects, it's not only about the data. It's also not about URLs being "pretty", there should be "atomicity" when you use URLs, etc.
Comment: No, I read correctly. You wrote (methods and pretty URLs are pointless) which is totally false.
Comment: Sorry .. I meant "worthless as a determining factor". Updated.
Comment: It does matter, and is determining. In fact the lecture you provided shows how to refer to resources using URLs, and talks about safe GETs.
Quoted from the lecture link you provided:
"So now rather than making all our requests to a singular service endpoint, we now start talking to individual resources." which has to do with URL naming.
"Level 2 moves away from this, using the HTTP verbs as closely as possible to how they are used in HTTP itself."  which talks about the importance of HTTP verbs.
I think you are misleading the person who asked.
Comment: I read a book: http://shop.oreilly.com/product/0636920028468.do, so no need for those links. Bye!
Answer: REST is a misused term for some time and the community especially at Stackoverflow doesn't even care about its actual intention, the decoupling of clients from server APIs in a distributed system.
Client and server achieve the decoupling by following certain recommendations like avoiding stateful connections where client state is stored at and managed by the server, using unique identifiers for resources (URIs) and further nice-to-have features like cacheability to reduce the workload both server and clients have to perform. While Fieldings dissertation lists 6 constraints, he later on explained some further rules applications following the REST architectural style have to follow and the benefits the system gains by following these. Among these are:

The API should not depend on any single communication protocol and adhere to and not violate the underlying protocol used. Altough REST is used via HTTP most of the time, it is not restricted to this protocol.
Strong focus on resources and their presentation via media-types.
Clients should not have initial knowledge or assumptions on the available resources or their returned state ("typed" resource) in an API but learn them on the fly via issued requests and analyzed responses. This gives the server the opportunity to move arround or rename resources easily without breaking a client implementation.

So, basically, if you limit yourself only to HTTP you somehow already violate the general idea REST tries to impose.
As @tereško mentioned the Richardson maturity model I want to clarify that this model is rather nonsense in the scope of REST. Even if level 3 is reached it does not mean that this architecture follows REST. And any application that hasn't reached level 3 isn't following this architectural style anyways. Note that an application that only partially follows REST isn't actually following it. It's like either properly or not at all.
In regards to RESTful (the dissertation doesn't contain this term) usually one regards a JSON based API exposed via HTTP as such.
To your actual question:
Based on this quote

... such an API should provide functions you can trigger with GET, POST, PUT & DELETE requests

in terms of REST architectural style I'd say NO as you basically use such an API for RPC calls (a relaxed probably JSON based SOAP if you will), limit yourself to HTTP only and do not use the semantics of the underlying HTTP protocol fully; if you follow the JSON based HTTP API crowd the answer is probably it depends on who you ask  as there is no precise definition of the term "RESTful" IMO. I'd say no here as well if you trigger functions rather than resources on the server.
Answer: Yes. Restful has some guidelines you should follow. As long as you use HTTP verbs correctly and good practices with regards to URLs naming having only POSTs would be OK. If, on the other hand, a POST request in your application can also delete a record, then I would not call it Restful.
Comment: My answer stands true. If you down-vote you should explain why.


Why is the response I am receiving from my request not filtering correctly?

Question: Good day,
I am trying to integrate an API into a Wordpress site.
API Documentation
I have tested the API using Postman and I am able to get the correct response.
Reading the documentation and various other sources I have come up with the following code to list the various results and then perform a search on the results.
public function search_jobs( $param = [], $filter = [] ){
    $update_token                   = [];

    $this->id_token                 = $this->settings_obj->get_setting( 'id_token' );

    $response_arr                   = [];
    $response_arr['code']           = 0;
    $response_arr['alert']          = "";
    $response_arr['data']           = [];

    $endpoint                       = $this->base_url . "job/search/fl=id,job_title,location,created_date,industry,public_description,summary;sort=published_date desc";

    if( $filter && !empty( $filter ) ){

        $search_string = isset( $filter['vj_search'] ) ? sanitize_text_field( $filter['vj_search'] ) : "";

        $search_industry = isset( $filter['industry'] ) ? $filter['industry'] : [];
        $search_location = isset( $filter['location'] ) ? $filter['location'] : [];
        $search_function = isset( $filter['function'] ) ? $filter['function'] : [];

        $search_filter_qry = [];
            $search_filter_qry[] = "fq=private_job:0";

        if( $search_industry && !empty( $search_industry ) ){
            $search_filter_qry[] = "fq=sub_industry_id:" . implode( " OR ", $search_industry );
        }

        if( $search_location && !empty( $search_location ) ){
            $search_filter_qry[] = "fq=country_code:" . implode( " OR ", $search_location );
        }

        if( $search_function && !empty( $search_function ) ){
            $search_filter_qry[] = "fq=sfe_id:" . implode( " OR ", $search_function );
        }

        $search_filter_qry_str = implode( "%23&", $search_filter_qry );

        if( !empty( $search_filter_qry_str ) ){
            $endpoint = $endpoint . "?" . $search_filter_qry_str . "%23";
        }

        if( !empty( $search_string ) ){
            $endpoint = $endpoint . "&q=text:" . $search_string . "%23";
        }

I am able to get the response on the page required and I am also able to search by location and industry, however I have the following issue:
The result includes all results where I am trying to only get jobs that are not private $search_filter_qry[] = "fq=private_job:0";
If I edit $endpoint and change it to:
$endpoint                       = $this->base_url . "job/search/fl=id,job_title,location,created_date,industry,public_description,summary;sort=published_date desc?fq=private_job:0 %23";

I get the correct response on the original display of jobs with only results that are public, but then I am unable to perform any searches.
I understand it is because of the concatenation that Is then creating the wrong request when I edit the $endpointand it returns 0 results found.
I have spent a couple of days on this by changing for example $search_filter_qry[] = "fq=private_job:0"; to $search_filter_qry[] = "?fq=private_job:0"; by adding in the ?. I will be honest I am not to comfortable yet with the SOLR Backend that the API uses.
Can anyone please have a fresh look at my code and give me an idea as to what I am missing please.
Comment: Is the `/job/search` part a _direct_ mapping to Solr? or is that endpoint inside your Wordpress installation?
Comment: @MatsLindh Hi, It is direct mapping used by the API.
Comment: My full request to list all jobs that are set to public is as follows: https://domain.vincere.io/api/v2/job/search/fl=id,job_title,location,created_date,industry,public_description,summary;sort=published_date desc?fq=private_job:0%23
Comment: But is `/job/search` the Solr server, or is it your Wordpress installation? If the query is sent directly to a Solr server, the syntax is wrong (i.e. it should be `job/search?fl=..&q=..&fq=...`) Since you're not showing how you're sending the query to the server, it might be that you're also prepending `$endpoint` multiple times.
Answer: I was able to find the solution as follows:
I changed the $endpoint before the if statement to:
$endpoint                       = $this->base_url . "job/search/fl=id,job_title,location,created_date,industry,public_description,summary;sort=published_date desc?fq=private_job:0%23";

And then after the initial if statement,
if( $filter && !empty( $filter ) ){
I added the $endpoint as
$endpoint                       = $this->base_url . "job/search/fl=id,job_title,location,created_date,industry,public_description,summary;sort=published_date desc";

This allowed the concatenation to work correctly if the search parameters are not empty.


Using hook_form_alter in overlay admin theme

Question: I am using hook_form_alter in a custom module to remove some fields from the block edit screen to clean up the ui for users of a certain role
function module_form_block_admin_configure_alter(&$form, &$form_state, $form_id) {
  global $user;
  if (in_array('staff member', $user->roles)) {
    $form['visibility_title']['#access'] = FALSE;
    $form['visibility']['#access'] = FALSE;
    return $form;
  }
}

It works great. However, when the form appears in Drupal's admin overlay using the site's admin theme, Seven, the above code is not applied.
Is this because it's in an overlay? Or because it's a different theme? How can I get the hook_form_alter to apply globally?
FWIW, adding
function module_form_alter(&$form, &$form_state, $form_id) {
    dpm($form);
}

doesn't print anything above the form in the overlay. But when I switch the admin theme to the site's theme, it properly dpm's the form.
Note: The custom module and the site's custom theme have the same name. Is this the problem?
Comment: If you implement a form alter hook in a .module file it will be invoked no matter what theme you're using or whether the form is displayed in an overlay...is it possible you're actually implementing the hook at the theme level?
Comment: Thanks, Clive. My code is identical to what's above. It's in a .module file. Also, when I add:

function module_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);
}

it doesn't show anything above the form in the overlay. Hmmm...
Answer: Thanks to Clive's tip I realized that because my module and theme had the same name, the hook was being applied at the theme level. I renamed my module and now it works!