Change node author on node save with rules

Question: I have a very simple rule with Event "Before saving content" and Elements "Content is of type (page)" and would like the action to be something similar to "Change node author to UID X", which would be the UID I want.
I can't seem to be able to achieve that with the actions exposed. To test my rule I've been trying to display a message on the site when triggering the rule and it works just fine.
Any idea how to do that without having to write code?
This is on Drupal 7 (latest) with latest stable Rules version.
Answer: I think you can do this by adding a new action - "Fetch entity by ID", then selecting users and using that to update the node.
Comment: I've been trying the "Fetch entity by ID" and while it's promising since it does expose "User" and asks for an identifier, I'm not sure how to manipulate that data next to actually tell Rules I want to change the node author?
Comment: I think I made it work. Create "Fetch entity by ID" action with Entity type valye = User and identifier value = my_ID, then create another action "Set a data value" with selected data "node:author" and data selector "entity-fetched". Voila!
Comment: Glad you got it working :)
Answer: I have a suggestion for you for achieve this.(Its tested by myself).
create a new rule and in create node event(or every event you want ) , in action use Php(Execute custom PHP code)(make sure you php filter module installed).
and in there write this
<code> $mynode=node_load($node->nid);
 $mynode->uid='user_id_want';
 node_save($mynode);
</code>
-------------update------------
put your user id instead 'user_id_want';
as example
<code>   $mynode=node_load($node->nid);
   $mynode->uid=20;
   node_save($mynode);
</code>
Comment: This PHP code is throwing the following message: EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7562 of docroot/includes/common.inc).
Comment: which event you choosed?
Comment: @vanz I choose `After saving new content` event and test it again, work charmly.
Comment: as I said in my initial question, my goal is to make this work without code, which I was able to achieve just now (see my other comment). The method you are suggesting might probably work but I couldn't get around it. Thanks for the suggestion anyway.


Should a delegate go through a controller to get the model?

