Post JSON no Android

Question: Gostaria de saber se o android está sim ou não realizando o post do meu JSON.
Segue o código:
public void login(JSONObject dados) {
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost hp = new HttpPost();

        hp.setURI(URI.create("http://10.0.2.2/restq/pages/salas"));
        hp.setHeader("Accept", "application/json");
        hp.setHeader("Content-type", "application/json");

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("json", dados.toString()));

        hp.setEntity(new StringEntity(dados.toString()));

        HttpResponse response = client.execute(hp);

        HttpEntity entity = response.getEntity();

        InputStream instream = entity.getContent();

        String resp = new Scanner(instream, "UTF-8").next();
        JSONObject jo = new JSONObject(resp);

        Log.d("JSON Retorno", jo.toString());
    }
}

Comment: Você não consegue obter esta informação através do objeto `response`?
Answer: Sim, você está fazendo uma requisição HTTP utilizando o método POST.
Para verificar o que está sendo enviado na requisição você pode utilizar algumas ferramentas, como o RequestBin, ele coleta as informações da requisição e lhe deixa inspecionar o que está sendo enviado.
Um ponto interessante a ser notado, é que já que você não está utilizando a variável pairs, você poderia removê-la do seu código, ficando assim:
public String post(final JSONObject data) {
    try {
        final HttpClient client = new DefaultHttpClient();
        final HttpPost httpPost = new HttpPost();

        httpPost.setURI(URI.create("http://requestb.in/1e4rp5p1"));
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        httpPost.setEntity(new StringEntity(data.toString()));

        final HttpResponse httpResponse = client.execute(httpPost);
        final HttpEntity entity = httpResponse.getEntity();
        final InputStream stream = entity.getContent();
        return new Scanner(stream, "UTF-8").next();
    } catch (Exception e) {
        Log.e("Your tag", "Error", e);
    }

    return null;
}

Outro ponto a ser notado, é que a classe DefaultHttpClient está obsoleta a partir da API 22. Dito isto, eu recomendo você utilizar a classe URLConnection:
public String post(final JSONObject data) {
    try {
        final URL url = new URL("http://requestb.in/1e4rp5p1");
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-type", "application/json");

        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);

        final OutputStream outputStream = connection.getOutputStream();
        final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));

        writer.write(data.toString());
        writer.flush();
        writer.close();
        outputStream.close();

        connection.connect();

        final InputStream stream = connection.getInputStream();
        return new Scanner(stream, "UTF-8").next();
    } catch (Exception e) {
        Log.e("Your tag", "Error", e);
    }

    return null;
}

Você também pode utilizar bibliotecas para simplificar essa parte como OkHttp, Volley ou até mesmo Retrofit.
Um exemplo de utilização da biblioteca OkHttp:
public String post(final JSONObject data) {
    try {
        final RequestBody body = RequestBody
                .create(MediaType.parse("application/json"), data.toString());
        final Request request = new Request.Builder()
                .url("http://requestb.in/1e4rp5p1")
                .post(body)
                .addHeader("Accept", "application/json")
                .build();
        final OkHttpClient client = new OkHttpClient();
        final Response response = client.newCall(request).execute();
        return response.body().string();
    } catch (Exception e) {
        Log.e("Your tag", "Error", e);
    }

    return null;
}

Lembrando que em nenhum dos exemplos acima é feita a verificação de status da requisição, e que é tratada a classe Exception, onde é interessante que sejam tratadas apenas as exceções específicas como IOException.
Espero ter ajudado.
Comment: Pedro obrigado pela ajuda.
Creio que estou fazendo algo de errado pois tentei das duas formas acima e tentei devolver o $_REQUEST do php para ver se voltava algo. Porém toda vez ele retorna vazio.
Comment: Pedro no fim das contas você me passou a resposta. Usei a biblioteca OkHttp e testei se estava enviando algo por post. O resultado foi que passou os dados por post. Ajustei o PHP pra pegar file_get_contents ao invés de $_REQUEST e funcionou.
Agradeço muito muito mesmo pela ajuda
Comment: Fico feliz por ter ajudado! :)

Post JSON no Android


PhalconPHP - How to display 500 error to users

Question: How to display 500 error with PhalconPHP to users?
I use this code to display 404 error (display error404.volt view) and 500 error (display error500.volt view).
The 404 error page display as expected but not the 500 error page.
<code>$di->set('dispatcher', function() {
    //Create/Get an EventManager
    $eventsManager = new \Phalcon\Events\Manager();
    //Attach a listener
    $eventsManager->attach("dispatch:beforeException", function($event, $dispatcher, $exception) {
        //Handle 404 exceptions
        if ($exception instanceof \Phalcon\Mvc\Dispatcher\Exception) {
            $dispatcher->forward(array(
                    'controller' => 'index',
                    'action' => 'error404'
            ));
            return false;
        }
        //Handle other exceptions
        $dispatcher->forward(array(
                'controller' => 'index',
                'action' => 'error500'
        ));
        return false;
    });
    $dispatcher = new \Phalcon\Mvc\Dispatcher();
    //Bind the EventsManager to the dispatcher
    $dispatcher->setEventsManager($eventsManager);
    return $dispatcher;
}, true);
</code>
Answer: You can do this by setting the status of the request in the forwarded controller's action. In your case indexController::error500Action()
<code>$this->response->setStatusCode(500, "Internal Server Error");
</code>
Comment: then try using the php function header("HTTP/1.0 500 Internal Server Error");
Comment: sorry for that. i see you are forwarding the request to error500Action in indexController. This being said you need to create the controller and the action for it. I highly recommend you to read the documentation for phalcon and check out the invo site example: http://docs.phalconphp.com/en/latest/index.html
Comment: I did and it still does not show error in the browser.
Comment: please see my updated question, I'd like to display view "error500" to users when the Internal Server Error happens, using function header currently display nothing in the browser.
Comment: I have created the controller "IndexController.php" and action "public function error500Action(){}" but still nothing is displayed.
Comment: did you also create the views for it?
Comment: Yes, I have created a view for it.
Answer: I use the following in public/index.php
An empty error404Action function is needed in Controllers/IndexController.php
along with a views/index/error404.phtml file where i create my custom error page
<code>    try
    {
        //load phalcon
    }
    catch(Exception $e)
    {
        $errorCode = $e->getCode();
        if($errorCode === 2 OR $errorCode === 5)
        {
            $response = new \Phalcon\Http\Response();
            $response->redirect('index/error404');
            $response->send();
            //return;
        }

        // put here code for managing your case

    }
</code>


Django Rest Framework Foreign Key in Junction Table

Question: I have the following model structure:
game
| id | name | description |
|:-- |:---- |:----------- |
platform
| id | name |
|:-- |:---- |
game_detail
| id | release_date |
|:-- |:------------ |
game_platform
| id | game_id | platform_id | game_detail_id |
|:-- |:------- |:----------- |:-------------- |
game_platform table is the junction table and in which the game_detail_id is foreign key of the game_detail table. Following is the models.py file:
class Game(models.Model):
name = models.CharField(max_length=50)
description = models.TextField(blank=True, null=True)
genre = models.ForeignKey(Genre, related_name="games", on_delete=models.CASCADE)
platforms = models.ManyToManyField(
    "Platform", related_name="games", through="GamePlatform"
)

class Platform(models.Model):
    name = models.CharField(max_length=50)

class GameDetail(models.Model):
    release_date = models.DateField()

class GamePlatform(models.Model):
    game = models.ForeignKey(Game, on_delete=models.CASCADE)
    platform = models.ForeignKey(Platform, on_delete=models.CASCADE)
    game_detail = models.ForeignKey(GameDetail, on_delete=models.CASCADE)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["game", "platform"], name="unique_game_platform"
            )
        ]

How do I serialize in serializers.py and write the logic in modelviewset so that I can get something like this as the game api response:
[
    {
        "id": 33,
        "name": "Crysis Remastered",
        "description": "",
        "genre": {
            "id": 1,
            "name": "Fps"
        },
        "platforms": [
            {
             "id": 1,
             "name": "PS5",
             "game_detail": {
              "release_date": "2020-11-03"
             }
            },
            {
             "id": 2,
             "name": "PC",
             "game_detail": {
              "release_date": "2020-11-13"
             }
            }
        ]
    }
]

Answer: I guess You will have to create some serializers to get the response you want
First, we will create a serializer for Genre model
Class GenreSerializer(serializers.ModelSerializer):
      class Meta:
        model=Genre
        fields =('id','name')

Second a serializer for GameDetail model
Class GameDetailSerializer(serializers.ModelSerializer):
      class Meta:
        model=GameDetail
        fields =('release_date')

Third a serializer for GamePlatform model
Class GamePlatformSerializer(serializers.ModelSerializer):
      game_detail=GameDetailSerializer(read_only=True)
      class Meta:
        model=GamePlatform
        fields =('id','name','game_detail')

The final piece is the serializer for Game model
Class GameSerializer(serializers.ModelSerializer):
      genre=GenreSerializer(read_only=True)
      platforms=GamePlatformSerializer(read_only=True,many=True)
      class Meta:
        model=Game
        fields =('id','name','description','genre','platforms')

Answer: The below code will give you the exact response.
models.py
class GamePlatform(models.Model):
    game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name="game_platforms")
    platform = models.ForeignKey(Platform, on_delete=models.CASCADE)
    game_detail = models.ForeignKey(GameDetail, on_delete=models.CASCADE)

views.py
class GameModelViewSet(ModelViewSet):
    permission_classes = (permissions.AllowAny, )
    serializer_class = GameSerializer
    queryset = Game.objects.all().prefetch_related('game_platforms')

serializers.py
class GameSerializer(serializers.ModelSerializer):
    platforms = serializers.SerializerMethodField()

    class Meta:
        model = Game
        fields = '__all__'
        depth = 1

    def get_platforms(self, obj):
        platforms = GamePlatform.objects.filter(game=obj).values('id', 'platform__name', 'game_detail__release_date')
        final_data = {}
        for platform in platforms:
            final_data['id'] = platform['id']
            final_data['name'] = platform['platform__name']
            final_data['game_detail'] = {
                'release_date': platform['game_detail__release_date']
            }
        return final_data


cassandra skip columns on copy data from csv file

Question: I want to copy some columns from csv file to cassandra table. There's 300 columns in csv file and I only need the first ten columns. There's no header in the csv file.
I tried
copy table from 'file.csv' with header=false and skipcols=[range(11,300)]

but it didn't work.
Comment: "it didn't work" - what happened? Did you get an error message? Did it do the import but not as you expected? What version are you using? The docs (https://docs.datastax.com/en/dse/5.1/cql/cql/cql_reference/cqlsh_commands/cqlshCopyFrom.html) don't make any mention of using `range` in the skipcols option.
Answer: Can you specify column names after table name i.e.
COPY TABLE xx(c1,c2..C30) FROM ..


Looping back through string array

Question: So I got this String array that I'm looping through. A rookie question, but, how do I reverse and loop back? Basically what I want is both a "forward" and a "back" function so one doesn't have to loop through the entire array to get back to "a". Thanks!
<code> public class FirstActivity extends Activity {

    private static int counter = 0;
    private TextView exampleTextView;
    string exampleText;

    private static final String[] EXAMPLESTRINGS = {
    "a",
    "b",
    "c"
    };

public void generateText(View v) {

    String exampleText = EXAMPLESTRINGS[counter++];
    if( counter == EXAMPLESTRINGS.length ) {
        counter = 0;
    }
    exampleTextView.setText(exampleText);
}
</code>
Comment: Have you tried `counter--`? or just `EXAMPLESTRINGS[0]`? It's a little hard to tell exactly what your problem is or how you expect to implement this. It sounds like you might be thinking an array is sort of like a tape and can only be accessed successively — it's not. You can get any value from an array, not just the "next" one.
Comment: http://stackoverflow.com/questions/2297110/java-linkedlist-previous-next might help
Answer: I'm guessing that the generateText() method is a method that gets called from the UI somehow?
Try something like:
<code>public void generateTextForward(View v) {
    if( counter == EXAMPLESTRINGS.length -1 ) {
        counter = 0;
    }
    String exampleText = EXAMPLESTRINGS[counter++];
    exampleTextView.setText(exampleText);
}

public void generateTextBackward(View v) {
    if( counter == 0 ) {
        counter = EXAMPLESTRINGS.length -1;
    }

    String exampleText = EXAMPLESTRINGS[counter--];
    exampleTextView.setText(exampleText);
}
</code>
And now you have two methods, one for forward and one for backwards. Don't really know the application for this :)
But as some comment above suggested, take a look at a linked list for this instead.
Comment: Exactly, the idea is to have a backwards and a forwards button that deliver the previous/next string in the array. Your code seem to be on the right track, however the behavior is somewhat strange: When executing generateTextBackward, it first goes forward, and only upon executing the function again (and consequent executions) does it go backwards. So starting on "a" it goes "a"-"b"-"a"-"c". Any idea why?

Looping back through string array


$\langle a_1, \cdots, a_n \mid 2a_1 + \cdots + 2a_n = 0 \rangle \cong \mathbb Z \oplus \cdots \oplus \mathbb Z \oplus \mathbb Z/2$?

Question: Let $nP$ be connected sum of $n$ Real projective planes. Then, abelianization of $\pi_1(nP)$ is the additive group generated by $a_1, \cdots, a_n$ with one relation $2a_1 + \cdots + 2a_n = 0$, where $a_1, a_2, \cdots, a_n$ are generators of $\pi_1(nP)$. This makes sense, but why is it isomorphic to: $\mathbb Z \underbrace{\oplus \cdots \oplus}_{n-1} \mathbb Z \oplus \mathbb Z/2$?
Can anyone help me to identify such isomorphism? Thank you.
Comment: Smith Normal Form.
Answer: $\pi^{ab}(nP)=\bigoplus_{i=1}^n \mathbb Za_i/ \langle 2\sum_{j=1}^n a_j \rangle $  Consider the abelian group isomorphism $\bigoplus_{i=1}^n \mathbb Za_i\rightarrow \bigoplus_{i=1}^n \mathbb Za_i$ given by $a_i\mapsto a_i$ for $i<n$ and $a_n \mapsto \sum_{j=1}^n a_j$. Under this isomorphism, if we write $e_i$ as the image of $a_i$, then  $\pi^{ab}(nP)=\bigoplus_{i=1}^n \mathbb Za_i/ \langle 2\sum_{j=1}^n a_j \rangle \cong \bigoplus_{i=1}^n \mathbb Ze_i/ \langle 2 e_n \rangle\cong \mathbb Z \underbrace{\oplus \cdots \oplus}_{n-1} \mathbb Z \oplus \mathbb Z/2$
Answer: Let $v=(1,1,1,\dots,1) \in \mathbb Z^n$. Then, the vectors $v,e_2,e_3,\dots,e_n$ form a basis of $\mathbb Z^n$. Your group is isomorphic to $\mathbb Z^n/ \langle 2v \rangle$ and so
$$
\frac{\mathbb Z^n}{\langle 2v \rangle}
=
\frac{\mathbb Z v \oplus \mathbb Z e_2 \oplus \cdots \oplus Z e_n}{2\mathbb Z v \oplus 0 e_2 \oplus \cdots \oplus 0 e_n}
\cong
\mathbb Z/2\mathbb Z \oplus \mathbb Z \oplus \cdots \oplus Z
$$


Laravel and HTML Form Builder

Question: I like the Form Builder.  Go Laravel.
What's the difference between the Illuminate version and the Laravel Collective version, and which should we use?  Is the Illuminate version now defunct?
Answer: You have an explanation here : http://laravel.com/docs/5.0/upgrade#upgrade-5.0
under Form & HTML Helpers
Basically, the Illuminate versions of the Form helper and HTML helper are deprecated in the current version of Laravel and have been removed from the framework's core. They are now maintained by the Laravel Collective.
So if you working with Laravel 5, you should use the Laravel Collective version, you can find it here: laravel Collective: Forms & HTML
Comment: I think it's to keep the framework as minimal and modular as possible. Html and form helpers are more like an extension that you can use if you need to.
Comment: Thanks for the ref.  Do you know why Taylor has deprecated this in L5?
Comment: exactly, plus html/form helpers are pretty lame.. just write html, plain and simple, more readable, etc
Answer: In Laravel 5 it is not standard anymore, but you can add it quickly in the composer file if you prefer to work with forms like you did in Laravel 4.
Just add this line in the composer.json, under the require section:
<code>"illuminate/html": "5.*"
</code>
After this step you first need to run the composer update command and you should be good to add the rest.
Then you need to add the service providers in config/app.php under providers section like this:
<code>Illuminate\Html\HtmlServiceProvider
</code>
And as the last part enter these two lines in the config/app.php under aliases section:
<code>'Form'=> 'Illuminate\Html\FormFacade',
'HTML'=> 'Illuminate\Html\HtmlFacade'
</code>

Laravel and HTML Form Builder


Change mouse cursor in Processing

Question: How can I change the mouse cursor in Processing to a png with transparency?
Only in the application window.
Answer: Try this:
<code>PImage mouseCursor;

void setup() {
  size(640,480);

  mouseCursor = loadImage("MouseCursor.png");
}

void draw()
{
  if(mouseX < 100) {
    cursor(mouseCursor, 0, 0);
  } else {
    cursor(HAND);
  }
}
</code>

Change mouse cursor in Processing


Cannot insert images in body of a basic page

Question: I am using CKEditor and WYSIWYG. After updating Drupal core to 8.5.6, I cannot upload an image using the CKEditor's 'image' button anymore saying "Image Field is required."

I have checked CKEditor's plugin settings. Image upload's enabled there.

I have not found a solution yet. Any help will be appreciated.
PS: If I add an image using html "img" tag then it shows up properly, it's only the button that is not working properly.
Comment: I'm voting to close this question as off-topic because it has been cross-posted and answered on drupal.org https://www.drupal.org/forum/support/post-installation/2018-08-24/ckeditor-image-button-cannot-insert-images-in-body-of-a#comment-12854570
Comment: What version did you update from? D8.5 brought in Media module. New way:  https://www.webwash.net/managing-media-assets-using-core-media-in-drupal-8/ Old way: https://www.webwash.net/manage-media-assets-drupal-8/
Comment: Have you updated all your other modules?
Comment: Yes. Every module has been updated.
Comment: Have you tried the Imce file manager module?
https://www.drupal.org/project/imce
I have struggled with CK Editor in the past earlier D8 cores but its getting better. At the moment using the above module works the best and setting up my own styling for left float etc. I'm trying to get it so my client can use it intuitively and I don't think CKE is quite there yet in D8 ..
Answer: I found a solution. Suggested by Tech-Tonic:
https://www.drupal.org/forum/support/post-installation/2018-08-24/ckeditor-image-button-cannot-insert-images-in-body-of-a#comment-12854570

Does your content type have other file fields on it?
  If so, try temporarily disabling all file/image fields for the content type in "Manage form display" and save. Then enable them again and save. Worked for me, in Drupal 8.6.3.

As mentioned above, I also had an image/file field in the content type. Under 'Manage form display', I disabled the image field and saved. I then went back to 'Manage form display', moved it back to where it originally was and saved again.
After this the error no longer appears. This worked on the production, staging and development copies of the same site.


How to prove the following inequality

Question: How to show this inequality:
$1.3.5...(2n-1)<n^n$
the inequality is satisfied for $n=2$
Now proving by induction
$1.3.5...(2n-1)(2n+1)<n^n.(2n+1)$
but the RHS can't be made less than $(n+1)^{n+1}=(n+1)^n.(n+1)$
Obviously $n^n<(n+1)^n$ but $2n+1$ is not less than $n+1$.Any help
Comment: Perhaps you meant $1 \cdot 3 \cdot 5 \cdots (2n-1) < n^n$, i.e. the product of the first $n$ odd numbers ?
Comment: @Neeraj: Did you edit the question based on what OP *could* have meant? It is a completely different question now. Also you have removed OP's attempt to solve the question, so that it looks like a bad question now.
Comment: Yeah there's was an error so I edited it to the correct problem.
Comment: @martinr that makes more sense. The lhs was blowing up way to fast.
Answer: Use AM-GM as follows $$\frac{1+3+\cdots +(2n-1)}{n}\ge \left(1\cdot 3\cdots (2n-1)\right)^{1/n}$$ then $$\frac{n^2}{n}\ge \left(1\cdot 3\cdots (2n-1)\right)^{1/n}$$ gives $$n^n\ge \left(1\cdot 3\cdots (2n-1)\right)$$
Answer: Your inequality is false for $n=2$. The left side is equal to $1\cdot 2 \cdot 3 = 6$, and the right side is equalt to $2^2=4$.
Answer: A proof by induction will probably not work here. But can obtain the result
quite easily by combining factors from "both ends" of the product with
the third binomial formula:
$$
  1 \cdot 3 = (2-1)\, (2+1) = 2^2 - 1^2 < 2^2 \\
  1 \cdot 3 \cdot 5 = (3-2) \, 3 \, (3+1) = (3^2 - 1^2) \, 3 < 3^3 \\
  1 \cdot 3 \cdot 5 \cdot 7 = (4-3)\,(4-1)\,(4+1)\,(4+3) = (4^2 - 3^3)\,(4^2 - 1^2) < 4^4 \\
  \ldots
$$
This should show the idea how the inequality can be proved in general.

How to prove the following inequality


Find the polynomial $p(x)$ such that $p(p(x)) = xp(x)+x^2$

Question:
Find the polynomial $p(x)$ such that $p(p(x)) = xp(x)+x^2$.

First, we let $p(x) = a_0 x^n + a_1 x^{n - 1} + a_2 x^{n - 2} + \cdots + a_n x^0$. Then, on the left side of the given equation we get the term $a_0^2 x^{n^2} + a_n$ and some other terms that aren't so important. Because the right side is divisible by $x$, the left side must also be divisible by $x$. Because all terms in $p(p(x))$ except for $a_n$ are divisible by $x$, we know that $a_n$ must be $0$. That is, $p(x)$ has no constant term.
Next, we look at the degree of $p(x)$. We get that $n^2 = \max(n + 1, 2)$. None of these choices give integer solutions.
However, the degree of $xp(x) + x^2$ can also be less than $\max(n + 1, 2)$. One example is $p(x) = -x$. So, we need the degree of $p(p(x))$ to be less than $\max(n + 1, 2)$. If $p(p(x)) = n^2$ is less than $n + 1$, then $n^2 - n - 1 < 0$. So, $\frac{1 - \sqrt{5}}{2} < n < \frac{1 + \sqrt{5}}{2}$. This means that $n$ can only be $1$ or $0$.
If $n = 0$, then the left hand side is a constant, while the right hand side is a quadratic. This cannot satisfy the problem statement, so we move on to the next case.
If $n = 1$, then $p(x)$ must be in the form $kx$ for some constant $k$ because $p(x)$ has no constant term. Plugging $p(x) = kx$ into the given equation, $k^2x = kx^2 + x^2$. Cancelling $x$ out gives $k^2 = (k + 1)x$. Because the left hand side is a constant, the right hand side must also be a constant. So, $k + 1 = 0$ and $k = -1$. However, this means that $1 = 0$ which is obviously false.
I conclude that there are no solutions, but the problem says that there has to be exactly one solution.
Comment: There is a degree one polynomial satisfying the identity, $p(x)=1-x.$
Comment: You made a mistake with the constant term of $p$. You wrote "because $p(x)$ has no constant term". This is false.
Comment: Why is the first part wrong where it showed that it has no constant term?
Comment: $\deg(p+q)\le\max\{\deg p,\,\deg q\}$; you can't in general change the $\le$ to $=$ as the leading terms of $p,\,q$ may cancel if $\deg p=\deg q$.
Comment: What you have given is mostly Correct , except that you (wrongly) assumed $kx+0$ , where you should check whether $kx+c$ gives a Solution. (A) It may eventually imply $c=0$ , then you have shown that your unproven assumption was right. (B) It may instead give you the Solution !!
Answer:
If $n = 1$, then $p(x)$ must be in the form $kx$ for some constant $k$ because $p(x)$ has no constant term.

It is not sufficient to claim this. It is true that the RHS $xp(x)+x^2$ has no constant term. But for LHS, if we take the general form $p(x)=kx+b$, we get
$$p(p(x))=k(kx+b)+b=k^2x+kb+b$$
So it is still possible for LHS has no constant term. For example, if $kb+b=0$, equivalently, either $b=0$ or $k=-1$. What you have done is to exclude $b=0$. But it is still possible for $k=-1\land b\neq 0$. You still need to discuss this case and get the final conclusion.
Answer:
Find a polynomial $p(x)$ which satisfies $p^2(x)=xp(x)+x^2.$

\begin{align}
& \text{let } \deg(p)=n. \\
\Rightarrow \; & \deg(LHS)=n^2, \deg(RHS)\leq\max\{n+1, 2\}. \\
\therefore\; & n^2\leq\max\{n+1, 2\}. \\
\Rightarrow \; & n^2 \leq 2 \text{ or } n^2\leq n+1. \\
\Rightarrow \; & n \leq 1. \\
\ \\
\text{Case 1. } & n=1: \\
& \text{let } p(x)=ax+b. \\
\Rightarrow \; & a(ax+b)+b=x(ax+b)+x^2. \\
\therefore \; & (-a-1)x^2+(a^2-b)x+b(a+1)=0. \\
\Rightarrow\; & a=-1, b=1 \Rightarrow p(x)=1-x. \\
\ \\
\text{Case 2. } & n=0: \\
& c=cx+x^2, \text{Contradiction.} \\
\ \\
\therefore \; & \boxed{p(x)=1-x \text{ is the only solution.}}
\end{align}
Answer: If $\deg p=1$ then $\deg (p\circ p)=1.$ Thus $p$ must be of the form $p(x)=a-x$ in order to eliminate $x^2$ on RHS. Then we get $p(p(x))=x$ and $xp(x)+x^2 =ax.$ Hence $a=1.$ Thus $p(x)=1-x$ is the only solution, mentioned in the first comment to OP.


How to create menu when dynamic routes

Question: This link https://www.drupal.org/node/2122201 suggest us to make use of route_callbacks when we are using dynamic routes.Can someone tell me how to make use of this route name in *.links.menu.yml file to make menu? The problem is when we are returning $route_collection in the routes() function then it must be containing multiple routes then how to generate menu for any particular dynamic route.
 I did a search inside menu_tree table in the database and find out that no menu has been created with help of dynamic routes so I am beginning to think whether this is possible or not. If it is not possible that what is the possible solution?
Comment: I think actually this a follow up question of the previous question because over here I am asking about menus.If you still think we can close this question and I can ask this question over there.
Comment: I know my problem always revolves around routes everytime but I guess I can't really stop posting about them because I still have not got solution to my problem. Please help me in this question related to route_callbacks().
Comment: In context of the "original" question, you can always use hook_entity_insert to create appropriate menu link. That's how it's done in D7 too.
Answer: You need a derivative plugin, see views module for an example, it dynamically generates menu links for views configured to have a menu entry
Comment: I made an example here http://drupal.stackexchange.com/questions/229813/creating-a-dynamic-menu/229816#229816

How to create menu when dynamic routes


Programatically change user field (entity reference) in drupalgap with user_save()?

Question: We are using DrupalGap to make an app. We have nodes (content type chargingstations) which we want our users to be able to "check" into by pressing a button. Until now I have created a button on the nodes page in DrupalGap which executes a function on an onClick event.
This function takes in a NID which is the node I want the user to check into. I then have a field on the user called "checked_in_chargingstation" which is an entity reference field.
In the DrupalGap documentation there is not much information on user_update. It just says "...". But it seems like you can update a node by passing the NID. So I figured I could do the same for user? But it doesen't seem to work. I get a success alert, but I can't see any changes to the users.
My check in code. Drupal.user.uid gets the current users uid.
<code>function check_in($nid){
  var $field_checked_in_chargingstation = {};
  $field_checked_in_chargingstation["und"] = {
    target_id: $nid,
  };

  var user = {
    uid: Drupal.user.uid,
    field_checked_in_chargingstation: $field_checked_in_chargingstation,
  }

  user_save(user, {
    success:function(result){
      console.log(result);
    }
  });
}
</code>
In the console I get:

Looking at the json I can see:
<code>"field_checked_in_chargingstation": {
 "und": [
  {
   "target_id": "29088"
  }
 ]
},
</code>
But this is the wrong id. This is an old node which I have assigned before from Drupal and "edit" user. So it doesen't seem updated. Trying to drush cc all doesen't seem to work either.
If I try to edit the user from the app I only see null values for the entity reference field. One suggestion in the Drupalgap documentation is to make an entity reference view http://docs.drupalgap.org/7/Entities/Entity_Reference which I also did.
Sorry if this is a bit long. And I'm not sure if I should post it here on Stack Exchange or as an issue on DrupalGap.
Answer: It depends largely on what Widget you have selected for your entity reference field on your Manage Display page. The easiest widget to work with is the Autocomplete widget, at which point you'd send up this JSON:
<code>"field_checked_in_chargingstation": {
 "und": [
  {
   "target_id": "... (29088)"
  }
 ]
},
</code>
The Services module is coupled with the forms system in Drupal, so as you change the widget on a field, the JSON data you need to send to Drupal may change.
Comment: On my manage fields  i have chosen Autocomplete. In the manage display i can choose format and I have chosen "Entity id".
Comment: Since I was only sending the NID i changed my own entity refernece view to only contain the nid.

Tried this, but it didn't seem work. Nothing is changed. Now I tried to send "nodetitle (nid)" by loading the nodes title. And change back to the default "entity selection". Still not working.
And im a bit concerned that I cant edit or see the field when i try to edit the user in drupalgap. It just says "null".
Comment: I also get this error
"WARNING: drupalgap_entity_render_field - entityreference_field_formatter_view() does not exist! (field_user_queue)"
Comment: Have you installed the `entityreference.js` module in DrupalGap? http://drupalgap.org/project/entityreference - that should fix your latter problems. You only need to send the ellipsis and the target id, you don't actually have to send the node title `"... (29088)"`
Comment: No, I had not heard of the entityreference module! Now I can finally change the field from user/edit. But regarding updating the node from a button click: Now i changed to elipsis, but it still won't save.
In the console I get a success with the node as it should be saved.

`field_checked_in_chargingstation:
Object:
  und
     Object:
       target_id:
             "... (26575)"`

But checking my users field from either drupalgap or drupal stills shows the old node. And if i go to the put url it shows the old node.
`"PUT: http://ifi-diw00.uio.no/?q=drupalgap/user/19.json"`
Comment: Careful, there is an array immediately inside the `und`, from your output it looks like you are forgetting the `[]` wrapper.
Comment: Wow, thank you! Such a stupid error of me! :)
`$field_checked_in_chargingstation["und"] = [{
        target_id: "... ("+$nid+")"
      }];`
`var user = {
        uid: Drupal.user.uid,
        field_checked_in_chargingstation: $field_checked_in_chargingstation,
      }
      user_save(user, {
        success:function(result){
          console.log(result);
        }
      });`
Adding the brackets, worked!


How to replace static error.html to custom-error.html in Nuxt 2

Question: I tried to repalace error.html in .nuxt/views/ directory, but I don't know how I can do it.
I use Nuxt 2.15.8.
I tried to follow steps from this article https://blog.lichter.io/posts/nuxtjs-change-server-error-page
This article a bit old, so I am not sure that this approach still works.
Comment: I believe to do what you are wanting you can create a view in layouts directory  i.e. `layouts/error.vue`  nuxt should automatically recognize it and use it as the default.  Here is the documentation entry https://v2.nuxt.com/docs/concepts/views/#error-page
Comment: @skribe thanks for your answer. As far as I understand Nuxt will use `layouts/error.vue` only for client-side errors or when we handled it. For unhandled server-side errors, Nuxt will show static `error.html`.
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: Example from article works. We can replace the default error.html. Also, we can configure custom error messages in nuxt.config.js to do this we need to add messages field in nuxt.config.js. For instance:
export default {
 messages: {
   hello_world: "Hello World!"
 }
}

in your custom error.html, we need to do this

<%= messages.hello_world %>


.Net 4.7.2 app does not honor SCHANNEL protocol settings

Question: I disabled TLS 1.0 and 1.1 like so:
[HKEY_LOCAL_MACHINE\SYSTEM...\SCHANNEL\Protocols\TLS 1.0\Client]
"DisabledByDefault"=dword:00000001
"Enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM...\SCHANNEL\Protocols\TLS 1.0\Server]
"DisabledByDefault"=dword:00000001
"Enabled"=dword:00000000

[repeat for 1.1]

When I hit https://clienttest.ssllabs.com:8443/ssltest/viewMyClient.html with a browser, I get
TLS 1.3 No
TLS 1.2 Yes
TLS 1.1 No
TLS 1.0 No

When I hit the same endpoint from the same server with a .Net 4.7.2 console app that executes these lines
HttpClient c = new HttpClient();
var response =
  c.GetAsync("https://clienttest.ssllabs.com:8443/ssltest/viewMyClient.html").Result;

I get
TLS 1.3 No
TLS 1.2 Yes*
TLS 1.1 Yes*
TLS 1.0 Yes*

Why is that and how can I restrict (or enable) protocols from outside the app?
The underlying issue is actually that I cannot get .Net clients on this server to use TLS 1.2 on outbound connections even though it is enabled at the OS level, and understanding why I cannot disable other protocols might help me figure this out.
Answer: Ah, never mind, I missed the (*) footnote:
(*) Without JavaScript, this test reliably detects only the highest supported protocol.


Windows Server 2008 R2 Troubleshooting PID Leaking

Question: One of our servers has been leaking PID like crazy. I wrote a simple scheduled script, and it seems that every day the highest PID increases by approx. 300'000. E.g., if on Aug.24 00:00 the highest PID is 50'796, on Aug.25 00:00 the highest PID is 345'899, on Aug.26 00:00 the highest PID is 655'241, and so on.
If the server is left on for more than one week, then sometimes during the 10th ~ 12h day, the server will hang, we can access it no longer via RDP. At such situation, we would have to power cycle the server because it simply refuses to acknowledge any remote commands.
So, I've written a simple script to ensure orderly shutdown and restart of the server; every Tuesday at 02:00 the script fires and rebooted the system. Now we no longer experience a system lockout, but of course the root cause is not fixed.
What tool(s) do you recommend to troubleshoot this problem?
More Info: The server was originally running without problems physically. Then it got migrated to the regional datacenter using P2V operation, now running on top of VMware. The 'heavyweight' application in it would be Microsoft SQL Server 2008 Enterprise.
Answer: Sounds like you might have a process constantly spawning a sub-process, which then fails.  I'd recommend using SysInternals (Microsoft's) ProcessMonitor (here) - it really is the dog's danglies when it comes to nailing problems like this.
Comment: Okay, I got a bucketload of events... any recommendation which events I should eyeball on?