Question: Trying to figure out the MVC-concept.
I have a NSCustomView that implements drawRect:, which is based on a delegate specified in the controller of the custom view.  My question is, should the delegate point to the model's controller, or is it ok to point the delegate directly to the model?
Should the NSCustomView ask the NSWindowController, to ask the Model's Controller, to ask the model for the data?  Seems like there are too many layers to a "proper" MVC design.
Comment: Read [MVC as a Compound Design Pattern](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaDesignPatterns/CocoaDesignPatterns.html#//apple_ref/doc/uid/TP40002974-CH6-SW22). Although it is quite possible to make the Model and the View communicate directly, in the Cocoa version of MVC, they always communicate through the Controller.
Answer: More often than not, the delegate is the view controller, or fits into a controller-type role. If that's not your situation, it'll help if you explain what's going on in greater detail.
Comment: Here's what I'm not understanding. If I'm supposed to have complete separation between M V and C. What in the app is supposed to "own" the M part? Does the C own the M?  What creates the M part? Right now I have my C create the M, but this is causing problems because I'm trying to archive the data, which isn't playing well because it also archives the C.
Comment: You have a fair bit of freedom in that respect, and much depends on your app design. For example, iOS apps often don't have any sense of a document, so the model may be created by the app delegate and then passed along to the controllers as necessary. Desktop apps are more likely to work with documents, and in that case it might be the document that creates the model, and the app delegate just creates documents in response to New and Open commands.
Comment: So in the desktop example, does the Document create the view instance too?  I seem to be missing something.  I looked at the TextEdit example, but not seeing how the MVC are allocated and where they're kept.  I have a "document-based" desktop app.  But each project is comprised of multiple NSWindowControllers.
Comment: See `-[Document makeWindowControllers]` in the TextEdit source. That instantiates a DocumentWindowController, which loads a window from a nib. That's the view. Then look at `-[Document init]` and `-[Document readFromURL:ofType:encoding:ignoreRTF:]` and notice how the documents NSTextStorage object is created and populated with data; that's the model. The document itself and the document window controller play controller roles.
Comment: That's really odd because NSDocument (model/data) owns the WindowController (controller), which in turn owns the nib instance (view).
Comment: I think you misunderstand. It's not that there can't be relationships between model and controller, or controller and view. The idea is to avoid dependencies between view and model and vice versa, so that they can each be modified without impacting the other. NSDocument better fits into the controller category than the model category. Read [The Role of NSDocument](http://tinyurl.com/3vzuh55).


What's the furthest a player has run in a single match?

Question: For a while now, football matches have recorded how far each player has run. This link states that N'golo Kante (Chelsea) ran 306.7 km in 26 matches, for an average of 7.33 miles per game.
How about the record for a single match? What's the known record for the furthest a player has run in a single match?
Comment: [This Reddit comment](https://www.reddit.com/r/soccer/comments/3foaha/comment/ctquwdz/?utm_source=share&utm_medium=web2x&context=3) claims that Michael Bradley ran 16.9 km during the USA's match against Belgium at the 2014 World Cup, but the link to their source is broken and I haven't found an alternate source, so I'm hesitant to post it as an answer.
Comment: That Reddit comment is just wrong. [Bradley covered a total of 38 km in three group matches](https://www.si.com/soccer/2014/06/28/michael-bradley-usa-world-cup-jurgen-klinsmann), playing 90 minutes every time, and USA were beaten in the next match without e.t. That he somehow did an extra 30% compared to average from three games? Nonsense.
Comment: Of course distance-run does not tell us everything about a player's commitment, or physical stress.
Answer: For the FIFA World Cup, midfielder Marcelo Brozovic of Croatia has held the record since 2018.
His initial record was 16.3 kilometres in the quarterfinal versus Russia, 2018, and was increased to 16.9 kilometres in the round of 16 versus Japan, 2022.
Both games eventually went to kicks from the penalty mark, and Croatia won both from there. The extra time spent on the field  combined with Brozovic's workrate and his positional requirements as a defensive midfielder, explain both the large distances involved and the ability to keep (then improve) the record himself.
This information is reported in various sources, including Inter Milan's media website, the UK's Daily Mail, and a variety of Croatian and worldwide news providers.


Android SQLite throws Failed to read row 0, column -1 from a CursorWindow

Question: Today I wanted to implement a simple SQLite database into my messaging app that should take care of saving messages, unfortunately I am not able to read back the data from the Database and display them into a ListView.
I looked into the database via ADB on my emulator and I saw that the data is saved correctly.
Here is my code
Initialisation of the TABLE with a empty column
db.execSQL("CREATE TABLE IF NOT EXISTS Messages(zero);");

Creating of a column with the chat contact as the column name
public void addMessagetoDB(String message, String from) {
    Toast.makeText(this.getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
    try
    {
        db.execSQL("ALTER TABLE Messages ADD COLUMN '" + from + "' TEXT");
    }
    catch (android.database.sqlite.SQLiteException e)
    {

    }
    db.execSQL("INSERT INTO Messages ('" + from + "') VALUES('" + message + "');");
}

Here I can also see that SQLite recognizes my column names, because when I send multiple messages to my client I get the debug messages
E/SQLiteLog﹕ (1) duplicate column name: firstname.lastname@example.com

This is my readout which won't work
public void updateView(String from) {
        Cursor crs = zapp.rawQuery("SELECT * FROM Messages", null);
        while (crs.moveToNext()) {
            String name = crs.getString(crs.getColumnIndex(from));
            messages.add(name);
        }
        arrayAdapter.notifyDataSetChanged();
}

This is my exception
06-05 22:15:45.841    4926-4926/? E/SQLiteCursor﹕ requesting column name with table name -- email@example.com
    java.lang.Exception
            at android.database.sqlite.SQLiteCursor.getColumnIndex(SQLiteCursor.java:180)
            at org.reisacher.zapp.ChatActivity.updateView(ChatActivity.java:43)
            at org.reisacher.zapp.MainActivity$1.onItemClick(MainActivity.java:52)
            at android.widget.AdapterView.performItemClick(AdapterView.java:305)
            at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
            at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
            at android.widget.AbsListView$3.run(AbsListView.java:3860)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
06-05 22:15:45.841    4926-4926/? E/CursorWindow﹕ Failed to read row 0, column -1 from a CursorWindow which has 5 rows, 2 columns.
06-05 22:15:45.841    4926-4926/? D/AndroidRuntime﹕ Shutting down VM
06-05 22:15:45.841    4926-4926/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: org.reisacher.zapp, PID: 4926
    java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
            at android.database.CursorWindow.nativeGetString(Native Method)
            at android.database.CursorWindow.getString(CursorWindow.java:438)
            at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
            at org.reisacher.zapp.ChatActivity.updateView(ChatActivity.java:43)
            at org.reisacher.zapp.MainActivity$1.onItemClick(MainActivity.java:52)
            at android.widget.AdapterView.performItemClick(AdapterView.java:305)
            at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
            at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
            at android.widget.AbsListView$3.run(AbsListView.java:3860)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

As one can see SQLite is trying to get the column name, which matches the one I am saving the messages to, but the somehow then reads column -1
I didn't find a solution for this behavior
Thanks
Comment: Did you somehow named one of the columns: "firstname.lastname@example.com"?
Maybe by mistake you try to retrieve data using this email(/id)?

I ask because it seems like you invoke method updateView(String from) with this email as a parameter.

[code] requesting column name with table name -- firstname.lastname@example.com[cod]
Answer: The problem is the you have a '.' in the field name and that is being understood by the engine as a table.field separator.
In other words, getColumnIndex() is trying to find the numeric index of 'org' in the table 'test@zapp' ... another reason to not use that type of value for your field names.
The clue that gave it away was the "E/SQLiteCursor﹕ requesting column name with table name -- email@example.com"
I would also question your idea of dynamically adding columns to the table based on the 'from' value, growing your table horizontally instead of the normal method of letting it expand vertically. Makes it slower and slower as it gets bigger and more unwieldy.
Comment: Thanks, that got it working, substringed the "from" value at the "@" character. What do you mean by expanding it vertically. I am adding a column for a contact, then the messages from or to that contact are being added below in the corresponding column making the table grow vertically


Move timezone field in user/%/edit field

Question: I want to move timezone field in user/%/edit form. I have used$form['#weight'] in hook_form_alter() and $page['#weight'] in hook_page_alter(), but not working.
Answer: The next snippet should work
<?php

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    $form['#after_build'][] = 'MYMODULE_user_profile_form_pre_render';
  }
}

function MYMODULE_user_profile_form_pre_render($form) {
  $form['timezone']['#weight'] = -10;
  return $form;
}

Comment: I have tried this but not working
Comment: I can able to move all fields except this.
Comment: I have updated code
Comment: This also not working
Comment: I tested this code on my site and it works fine. Could you please try to clear caches?
Comment: I have changed the weight but I can't move the field. See [this screenshot](http://i.stack.imgur.com/gH3an.png).


How to set Design for all Screen in android?

Question: I've develop an application for my project. In that I don't know how to set layout in all screen. If I change another screen that default screen is also changes. Here is my code. So how can I set layout in all screen.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/custom_bg">

<RelativeLayout
    android:id="@+id/relativemail"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="5dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginTop="5dp" >

 <LinearLayout
     android:id="@+id/imageid"
     android:layout_width="wrap_content"
     android:layout_height="180dp"
     android:layout_marginLeft="55dp"
     android:layout_marginRight="55dp"
     android:layout_marginTop="20dp"
     android:background="@drawable/image_bg"
     android:gravity="center" >

        <ImageView
            android:id="@+id/photo"
            android:layout_width="140dp"
            android:layout_height="140dp"
            android:background="@drawable/upload_photo" />
</LinearLayout>

<LinearLayout
    android:id="@+id/buttonid"
    android:layout_width="match_parent"
    android:layout_height="65dp"
    android:layout_below="@id/imageid"
    android:layout_marginLeft="12dp"
    android:layout_marginRight="12dp"
    android:layout_marginTop="15dp"
    android:background="@drawable/galary_bg"
    android:gravity="center"
    android:weightSum="2" >

        <RelativeLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:gravity="center" >

                        <Button
                            android:id="@+id/camera"
                            android:layout_width="120dp"
                            android:layout_height="50dp"
                            android:background="@drawable/cameraxml" />
        </RelativeLayout>

        <RelativeLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:gravity="center" >
                        <Button
                            android:id="@+id/galary"
                            android:layout_width="120dp"
                            android:layout_height="50dp"
                            android:background="@drawable/galeryxml" />
        </RelativeLayout>

</LinearLayout>

 <LinearLayout
     android:id="@+id/saveid"
     android:layout_width="wrap_content"
     android:layout_height="65dp"
     android:layout_below="@+id/buttonid"
     android:layout_marginLeft="40dp"
     android:layout_marginRight="40dp"
     android:layout_marginTop="15dp"
     android:background="@drawable/save_bg"
     android:gravity="center" >

     <Button
        android:id="@+id/save"
        android:layout_width="120dp"
        android:layout_height="50dp"
        android:background="@drawable/savexml"/>
     </LinearLayout>

 <RelativeLayout
     android:layout_width="wrap_content"
     android:layout_height="40dp"
     android:gravity="center"
     android:layout_alignParentBottom="true"
     android:layout_below="@+id/saveid"
     android:layout_marginBottom="15dp"
     android:layout_marginLeft="84dp" >

     <ToggleButton
         android:id="@+id/toggleButton1"
         android:layout_width="150dp"
         android:layout_height="40dp"

         android:background="@drawable/chapxml" />
 </RelativeLayout>

</RelativeLayout>

</RelativeLayout>

Comment: avoid use of hardcoded values of height and width,use wrap_content or match_parent.and in case of you have to put hardcoded values then create dimens for different devices into values/dimens.xml
Answer: Instead of using dp, sp, px and other hard values you have to use match_parent and wrap_content. Those are dynamic values that change by screen width, height and dpi.
Comment: @user3755817 I don't know how it should look like exactly, just play with the dynamic values and figure it out.
Answer: You could do it using fragments and only change the specific views that you need to change across activities but an easier option would be to re-use layout using .
Create a layout with all those views and use <merge> tag to enclose them. Then create different layout files(xml) for different activities and use <include> as described in the link.


RxJava Scheduler.Worker schedule Action that subscribes to an Observable

Question: I schedule an Action0 that triggers a function that I want to subscribe to. Currently I can't think of a better way to do this beyond calling toBlocking().single(). What's more, I also want to schedule the Action0 again after it has completed.
There must be a more idiomatic way of doing this. Do I also leave myself open to memory leaks by not handling the Subscription returned by the .schedule()?
worker.schedule(new Action0() {
        @Override
        public void call() {
            try {
                consumer.doSomething().toBlocking().single();
            } finally {
                worker.schedule(this);
            }
        }
});

FWIW I'm stuck with RxJava 1.
Answer: In the RxJava world, you probably don't want to use the explicit schedule() operations.
A better way to accomplish what your describe would be:
Observable.fromCallable( consumer.doSomething() )
  .repeat()
  .subscribeOn( scheduler )
  .subscribe();

This will invoke doSomething() over and over again, ignoring the output. The repeat operator will resubscribe when the call is done.
Comment: Ok, I like this! Given that consumer returns an observable itself, what if I just put a `.repeat` on `consumer.doSomething()` directly?
Comment: Yes: add the `repeat` operator to `consumer.doSomething()` directly.
Comment: And how about if I wanted schedule it to run periodically. ie: `worker.schedule(initialDelayMillis, periodMillis, TimeUnit.MILLISECONDS)`
Comment: Use `Observable.interval( initialDelayMillis, periodMillis, TimeUnit.MILLISECONDS )` as the first step, and `flatMap()` to introduce `consumer.doSomething()` into the chain.


Problema com matrizes em C

Question: Tenho que fazer um programa que vai ler 4 notas de cada um dos 6 alunos de uma turma e armazená-las em uma matriz NOTAS[6][5]. Para cada aluno, deve-se calcular a média aritmética das 4 notas e armazenar esta média na última coluna da matriz (coluna de índice 4). O programa também deve imprimir a média de cada aluno e, por fim, a média aritmética da turma.
Fiz um código e fui executar, na hora de pegar o ALUNO 6 NOTA 2, em vez de ser digitado ALUNO 6, ele digita um número totalmente aleatório, e acaba o programa, e dependendo, o código da erros diferentes!
Qual erro estou cometendo?
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

int main() {
setlocale(LC_ALL, "Portuguese");
float nota[6][5], media;
int i, j;
media = 0;

for(i=1; i<=6; i++) {
    for(j=1; j<=5; j++) {
        printf("\nAluno %d Nota %d \n", i, j);
        scanf("%f", &nota[i][j]);
    }
}

for(i=1;i<=6;i++)
    {
    for(j=1;j<= 5;j++) {
        printf("%f", nota[i][j]);
    }
    printf("\n");
}

for(i=0; i<=6; i++) {
    for(j=0; j<5; j++) {
        nota[i][5] = nota[i][5] + nota[i][j];
    }
}

for(i=0; i<=6; i++) {
    nota[i][5] = nota[i][5]/4;
    media = nota[i][5] + media;
}

media = media/6;
for(i=0; i<=6; i++) {
    printf("\nA média do aluno %d = %.2f", i, nota[i][5]);
}
printf("\nA média dos alunos: %.2f", media);

return 0;
}

Answer: Todos os loops estão com índices errados.
primeiro loop
int n_alunos = 6;
int n_notas = 4;
for(i=0; i != n_alunos; i++) {
  for(j=0; j != n_notas; j++) {
    printf("\nAluno %d Nota %d \n", i, j);
    scanf("%f", &nota[i][j]);
  }
}

O valor inicial da soma tem que ser zero.
int j_media = 4;
for(i = 0; i != n_alunos; ++i)
{
  nota[i][j_media] = 0.0;
}

Soma das notas e média
for(i=0; i != n_alunos; ++i) {
  // soma das notas
  for(j = 0; j != n_notas; j++) {
    nota[i][j_media] = nota[i][j_media] + nota[i][j];
  }
  // média do aluno
  nota[i][j_media] = nota[i][j_media] / n_notas;
}

média da turma
for(i = 0; i!=n_alunos; i++) {
  media = nota[i][j_media] + media;
}
media = media / n_alunos;

os loops de saída ficam por sua conta.
Answer: Em C as o for jamais deve começar em 1 e ir até N quando se trabalha com vetores e matrizes, pois o tamanho do vetor ou da matriz vai de 0 até N-1.
Caso tenha uma matriz 6x5, sou for o i deve ir de 0 a 5 e o j de 0 a 4.
O erro é porque você certamente está tentando escrever em uma posição inexistente da sua matriz.
Comment: Arrumei os for, e mesmo assim está dando números aleatórios, sendo que para todos alunos, usei a mesma nota e deu valores diferentes e mesmo e também usando o %.2f para a média de todos os alunos, parece que a formatação foi anulada.                                       A média do aluno 0 = 3,75
A média do aluno 1 = 11,25
A média do aluno 2 = 15,25
A média do aluno 3 = 20,75
A média do aluno 4 = 1636992022601586400000000000000000,00
A média dos alunos: 272832003766931070000000000000000,00

Problema com matrizes em C


How to use managed_file to upload many files

Question: I'm looking for a way to upload many files by means of the managed_file form API element. I would like it be like while uploading for node where is 'add new item' button.
How to do it?
Comment: What is managed_file field. Is it a field you created.
Comment: It's #type from Drupal Form API. I want to do it by code.
Comment: If it's about Form API, it's not a "field", it's a "form element" - these terms have very specific meaning. So, if I read you right, you should remove tag [tag:fields] and add [tag:form-api]. And of course edit content to replace word "field".
Answer: You may want to use plupload form element instead. Install Plupload integration module and then use something like:
$form['my_element'] = array(
  '#type' => 'plupload',
  '#title' => t('Upload files'),
  '#description' => t('This multi-upload widget uses Plupload library.'),
  '#upload_validators' => array(
    'file_validate_extensions' => array('jpg jpeg gif png txt doc xls pdf ppt pps odt  ods odp'),
    'my_custom_file_validator' => array('some validation criteria'),
  ),
  '#plupload_settings' => array(
    'runtimes' => 'html5',
    'chunk_size' => '1mb',
  ),
);

Comment: I installed it and there is only info like "This multi-upload widget uses Plupload library.
Allowed file types: jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp."
Comment: Check with Firebug, probably there is some javascript error.
Comment: Paths issue, however I would like to use the managed_file type.
Comment: @daroPL Sadly, there is no "managed_files" type, just "managed_file".
Comment: I had a look on `file_field_widget_form()` and there it is done it by `manage_file`.
Answer: I used below Solution. Its worked for me.
Click Here


How to be consistent in studio performance?

Question: Every time I hear myself playing in a studio recording setup, I feel like my playing is inconsistent in terms of tempo and dynamics, regardless of the instrument (drums or guitar).
I know I can improve my tempo by practicing with a click but there are always some volume inconsistency between two successive hits or picks. In the case of guitar recording, sometimes I can accidentally hit open strings or get noise.
How else can I improve?
Answer: Those two problems you describe (mishitting strings and inconsistency in volume/tone) are only fixed by practice. Lots and lots of practice.
They are things you can get away with in a live environment, but they do show up in a studio where every mistake is very evident.
I had the same problem - I love gigging, but the first time I went into the studio I was incredibly disappointed in myself - I sounded terrible: out of time, many mistakes etc.
But the solution was to practice - I used a metronome to practice consistent alternate picking (this was the biggest problem I had) and worked out a couple of complicated chord sequences to practice over and over at steadily increasing speed.
Now I love the studio - I always want to improve, but my notes now sound like I want them to.
Comment: The studio is a great way to have your nose rubbed in reality, which this is really useful, but you can also psych yourself out by overhearing mistakes.  By paying attention to your recordings you can improve your awareness and sensitivity and learn to recognize opportunities for improvement as you play.  This sensitivity is part of what makes great players great.
Comment: For fast parts I like to increase until faster than normal speed to know the ceiling is higher than what I need to do.
Answer: I agree with Dr Mayhem that practice is important to solving the core issues you raise.
However, in terms of dynamics between successive picks/hits, some compression might help you. In short, a compressor will even out a signal by attenuating the volume over a certain threshold. These are commonplace in any studio (in fact, if you ask me, they tend to be overused nowadays).
Comment: I was looking more for a response on the performance side rather than the post-processing of recording side but thanks for the insight. It might be a good solution to "fix" things rather than solving it from the root of the problem.
Comment: @hazer_drum  "rather than solving it from the root of the problem."  Why not both?  Get a great performance and then add great production.  There's no need to choose one or the other.
Answer: This boils down to practice, but the key question is what to practice and how. This might be different for every person.
For exercise record and produce on your own, applying post-processing that is typical to the style of music. Nowadays the needed equipment is cheap, so is the software, there are also many free programs – so there is no excuse. This will give you the most direct feedback on:

what are your specific issues and what kind of practice results in improvement. If you make a mistake, analyze what you're doing and focus on fixing it. There might be a detail of technique that you have not paid attention to before.
how your instrument sounds in the mix. When we practice our instruments on its own the details that stand out the most might not be the same that are the most relevant for the sound of a full band. E.g. if your instrument has large dynamics, and another instrument in the mix has low dynamics, large variety of loudness of your instrument may seem like inconsistency, even if it sounds good on its own.
how your instrument sounds after typical post-processing for the style. E.g. if a heavy compression is used, small dynamics inconsistencies might be completely irrelevant, while a wrong note, even if played lightly, would be amplified and stand out.


A basis question of least upper bound property.

Question: A set $A$ is said to have least upper bound property if every subset $A_0 \subset A$ has a least upper bound. $\mathbb{R}$ has least upper bound property is well known. Now consider the subset $A = [0,1)$ of $\mathbb{R}$. Does $A$ have the least upper bound property?
I am considering the subset $A_0 = [\frac{1}{2} , 1)$. Clearly it is bounded above in $\mathbb{R}$ with least upper bound $1$. Is $A_0$ is bounded above in $A$? Shall we consider $1$ as its least upper bound?
Thank you for your help.
Answer: You haven't quite got the definition correct: an ordered set $A$ is said to have the least upper bound property if for every non-empty subset $A_0\subset A$ with an upper bound in $A$ has a least upper bound in $A$. By the definition you've written, $\Bbb R$ would not have the least upper bound property, since the empty set is vacuously bounded but has no least upper bound, and since an upper bound of $\Bbb R$ in $\Bbb R$ would be a greatest element (and no such element exists).
As for your example, $A_0$ does not have an upper bound in $A$, so has no least upper bound in $A$. You are correct that it has a least upper bound in $\Bbb R,$ though.
Here's an approach you can take to show that $A$ does have the least upper bound property. Take any non-empty subset $A_0\subseteq A$ such that there is some $x\in A$ such that $a\le x$ for all $a\in A_0$ (that is, such that $A_0$ has an upper bound in $A$). It follows that $A_0$ has an upper bound in $\Bbb R$, so has a least upper bound, say $y\in\Bbb R$. Show that $y\in A,$ and that $y$ is the least upper bound of $A_0$ in $A$. The latter should be easy. For the former, you can use the fact that $A_0$ is non-empty, that $x$ is an upper bound of $A_0$, that $y$ is an upper bound of $A_0$ with $y\le x$ and that $A$ is an interval.
Comment: Thank you very much for your explanation. It happened because of my misunderstanding. It is clear now.


Chave Primária: HashMap ou Object Comum?

Question: Boa tarde pessoal, tudo bem?
A minha dúvida é a seguinte...
Estou querendo utilizar HashMap como chave primária. Há algum problema? Ou devo utilizar Object?
OBS: Estou modelando o banco de dados, que será com MongoDB.
Desde já, agradeço!
Comment: Hashmap como chave primária? Qual seria a lógica disso?
Comment: Eu estava querendo utilizar uma chave primária composta, e como nunca utilizei, estou querendo saber se é possível e recomendado... Object seria a melhor opção?
Comment: Como seria a sua chave composta?
Comment: Ela teria dois atributos, o "tipo" da máquina e o "número" dela. Queria utilizar uma forma bem simples, sem criar um objeto.
Comment: Porque não usar 2 integer?
Comment: Eu pensei nisso... mas gostaria de "tentar" colocar uma chave composta. Será que há alguma forma simples? Senão, vou utilizar esses atributos
Answer: Vc pode criar seu objeto com os campos normalmente e depois criar a chave composta com os campos que quiser. No seu caso, vc criaria "tipo" da máquina e "número" e depois anotaria os dois para criar a chave composta.
Sua classe poderia ser algo assim:
import javax.persistence.*;

@Entity
@IdClass(MaquinaID.class)
public class Maquina {

    @Id
    private Integer tipoMaquina;

    @Id
    private Integer numero;

    // [...]
}

Classe para a chave composta:
import java.io.Serializable;

public class MaquinaID implements Serializable {
    private Integer tipoMaquina;
    private Integer numero;

    public MaquinaID() { }

    public MaquinaID(Integer tipoMaquina, Integer numero) {
        this.tipoMaquina = tipoMaquina;
        this.numero = numero;
    }

    // getter e setter
}

Segue abaixo o link pra vc dar uma olhada mais detalhada e outras opções de como fazer uma chave composta:
https://receitasdecodigo.com.br/hibernate/chaves-compostas-com-hibernate
Eu não sei dizer como seria o HashMap no BD, mas acredito que não seja a melhor forma pra criar uma chave composta.
Comment: Amigo, muito obrigado pela sua ajuda, de verdade! Você deu uma luz para mim! Fique com Deus!


Group Homomorphisms into an Abelian Group

Question: The following comes from Hungerford's Algebra.

[Prove that if] $f: G \to H$ is a homomorphism, $H$ is abelian and $N$ is a subgroup of $G$ containing $\ker f$, then $N$ is normal in $G.$

A solution found here (at I.5.16) begins by saying "since $H$ is abelian, $f(H)$ is an abelian subgroup." Obviously, this makes sense, but the domain of $f$ is $G.$  Why does $f(H)$ make sense here? This is really the part of the proof I don't understand.
Is there also another way to proceed with the proof?
Comment: It seems to be a typo.  Try reading it as "$f(G)$ is an abelian subgroup" instead.
Comment: Possible duplicate of [Subgroups containing kernel of group morphism to an abelian group are normal.](https://math.stackexchange.com/questions/542264/subgroups-containing-kernel-of-group-morphism-to-an-abelian-group-are-normal)
Comment: Look at Theorem 5.11 on page 45 of Hungerford.
Answer: That entire solution is wrong, in my opinion. For instance following sentence in the proof don't make any sense: Thus for every $g\in G$, $n\in N$, $(gH)nH(g^{-1}H)=(gH)(g^{-1}H)nH=nH$. Product between elements of $G$ and $H$ are not defined. There are two approaches to solve this exercise. One of the solution is bit harder relative to another. First (easy) approach and second approach.


Access to $content['links'] from page.tpl.php in D7

Question: I understand how to print node fields and custom fields in the page.tpl.php files but how would I go about adding the $content['links'], (or I suppose $content['comments'], but I am really just looking for the links) like it is in the node.tpl.php?
I took a look at the node object and I don't see it in there. I would like to ultimately have the node links printed in two places, and one of the places is easiest to access from the page.tpl.php.
Answer: Well it looks like it can be pulled off with (in the page.tpl.php files):
<code>$links = node_view($node);
print render($links['links']);
</code>
Anyone know if there is a better approach?
Comment: This has a side-effect that hook_node_view will be called twice for each node visit. So that, it can be that the statistics, logs are not updated correctly.


Replace Pickups on ANY Electric Guitar

Question: I'm new to Electric guitars and I have a simple question:
If I buy ANY electric guitar on Ebay (really ANY), can I buy some new pickups and install them on it without compatibility problems?
In other words, is the system of an electric guitar standardized enough that any pickup will give me a usable signal on any guitar?
Furthermore, what is the broadest range of electrics that might be sitting inside the body between the pickup and the output jack?
Comment: Can you clarify what you mean by 'what is the broadest range of electronics'? You can use a wide variety of pickups, but ultimately it comes down to what fits in your guitar, which will leave you with a LOT of options in most scenarios
Answer: The question may appear simple, the answer's not.
First consideration - physical size of pick-up. Whilst a lot of single-coils may look the same, they may well not be a direct fit into any-old guitar. The same applies to humbuckers, probably more so.Depth needs to be looked at.
Second - the pots, caps and their values may not match replacement pick-ups.
Third - The general wiring in the cavity will be for the original, so replacing say, a two wire pup with a 3 wire is going to cause further problems.
Fourth - If you think by fitting, say a Strat. pup, your guitar will sound exactly like a Strat, prepare for a disappointment.
Fifth - consider passive against active electronics.
Sixth - Really, really good luck ! Yes it can work, but there's far more chance of enough problems that it ends up either going to a guitar tech. or in the skip.
Answer: In principle, yes, you can pop pretty much anything into your guitar, but this may depend on your skills and experience in electronics, woodworking, metalwork etc.
If you are new to this then the first hurdle is the size of the pickups, and how they are wired. It is a fun learning curve though, as except for guitars with complex active circuitry, they are quick and easy to replace. An experienced tech can replace the full set of electrics in ten or fifteen minutes.
I would suggest asking the seller what the electrics are, or even get some photos sent through.
Answer: The easiest and most foolproof way to check for 'Compatibility', is to measure the hole under the pickup's edge guard and compare that with the dimensions the supplier provides for the ones you want. There will be a guard that comes with your electronics that hides that hole.
If you're on ebay, send the seller a message and inquire about the dimensions, chances are they'll have no problem taking a minute to measure it for you.
They aren't really standardized from what I've seen. Some are larger than others and some are smaller. The hole that gets routed into your guitar when it is built is made with generic pickups in mind, or generic style of pickup.

Replace Pickups on ANY Electric Guitar


How to pass variables from .gitlab.ci.yml to Dockerfile

Question: How can I pass one variables value from .gitlab-ci.yml to Dockerfile?
e.g.
The .gitlab-ci.yml contains:
variables:
  var1: ex_variable_1
  var2: ex_variable_1

stages:
  - build

build:
  stage: build
  script:
    - sudo docker build . -t ${CI_PROJECT_PATH_SLUG}
                          --build-arg var1
                          --build-arg var2
    - sudo docker run -dit --name ${CI_PROJECT_PATH_SLUG} --cap-add=NET_ADMIN ${CI_PROJECT_PATH_SLUG}:latest

The Dockefile contains:
FROM centos:6.9

ENV var1 ${var1}
ENV var2 ${var2}

RUN echo "Print var1 $var1"
RUN echo "Print var2 $var2

So what I want is to pass var1 and var2 from .gitlab-ci.yml to Dockerfile.
Comment: OK, I do several additional tests and it seems **because of sudo** (which does not export the environment "as is" across the privilege elevation), `--build-arg var1` won't work, but `--build-arg var1="$var1"` should (unless you just remove `sudo`, because in a GitLab CI context, **you are already root**). I will update my answer accordingly
Comment: OK great! but my answer should already be up-to-date… by the way, I added a remark telling that the command `ENV var1 $var1` (or `ENV var1=$var1`, this is the same) is really optional: you don't need this command to be able to use `$var1` within the Dockerfile. You only need it if you reuse the variable at runtime.
Comment: @ErikMD and Rekovni your options aren't working :|
Comment: Can you give more details than just "this doesn't work"? Did you add the `ARG` instruction in your Dockerfile as suggested in [my answer](https://stackoverflow.com/a/64266911/9164010)? what is the observed outcome?
Comment: @ErikMD thanks a lot, man. After I have put `--build-arg var1=$var1` in running docker command and `ARG var1` & `ENV var1 $var1`  in Dockerfile the variable can be accessed in the Docker file and in other files. Please Update the answer and your answer will be a solution for the issue!
Answer: To pass environment variables from .gitlab-ci.yml to an image or container:

at build time (if the variable is used by the Dockerfile):

use the docker build --build-arg option: docker build --build-arg var1="$var1"

and change your Dockerfile like this:
  FROM centos:6.9
  ARG var1
  ARG var2

  RUN echo "Print var1 $var1"
  RUN echo "Print var2 $var2

  # The following is optional − only useful if you want to
  # keep the environment variables at runtime (docker run)
  ENV var1=${var1}
  ENV var2=${var2}

Note: the ARG instruction can also take a default value:
  ARG var1="default value if var1 was not passed using --build-arg"

at runtime (if the variable is used by the container, i.e., by the ENTRYPOINT / CMD-specified program):

use the docker run -e CLI option: docker run -e var1="$var1".


$X$ fixed in a linear regression

Question: Let $y=x^t\beta+e$ be a linear regression where $x$ is fixed and $e$~$N(0,I\sigma^2)$. What are the consequences of having fixed regressors instead of stochastic regressors? How does the estimation or inference of the regression change?
Answer: The first difference is conceptual. The idea of fixed regressors is usually traced back to developments in statistics for experiments. In a highly controlled trial, regressors can sometimes be fixed, chosen, or controlled by the experimenter and are thus not stochastic. In domains such as social sciences, or really most observational sources of data, it is often not realistic to think of regressors as being fixed quantities, they are typically realizations from probabalistic processes and just as random as the outcome variables.
Now when does this matter, do you need to treat your estimation different in one case or the other?
There are two perspectives that I think can be useful to bear on this question.

Conditioning on stochastic regressors.

You may be familiar with standard results from OLS, such as conditions for unbiasedness, consistency, and BLUE (Gauss-Markov theorem). Some introductory texts show these results under the assumption that the regressors are fixed.
Take unbiasedness as an example
Treating $X$ as fixed, we can prove that $\hat{\beta} = (X^TX)^{-1}X^TY$ is unbiased as long as $E[e] = 0$.
\begin{align}
E[\hat{\beta}] &= E[(X^TX)^{-1}X^TY]\\
&= E[(X^TX)^{-1}X^T(X\beta + e)]\\
&= \beta + E[(X^TX)^{-1}X^Te]\\
&= \beta + (X^TX)^{-1}X^TE[e]
\end{align}
When the regressors are fixed, they can be taken outside of the expectation. However, we could prove unbiaseness in the stochastic case with the assumption that $E[e|X] = 0$. This says given the information in the random variable $X$, the error is mean 0. See
$E(e|X)=0$ assumption implies that the linear regression model is correctly specified?.
We can similarly show consistency using some conditioning arguments and there is a version of the Gauss-Markov theorem, sometimes called the conditional gauss-markov theorem, that states if $E[e|X]$ and $E[ee^T|X] = \sigma^2I$ that OLS is more efficient than any other linear unbiased estimator for $\beta$.
It turns out that with linear regression, many of the properties that we want are preserved when the regressors are stochastic by making assumptions that are conditional or by translating the results to conditional forms (See Davidson and Mackinnon for example, but many books derive all of their results this way). The conditioning can roughly be thought of as taking the information in $X$ as given and loosely once we condition on this information we are back conceptually closer to the experimental case where things are fixed.

Nuisance parameter

This useful perspective comes from the semi-parametric literature. The idea is that sometimes we can partition all of the parameters which generated our data into two parts, the first part is the part we care about making inferences about. In linear regression, this is $\beta$. The second part we don't care about in itself, but we will have to account for in some way to correctly make inferences about $\beta$ called the nuissance parameter, denoted $\eta$. (See Tsiatis (2006) on Restricted Moment Estimators for a deeper look at this)
The observed data that we get in the linear regression example are the vectors $(Y,X)$. And we want to infer something about $\beta$.
We can break the joint density of these observations, $p_{Y,X}$ into the following:
\begin{align}
P_{Y,X}(y,x,|\beta,\eta) = P_{Y|X}(y|x,\beta, \eta_1)P_X(x|\eta_2)
\end{align}
Where we break the nuissance parameter into two parts $(\eta = (\eta_1, \eta_2))$, one that is indexes the conditional distribution of $Y|X$ ($\eta_1$) and the other which indexes the distribution of $X$ ($\eta_2$).
Notice that if we were to find the maximum likelihood solution for $\beta$ of this joint density, that it would have nothing to do with $P_X(x|\eta_2)$, since this part is not a function of $\beta$. In other words, it wouldn't matter what the distribution of $X$ is, it could be completely arbitrary but we could still make inference about $\beta$.
In this particular case, we do have to place restrictions on $\eta_1$ or the distribution of $P_{Y|X}$. In Tsiatis (2006), it is shown that for a broader class of models which encompasses linear regression that the necessary restrictions are that error distribution given X satisfies $E[e|X] = 0$, just like above. Thus we could estimate the thing we care about $\beta$ treating the regressors as random quantities with distributions and in the is case we wouldn't even have to make any assumptions about what that distribution looks like.
Your question was about linear regression and to understand stochastic regressors in this context, the first point about conditioning is more or less sufficient. However, if you want to go deeper into the question of when or how does the regressors being stochastic change our approach to estimation and inference in a broader class of models, then nuissance parameters is the way forward.
Answer: I guess this would be equivalent to $y=\mu+e$, where $\mu$ is the sample mean.

$X$ fixed in a linear regression


change variable with void method java

Question: boa queridos, estou precisando sua ajuda...
estou fazendo um curso, e um dos exercicios consiste em criar uma classe  com um metodo void(inicialmente)  que avance uma posicao na fila para un array, exemplo:
{1,2,3,4}-> after Cycle.swap({1,2,3,4})-> {4,1,2,3}
class CycleSwap {
static void cycleSwap(int[] array) {
    int[] replace= new int[array.length];
    for (int i=0;i<array.length;i++){
        if(i==0){
            replace[i]=array[array.length-1];
        }else{
            replace[i]=array[i-1];
        }
    }
}

e o metodo que testa e o seguinte(teste q nao pode ser alterado e que nao esta pasando)
@Test
public void testCycleSwapSimpleCase() {
    int[] array = new int[]{1, 3, 2, 7, 4};
    CycleSwap.cycleSwap(array);
    assertArrayEquals(new int[]{4, 1, 3, 2, 7}, array);
    CycleSwap.cycleSwap(array);
    assertArrayEquals(new int[]{7, 4, 1, 3, 2}, array);
    CycleSwap.cycleSwap(array);
    assertArrayEquals(new int[]{2, 7, 4, 1, 3}, array);
}

o erro q retorna e o seguinte:
org.opentest4j.AssertionFailedError: array contents differ at index [0], expected: <7> but was: <1>
desde ja agradeço cualquer ajuda :)
Answer: O valor de array nunca é modificado, você está salvando os valores novos dentro de replace, então array nunca muda no seu teste.
Uma possível solução seria atribuir o valor de replace a array no final do cycleSwap.

change variable with void method java


JavaFX - using setRowFactory to highlight new rows

Question: I am writing a JavaFX app where a series of messages appear in a TableView.  When a new message appears, its row in the table should be highlighted, meaning its background color should be orange or something.  Once the user clicks it, the background color should clear, acknowledging the message was read.  Should be simple.
I've done enough research to realize that I need to use a rowFactory to set or clear a row's background.  But I'm struggling with the mechanics of setRowFactory().  The documentation on Oracle is over my head, and every example I pull up online seems radically different than the last one.
Here's what I have:
public class Message {
    private boolean readOnce;
    private int date;
    private String msg;

    public Message(int date, String msg, String msg2){
        this.readOnce = false;
        this.date = date;
        this.msg = msg;
    }

    public boolean isReadOnce() {
        return readOnce;
    }
    public void setReadOnce(){
        readOnce = true;
    }
    // ...and more standard getters & setters here...
 }

The TableView is set up in the main controller:
    @FXML   TableView<Message> messageTable;
    @FXML   TableColumn<Message, Integer>   Col1;
    @FXML   TableColumn<Message, String>    Col2;
    ObservableList<Message> tableItems;

// ...

    // Setting up the Table:
    PropertyValueFactory<Message, Integer> dateProperty = new PropertyValueFactory<Message, Integer>("date");
    PropertyValueFactory<Message, String>  msgProperty  = new PropertyValueFactory<Message, String>("msg");
    Col1.setCellValueFactory( dateProperty );
    Col2.setCellValueFactory( msgProperty );
    messageTable.setItems( tableItems );

    // If we click an item in the table:        messageTable.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> {
        if (newSelection != null) {
            System.out.println("Troubleshoot:  You clicked: "+newSelection.getMsg());
            newSelection.setReadOnce(true);
        }
    });

And if I want to add a new message to the table, I just add it into the observable list:
public void addMsg(int num, String msg){
    tableItems.add(new Message(num, msg));
}

So far, pretty easy.  But I'm all thumbs when it comes to the rowFactory:
    messageTable.setRowFactory(messageTable -> {
        TableRow<Message> row = new TableRow<>();
        ObjectProperty<Message> opMsg = row.itemProperty();
        Message tmpMsg = opMsg.get();
        if(!tmpMsg.isReadOnce()){
            row.getStyleClass().add("highlight-message");     // defined in CSS
        } else {
            row.getStyleClass().add("clear-message");         // defined in CSS
        }
        return row;
    });

To be very honest, I have no idea what I'm doing here.  I understand that the rowFactory takes in the entire table and regenerates each row one-by-one.  What I don't understand is how does the RowFactory code examine each Message in the table and how can I access them?  Originally I thought these line might allow me to see the Message within the row:
        TableRow<Message> row = new TableRow<>();
        ObjectProperty<Message> opMsg = row.itemProperty();
        Message tmpMsg = opMsg.get();

But when I debug the code, tmpMsg == NULL.  So that's a big fat dead end.
Anyone see what I'm doing wrong?  I've been researching this for about a week, getting absolutely no-where.  Any help anyone can offer is wildly appreciated.
Many thanks,
-RAO
Comment: Can you use JavaFX properties in your `Message` class?
Comment: @James_D Sure, I don't see why not.  In fact, is that helps me, I'm all for it...!
Comment: Actually - Fabian's answer is a simpler approach than the one I had in mind, and makes that redundant
Answer: TableRows are created by TableView to fill it's viewport and contain TableCells. At the time they are created the item property still contains the default value null. You could register a listener to that property but usually I prefer overriding the updateItem method of a cell.
Also using PseudoClass is simpler than using style classes. New items can be assigned to a row; this could result in the same style class being added multiple times and even both style classes could be added to the same cell. PseudoClasses however can be switched on/of without the need to take care of removing other classes.
final PseudoClass highlightMessage = PseudoClass.getPseudoClass("highlight-message");

messageTable.setRowFactory(messageTable -> new TableRow<Message>() {

    {
        selectedProperty().addListener((o, oldVal, newVal) -> {
            if (newVal) {
                Message item = getItem();
                if (item != null) {
                    item.setReadOnce();
                    pseudoClassStateChanged(highlightMessage, false);
                }
            }
        });
    }

    @Override
    protected void updateItem(Message item, boolean empty) {
        super.updateItem(item, empty);

        pseudoClassStateChanged(highlightMessage, item != null && !item.isReadOnce());
    }

});

In a CSS stylesheet you could use rules like this:
.table-row-cell:filled {
    /* style for non-highlighted rows */
}

.table-row-cell:filled:highlight-message {
    /* style for highlighted rows */
}

Note that this does not allow you to programmatically alter the read state. It updates the state on selecting a cell. You could add a BooleanProperty to Message or use a ObservableSet to store the highlighted messages and update the state of cells from a listener if you need to programmatically update the readOnce property. In the latter case you do not need to store a readOnce property in the Message itself...
Comment: --  EXCELLENT!!!  Wow, that did the trick.  I have a follow-up question, if you don't mind...  I've noticed all the online examples do an Override of updateItem() and then immediately do an "super.updateItem(...) ;"  I assume this means "do updateItem() and then do this extra stuff."  But why is this call necessary?  Many, many thanks  :)
Comment: that previous praise & comment was meant for fabian... not sure why the system scrubbed their name.  Again, many, many thanks  :)
Comment: `TableRow.updateItem` handles updating the `empty` and `item` properties and set the `filled` or `empty` pseudoclasses so you unless you want to do all that yourself you need to do eveything `TableRow.updateItem` would have done plus you custom code...


Find the limit of $n \ln(\frac{\ln(n+1)}{\ln n})$ as $n$ tends to infinity.

Question: Find the limit of
$\displaystyle\ n \ln\left(\ln\left(n + 1\right) \over \ln\left(n\right)\right)\ $ as $n$ tends to infinity.
I used L hospital's rule to find the limit, but it made the calculations complicated.
How to find this limit ?.
Any hint would be helpful.
Answer: $\log(1+1/n) < 1/n$ implies that $\log(n+1)< \log n +1/n.$ Hence, $$\log\log (n+1) < \log (\log n + 1/n) $$
$$= \log \log n + \log \Big(1+\frac{1}{n\log n}\Big)$$
$$<\log \log n + \frac{1}{n \log n}$$
Therefore,
$$ 0<n \Big(\log \log (n+1) - \log \log n\Big) <\frac{1}{\log n}.$$
Answer: Instead of using L'Hospital's rule, it is often more convenient to expand such composed functions via Taylor series or similar asymptic expressions.
Here,
$$ \lim_{n\rightarrow \infty} n\ln(\frac{\ln(n+1)}{\ln(n)}) =
\lim_{n\rightarrow \infty} n\ln(\frac{\ln(n)+\frac{1}{n}+\mathcal{O}(\frac{1}{n^2})}{\ln(n)}) = \\ \lim_{n\rightarrow \infty} n\ln (1 + \frac{1}{n\ln(n)} + \mathcal{O}(\frac{1}{n^2})) = \lim_{n\rightarrow \infty} n\ln (1 + \frac{1}{n\ln(n)} + \mathcal{O}(\frac{1}{n^2})) = \\ \lim_{n\rightarrow \infty} n\left( \frac{1}{n\ln(n)} + \mathcal{O}(\frac{1}{n^2})\right) = \lim_{n\rightarrow \infty} \left( \frac{1}{\ln(n)} + \mathcal{O}(\frac{1}{n})\right) = 0.$$
This basically always works, if your limit exists and your functions are well-behaved throughout. It gives you nice extra information, like speed of convergence. L'Hospital's rule has the theoretical upper hand, since the functions involved don't even have to be differentiable at zero, but it's messy and doesn't yield extra information.
Answer: Hint: $\lim\dfrac {\ln(n+1)}{\ln n}=1$, because $\lim\ln n=\lim\ln (n+1)$.  Then use that $x^n$ and $\ln x$ are continuous.
The limit is $0$.
Answer: You can have a bit more than the limit itself, using, as in other answers and comments, you compose Taylor series
$$y=\frac{\log (n+1)}{\log (n)}=\frac{\log (n)+\log \left(1+\frac{1}{n}\right)}{\log (n)}=\frac{\log (n)+\frac{1}{n}-\frac{1}{2 n^2}+O\left(\frac{1}{n^3}\right) }{\log (n)}$$ that is to say
$$y\sim 1+\frac1{n\log (n)}-\frac1{2n^2\log (n)}+\cdots$$ Continuing with Taylor
$$\log\left(\frac{\log(n+1)}{\log( n)}\right)=\log(y)=\frac{1}{n \log \left({n}\right)}-\frac{\log \left({n}\right)+1}{2
   n^2 \log ^2\left({n}\right)}+\cdots$$
$$n \log\left(\frac{\log(n+1)}{\log( n)}\right)=\frac{1}{ \log \left({n}\right)}-\frac{\log \left({n}\right)+1}{2
   n \log ^2\left({n}\right)}+\cdots$$ Try it with your pocket calculator for $n=10$ (which is a bit far away from $\infty$). You should get $0.4056$ while the above truncated series would give $0.4031$.
Answer: By Lagrange's theorem, since $\frac{d}{dx}\log\log(x)=\frac{1}{x\log x}$,
$$ \log\log(n+1)-\log\log(n) = \frac{1}{(n+\xi)\log(n+\xi)},\qquad \xi\in(0,1) $$
hence
$$ \lim_{n\to +\infty} n\left(\log\log(n+1)-\log\log(n)\right) = 0.$$


Is the condition on the roots of $\phi(x)$ for stationarity the same for AR(p) and ARMA(p,q) processes?

Question: I've become a bit confused by texts and answers that seem to contradict each other but I think I am just not understanding it quite right.
For an ARMA(p,q) process
$$
 X_{t} = Z_{t} + \phi(1)X_{t-1} + \dots \phi(p) X_{t-p} + \theta(1)Z_{t-1} + \dots \theta(q)Z_{t-q}
$$
I have seen the condition for stationarity being that the roots of $\phi(x)$ are not on the unit circle.
And for $AR(p)$ processes
$$
 X_{t} = Z_{t} + \phi(1)X_{t-1} + \dots \phi(p) X_{t-p}
$$
that they are outside of the unit circle.
A comment in this accepted answer mentions that its stationary but not invertible and it has some upvotes.
Yet in my homework problems we have a few that are inside the unit circle and they are not stationary. I also checked them visually and they dont' seem to be.
Yet, an AR(p) process is just an ARMA(p, 0) process, so I don't understand how the conditions could differ?
Any insights are appreciated, I've been reading a lot of different sources trying to understand this and I'm still confused after a few weeks.
Answer: This is the basic fact that stationarity of an $\sf ARMA$ process depends solely on the autoregressive parameters.
Notice for $\sf ARMA(p, q), $
$$\left(1-\phi_1L-\phi_2L^2-\cdots-\phi_pL^p\right)X_t=\left(1+\theta_1L+\theta_2L^2+\cdots+\theta_qL^q\right)Z_t,$$ the roots of $1-\phi_1 x-\phi_2x^2-\cdots-\phi_px^p=0\tag 1\label 1$ must lie outside the unit circle for both sides of $\eqref 1$ to be divided by the compound lag operator $\phi(L)$ to reach $$ X_t =\psi(L)Z_t$$ where $\sum_{i=0}^\infty |\psi_i|<\infty.$

Reference:
$[\rm I] $ Time Series Analysis, James Douglas Hamilton, Princeton University Press, $1994, $ sec. $3.5, $ pp. $59-60.$
Comment: (+1), especially for the nice reference, I love that book! @Oliver, it seems to me that this answers your query, and if so, please consider upvoting & accepting it.
Comment: See, Oliver you are near and yet far. Yes, if you ask what should be the condition for stationarity? The answer is straight forward: not on the unit circle. But then if you want real practical stationarity ie. along with causality, then the roots must lie outside the unit circle. Hamilton and others didn't mention explicitly causality but for all practical purpose, we would entertain the causal stationarity.
Comment: Technically, BD is talking about causality. So, yes, if the roots of $\phi(L) $ don't lie on the unit circle, they are stationary but only when they lie outside the unit circle, they are stationary and causal. But to answer your title question, it still depends on the $\sf AR$ part.
Comment: That's what I happened to come across while googling casually - check this [note](https://ealdrich.github.io/Teaching/Econ211C/LectureNotes/Unit1-ARMA/causality.html).
Comment: thank you for your patience. I am still confused. This is precisely my question. If not being on the unit circle is enough, then being inside it is ok, and from what I am reading, the comment, BD and the note you linked as well as your comment above say that if the $\phi(L)$ are not on the unit circle an $ARMA(p,q)$ process is stationary, this only relies don't he $AR$ part, but to me it contradicts that for $AR$ the $\phi(L)$ have to lie outside the unit circle. This is my whole confusion, they seem to be different conditions when they shouldn't be.
Comment: Thanks again for being so patient with me.
I will have to ponder more on what you mean. Though for many simpler examples, where the roots are inside the unit circle we get explosive behaviour with trend.
And this clearly violates the constant mean condition of stationarity, I am probably missing something here.
Comment: @utobi I upvoted it (and all the comments, as I am grateful for the attempt) but it didn't answer my query. From the discussion, the answerer provides the same contradiction that led me to this question. Seemingly different conditions for $AR$ and $ARMA$ processes, but also the same. Above the answerer says not on the unit circle => stationary. Just not practical. But I have countless examples that aren't stationary and are inside the unit circle.
Comment: @utobi if you or anyone else agrees that I am just not getting it and it answers it, I guess then I'll accept, to not keep this questions lingering around. Also mentioning that the reference given, is one of the texts I mention in my question that contradicts other texts leading to my confusion
Comment: Thanks a lot, so that top comment in the other answer is wrong right?
I've also seen this in endless lecture texts (upenn and UCLA), and I was utterly confused. Brockwell Davis p. 49 also notes that it is stationary if not on the unit circle. I would say I have found a 60/40 split in references. Though interestingly the references that provide AR stationary conditions often don't provide it for ARMA, which led me to this question.


How does a pdf of the difference of two random variables relate to the pdf of each random variable

Question: Let $T_1$ and $T_2$ be non-negative continuous random variables (rv) denoted in the form $T_i = \mu_i + \sigma_i X_i$ for $i=1,2$ where
\begin{eqnarray*}
T_{1} &=&\mu _{1}+\sigma _{1}X_{1} \\
T_{2} &=&\mu _{2}+\sigma _{2}X_{2}
\end{eqnarray*}
Suppose that $X_1$ and $X_2$ are iid with $f_{X_i} (x)=\lambda e^{-\lambda x}$ for $x\geq 0$ or zero otherwise.
Now define $Z=T_2 - T_1$ such that $Z=\mu_z + \sigma_z Y$; where $Y$ is a standardized rv with pdf $f_{Z}(z)$.
Question:
Express $f_Y(y)$ in terms of $f_{X_1}(x) \text{ and/or } f_{X_2}(x)$.
Trial
Following steps suggested by sds; I arrived at the following.
I expressed the pdf of $T_{i}$ in terms of the pdf of $X_i$ starting from the CDF of these variables as follows.
\begin{equation*}
F_{T_{i}}\left( x\right) =F_{X_{i}}\left( \frac{x-\mu _{i}}{\sigma _{i}}
\right)  \mbox{ and }
F_{-T_{i}}\left( x\right) = 1-F_{X_{i}}\left( \frac{-x-\mu _{i}}{\sigma
_{i}}\right)
\end{equation*}
hence
\begin{equation*}
f_{T_{i}}\left( x\right) =\frac{1}{\sigma _{i}}f_{X_{i}}\left( \frac{x-\mu
_{i}}{\sigma _{i}}\right) \text{ and }f_{-T_{i}}\left( x\right) =\frac{1}{%
\sigma _{i}}f_{X_{i}}\left( \frac{-x-\mu _{i}}{\sigma _{i}}\right)
\end{equation*}
Defining $-T_1 = Z-T_2 $ and using the convolution of pdfs, we have:
\begin{align*}
f_{Z}\left( z\right)  &=\int_{-\infty }^{\infty }f_{T_{2}}\left( x\right)
f_{-T_{1}}\left( z-x\right) dx \\
&=\int_{-\infty }^{\infty }\frac{1}{\sigma _{2}}f_{X_{2}}\left( \frac{x-\mu
_{2}}{\sigma _{2}}\right) \frac{1}{\sigma _{1}}f_{X_{1}}\left( z-\left(
\frac{-x-\mu _{2}}{\sigma _{2}}\right) \right) dx \\
&=\left( \sigma _{1}\sigma _{2}\right) ^{-1}\int_{-\infty }^{\infty
}f_{X_{2}}\left( \frac{x-\mu _{2}}{\sigma _{2}}\right) f_{X_{1}}\left( z+%
\frac{x+\mu _{2}}{\sigma _{2}}\right) dx
\end{align*}
The integral is nonzero for $ \left( x>-\sigma _{2} z-\mu _{2}\right) \text{ and }\left( x>\mu _{2} \right) $ which is:
\begin{equation*}
\max \left( -\sigma _{2}z-\mu _{2},\mu _{2}\right) =\left\{
\begin{array}{l}
-\sigma _{2}z-\mu _{2}\text{ if }z\leq \frac{-2\mu _{2}}{\sigma _{2}} \\
\mu _{2}\text{ otherwise}%
\end{array}%
\right.
\end{equation*}
First, I attempted deriving $f_{Z}\left( x\right) $ for $z\leq \frac{-2\mu _{2}%
}{\sigma _{2}}$ as:
\begin{equation*}
f_{Z}\left( z\right) =\left( \sigma _{1}\sigma _{2}\right)
^{-1}\int_{-\sigma _{2}z-\mu _{2}}^{\infty }f_{X_{2}}\left( \frac{x-\mu _{2}%
}{\sigma _{2}}\right) f_{X_{1}}\left( z+\frac{x+\mu _{2}}{\sigma _{2}}%
\right) dx
\end{equation*}
However, I am not sure about the limits of integration and if everything is correct, after all. I will appreciate any help on this!
Comment: @Henry I have now edited the sentence
Answer: You need to take 3 steps:

Express the pdf of $T_1=\mu_1+\sigma_1 X_1$ in terms of $f_{X_1}$.
Express the pdf of $-T_2=-\mu_2-\sigma_2 X_2$ in terms of $f_{X_2}$.
Use the fact that the pdf of a sum of independent RVs is the convolution of the pdfs of the summands.


Samba default permissions not respected

Question: I'm almost ready to tear my hair off (At least i have a decent amount of it :P)
I built a Ubuntu 11.04 box at work for all the development team to work on it. Everything working fine so far but there is a small problem about default file permissions.
I've been searching for over 2h how to set the default permissions for files and folders when someone create something on the samba share.
So far, from my linux machine to the linux server through SMBFS, it works fine for directories and they are tabbed DRWXRWX--- which is what i want.
The files tho are not set to -RW-RW---- like i want. The darn group write never wants to light up.
I've tried a combination of all the possible configuration flags for create mode, create mask, force create mode force security mode, nothing works. So i finish by asking here.
Relevant config file section:
[homes]
comment = Home Directories
browseable = yes

# By default, the home directories are exported read-only. Change the
# next parameter to 'no' if you want to be able to write to them.
read only = no

# File creation mask is set to 0700 for security reasons. If you want to
# create files with group=rw permissions, set next parameter to 0775.
#   create mask = 0660
   create mode = 0660
#   force security mode = 0660
#   force create mode = 0660

# Directory creation mask is set to 0700 for security reasons. If you want to
# create dirs. with group=rw permissions, set next parameter to 0775.
#   directory mask = 0777
#   force directory security mode = 0770
#   force directory mode = 0770
   directory mode = 0770

valid users = %S

Comment: An all too common problem. Used to know how to fix that too.
Comment: Update, still not working, tried also to set inherit permissions and it still fails, i think i'll just drop the idea and force my developpers to chmod 777 the directories they want writable...
Answer: It sounds like you may have already tried this combination but my samba shares are set up like this, and new files and directories are created with the correct permissions if that's any help:
[public]
comment = samba share
path = /path/to/my/share
browseable = yes
force group = smbuser
create mask = 0660
directory mask = 0660

Comment: Nope, tried it at least, but was pretty sure it wouldnt work. Thanks anyway...
Answer: Use force create mode. All the bits set in force create mode will be forced on in every file created. This only affects file create -- if you want to prevent someone from turning any permission flags off after a file is created, use force security mode as well.
Comment: Well then I'm *quite* baffled. Have you ruled out demonic possession?
Comment: Tried it already, still doesn't work, but i've been reading something about Windows clients not sending the right permissions by default. For example, there seems to be something about the fact that windows sends group write permissions as readonly, so by default it will not map it on the linux server.

But then i tried the force create mode and it still doesn't set the bits. Still trying this morning...
Comment: To confirm, you set a bit in both `force create mode` and `force security mode`, and Samba created a file without that bit set?
Comment: Exactly, i tried setting everything to 777 in create mode, create mask, force create mode and force security mode and it still created the file as -RWXR-XR-X, can you believe that?
Comment: No sorry mistake, retested it, it gives -RWXR-XRWX... what the hell is that. it gives write to world and not to group?
Comment: I'm assuming that's a typo and you meant `0777`. If you really entered `777` by mistake, that's your problem, since 777 = 01411
Comment: It is a typo :) i indeed put 0777 just as shown in the above config file... OCTAL baby!
Comment: @Mathieu: You sure, you set both `force create mode` and `force security mode`, with 0 at the beginning and *restarted*, not reloaded samba? Best to `stop`, make sure no `smbd` and `nmbd` runs and only then `start` it.
Comment: Current configuration:
create mask = 0777
create mode = 0777
force create mode = 0777
force group = www-data
directory mask = 0777directory mode = 0777
Comment: Used service smd stop/start instead of restart and same for nmbd which i was not aware existed and still the same problem: -rwxr-xrwx  1 mdumoulin www-data          0 2011-09-29 09:42 hello.txt
Comment: @MathieuDumoulin: Then I'm with David -- try to rule out demonic possession ;). The samba dev list would be a good place to ask next, as this *is* baffling.
Comment: @MathieuDumoulin: `force create mode` and `force security mode` are two different things, so you have to set them *both* to `0777`. You can also use `testparm -v` to list values of both set parameters and defaults of other parameters.

Samba default permissions not respected


Galera or master/slave MariaDB

Question: What would be the recommended choice for database replication with failover? I know this is a broad question but I'm curious what the general experiences are when it comes to real life setups.
As far as I understood galera is not a failover setup since it refuses to handle queries as soon as the cluster becomes too small when servers start failing.
Is going with a master / slave better?
The goal is: database always available on at least one server. It's a relative small setup data-wise (max 2 gig of data, low-traffic)
Answer: I think you are a bit confused as to what Galera is and what it isn't.
Galera is a multi-master replication system that allows 2 (preferably 3) or more nodes to replicate data amongst themselves and provide some level of high availability or load balancing. You should not use it with less than 3 nodes because of split brain cases.
Galera can operate with one node left standing and does not start failing due to number of nodes - however if all nodes go down, you need to bootstrap the entire cluster manually as it does not have an automated way of doing this (apart from Percona but that's a different thing altogether).
I think you should be asking yourself the question; how will I implement the failover system? You need to either have your application / service maintain a list of healthy servers using a proxy server (for example HaProxy can do this) or have your application / service internally do this by seeing which servers reply and hop to the next MySQL/MariaDB node.
All in all, your question is a very broad one and it's quite hard to give an exact answer as it all depends on what type of service and infrastructure you have at your disposal.

Galera or master/slave MariaDB


HashMap null value issue

Question: What is the difference between both of result.

When I've null value with key
When key itself is not exist

In above both condition result is null. So how can i identify my key value
Map map = new HashMap();
map.put(1,null);
System.out.println(map.get(1));
System.out.println(map.get(2));

Answer:
null

null

Comment: possible duplicate of [Key existence check in HashMap](http://stackoverflow.com/questions/3626752/key-existence-check-in-hashmap)
Answer: While get returns the same result for null value and non-existing key, containsKey doesn't:
map.containsKey(1) would return true.
map.containsKey(2) would return false.
In addition, if you iterate over the keys of the Map (using keySet()), 1 will be there and 2 won't.
Answer: Hashmap returns null if no Value is mapped to the key. So this can be solved by your code also:
if( map.get(1) != null ){
     //
}

Reference Here
Comment: This suggestion doesn't help the OP.
Answer: Make a check for if the value is null to avoid the null prints.
pseudo code:
//For inputting
if(object != null){
   map.put(1, object);
}
//For getting the value
if(value != null){
     map.get(value)
  }

HashMap null value issue


nginx - rewrite to HTTP or HTTPS in nginx.conf file

Question: In nginx.conf file, is it possible to rewrite to HTTP or HTTPS based on whether the current connection is secured or not?
Some pseudocode of what I want to do.
location ^~ /test_api {
    if (secured connection)
        rewrite "/test_api"   https://www.somedomain.com/test_api     break;
    else
        rewrite "/test_api"   http://www.somedomain.com/test_api      break;
}

Thanks.
Answer: You're looking for $scheme.
rewrite /test_api $scheme://www.example.com/test_api break;


SyntaxError invalid syntax (views.py, line 52)

Question: Do you know why does it say invalid syntax in the return line? Everything seems to be ok I checked. I have replaced tabs with spaces if indentation is a problem.
def detail(request, sl):
    try:
        post = Post.objects.filter(slug=sl)[0]
        try:
            previous_post = post.get_previous_by_published()
        except:
            previous_post = ""
        try:
            next_post = post.get.next_by_published()
        except:
            next_post = ""
    return render_to_response('blog/detail.html',{'post':post,
                                                  'next_post':next_post,
                                                  'previous_post':previous_post,
                                                 },)

Thanks in advance.
Comment: for invalid syntax, try removing the ',' (comma) in the end of the return statement
Answer: Erm, you're opening three trys and only have two excepts... you need to catch that first try before the return
Comment: If you're not currently using a linter of some kind (a plugin which checks syntax for you) then you may find it very useful for tracking down bugs like this. Indeed, I highly recommend SublimeText (http://www.sublimetext.com/) and the Sublime Linter plugin (https://github.com/SublimeLinter/SublimeLinter), which will auto-lint as you code.
Comment: No, I am not using. Thanks, I will check them out!
Answer: list index seems to be on the line
post = Post.objects.filter(slug=sl)[0]

If you know that your query would return a single result then don't use FILTER, replace it with GET and along with it use try except.
try:
    post = Post.objects.get(slug = sl)
except:
    pass #something

else you could simple do
try:
    post = Post.objects.filter(slug = sl)[0]
except IndexError, e:
    pass #something

Comment: the question has been CHANGED after I uploaded the answer :|
Comment: Hey I say your answer after I edited the question. It was ok, this here was the solution http://stackoverflow.com/questions/3257414/django-in-debug-py-list-index-out-of-range but I still get the invalid syntax at the render line error though.
Comment: Sorry I was browsing at the same time and that showed up, thought it would be a good idea to change it not to confuse people and lead a discussion in a different way.
Answer: Add a RequestContext in your return statement
from django.template.context import RequestContext

return render_to_response('blog/detail.html',{'post':post,
                                              'next_post':next_post,
                                              'previous_post':previous_post,
                                             },
                          context_instance=RequestContext(request))

Comment: The problem is still there! I really don't understand, all my other view functions are written in the same way and yet just this is not working.
Comment: I don't have any logger implemented in this site (I am a beginner to django)


Getting null value to a variable after async method flutter

Question: I'm getting null value in flutter build method for this code.
  String userEmail;
  var data;
  String userName;
  @override
  void initState(){
      setState(() {
        getUserName();
        print(userName);
      });
    super.initState();
  }

  void getUserName() async {
    MyFirebaseAuth myFirebaseAuth = MyFirebaseAuth();
    userEmail =await myFirebaseAuth.getUser();
    if (userEmail == null){
      print("no user");
    }
    else{
      data =await fb.firestore().collection('users').doc(userEmail).get().then((onValue){
        return onValue.data();
      });
      print(data);
      print(data['name']);
      userName = data['name'];
      print("Username is $userName");
    }
  }

output is
Performing hot restart...
Restarted application in 759ms.
null
{entries: 3, name: xmr}
vraj
Username is xmr

Comment: can you please show us `MyFirebaseAuth` ? and try to remove setState from the initstate
Answer: The getUserName is future so the method should be
Future<void>getUserName() async {
MyFirebaseAuth myFirebaseAuth = MyFirebaseAuth();
userEmail =await myFirebaseAuth.getUser();
if (userEmail == null){
  print("no user");
}
else{
  data =await fb.firestore().collection('users').doc(userEmail).get().then((onValue){
    return onValue.data();
  });
  print(data);
  print(data['name']);
  userName = data['name'];
  print("Username is $userName");
}
}

And also make sure to use setState inside the getUserName() instead of initState


Grass tennis compared to hard court

Question: What are the differences between playing tennis on grass compared to hard courts?
What adjustments do professional tennis players have to make for grass vs hard court season?
Comment: This older post is to some extent related (although it is not specifically about grass): [How do the different court surfaces at the majors affect the games and mix of players?](https://sports.stackexchange.com/q/4842) And perhaps to some extent also this might be interesting in connection with this question: [How changing tennis balls influence players using serve and volley?](https://sports.stackexchange.com/q/5097)
Answer: The three fundamental differences between grass courts and hard courts are:

Reduced friction between the shoes and the grass.
Reduced friction between the ball and the grass.
Softer impact of the ball on the grass.

Reduced friction between the shoe sole and the surface makes it far harder to change directions quickly.
Reduced friction between the ball and the grass manifests in that the ball "skids", or "slips" along the grass blades upon impact. This makes the surface faster, the bounces lower and less predictable, and also reduces the effect of spin (whose effect increases as friction increases).
Softer impact on the surface also makes the ball bounce lower, since the impact is more elastic.

The main technical adjustments are usually:

Flattening out ground strokes.
Getting used to taking balls early.
Emphasizing slice and flat serve.

The main tactical adjustments are usually:

Incorporating more approaches into the net.
Playing closer to the baseline.

The main physical adjustments are usually:

Reduce upper body strength work (especially compared to clay).
Focus on low center-of-gravity exercises.

Grass tennis compared to hard court


Accessing an array present in a class using pointers

Question: #include <iostream>

using namespace std;

class sort_overload
{
    int a[10];
public:
    void sort(int ,int);
    void display();
    void getdata();
}s;

void sort_overload::sort(int first,int last) //quick sorting
{
    int sort_overload :: *sp = &sort_overload :: a[0]; //pointer to the         base address of a present in class sorted_overload

sort_overload *sp_obj = &s;
int pivot = sp_obj->*(sp+last);
int i=first,j=last;
int temp;

if(i<j)
{

    while((sp_obj->*(sp+i)) < pivot)
        i++;
    while((sp_obj->*(sp+j)) > pivot)
        j--;
    if(i<j)
    {
        temp = (sp_obj->*(sp+i));
        (sp_obj->*(sp+i)) = (sp_obj->*(sp+j));
        sp_obj->*(sp+j) = pivot;
        sp_obj->*(sp+last)=temp;
    }
}

    s.sort(first,j-1);
    s.sort(j+1,last);

}
void sort_overload::display()
{
    int sort_overload :: *sp = &sort_overload :: a;
    sort_overload *sp_obj = &s;
    for(int i=0;i<10;i++)
        cout<<"Sorted array numbers:"<<sp_obj->*(sp+i)<<endl;

}
void sort_overload::getdata()
{
    int sort_overload:: *sp = &sort_overload :: a;
    sort_overload *sp_obj = &s;
    cout<<"Enter numbers";
    for(int i=0;i<10;i++)
        cin>>sp_obj->*(sp+i);
}

int main()
{
    s.getdata();
    s.sort(0,9);
    s.display();
    return 0;
}

This statement gives me an error:
int sort_overload :: *sp = &sort_overload :: a[0];

Could somebody tell me why the error is coming up?
I'm trying to sort 10 integer values, and further overload it to sort double and float values as well, but I am stuck on the sorting part.
Answer: Since
void sort_overload::sort(int first,int last)

is a member function of your class, you can can access your array by replacing
int sort_overload :: *sp = &sort_overload :: a[0];

by
int *sp = this->a;

or better just use this->a instead of sp
You cannot use the syntax :
&sort_overload :: a[0];

because your array is not a static attribute.


Como chamar uma viewcontrolller runtime

Question: Amigos eu só preciso abrir uma ViewController , e eu estou dando bobeira, poderiam ajudar.
Quem pode ajudar .... Obrigado. .
LoginViewController *tela2 =
[self.storyboard instantiateViewControllerWithIdentifier:@"login"];
[self presentViewController:tela2 animated:YES completion:nil];

Comment: Marcio, se você já encontrou a solução por conta propria, basta responder a pergunta, como já o fez, e marcá-la como aceita, clicando no `V` ao lado esquerdo.
Answer: Com o que você enviou parece estar tudo certo, o problema deve estar ocorrendo pelo local onde você está fazendo essa chamada, então.
Se estiver chamando esse método dentro de:
override func viewDidLoad() {
    super.viewDidLoad()

}

Tente executando ele dentro do seguinte método:
override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

}

Answer: resolvido, é so criar um navigation controller.

Como chamar uma viewcontrolller runtime


Join cells from Pandas data frame and safe as one string or .txt file

Question: I am trying to extract data from a data frame in Pandas and merge the results into one string (or .txt file)
Data Frame:

NUM
LETTER

0
4
Z

1
5
U

2
6
A

3
7
P

4
1
B

5
4
P

6
5
L

7
6
T

8
7
V

9
1
E

Script so far:
data = pd.read_csv("TEST.csv")
fdata = data[data["LETTER"].str.contains("A|E|L|P")]
ffdata = fdata.RESULT.to_string()
print(ffdata)

Running the script on TEST.csv gives me this result:

LETTER

2
A

3
P

5
P

6
L

9
E

Next, I want to join the data from the filtered cells and join them into one string:
--> "APPLE", optional with saving them as .txt to use them later.
How do I proceed from here? I was thinking about iterating over the data frame and use join, but I have no idea how to implement this. Any clues?
Comment: `"".join(fdata.LETTER.to_list())`
Answer: Based on @Frodnar's answer, this is the code that works:
data = pd.read_csv("TEST.csv")
fdata = data[data["LETTER"].str.contains("A|E|L|P")]
ffdata = ''.join(fdata.LETTER.to_list())
print(ffdata)

which gives the output 'APPLE'
Thank you for your help!!


Como adicionar um Library no modulo principal [ module-info.java ]?

Question: Eu utilizo o pacote jssc para acessar porta serial.
eu adicionei ele ao modulo principal
module DeskCheck {
  requires java.desktop;
  requires java.logging;
  requires jssc;
}

Mas acredito estar fazendo de forma errada,  pois ocorre erro dizendo que módulo não existe.
Creating jlink image in dist\jimage/.
Executing: C:\Program Files\jdk-12.0.2\bin\jlink.exe --module-path dist\DeskCheck.jar;C:\Program Files\jdk-12.0.2\jmods --add-modules DeskCheck --output dist\jimage --compress=2
Error: Module jssc not found, required by DeskCheck

Answer: Você está sofrendo com os módulos automáticos.
Módulos automáticos são módulos nomeados que são criados automaticamente para um JAR não-modular. Isso acontece quando o JAR é colocado no module-path (como dependência) de uma aplicação modular.
Em outras palavras: Arquivos JAR não modulares se tornam modulares quando usados por uma aplicação modular.

Vamos dizer que temos uma aplicação modular "app" que quer usar um JAR não-modular lib.jar (não tem module-info). Para rodarmos o main do app (com.app.Main.class) usaremos o seguinte comando:
java --module-path appClasses lib --module app/com.app.Main

No comando acima, appClasses é a pasta onde app tem suas classes e lib é a pasta onde temos o JAR lib.jar.
Assim lib.jar (que está na pasta lib) automaticamente se torna modular para app. Esse módulo tem o mesmo nome que o nome do JAR (sem a extensão .jar; hífens ("-") se tiver, são substituídos com pontos ("."); a versão, se tiver, é retirada também). O módulo app ainda tem que requires o módulo do JAR pelo seu nome.

Que pacotes os módulos automáticos exports?
Ele exports todos os pacotes do JAR.
Que módulos ele requires?
Ele requires todos os módulos no module-path.

Exemplo
Esse exemplo irá criar 2 aplicações. A primeira aplicação irá representar uma biblioteca de terceiros, e a segunda vai ser uma aplicação modular que vai estar usando a primeira.
A biblioteca não-modular
// matematica-iz/src/matematica/iz/CalculoBasico.java
package matematica.iz;

public class CalculoBasico {
  public static int soma(int a, int b) {
      return a + b;
  }
}

C:\exemplo-modulo-automatico\matematica-iz> tree /F /A
|
\---src
    \--matematica
        \---iz
                CalculoBasico.java

Compilando a classe:
C:\exemplo-modulo-automatico\matematica-iz> javac -d out src/matematica/iz/CalculoBasico.java

Criando o JAR:
C:\exemplo-modulo-automatico> jar -cf matematica-iz.jar -C matematica-iz/out .

A aplicação modular
// mat.app/src/com/exemplo/Main.java
package com.exemplo;

import matematica.iz.CalculoBasico;

public class Main {
  public static void main(String[] args) {
      int soma = CalculoBasico.soma(4, 7);
      System.out.println("O resultado da soma é: " + soma);
  }
}

// mat.app/src/module-info.java
module mat.app {
 requires matematica.iz;
}

Note que a aplicação acima requires o módulo do JAR (automático) pelo seu nome, que vai se transformar de matematica-iz.jar para matematica.iz
C:\exemplo-modulo-automatico\mat.app> tree /F /A
|
\---src
    |   module-info.java
    |
    \---com
        \---exemplo
                Main.java

Movendo matematica-iz.jar para a aplicação do mat.app:
C:\exemplo-modulo-automatico> mkdir mat.app\lib
C:\exemplo-modulo-automatico> move matematica-iz.jar mat.app\lib\
        1 arquivo(s) movido.

Agora, aqui está a estrutura do nosso diretório
C:\exemplo-modulo-automatico> tree /F /A
|
+---matematica-iz
|   |
|   +---out
|   |   \---matematica
|   |       \---iz
|   |               CalculoBasico.class
|   |
|   \---src
|       \---matematica
|           \---iz
|                   CalculoBasico.java
|
\---mat.app
    |
    +---lib
    |       matematica-iz.jar
    |
    \---src
        |   module-info.java
        |
        \---com
            \---exemplo
                    Main.java

Compilando a aplicação:
C:\exemplo-modulo-automatico\mat.app> javac --module-path lib -d out src/module-info.java src/com/exemplo/Main.java

Executando a aplicação
C:\exemplo-modulo-automatico\mat.app> java --module-path out lib --module mat.app/com.exemplo.Main
O resultado da soma é: 11

Usando jdeps
C:\exemplo-modulo-automatico\mat.app> jdeps --module-path lib out -s --module mat.app
mat.app -> matematica.iz
mat.app -> java.base

Além desse conceito, temos também os módulos sem-nome, mas isso eu deixo para você pesquisar.


HP FORTIFY 360 a

Question: While Scanning a Asp.Net project  got a error saying Access control Database,
It says

"Without proper access control, executing a SQL statement that contains a user-controlled primary key can allow an attacker to view unauthorized records."

Even though there is a proper validation for the input fields and the data is moved across layers ie., Front END(UI)->BUSINESS Layer->data layer.
Is there any property on the control or database to set so that the issue can be resolved
Comment: What is the Rule ID, Impact and Likelihood (found on the Detail tab)? How is the data validated? Are you using an ORM (nHibernate, LINQ, etc.)?
Answer: "Access Control: Database" means a NUMERIC input data is received from the attacker, and provided to the query.  It may be validated for format, like "be sure it is a positive integer", but the risk is that if the attacker has control of the value he can change the primary key of the query, getting different data back.
This is different from SQL Injection only in the sense that SQL Injection by convention means that the attacker changed the structure of the query (e.g. by adding keywords).  But of course they are both injections of content into SQL.
"Is there a property on the control or database...?" No.

To properly validate this data, you have to place an application level control so that you are sure the attacker is only providing the primary key he is allowed to add.  You could do this for instance, by not giving the value at all to the remote client. You could perhaps just keep it in the session across requests.
To properly resolve a completely legitimate issue:
Select "Not an Issue" in the audit analysis or primary tag dropdown.
Enter a comment, explaining to the security lead why you believe the logic is justified and safe.
Submit the comment using the stupid submit button that should not be necessary.
To properly resolve an entire class of legitimate issues:
I commonly create a filter to hide Access Control:Database issues where the source of untrusted data was not the remote attacker but rather the database.

In this case, query 1 looks up "Jane Doe" and gets her foo ID.  Query 2 looks in another place where ID = Jane's foo ID.  The ID originated from the first database query.  The data will carry a Fortify Taint Flag called "DATABASE".  YOU AND YOUR SECURITY AUDITOR MAY TRUST THIS SOURCE OF INFORMATION.  Or, it may be considered another place where hackers have stashed malicious data intended to enable subversion of your app.  I wouldn't know.
In the case you and your security auditor trust the database, you can create a filter "if taint:database -> hide the issue" and then put this filter into the default filterset of your projects' template(s).  You do this using Audit Workbench's Tools->Project Configuration... dialog.
Comment: I'm sorry my answer was so long.  Access Control: Database is a really simple vulnerability pattern, but not so simple to apply the mitigation.
Answer: As long as it comes directly from user fortify warns you. Often it is false-positive. Fortify expects, user input have to be validated from another source like an array.
The other possibility to fix it, create a custom dll which contains a validation function for user inputs. Do not pass user parameters directly to the database layer. Validate these inputs by using your custom dll. That will %100 work.

HP FORTIFY 360 a


MySQL Date Issue - how to compute?

Question: I have a MySQL database with a date_of_birth field. The data stored in this field is of the format: MM-DD-YYYY.  I need to compute age for this field so I must compare and take the difference of CurDate().
To do this I have written the following:
select FLOOR((DATE_FORMAT(curdate(), '%m-%d-%Y') - date_of_birth)/10000)
from patients

So I would expect it to be comparing the CurDate() of MM-DD-YYYY minus DOB of MM-DD-YYYY.  However, for my one test case it continues to return a -1.  I've got this working fine with MSSQL but it seems MySQL is a bit more picky/less user friendly.
Am I missing something here? Whats the deal, please help!
Thanks
Comment: Eh, why aren't you using mysql date format? Storing it in native is just... Inefficient. Is it possible to change your table structure?
Comment: It's not my design Vyk. It was the idiots before me that knew nothing about MySQL. So I'm stuck with it but I got it working now.
Answer: SELECT DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(date_of_birth, '%Y') -
      (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(date_of_birth, '00-%m-%d'))
       AS age
FROM patients

http://ma.tt/2003/12/calculate-age-in-mysql/
ps: if your date is in another format (but I would advise you to keep it 'native' format YYYY-MM-DD) then
SELECT
 DATE_FORMAT(NOW(), '%Y') -
              DATE_FORMAT(STR_TO_DATE(date_of_birth, '%m-%d-%Y'), '%Y')
- (DATE_FORMAT(NOW(), '00-%m-%d') <
              DATE_FORMAT(STR_TO_DATE(date_of_birth, '%m-%d-%Y'), '00-%m-%d'))
   AS age
FROM patients

Comment: Still just returning NULLs. My date_of_birth is stored in format MM-DD-YYYY - this is the stumbling block.
Comment: Thanks Cheery! Was attempting to make those same modifictations.. As for it being stored in an unconventional format for MySQL, well that cannot be helped at this point :( Gotta deal with it.
Comment: @Encryption You can easily update all the data in DB to the specified format with the couple of requests (including altering of the table's structure). The best way is to format date at output.
Comment: I realize that but this is connected to a web interface. Would require interface changes as to how that information is displayed and saved. Not something I'm going to deal with right now(all I need was a report, heh).
Answer: You can use datediff()
SELECT DATEDIFF(CURDATE(),date_of_birth) AS Age

Comment: Doesn't work. Just returns NULLs. Even tried using DATEDIFF(DATE_FORMAT(curdate(), '%m-%d-%Y'), date_of_birth)
Comment: DATEDIFF returns difference in days
Comment: do the date_format on date_of_birth and see if that works.  I know with oracle, even fields stored as dates can be quirky and I had to cast it as a date anyway.  Try masking both dates as well so that the db is comparing apples to apples.

MySQL Date Issue - how to compute?


Inner regular content is premeasure

Question: Let $(X,\mathcal{T})$ be a topological space and $\mu$ be a content on a semiring $\mathfrak{J}$ over $X$. Suppose that $\mu$ is inner regular, i.e., for every $\epsilon > 0$, $A \in \mathfrak{J}$, there is a $K\in \mathfrak{J}$ such that $\overline{K}$ is compact, $\overline{K} \subseteq A$ and $\mu(A)\leq \mu(K)+\epsilon$. I want to show that this implies that $\mu$ is a premeasure.

My attempt:
First of all, I showed that if $\mu$ is an inner regular content on $\mathfrak{J}$, then its extension to the ring $\mathfrak{R}$ (which I denote by $\mu$ as well) generated by $\mathfrak{J}$ is inner regular as well. This allows us to use the following lemma:
Lemma:
Let $\mu$ be a content on a ring $\mathfrak{R}$. If for every sequence $(A_n)_{n\in\mathbb{N}}$ of sets in $\mathfrak{R}$ satisfying $\mu(A_1) < \infty$ and $A_n \downarrow \emptyset$ we have $\mu(A_n)\downarrow 0$, then $\mu$ is a premeasure on $\mathfrak{R}$.
So, in order to use the lemma, let $A_n$ be defined as in the lemma. Take $K_n \in \mathfrak{R}$ such that $\overline{K_n}$ is compact, $\overline{K_n} \subseteq A_n$ and $\mu(A_n) \leq \mu(K_n) + \epsilon$ for all $n \in \mathbb{N}$. We have $$\bigcap_{n=1}^{\infty} \overline{K_n} \subseteq \bigcap_{n=1}^{\infty} A_n = \emptyset.$$
Due to the compactness of the $\overline{K_n}$, this means that the family $(\overline{K_n})_{n\in\mathbb{N}}$ does not have the finite intersection property. Hence, there is a $N \in \mathbb{N}$ such that
$$ \bigcap_{n=1}^{N} K_n \subseteq \bigcap_{n=1}^{N} \overline{K_n} = \emptyset.$$
I've tried to use $\cap_{n=1}^{N} A_{n} = A_{N}$ and estimate $\mu(\cap_{n=1}^{N} A_n)$ by something depending on $\mu(\cap_{n=1}^{N} K_n)$ plus something depending on epsilon, but without success. I've also tried to make the $K_n$ disjoint, that is, define $C_n := K_n \setminus \cup_{i=1}^{n-1}K_i$ and then use that
$$\mu(A_1) \geq \mu\left(\bigcup_{n=1}^{N} C_n\right) = \sum_{n=1}^{N} \mu(C_n).$$
As $N$ was arbitrary, this shows that $\mu(C_n) \to 0$, but I've been unable to conclude from this.
Answer: Let $A_n$ be defined as in the lemma. Fix $\epsilon>0$ and choose $K_n \in \mathfrak{R}$, $\overline{K_n}$ compact and $\overline{K_n} \subseteq A_n$, such that $\mu(A_n)<\mu(K_n) + \epsilon/2^n$. By what you've already shown, there's an $N$ such that $\bigcap_{n=1}^N K_n = \emptyset$. Now,
\begin{align}
\mu(A_N) &= \mu(\cap_{n=1}^N A_n) \leq \mu(\cup_{n=1}^N (A_n - K_n))\\
&\leq \sum_{n=1}^N \mu(A_n - K_n) = \sum_{n=1}^N \big( \mu(A_n) - \mu(K_n)\big) < \epsilon.
\end{align}
Since $(A_n)$ is decreasing, $\mu(A_n) < \epsilon$ for all $n \geq N$, so $\mu(A_n) \to 0$.
Comment: Nice! It took me a little to get that we have $$\bigcap_{n=1}^{N} A_{n}  = \left(\bigcap_{n=1}^{N} A_{n}\right) \setminus \left(\bigcap_{n=1}^{N} K_n\right) \subseteq \bigcup_{n=1}^{N}A_{n} \setminus K_{n}$$ to understand where the first inequality was coming from.

Inner regular content is premeasure