What are chunk tests?

Question: In answer to a question on model selection in the presence of multicollinearity, Frank Harrell suggested:

Put all variables in the model but do not test for the effect of one
variable adjusted for the effects of competing variables... Chunk
tests of competing variables are powerful because collinear variables
join forces in the overall multiple degree of freedom association
test, instead of competing against each other as when you test
variables individually.

What are chunk tests? Can you give an example of their application in R?
Comment: I'd imagine this refers to testing blocks of variables at a time, where all potential collinearity occurs within a block, which does not affect omnibus tests like the $F$-test or the likelihood ratio test, but I've never heard the term "chunk test".
Comment: One situation that I have seen them suggested (and have done them myself) is when you have a series of many mutually exclusive dummy variables (e.g. a nominal independent variable with many potential categories). A test of any individual coefficient associated with any single dummy variable is not very interesting, as it tests a particular contrast with whatever you choose as the baseline. Hence a more informative test is the likelihood ratio test of the restricted model omitting all of the dummy variables.
Comment: @AndyW Why would a test on an individual coefficient not be interesting because it tests the contrast with the chosen baseline? Isn't that an interesting comparison to make in many situations? Additionally, isn't the fact that it is more precise than testing whether they are all 0 or not useful?
Answer: @mark999 provided an excellent answer.  In addition to jointly testing polynomial terms, you can jointly test ("chunk test") any set of variables.  Suppose you had a model with competing collinear variables tricep circumference, waist, hip circumference, all measurements of body size.  To get an overall body size chunk test, you could do
    require(rms)
    f <- ols(y ~ age + tricep + waist + pol(hip, 2))
    anova(f, tricep, waist, hip)  # 4 d.f. test

You can get the same test by fitting a model containing only age (if there are no NAs in tricep, waist, hip) and doing the "difference in $R^2$ test".  These equivalent tests do not suffer from even extreme collinearity among the three variables.
Answer: Macro's comment is correct, as is Andy's. Here's an example.
> library(rms)
>
> set.seed(1)
> d <- data.frame(x1 = rnorm(50), x2 = rnorm(50))
> d <- within(d, y <- 1 + 2*x1 + 0.3*x2 + 0.2*x2^2 + rnorm(50))
>
> ols1 <- ols(y ~ x1 + pol(x2, 2), data=d) # pol(x2, 2) means include x2 and x2^2 terms
> ols1

Linear Regression Model

ols(formula = y ~ x1 + pol(x2, 2), data = d)

                Model Likelihood     Discrimination
                   Ratio Test           Indexes
Obs       50    LR chi2     79.86    R2       0.798
sigma 0.9278    d.f.            3    R2 adj   0.784
d.f.      46    Pr(> chi2) 0.0000    g        1.962

Residuals

    Min      1Q  Median      3Q     Max
-1.7463 -0.4789 -0.1221  0.4465  2.2054

          Coef   S.E.   t     Pr(>|t|)
Intercept 0.8238 0.1654  4.98 <0.0001
x1        2.0214 0.1633 12.38 <0.0001
x2        0.2915 0.1500  1.94 0.0581
x2^2      0.2242 0.1163  1.93 0.0602

> anova(ols1)
                Analysis of Variance          Response: y

 Factor     d.f. Partial SS MS          F      P
 x1          1   131.894215 131.8942148 153.20 <.0001
 x2          2    10.900163   5.4500816   6.33 0.0037
  Nonlinear  1     3.196552   3.1965524   3.71 0.0602
 REGRESSION  3   156.011447  52.0038157  60.41 <.0001
 ERROR      46    39.601647   0.8609054

Instead of considering the x2 and x2^2 terms separately, the "chunk test" is the 2-df test which tests the null hypothesis that the coefficients of those terms are both zero (I believe it's more commonly called something like a "general linear F-test"). The p-value for that test is the 0.0037 given by anova(ols1).
Note that in the rms package, you have to specify the x2 terms as pol(x2, 2) for anova.rms() to know that they are to be tested together.
anova.rms() will do similar tests for predictor variables which are represented as restricted cubic splines using, for example, rcs(x2, 3), and for categorical predictor variables. It will also include interaction terms in the "chunks".
If you wanted to do a chunk test for general "competing" predictor variables, as mentioned in the quote, I believe you would have to do it manually by fitting the two models separately and then using anova(model1, model2). [Edit: this is incorrect - see Frank Harrell's answer.]
Comment: (+1) It is also worth noting that testing individual polynomial terms can be problematic because, except in special cases (like when the predictor,$X$, is symmetric around zero, ${\rm cor}(X,X^2)=0$), they are (often very highly) collinear with the other polynomial terms.
Comment: For the sake of clarity, I think I was taught this as a "Partial F-test" where you test 2 or more variables for joint significance. Or whether a subset of variables in your model improves over the more restricted model (just like a likelihood ratio test). Am I correct?
Comment: @C.Pieters I don't know if you're correct, but it sounds reasonable.

What are chunk tests?


How to get Alfresco login ticket without user password, but with impersonating user with user principal name (UPN)

Question: I'm writing a DLL that has function for getting Alfresco login ticket without using user password, using only a user principal name (UPN). I'm calling alfresco REST API service /wcservice. I use NTLM in Alfresco.
I'm impersonating users using WindowsIdentity constructor as explained here http://msdn.microsoft.com/en-us/library/ms998351.aspx#paght000023_impersonatingbyusingwindowsidentity. I checked and user is properly impersonated (I checked WindowsIdentity.GetCurrent().Name property).
After impersonating a user, I try to make HttpWebRequest and set its credentials with CredentialsCache.DefaultNetworkCredentials. I get the error:
The remote server returned an error: (401) Unauthorized.
   at System.Net.HttpWebRequest.GetResponse()

When I use new NetworkCredential("username", "P@ssw0rd") to set request credentials, I get Alfresco login ticket (HttpStatusCode.OK, 200).
Is there any way that I can get Alfresco login ticket without user password?
Here is the code that I'm using:
private string GetTicket(string UPN) {
 WindowsIdentity identity = new WindowsIdentity(UPN);
 WindowsImpersonationContext context = null;

 try {
  context = identity.Impersonate();

  MakeWebRequest();
 }
 catch (Exception e) {
  return e.Message + Environment.NewLine + e.StackTrace;
 }
 finally {
  if (context != null) {
   context.Undo();
  }
 }
}

private string MakeWebRequest() {
 string URI = "http://alfrescoserver/alfresco/wcservice/mg/util/login";

 HttpWebRequest request = WebRequest.Create(URI) as HttpWebRequest;

 request.CookieContainer = new CookieContainer(1);

 //request.Credentials = new NetworkCredential("username", "p@ssw0rd"); // It works with this
 request.Credentials = CredentialCache.DefaultNetworkCredentials;  // It doesn't work with this
 //request.Credentials = CredentialCache.DefaultCredentials;    // It doesn't work with this either

 try {
  using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) {
   StreamReader sr = new StreamReader(response.GetResponseStream());

   return sr.ReadToEnd();
  }
 }
 catch (Exception e) {
  return (e.Message + Environment.NewLine + e.StackTrace);
 }
}

Here are records from Alfresco stdout.log (if it helps in any way):
17:18:04,550  DEBUG [app.servlet.NTLMAuthenticationFilter] Processing request: /alfresco/wcservice/mg/util/login SID:7453F7BD4FD2E6A61AD40A31A37733A5
17:18:04,550  DEBUG [web.scripts.DeclarativeRegistry] Web Script index lookup for uri /mg/util/login took 0.526239ms
17:18:04,550  DEBUG [app.servlet.NTLMAuthenticationFilter] New NTLM auth request from 10.**.**.** (10.**.**.**:1229)
17:18:04,566  DEBUG [app.servlet.NTLMAuthenticationFilter] Processing request: /alfresco/wcservice/mg/util/login SID:7453F7BD4FD2E6A61AD40A31A37733A5
17:18:04,566  DEBUG [web.scripts.DeclarativeRegistry] Web Script index lookup for uri /mg/util/login took 0.400909ms
17:18:04,566  DEBUG [app.servlet.NTLMAuthenticationFilter] Received type1 [Type1:0xe20882b7,Domain:<NotSet>,Wks:<NotSet>]
17:18:04,566  DEBUG [app.servlet.NTLMAuthenticationFilter] Client domain null
17:18:04,675  DEBUG [app.servlet.NTLMAuthenticationFilter] Sending NTLM type2 to client - [Type2:0x80000283,Target:AlfrescoServerA,Ch:197e2631cc3f9e0a]

Answer: I've solved the problem!
I believe that we had a double-hop problem.
This is what had to be done to solve this problem:

User that runs my DLL must be Windows Server 2003 domain
user
Service that uses my DLL must have
registered Service Principal Name in
Domain controller with user that
runs it (user that runs my DLL)
User that runs my DLL must not have
Account is sensitive and cannot be
delegated option selected in Domain
controller
User that runs my DLL must have
Trust this user for delegation to
any service (Kerberos only) or Trust
this user for delegation to
specified services only option
selected in Domain controller (if
the user is in Windows Server 2003
functional domain this option is
available only when you register
Service Principal Name with this
user)
User that runs my DLL must have TrustedToAuthForDelegation user account control (UAC) set to true
Computer that runs service that uses
my DLL must have Trust computer for
delegation to any service (Kerberos
only) or Trust computer for
delegation to specified services
only option selected in Domain
Controller

This all (and more) is explained in Microsoft document Troubleshooting Kerberos Delegation. It contains:

checklist for Active Directory,
checklist for Client application,
checklist for Middle tier,
checklist for Back-end

plus

configuration examples for common
scenarios.

Setting TrustedToAuthForDelegation user account control (UAC) is done in PowerShell by Active Directory cmdlet explained here.
You can read more about Windows Authentication in ASP.NET 2.0.
Of course, Alfresco must have Kerberos login enabled.
Answer: I think that it is not possible for Alfresco. Only if you use special authentication subsystem where exists this 'impersonal' user.
Try this, because 'guest' user is transversal for all subsystem authentication.
request.Credentials = new NetworkCredential("guest", "guest");
And the URI, something like this:
string URI = "http://alfrescoserver/alfresco/s/api/login or whatever you propose.
Good luck.
Paco
Comment: If I use http://alfrescoserver/alfresco/s/api/login, I need to supply user's password as parameter which I'm trying to avoid.
I believe that what I'm trying to do should be possible. All I need to do is to get right credentials for HTTP request. Maybe I have double-hop problem (http://blogs.msdn.com/b/knowledgecast/archive/2007/01/31/the-double-hop-problem.aspx), and I'm reading Microsoft's document Troubleshooting Kerberos Delegation (http://www.microsoft.com/downloads/en/details.aspx?familyid=99b0f94f-e28a-4726-bffe-2f64ae2f59a2&displaylang=en) to try to resolve it.
I still need help.


SQL Server Tables Named With dbo Schema

Question: I've been finding SQL Server schemas to be very confusing. Maybe you guys can help me clear up some confusion. I'm using SQL Server 2008 Express and MS SQL Server 2008 Management Studio but I think my questions are relevant to any MS SQL Server 2008 version. I've been experimenting with different databases and different instances of SQL Server on different servers. For example, I've been doing some work on our company server but I've also been working quite a bit with some databases on my shared web hosting server. This might be part of the reason I've entered into some of the confusion.
1) Where did this schema name come from? I thought when I first started messing with SQL Server several weeks ago I didn't see any schema names appended to the table names. I started seeing them when a database was imported or when I used the MS Access Migration Assistant. Is it possible to not use schemas at all? Do they not show up under some circumstances?
2) Schema name not "dbo"? On a recent project my schemas have been showing up as MyLongUserName.tablename instead of dbo.tablename. I'm confused as to why sometimes a user account appears to default to the dbo schema and other times it's assigned to a schema with the same name as the user account. Does this have anything to do with logging in using NT Authentication versus SQL Server authentication?
3) User named dbo? I don't remember creating a user named dbo in the database that I'm currently working in but I see it in the list of users. Does the user account "dbo" have to exist for the schema "dbo" to exist? Do usernames and schema names always parallel?
4) To Use Schemas or Not - Can you not use them? Do you use schemas for small projects such as a two or three table database for a basic website? Can you avoid using schemas entirely or simply use only the default "dbo" schema? Would you create additional schema(s) and assign certain permissions and user accounts to it/them even on very small projects?
I've been using the book Murach's SQL Server 2008 for Developers and I haven't found it to be overly helpful in clearing up my confusion. I'm reading sentences like: "If you don't specify a schema when you create the objects, they're stored in the default schema." Wait, how do I know what "the default schema" is? Are we talking about the user account's default schema or is there "a default schema" for every database? Is it always "dbo"? Why when I create objects is it assigning them to schema MyLongUserName instead of "dbo"?
Answer: You might want to start by reading this: What good are SQL Server schemas?
From SQL Server 2005 onwards, schemas were separated from users http://msdn.microsoft.com/en-us/library/ms190387.aspx.
Prior to that, each user owns several tables, which will be in their "space".  That "space" is now a schema, which is a way to group tables.
SQL Server Objects have 4 parts to their names

server.database.schema.objectname

Whenever you omit one or more of them, you are naming it from the right

database.schema.objectname  - implied current server
schema.objectname  - implied current database
objectname  - implied default schema. each user can be assigned a default schema, but by default this will be "dbo"

"dbo" is a special schema, it is the database-owner.  It exists in every database, but you can add schemas (like folders) to databases
If you migrate from older installations of SQL Server 2000 dbs to 2005 or beyond, you may bring along the schemas-named-as-users, because the users "own"ed the tables.

SQL Server Tables Named With dbo Schema


A step in the proof of Sobolev embedding theorem

Question: I am reading the proof of the Sobolev embedding theorem in Brezis' book, but i can't understand the following fact.
Suppose we've already proved the following lemma:
Let $f_1$, $f_2$, $\dots$, $f_N \in L^{N-1}(\mathbb{R}^{N-1})$ and set $$\tilde{x_i}=(x_1,x_2,\dots,x_{i-1},x_{i+1},\dots,x_N) \in \mathbb{R}^{N-1}.$$
Then the function $$ f(x)=f_1(\tilde{x_1})\dots f_N(\tilde{x_N}), \quad x \in\mathbb{R}^N$$
is in $L^{1}(\mathbb{R}^N)$ and $$||f||_{L^{1}(\mathbb{R}^N)} \leq \prod_{i=1}^{N}||f_i||_{L^{N-1}(\mathbb{R}^{N-1})}.$$
Now, in the theorem, one considers $u\in C_c^1(\mathbb{R}^N)$ and
$$
f_i(\tilde{x_i}):= \int_{\mathbb{R}}\bigg|\frac{\partial u}{\partial x_i}(x_1,x_2,\dots,x_{i-1},t,x_{i+1},\dots,x_N)\bigg|dt
$$
so that
$$
|u(x)|^N \leq \prod_{i} f_i(\tilde{x_i})
$$
and then one should be able (by using the previous lemma) - and this is the point I am missing - to prove that
$$
\int_{\mathbb{R}^N} |u(x)|^{\frac{N}{N-1}}dx \leq \prod_{i} ||f_i||^\frac{1}{N-1}_{L^1(\mathbb{R}^{N-1})}
$$
Answer: Raise both sides of your penultimate inequality to the power $1/(N-1)$ and integrate to get
$$
\int_{\mathbb{R}^N} |u(x)|^{N/(N-1)}dx \le \int_{\mathbb{R}^N} \prod_{i} f_i^{1/(N-1)}.
$$
Now apply your lemma to
$$
g = \prod_{i} f_i^{1/(N-1)}
$$
with $g_i = f_i^{1/(N-1)}$.  This gives
$$
\int_{\mathbb{R}^N} \prod_{i} f_i^{1/(N-1)} = \Vert g \Vert_{L^1(\mathbb{R}^N)} \le \prod_{i=1}^N \Vert g_i \Vert_{L^{N-1}(\mathbb{R}^{N-1})} = \prod_{i=1}^N \Vert f_i \Vert_{L^{1}(\mathbb{R}^{N-1})}^{1/(N-1)}.
$$
Hence
$$
\int_{\mathbb{R}^N} |u(x)|^{N/(N-1)} dx\le \prod_{i=1}^N \Vert f_i \Vert_{L^{1}(\mathbb{R}^{N-1})}^{1/(N-1)},
$$
which is what you were after.


Removing double quotes from variables in batch file creates problems with CMD environment

Question: Can anybody help with effective and safe way of removing quotes from batch variables?
I have written a batch file which successfully imports a list of parameters %1, %2, %3 etc. and places them into named variables.  Some of these parameters contain multiple words, and therefor are enclosed in double quotes.
> "Susie Jo" (%1)
> "Smith Barnes" (%2)
> "123 E. Main St." (%3)

These %variables are next placed in named variables:
> set FirstName=%1
> set LastName=%2
> set ShipAddr=%3

verification of variables is done by echo.
> echo.%FirstName%
> echo.%LastName%
> echo.%ShipAddr%
results display as
"Susie Jo"
"Smith Barnes"
"123 E. Main St."

I need to eliminate the included quotes on selected variables.  For instance, FirstName and LastName are used elsewhere and must not include quotes.
In a test batch file I was successful at eliminating quotes using the ~tilde character in variables.
> set FirstName=%~1
> set LastName=%~2

I thought I had the solution, but I soon experienced unusual behavior with execution of batch files.  Suddenly CMD is no recognizing long path statments.  Normal execution of batch file from full path
> C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat

returns
> 'C:\Documents' is not recognized as an internal or external command....

So it would appear that the addition of the ~tilde character to the in-coming %1 %2...%n variables has caused some change.  Possibly some environment variables have been altered?
I also tried clearing quotes from within variable with various attempts using the FOR command.  That seems awkward and I have been unable to learn how to accomplish this by creating a list of variable to perform the task:
something like this:
for %%g in (%FirstName% %LastName%) do (
set %%g=%%~g
set %%h=%%~h
set FirstName=%%~g
set LastName=%%h
echo.%FirstName% %LastName%
)

I think I have two issues.

My 'short and sweet' idea of inserting ~tilde in the incoming %1 %2 variables (%~1, etc) seems to have affected some settings and altered how CMD navigates long pathnames.

I'm still in search of a clean and easy way to eliminate quotes from selected named variables.

Any help for those more experienced would be most appreciated.  I'm at the end of my skills here... need some guidance please!
edit 12/26/2009 13:36 PST
entire batch file:
:: dataout.bat
:: revision 12/25/2009 add ~tilde to incoming %variables to eliminate embedded "quotation marks.
:: writes address list using command line parameters
:: writes data output list for QBooks IIF import
:: writes Merchant Order data for RUI
:: sample command line string for testing
:: listmail[firstname][lastname]["address string"]["city string"][state][zip][Order#][PurchDate][Regname]["FirstName LastName"][TransactionID][PaymentMethod][Total][ProductID][Qty][Price_Each][PackPrep] [Shipping] [CommissionPmt] [Invoice#]
:: example: dataout Bellewinkle Moose "123 Green Forest Way" "Vancouver" WA 98664 1004968 05/25/2009 "Bellewinkle Moose" "Olive Oyl" 101738 "On Account" 20.67 FK-1P 1 8.95 3.00 1.39 239
@echo off
cls
c:
cd\
cd documents and settings\administrator\my documents\txt\batchtest
echo processing %1 %2
:VARISET
:: Convert %n command line parameters to string variables
set ($FirstName)=%~1
set ($LastName)=%~2
set ($BillingAddress1)=%~3
set ($BillingCity)=%~4
set ($BillingState)=%~5
set ($BillingPostal)=%~6
set ($OrderNumber)=%~7
set ($Purch_Date)=%~8
set ($RegistrationName)=%~9
shift
set ($TransactionID)=%~9
shift
set ($PaymentMethod)=%~9
shift
set ($Total)=%~9
shift
set ($ProductIdentifier)=%~9
shift
set ($Quantity)=%~9
shift
set ($Price_Each)=%~9
shift
set ($Pack_Prep)=%~9
shift
set ($Shipping)=%~9
shift
set ($ServiceFee)=%~9
shift
set ($Discount)=%~9
shift
set ($Invoice)=%~9
shift
set ($UnitPrice)=%~9
set _ShipCombName=%($FirstName)% %($LastName)%
echo ship combo name is %_ShipCombName%
pause
:: write string varibables to logfile
echo FN %($FirstName)% LN %($LastName)% BA %($BillingAddress1)% %($BillingCity)% %($BillingState)% %($BillingPostal)% %($OrderNumber)% %($Purch_Date)% %($RegistrationName)% %($TransactionID)% %($PaymentMethod)% %($Total)% %($ProductIdentifier)% %($Quantity)% %($Price_Each)% %($Pack_Prep)% %($Shipping)% %($ServiceFee)% %($Discount)% %($Invoice)% %($UnitPrice)% %_ShipCombName% >> d_out_log.txt
:: Assign Account by Service Provider
IF /i %($PaymentMethod)%==Amazon Receivables SET _QBAcct=Amazon.com
:: 12-25-2009 added second Amazon pm't method for versatility
IF /i %($PaymentMethod)%==Amazon SET _QBAcct=Amazon.com
IF /i %($PaymentMethod)%==MAST SET _QBAcct=Auth/Net
IF /i %($PaymentMethod)%==MasterCard SET _QBAcct=Auth/Net
IF /i %($PaymentMethod)%==Visa SET _QBAcct=Auth/Net
IF /i %($PaymentMethod)%==PayPal SET _QBAcct=PayPalPmts
IF /i %($PaymentMethod)%==On Account SET _QBAcct=%($RegistrationName)%
IF /i %($PaymentMethod)%==Mail SET _QBAcct=%($RegistrationName)%
IF /i %($PaymentMethod)%==AMER SET _QBAcct=Auth/Net
IF /i %($PaymentMethod)%==DISC SET _QBAcct=Auth/Net
:: Assign Rep designator based on QBAccount
IF /i %($PaymentMethod)%==Amazon Receivables SET _Rep=Amazon
:: 12-25-2009 added second Amazon pm't method for versatility
IF /i %($PaymentMethod)%==Amazon SET _Rep=Amazon
IF /i %($PaymentMethod)%==MAST SET _Rep=BlueZap
IF /i %($PaymentMethod)%==MasterCard SET _Rep=BlueZap
IF /i %($PaymentMethod)%==Visa SET _Rep=BlueZap
IF /i %($PaymentMethod)%==PayPal SET _Rep=BlueZap
IF /i %($PaymentMethod)%==On Account SET _Rep=R B
IF /i %($PaymentMethod)%==Mail SET _Rep=R B
IF /i %($PaymentMethod)%==AMER SET _Rep=BlueZap
IF /i %($PaymentMethod)%==DISC SET _Rep=BlueZap
:: check for duplicate address data
findstr /i /s "%_ShipCombName%" addrlist.txt
echo errorlevel: %errorlevel%
if errorlevel 1 goto :ADDRWRITE
if errorlevel 0 goto :ADDRFOUND
:ADDRWRITE
echo %_ShipCombName% >> addrlist.txt
echo %($BillingAddress1)% >> addrlist.txt
echo %($BillingCity)% %($BillingState)% %($BillingPostal)% >> addrlist.txt
echo. >> addrlist.txt
echo Address File Written
:ADDRFOUND
echo selected rep is %_Rep%
echo selected account is: %_QBAcct%
pause
:: RUI OUT
:: write Merchant Order ID & RUI Order ID to RUI
:: check for duplicate RUI data in writeRUI.txt
cd..
cd RegKOut
find /i "%($OrderNumber)%" writeRUI.txt
echo errorlevel: %errorlevel%
if errorlevel 1 goto :RUIWRITE
if errorlevel 0 goto :IIFWRITE
:RUIWRITE
echo %($Invoice)%   %($OrderNumber)% >> writeRUI.txt
:: end write RUI
:: IIF OUT
:IIFWRITE
:: Check for duplicate invoice data in writeIIF.txt
find /i "%($OrderNumber)%" writeIIF.txt
echo errorlevel: %errorlevel%
if errorlevel 1 goto :HEADWRITE
if errorlevel 0 goto :LINEWRITE
:HEADWRITE
:: write Header, Ship/Handling, discount, Rep & commission data to QB IIF import file
echo %($OrderNumber)%   %($Purch_Date)% Invoice %($TransactionID)%  %_QBAcct%   Accounts Receivable             %($Total)%  %_Rep% >> writeIIF.txt
echo                        H/P %($Pack_Prep)%  1   ? >> writeIIF.txt
echo                        SHP %($Shipping)%   1   ? >> writeIIF.txt
echo                        DISC    %($Discount)%   1   ? >> writeIIF.txt
echo                        Comm    %($ServiceFee)% 1   ? >> writeIIF.txt
:LINEWRITE
IF /i %($ProductIdentifier)% equ PH-1 goto WRITE_DEFA ELSE goto WRITE_DISC
echo %($ProductIdentifier)%
:WRITE_DISC
::writes discounted prices parsed from custom variable:
echo                        %($ProductIdentifier)%  %($Price_Each)% %($Quantity)%   ? >> writeIIF.txt
goto :EOF
:WRITE_DEFA
:writes default prices parsed from Product data
echo                        %($ProductIdentifier)%  %($UnitPrice)%  %($Quantity)%   ? >> writeIIF.txt
goto :EOF
:: 3-second delay
:: TYPE NUL | CHOICE.COM /N /CY /TY,3 >NUL
:EOF

Comment: I checked your batch file -- it seems to work fine (after I fixed the line "shift set ($ProductIdentifier)=%~9" -- which, I think, is an artifact of copying-and-pasting it here).
Comment: Could you use PowerShell to do this? I suspect you will get a little more control if you use PowerShell.
Comment: Thank you Robert Harvey; I have been eying PowerShell.  I'm not very experience w/ programming.. not sure what the learning curve would be like.  I do have some experience w/ batch files, main reason I chose this.  I'm intending to compile the batch so it will run faster. Thanks for response.
Comment: Thanks atzz:  I have since tested this batch file some more and I am reasonably confident that the ~tilde and banishing quotes is unrelated to the CMD problem w/ long pathnames.  I worked around that by just setting up a short-name subdirectory close to the root to eliminate long pathnames.
Comment: No need to show the full batch file. Please shorten your question.
Answer: You have an extra double quote at the end, which is adding it back to the end of the string (after removing both quotes from the string).
Input:
set widget="a very useful item"
set widget
set widget=%widget:"=%
set widget

Output:
widget="a very useful item"
widget=a very useful item

Note: To replace Double Quotes " with Single Quotes ' do the following:
set widget=%widget:"='%

Note: To replace the word "World" (not case sensitive) with BobB do the following:
set widget="Hello World!"
set widget=%widget:world=BobB%
set widget

Output:
widget="Hello BobB!"

As far as your initial question goes (save the following code to a batch file .cmd or .bat and run):
@ECHO OFF
ECHO %0
SET BathFileAndPath=%~0
ECHO %BathFileAndPath%
ECHO "%BathFileAndPath%"
ECHO %~0
ECHO %0
PAUSE

Output:
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
Press any key to continue . . .

%0 is the Script Name and Path.
%1 is the first command line argument, and so on.
Comment: @Imray - the `:old=new` is a pattern match and replacement in the variable expansion.  With `"` as the `old` and nothing as the `new`, the quotes are removed, even if they are in the middle, even if they are unbalanced.
Comment: I'm afraid this solution does not work when there is an `&` in the string, as in `set widget="hello&world"`.  In this case you need to use `set "widget=%widget:"=%"`
Comment: Thanks, this was what I was after `SET BathFileAndPath=%~0` (actually, my param array starts with 1 so I used `SET BathFileAndPath=%~1`
Comment: Can you explain why `%widget:"=%` gets rid of the quotation marks?
Comment: set widget=%widget:"=% has a strange behavior when widget is blank, it returns "="
Answer: Your conclusion (1) sounds wrong. There must be some other factor at play.
The problem of quotes in batch file parameters is normally solved by removing the quotes with %~ and then putting them back manually where appropriate.
E.g.:
set cmd=%~1
set params=%~2 %~3

"%cmd%" %params%

Note the quotes around %cmd%. Without them, path with spaces won't work.
If you could post your entire batch code, maybe more specific answer could be made.
Comment: I agreee; seems to me the set var=%~1 should work just fine.  I will post entire batch file as requested.
Comment: MS Reference: [Using batch parameters](http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/percent.mspx?mfr=true). Who knew there were so many modifiers? For reference, the official MS doc gives the description of `%~1` as `Expands %1 and removes any surrounding quotation marks ("").`
Comment: @cod3monk3y Also, it's possible to ask `cmd` itself about these modifiers: `call /?` for help on parameter modifiers, `set /?` for variable modifiers (probably not very intuitive). Quite handy.
Comment: `%~` works only for command parameters, not variables; there's a correct answer below mentioning `set var=%var:"=%` trick.
Answer: I usually just remove all quotes from my variables with:
set var=%var:"=%

And then apply them again wherever I need them e.g.:
echo "%var%"

Comment: I also had trouble with this at first, turned out I was seeing the `:` as a `.` - after figuring that out, worked without a hitch. Great tip!
Answer: Spent a lot of time trying to do this in a simple way.
After looking at FOR loop carefully, I realized I can do this with just one line of code:
FOR /F "delims=" %%I IN (%Quoted%) DO SET Unquoted=%%I

Example:
@ECHO OFF
SET Quoted="Test string"

FOR /F "delims=" %%I IN (%Quoted%) DO SET Unquoted=%%I

ECHO %Quoted%
ECHO %Unquoted%

Output:
"Test string"
Test string

Comment: This method is not relevant while "SET Quoted=Test string". The next question is how to differ does " (double quote) exist or not. To whom might concerned, thank you in advanced.
Answer: The simple tilde syntax works only for removing quotation marks around the command line parameters being passed into the batch files
SET xyz=%~1

Above batch file code will set xyz to whatever value is being passed as first paramter stripping away the leading and trailing quotations (if present).
But, This simple tilde syntax will not work for other variables that were not passed in as parameters
For all other variable, you need to use expanded substitution syntax that requires you to
specify leading and lagging characters to be removed. Effectively we are instructing to remove strip away the first and the last character without looking at what it actually is.
@SET SomeFileName="Some Quoted file name"
@echo %SomeFileName% %SomeFileName:~1,-1%

If we wanted to check what the first and last character was actually quotation before removing it, we will need some extra code as follows
@SET VAR="Some Very Long Quoted String"
If aa%VAR:~0,1%%VAR:~-1%aa == aa""aa SET UNQUOTEDVAR=%VAR:~1,-1%

Answer: I learned from this link, if you are using XP or greater that this will simply work by itself:
SET params = %~1
I could not get any of the other solutions here to work on Windows 7.
To iterate over them, I did this:
FOR %%A IN (%params%) DO (
   ECHO %%A
)

Note: You will only get double quotes if you pass in arguments separated by a space typically.
Answer: This sounds like a simple bug where you are using %~ somewhere where you shouldn't be.  The use if %~ doesn't fundamentally change the way batch files work, it just removes quotes from the string in that single situation.
Answer: All the answers are complete. But Wanted to add one thing,

set FirstName=%~1
set LastName=%~2

This line should have worked, you needed a small change.

set "FirstName=%~1"
set "LastName=%~2"

Include the complete assignment within quotes. It will remove quotes without an issue. This is a prefered way of assignment which fixes unwanted issues with quotes in arguments.
Answer: Azure devops sometimes uses double quoting character (") to specify string. Powershell can use single quote character (') to specify string. Naturally I wanted to have a flexibility to be able to specify parameters however I wish, so same parameter can be used from both - command line - via batch file, and as a powershell script, as any parameter, including empty value.
Quote natural thinking is to write something like this:
build.bat:

@echo off
setlocal enabledelayedexpansion
set args=%*
set args=%args:"='%
echo powershell -executionpolicy bypass "%~dpn0.ps1" %args%
endlocal

But like you can guess - this does not work out of box - if no arguments are provided to batch file so %* == empty string. args expands as no string, and next replacement notices that args is not set - and instead of replacing string - it would append extra "=' garbage to args parameter.
Solution to this was just to add extra space in first assignment.
build.bat:

@echo off
setlocal enabledelayedexpansion
set args=%*
set args=%args:"='%
echo powershell -executionpolicy bypass "%~dpn0.ps1" %args%
endlocal

After this character translation should be correct:
C:\test>build
powershell -executionpolicy bypass "C:\test.ps1"

C:\test>build aa
powershell -executionpolicy bypass "C:\test\build.ps1" aa

C:\test>build "aa"
powershell -executionpolicy bypass "C:\test\build.ps1" 'aa'

C:\test>build 'aa'
powershell -executionpolicy bypass "C:\test\build.ps1" 'aa'

Answer:
set widget="a very useful item"
set widget
widget="a very useful item"
set widget=%widget:"=%"
set widget
set widget=a very useful item"

The trailing quote " in line 4 is adding a quote " to the string. It should be removed.
The syntax for line 4 ends with %
Comment: @user195488 - read line 3 as **observe that it displayed: `widget="a very useful item"`** and read line 6 as **observe that it displayed: `widget=a very useful item"`** and understand that line 7 would be `set widget=%widget:"=%` and line 8 would be **observe that the displayed line `widget=a very useful item` no longer has a trailing quote**.
Answer:
I thought I had the solution, but I soon experienced unusual behavior with execution of batch files. Suddenly CMD is no recognizing long path statments. Normal execution of batch file from full path

C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat

returns

'C:\Documents' is not recognized as an internal or external command....

There's your whole problem. CMD doesn't understand spaces inside of filenames from the command line, so it thinks you're trying to pass

and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat

as parameters to the

"C:\Documents"

program.
You need to quote it to run a batch file with spaces in the path:
> "C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat"

would have worked.
Answer: @echo off

Setlocal enabledelayedexpansion

Set 1=%1

Set 1=!1:"=!

Echo !1!

Echo "!1!"

Set 1=

Demonstrates with or without quotes reguardless of whether original parameter has quotes or not.
And if you want to test the existence of a parameter which may or may not be in quotes, put this line before the echos above:
If '%1'=='' goto yoursub
But if checking for existence of a file that may or may not have quotes then it's:
If EXIST "!1!" goto othersub
Note the use of single quotes and double quotes are different.


@RooWebJson Generates Invalid Aspect File

Question: I have a simple object:
@RooJavaBean
@RooToString
@RooJpaActiveRecord
@RooJson
public class HJAddress {
    private String id;

}

And a simple, empty controller:
@RooWebJson(jsonObject = HJAddress.class)
@Controller
@RequestMapping("/hjaddresses")
public class HJAddressController {

}

The .aj files Roo generates for the controllers are fine, except for the end of the deleteFromJson method.  It always generates a compiler error for me.  Looking at it, it does:
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
public ResponseEntity<String> HJAddressController.deleteFromJson
        (@PathVariable("id") Long id) {
    HJAddress hJAddress = HJAddress.findHJAddress(id);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json");
    if (hJAddress == null) {
        return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
    }
>>> HJAddress_.remove();
    return new ResponseEntity<String>(headers, HttpStatus.OK);
}

And right at the end there, it says HJAddress_.remove() instead of hJAddress.remove().  All of the other methods do indeed use this HJAddress_ naming scheme.
I'm not really sure where to go from here since it's something internal to Roo.
EDIT: This is using roo 1.2 with STS based on eclipse indigo.
Answer: Apparently it is a bug in Roo 1.2 that is getting fixed in 1.2.1.
http://forum.springsource.org/showthread.php?122911-RooWebJson-Generates-Invalid-Aspect-Files&p=400871#post400871


If the regions of $H$ can be properly colored using at most four colors, then the edges of $H$ can be properly colored using at most three colors.

Question: Let $H$ be three regular and planar. If the regions of $H$ can be properly colored using at most four colors, then the edges of $H$ can be properly colored using at most three colors.
I'm not sure how to go about this. So the regions are properly colored with four or less colors and then we want to color all the edges using no more than three colors? Is this like showing the Four Color Theorem is equivalent to something else? I was given the hint to use $\mathbb{Z_2}$ $\times$ $\mathbb{Z_2}$. Any solutions or help is greatly appreciated.
Comment: Take $\mathbb{Z}_2 \times \mathbb{Z}_2$ to be the set of four colors that color the regions. Try to give a color to each edge based only on the colors of the two adjacent regions (it will help you to consider a vertex and think about the relationship between the colors of the three incident regions).
Answer: If you also have the condition that the graph is bridgless then you can let the colors be $0,1,2,3$ and color an edge with the xor value of the two faces around the edge.
If you don't have the bridgeless condition I believe there are counterexamples, for example the following graph.


NFS - Multiple sub dirs - Only one squashing as expected

Question: Getting an unexpected behavior when mounting more than a single share.
NFS Server
<code>$ -> cd /mnt/raid/nas && ls -lZa
drwxrwxr-x. nas        filer      unconfined_u:object_r:file_t:s0  file
drwxrwxr-x. nas        filer      unconfined_u:object_r:file_t:s0  repo

$ -> cat /etc/exports
/mnt/raid/nas                   10.1.0.0/18(rw,fsid=0,sync)
/mnt/raid/nas/repo              10.1.0.0/18(rw,all_squash,sync,no_subtree_check,anonuid=501,anongid=503)
/mnt/raid/nas/file/perm         10.1.0.0/18(rw,all_squash,sync,no_subtree_check,anonuid=501,anongid=503)

$ -> id nas && id filer
uid=501(nas) gid=501(nas) groups=501(nas)
uid=502(filer) gid=503(filer) groups=503(filer)
</code>
NFS Client
<code>$ -> id nas && id filer
uid=501(nas) gid=501(nas) groups=501(nas)
uid=502(filer) gid=503(filer) groups=503(filer)

$ -> cd /mnt/nas && ls -lZa
drwxrwxr-x. nas        filer      unconfined_u:object_r:mnt_t:s0   repo
drwxrwxr-x. nas        filer      unconfined_u:object_r:mnt_t:s0   store

$ -> sudo mount -t nfs4 nas-1:/repo /mnt/nas/repo
$ -> sudo mount -t nfs4 nas-1:/file/perm /mnt/nas/store/file/perm/

$ -> df -h
nas-1:/repo
                  550G  240G  283G  46% /mnt/nas/repo
nas-1:/file/perm
                  550G  240G  283G  46% /mnt/nas/store/file/perm
</code>
But when I write a test file to each, only the perm/ correctly squashes the user.
<code>$ -> touch /mnt/nas/repo/imagemagick/test_$$.txt
$ -> ls /mnt/nas/repo/imagemagick
-rw-rw-r--.  1 mpurcell mpurcell    0 Apr  5 20:31 test_24571.txt

$ -> touch /mnt/nas/store/file/perm/test_$$.txt
$ -> ls /mnt/nas/store/file/perm/
-rw-rw-r--. 1 nas filer    0 Apr  5 20:32 test_24571.txt
</code>
I tried disabling selinux on both boxes, but that did not work either.
Why is one mount correctly squashing the user/group and the other is not?
---Update---
Do I have to bind the NFS mounts on the NFS server? I had a weird entry in my /etc/fstab file where one of the shared directories was being mounted (with bind) and that was the one that was working. I removed the entry from /etc/fstab on the NFS server, remounted everything, and now the once working mount on NFS client is no longer working.
Comment: Lol not sure why the votes to close? Still experiencing this issue and it is quite related to SF.
Answer: Ugh finally got it working, had to do the following to hack the all_squash feature. I did it awhile ago and don't remember why it had to be done, but without it I couldn't get the perms to squash properly.
<code>$ -> ls /mnt/raid/nas
drwxrwxr-x. 2  nas  filer  repo
drwxrwxr-x. 3  nas  filer  repo_all_squash_hack

$ -> ls /mnt/raid/nas/file
drwxrwxr-x. 2  nas  filer  perm
drwxrwxr-x. 3  nas  filer  perm_all_squash_hack
</code>
Then in /etc/fstab:
<code>/mnt/raid/nas/file/perm_all_squash_hack /mnt/raid/nas/file/perm none    bind    0 0
/mnt/raid/nas/repo_all_squash_hack    /mnt/raid/nas/repo none    bind    0 0
</code>
Now everything mounts up as expected. Also confirmed via:
<code>$ -> cat /proc/fs/nfs/exports
/mnt/raid/nas   10.1.0.0/18(rw,root_squash,sync,wdelay,no_subtree_check,fsid=0,uuid=d962b590:d8986203:00000000:00000000,sec=1)
/mnt/raid/nas/repo  10.1.0.0/18(rw,root_squash,all_squash,sync,wdelay,no_subtree_check,anonuid=501,anongid=503,uuid=d962b590:d8986203:00000000:00000000,sec=1)
/mnt/raid/nas/file/perm 10.1.0.0/18(rw,root_squash,all_squash,sync,wdelay,no_subtree_check,anonuid=501,anongid=503,uuid=d962b590:d8986203:00000000:00000000,sec=1)
</code>


Entityset turns to IEnumerable at an early stage

Question: I have the following issue: I want to display Tickets from a helpdesk system in a neat overview. I also want to display summaries of the data, like groupings by priority and category. On top of that, the same data must be turned into a .pdf document.
I retrieve the data in several steps. Step one is raw data which is the base for the .pdf, the summaries and the actual overview. That way, I ensure they take the same data. Upon creating the .pdf I directly read from the data. The summaries are made by flattening the data. The overview is created by taking a page of 25 records from the data and putting the fields in a grid.
The problem is
<code>IQueryable<RelationHoursTicketItem> HoursByTicket =
            from Ticket t in allTickets
            let hours = t.Bezoekrapport.Urens.
                Where(h =>
                    (dateFrom == null || h.Datum >= dateFrom)
                    && (dateTo == null || h.Datum <= dateTo)
                    && h.Uren1 > 0)
            select new RelationHoursTicketItem
             {
                 Date = t.DatumCreatie,
                 DateSolved = new DateTime(2012, 11, 11),
                 Ticket = t,
                 Relatie = t.Relatie,
                 TicketNr = t.Id,
                 TicketName = t.Titel,
                 TicketCategorie = t.TicketCategorie,
                 TicketPriority = t.TicketPrioriteit,
                 TicketRemark = t.TicketOpmerkings.SingleOrDefault(tr => tr.IsOplossing)
             };
</code>
The problem is in TicketRemark. As soon as I execute the data, I get tens of subqueries since the TicketOpmerkings - Dutch for TicketRemarks - are retrieved one by one. The original intention was to create an IQueryable which would serve as base for all other queries. I have gone through great lengths to achieve this, creating custom expressions to calculate certain fields which I cut from this example.
What is the best possible approach? Writing expressions for all those links like t.TicketOpmerkingen? It would remove some of the best functionality of LINQ. Solutions I saw so far include manually creating Expressions, but then I can just as well forsake this approach and make several queries, each for its specific purpose. Then I forsake the neat 'layered' approach of LINQ and IQueryable.
Anybody some experience with this?
Answer: What you are experiencing is known as the n+1 problem.  It occurs when you retrieve entities using an ORM, using a Deferred/Lazy Loading capability.
You retrieve entities that are linked to other entities.  When you attempt to navigate to the second set of entities, the ORM/Framework has not currently loaded the entity.  So it queries the entity for you, allowing you to navigate as intended.
There are several ways to resolve this.  Here are some articles regarding Data Load Options:
If you are using Linq to Sql:
MSDN for DataLoadOptions
A small article explaining the usage of DataLoadOptions
For Entity Framework:
MSDN for ObjectQuery(Of T).Include
An article describing eager loading techniques
Hope that helps.
Comment: I have managed to fix it with LoadWith, I simply retrieve the required tickets after I set: options.LoadWith(t => t.TicketOpmerkings); I run into a different problem later: I cannot use order by on the sql, but I can just order the enumerable later.
Comment: Excellent.  There are some downsides to using load options in L2S - for one, you can only set the load options for a context **before** you run a query on the context - this can cause issues but hopefully not for you.  Happy coding =)
Comment: I found out quickly, I just create a separate datacontext for the tickets. That means I run into trouble with editing/updating later but currently all I need is retrieving a large load of connected data. Previous query sessions could take _minutes_!
Comment: Why can't you use order by - what happens?  I hadn't hit that problem before.  Perhaps start a new question for the new issue?
Comment: And yes, I do the same thing regarding a seperate context.  It's not an ideal practice but generally I try to ensure that I only return/expose entities not derived from the context.  I'm actively working on a solution to that, if I find one I'll drop a note in here for you.


Laravel 8, User = null, but session still has "_token", session persistence problem?

Question: The Problem:
After successful initial "csrf-cookie" and "login" requests, the authenticated user seems to disappear from the session on all subsequent requests.
$request->user() and Auth::user() and auth()-user() all return null.
$request->session()->all() returns just a "_token" field, and $request->session()->has('users') and $request->session()->has('user') both return false.
Context:
This only occurs on my production server (I've tried both a Laravel Forge server and my own server with setting up Nginx manually).
This is a SPA backend, using Laravel 8. Using Laravel's built in Sanctum authentication. Using database session driver (although I've tried all the others, the driver does not seem to be the issue, and I can see the sessions in my database).
My session config currently (although I have tried other configs to no avail):
same_site = 'none'
domain = null
secure = true
http_only = true

What I've Tried:
Countless google searches, have not found any issues or solutions that seem to apply to my situation.
I have tried digging into the session and request objects immediately before and after the problem occurs (as described in the problem section) and have not gotten any useful information that way.
I have tried playing around with the session config... changing the "same-site", "secure", etc. variables.
Comment: Sanctum SPA auth is cookie-based. Are you losing the cookie somehow? Do your SPA & API domains share the same TLD?
Comment: I don't think I'm losing the cookie, as the request headers all contain the cookies set by the csrf-cookie request. My SPA and API also DO share the same TLD.
Answer: I have found the problem, turned out to be extremely simple/silly: I had to add the \Illuminate\Session\Middleware\AuthenticateSession::class middleware to my route (specifically for me, in this case it was to the 'api' middleware group).


Prove that $A = G^{4}$ for some self-adjoint matrix $G$

Question: Let $A\in M_{n}(\mathbb{C})$, $n\geq 2$.
Let $P_A(x) = (x-\lambda_1)....(x-\lambda_n)$ be characteristic polynomial of $A$ and all $\lambda_i$ are positive reals.
Show that if $A$ is normal, then $A = G^{4}$ for some self-adjoint matrix $G$
I just started on the topic on adjoint, normal matrices, and self-adjoint.
Thus I feel that I'm missing some concepts behind this topic.
From what the question has given, I know the following:
$A^*A = AA^*$
and $\exists \ \beta$, such that $\beta$ is an orthonormal basis consisting of eigenvector of $A$
Both of which are not very helpful in this case.
Hence are there some concept I neglected, or is there some trick to solving these sort of questions?
Any help or insights is deeply appreciated.
Answer: You have an orthonormal basis $e_1, \dotsc, e_n$, such that w.r.t. this basis $A$ has the form $\operatorname{diag}(\lambda_1, \dotsc, \lambda_n)$.
All $\lambda_i$ are positive reals, so why don't you just take $G=\operatorname{diag}(\sqrt[4]{\lambda_1}, \dotsc, \sqrt[4]{\lambda_n})$?
This is clearly a self-adjoint operator, since it is given by a symmetric matrix w.r.t an orthonormal basis. Of course $A=G^4$ holds.
Comment: I see, I'm still uncomfortable switching between an abstract Linear map and a "concrete" Matrix, but thank you for the reply though, it helped familiarize myself without some older concept.


Decision Tree - What to avoid first a Skewed dataset or reduce too much the number of bins

Question: So I have a dataset with a categorical column rather skewed. Lets imagine something like this:
Type - AmountObservations
C1 - 10000
C2 - 9500
C3 - 8000
C4 - 2000
C5 - 500
C6 - 500
C7 - 10
C8 - 10
C9 - 9
C10 - 9
C11 - 9
C12 - 9
...
C299 - 1
C300 - 1

For this particular variable observations can have 300 possible values (from C1 to C300). But most of the observations are of type C1, C2 and C3.
To simplify the number of splits in a node, in a decision tree, I was planning to group the possible values into bins.
I know the binning process is some kind of compression, so it imply information loss. The less amount of bins, the bigger the loss of information.
Initially I was planning to make 30 bins to group categories like:
C1-C30 -> bin1
C31-C60 -> bin2
...
C271-C300 ->bin30

But then I will have a really skewed dataset, where almost the 99% of the observations will be of type bin1.
Another option would be to have:
C1 -> bin1
C2 -> bin2
C3 -> bin3
C4-C300 -> bin4

With this approach I will have a less skewed dataset, but I will move from 300 categories to 4. Which I believe may be a big loss of information.
What is the better approach? If there is another option I didn't come up with, please share.
Comment: Why do you want to simplify the number of splits in a node by combining bins?
Comment: @StephanKolassa I though it makes the algorithm to work better.
Comment: @StephanKolassa besides I read that a skewed column may cause as well problems in a node. However if I have this concepts wrong, please let me know. I am starting still on this and any hint is always appreciated.
Answer: Unbalanced classes are usually not a problem: Are unbalanced datasets problematic, and (how) does oversampling (purport to) help? The key is to use a good metric to evaluate your classification. Use probabilistic predictions, and evaluate them using proper scoring-rules. Using accuracy can mislead you badly: Why is accuracy not the best measure for assessing classification models? and Is accuracy an improper scoring rule in a binary classification setting?
That said, whether your current binning is what you truly need depends on what you will do with the end result of your model. Suppose your classification classifies people into

"will repay the loan on time" (C1)
"will repay after a reminder phone call" (C2)
"will repay after a reminder letter" (C3)
"will not repay because of reason X" (C4)
"will not repay because of reason Y" (C5)
"will not repay because of reason Z" (C6)
etc.

In this case, you are really only interested in whether people fall in bins C1-3 versus C4-300. In this case, you should at least try (probabilistic) classifications with these combined bins. However, note that this is not necessarily driven by any statistical issues with unbalanced data, but by the process that consumes your classification.
Comment: Ok thanks a lot for the feedback. So in that case it is fine for a note in a decission tree to create 300 splits, one per possible category in the column?
Comment: Base on your description, I see no *a priori* reason why there should be a problem on the statistical side. (300 bins may be harder to interpret.)


JQuery replace portion of text in  with an

Question: I have this code in my body :

    hello ok hello no

    ok hello ok ko

I want to replace for each
 the text 'ok' by  tag
Is it possible to do this ?
Note : i must apply this function for others texts who can contain apostrophe and/or quote
Comment: Which programming language?
Comment: @FokkoDriesprong It says that in the tags.
Comment: I know it's possible that this is a wacky constraint, but this should really be a server-side task.
Comment: What do you mean by "some other texts who can contain apostroph and/or quote?"
Comment: Pills : i mean for example replace this text : (i've blablabla, i've blalllll). replace i've by i have
Answer: Use each:
$('p').each(function() {
    this.innerHTML = this.innerHTML.replace(/\bok\b/g, '')
})

I used /\bok\b/ so that something like token won't match. \b means "word boundary."
Here's a fiddle.
Comment: thank's for ur solution, but i've this result : it remplace only first 'ok' of each  and it add breakline after replace
Comment: I try to change the word "ok" by others words as "how are you", i cant change it. If you have link of documentation for replace method, share it please, because of i found only documentation for replaceWith
Comment: @tchiko `replace is not jQuery, it is pure JS.
Comment: dont existe method in jquery for this ?
Answer: I'd personally suggest:
$('p').html(function(i,h){
    return h.replace(/\bok/g,'');
});

JS Fiddle demo.
References:

html().
Answer: I hope this helps
   var x=$('p').html();
    var n=x.replace("ok","");
    $('p').html(n);

Comment: this will replace all the `p`s with the text of the first `p`. Did you try it? You can try running it on this page and see why it doesn't work.
Answer: try replaceWith - jquery
$( "
" ).replaceWith( '');
$( "
" ).replaceWith( "" );

for more information read jquery documentation
http://api.jquery.com/replaceWith/
Comment: The OP's trying to replace only the word "ok" with the image, and anyway this answer is wrong since `$('')` creates a `p` element and the second one does absolutely nothing.


Criptografia em C - Cifra de César

Question: Boa tarde,
Estou desenvolvendo um código de criptografia básica (Cifra de César) em C.
Estou usando a lógica de percorrer 2 vetores: vetTexto e vetLetras, onde ocorre a comparação do char e posteriormente substitui-lo 3 posições a frente no vetLetras, porém não estou tendo sucesso. O código compila, mas na hora de rodar fica pedindo entradas do texto a ser criptografado várias vezes (entradas maiores do que o tamanho do vetor estipulado por mim).
Código:
#include<stdio.h>

int main (){

#define tamanhoTexto 4
#define qtdLetras 26

int i = 0, j = 0;
char vetTexto[tamanhoTexto];
char vetLetras[26] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

for(i=0; i<tamanhoTexto;i++){  //Lendo o texto a ser encriptado
scanf ("%c", &vetTexto[tamanhoTexto]);
}

for (i = 0; i < tamanhoTexto; i++){ //Varrendo os 2 vetores fazendo a busca de letras correspondentes
  for (j = 0; j < qtdLetras; j++){

      if(vetTexto[i] == vetLetras[j] && j+ 3 <qtdLetras){ //j+3(deslocamento) não pode sair do vetor letras

          vetTexto[i] = vetLetras[j+ 3];
      }else{

          j = j + 3;
          j = j - qtdLetras; //caso saia, faço a soma e tiro 26, pra voltar ao começo.
          vetTexto[i] = vetLetras[j];
      }
    }
  }
  for (i = 0; i < tamanhoTexto; i++){ //impressão do texto criptografado

  printf ("%c", vetTexto[i]);
}
  return 0;
}

Já vi algumas perguntas semelhantes aqui no fórum, mas estão usando uma lógica e sintaxe diferente da minha.
Sendo um pouco mais objetivo: as minhas dúvidas são:

Por quê o código não funciona?
A lógica está correta?
Existe uma forma melhor de aplicar esse tipo de criptografia em C?

Obrigado pela atenção.
Comment: Olá, tudo bem. Eu já fiz esse algoritmo em php, se quiser dar uma olhada... https://github.com/flhorizonte/caesar-cipher-algorithm/blob/master/CifraCesar.php
Answer: Primeiro problema
for(i=0; i<tamanhoTexto;i++){  //Lendo o texto a ser encriptado
scanf ("%c", &vetTexto[tamanhoTexto]);
}

Ao invés de &vetTexto[tamanhoTexto] era para ser &vetTexto[i].
Segundo problema
            j = j + 3;
            j = j - qtdLetras; //caso saia, faço a soma e tiro 26, pra voltar ao começo.
            vetTexto[i] = vetLetras[j];

Não altere as variáveis que servem como contador do laço, estando do lado de dentro dele. Isso daí acaba criando um loop infinito! Use isso:
            int k = j + 3;
            if (k > qtdLetras) k = k - qtdLetras; //caso saia, faço a soma e tiro 26, pra voltar ao começo.
            vetTexto[i] = vetLetras[k];

Ou simplificando isso:
            vetTexto[i] = vetLetras[(j + 3) % qtdLetras];

Terceiro problema
Observe o if. Ele tem que entrar se as letras dos dois laços forem a mesma e ele não ultrapassar o Z. No caso contrário ele entra no else. Entretanto, ele deveria entrar no else apenas se ele ultrapassar o Z, mas ainda sendo o caso de letras iguais, mas ele entra no else também quando as letras são diferentes. O certo seria então colocar assim:
  if (vetTexto[i] == vetLetras[j]) {
      if (j + 3 < qtdLetras) {
          vetTexto[i] = vetLetras[j + 3];
      } else {
          vetTexto[i] = vetLetras[(j + 3) % qtdLetras];
      }
  }

Primeira otimização
Você não precisa declarar o vetor vetLetras. Basta ver que, para qualquer x entre 0 e 25, vetLetras[x] tem o valor de 'A' + x. Assim, você pode substituir todas as ocorrências de vetLetras[...] por essa fórmula e com isso eliminar o vetor vetLetras.
Segunda otimização
Uma vez que você pode usar o % qtdLetras ao atribuir um valor ao vetTexto[i], você não precisará mais do if interno, pois com essa operação do else, tanto faz se ele ultrapassou ou não o Z, ele vai ficar correto.
Convenções de código
Para deixar o código mais alinhado com as convenções da linguagem, utilize LETRAS_MAIÚSCULAS para constantes e coloque as #defines antes do main. E também idente o seu código. Sugiro também mudar vetTexto para apenas texto.
Quarto problema
Seu código deve estar assim:
for (i = 0; i < TAMANHO_TEXTO; i++) {
    for (j = 0; j < QTD_LETRAS; j++) {
        if (texto[i] == 'A' + j) texto[i] = 'A' + (j + 3) % QTD_LETRAS;
    }
}

Você varre os dois vetores para fazer a substituição, mas esse if só vai entrar quando j for igual a texto[i] - 'A'. Nesse caso, você não precisa mais do laço interno, que fica assim:
for (i = 0; i < TAMANHO_TEXTO; i++) {
    j = texto[i] - 'A';
    texto[i] = 'A' + (j + 3) % QTD_LETRAS;
}

E isso por sua vez é reduzido para isso:
for (i = 0; i < TAMANHO_TEXTO; i++) {
    texto[i] = 'A' + (texto[i] - 'A' + 3) % QTD_LETRAS;
}

A variável j torna-se então desnecessária.
Código completo
O seu código completo revisado fica assim:
#include <stdio.h>

#define TAMANHO_TEXTO 4
#define QTD_LETRAS 26

int main() {

    int i = 0;
    char texto[TAMANHO_TEXTO];

    for (i = 0; i < TAMANHO_TEXTO; i++) {
        scanf("%c", &texto[i]);
    }

    for (i = 0; i < TAMANHO_TEXTO; i++) {
        texto[i] = 'A' + (texto[i] - 'A' + 3) % QTD_LETRAS;
    }

    for (i = 0; i < TAMANHO_TEXTO; i++) {
        printf("%c", texto[i]);
    }

    return 0;
}

Veja aqui funcionando no ideone. Com a entrada ABXY, ele produz a saída DEAB.
Comment: Muito obrigado pela ajuda Victor!
Poderia me tirar outra dúvida? eu entendi a fórmula final, mas não entendi o passo a passo lógico para chegar até o trecho de comparação e substituição, poderia me explicar?
Comment: for (i = 0; i < TAMANHO_TEXTO; i++) {
    texto[i] = 'A' + (texto[i] - 'A' + 3) % QTD_LETRAS;
Comment: @H.Lima `texto[i]` é a letra. Assim sendo, `texto[i] - 'A'` vai ser 0 para A, 1 para B, 2 para C, ... 25 para Z. Somando 3 nisso, temos que A vai para 3, B para 4, ... Z para 28. Aplicando o `% QTD_LETRAS`, o que vai acontecer é que um número entre 3 e 25 (que é do C ao W) após o `% 26` vai ficar igual. Já com o X, Y e Z (que são 26, 27 e 28), vão mudar para 0, 1 e 2. Depois disso tudo, o `A +` pega esses números (A->3, ..., W->25, X->0, ..., Z->2) e transforma em (A->D, ... W->Z, X->A, ..., Z->C). Isso é atribuído ao `texto[i]` encriptando então o texto.
Comment: Agora entendi, não tinha percebido que esse trecho estava atribuindo valores numéricos às letras, Obrigado novamente!
Answer: voce precisa da biblioteca do cc50 para compilar, pode encontrar ela aqui:
https://github.com/GabrielRCL/CC50/tree/main/Semana%202/lib
use o comando para compilar:
gcc -ggdb -std=c99 -Wall -Werror -Wformat=0 -o caesar caesar.c -lcc50 -lm

SCRIPT:
 #include <cc50.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h> //use this library to use "atoi()"

    //CIFRA DE CESAR - CRIPTOGRAFIA
    // FORMULA: Ci = ( Pi + k ) % 26
    // Ci = igésimo caractere criptografado
    // P = Frase para criptografar (string inserida)
    // Pi = igésimo caractere referente a String

    int
    main(int argc, char *argv[])    //char * = string
    {
        int k = atoi(argv[1]);  // k é o valor que o humano inserir no argumento transformado em inteiro

        char A = 'A';   // Int A = 65
        char a = 'a';   // Int a = 97

        printf("Insira o texto para criptografar: \n");
        string p = GetString();

    //   === [Criptografando] ===
        for (int i = 0, n = strlen(p); i < n; i++)
        {
            if (p[i] == 32) {
                //ESPAÇO - FIX BUG
                printf("%c", p[i]);

            } else if (p[i] < 97) {
                //LETRA MAIUSCULA
                int Pi = p[i] - ( (int)A - 1 ); //transformando para inteiro e subtraindo 64 para deixar o A = 1 / B = 2 / C = 3
                int Ci = ( ( Pi + k ) % 26 ) + ( (int)A - 1 );  //adicionando 64 para voltar aos valores normais de char A = 65 / B = 66 / C = 67
                printf("%c", Ci);

            } else {
                //LETRA MINUSCULA
                int Pi = p[i] - ( (int)a - 1 ); //transformando para inteiro e subtraindo 64 para deixar o a = 1 / b = 2 / c = 3
                int Ci = ( ( Pi + k ) % 26 ) + ( (int)a - 1 );  //adicionando 96 para voltar aos valores normais de char A = 97 / B = 98 / C = 99
                printf("%c", Ci);
            }
        }
        printf("\n");

    return 0;
    }

Criptografia em C - Cifra de César