input Textboxes over an image

Question: How can I place textboxes over an image, and anchor the textboxes
fix on the image.
When I resize the image anchoring is lost.
the textbox should be scaled proportionally to the image

body, html {
    width: 100%;
    height: 100%;
  }

/* Container holding the image and the text */
.bg_img {
    /* Control the height of the image */
   height: 1500px;
   background-repeat: no-repeat;
   position: relative;
  }

.innerContainer {
    position: absolute;
    left: 20px;
    width: 100%;
    height: 100%;
}

/* Full-width input fields */
input[type=text], input[type=password] {
    position: absolute;
    border: none;
    background: #f1f1f1;
}

input[type=text]:focus, input[type=password]:focus {
    background-color: #ddd;
    outline: none;
}

                <input type="text" placeholder="h" name="l1" style="left: 20px; top: 320px; width: 80px; transform: rotate(90deg);">
                <input type="text" placeholder="b" name="l1" style="left: 20px; top: 220px; width: 80px; transform: rotate(90deg);">
                <input type="text" placeholder="h2" name="l1" style="left: 300px; top: 320px; width: 80px;">

The images size are different.
Comment: Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: your inline style has left and right pixel that's why it's  make a scrollbar you can try to use % instance of px.
hope you solve your problem, if not let me know details

input Textboxes over an image


Prevent back button from closing a dialog box

Question: I am trying to prevent an AlertDialog box from closing when pressing the back button in Android. I have followed both of the popular methods in this thread, and with System.out.println I can see that in both cases the code executes. However, the back button still closes the dialog box.
What could I be doing wrong? Ultimately I'm trying to prevent the back button closing a dialog box - it is a disclaimer that is displayed the first time the app is run and I don't want the user to have any option but to press the "Accept" button in order for the app to continue.
Comment: If you require a user to accept a license or disclaimer (or whatever) then you **MUST** allow them to refuse. If they click the `BACK` button then make sure your license/disclaimer dialog appears again next time they start the app and again and again until they either accept or remove the app from their device. If you choose to use the approach suggested by Sam then you **MUST** provide a 'Refuse' button but then re-create the license/disclaimer next time they start the app.
Comment: I would remove an app that gives me "accept" as the only option... and don't even think about disabling the home button!
Comment: The app can be closed through pressing the home button, but essentially the app cannot progress past the disclaimer if the license is not accepted. @Squonk, you mention that I *must* allow them to refuse; is this a legal issue? i.e. is there a law that software must be usable (if it has been paid for) without accepting the licence agreement? n.b. I already have a 'decline' button, and pressing this pops up a Toast() saying that you must accept the agreement in order to use the app. The dialog box thus persists until accept is pressed.
Comment: @CaptainProg : I'm not a lawyer but I suspect in some countries it might be considered a *legal* issue. I'm not suggesting that you allow people to use you app if they refuse/decline the disclaimer. All I'm saying is it is bad policy, bad customer relations (even if the app is free) and bad for the UX to lock somebody in. Simply have the 'decline' option close the app and next time the user tries to start it, present the same dialog. Don't just popup a `Toast`, leave them locked in and rely on them using thw `HOME` button to get out.
Answer: Simply use the setCancelable() feature:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);

This prevents the back button from closing the dialog, but leaves the "negative" button intact if you chose to use it.

While any user that does not want to accept your terms of service can push the home button, in light of Squonk's comment, here two more ways to prevent them from "backing out" of the user agreement. One is a simple "Refuse" button and the other overrides the back button in the dialog:
builder.setNegativeButton("Refuse", new OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int which) {
               finish();
           }
       })
       .setOnKeyListener(new OnKeyListener() {
           @Override
           public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
               if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP)
                   finish();
               return false;
           }
       });

Comment: Additionally, If using a `DialogFragment`, you should call `setCancelable` on that and not on the `Dialog` itself
Comment: thanks a lot @Kuffs. I was setting it on the Dialog and wondering why it isn't working !
Answer: To prevent the back button closes a Dialog (without depending on Activity), just the following code:
alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        // Prevent dialog close on back press button
        return keyCode == KeyEvent.KEYCODE_BACK;
    }
});

Comment: Worked beautifully in my case. I had to load a `WebView` on my app. I had to check `canGoBack()` and close the dialog if it was false.
Comment: worked well. keep it up
Answer: When using DialogFragment you will need to call setCancelable() on the fragment, not the dialog:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    dialog = new ProgressDialog(getActivity());
    dialog.setIndeterminate(true);
    dialog.setMessage(...);
    setCancelable(false);

    return dialog;
}

Calling dialog.setCancelable() seem to have no effect. It seems that DialogFragment does not takes notice of the dialog's setting for cancelability.
Answer: Use setCancelable(false)
SampleDialog sampleDialog = SampleDialog.newInstance();
sampleDialog.setCancelable(false);
sampleDialog.show(getSupportFragmentManager(), SampleDialog.class.getSimpleName());

Answer: Only this worked for me:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title);
builder.setMessage(content);

/**
 * Make it when the Back button is pressed, the dialog isn't dismissed.
 */
builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            Utilities.makeToast(getContext(), "There is no way back!");
            return true; // Consumed
        }
        else {
            return false; // Not consumed
        }
    }
});

Dialog dialog = builder.create();

/**
 * Make it so touching on the background activity doesn't close the dialog
 */
dialog.setCanceledOnTouchOutside(false);

return dialog;

As you can see, I also added a dialog.setCanceledOnTouchOutside(false); line so tapping outside of the dialog doesn't result in it being closed either.
Answer: In JQuery Mobile a popup adds a hash to the url, the following code allows the back to dismiss the popup when open and return to the app when closed. You could use the same logic for a custom ui framework.
@Override
public void onBackPressed() {

    // check if modal is open #&ui-state=dialog

    if (webView.getVisibility() == View.VISIBLE && webView.getUrl().contains("#&ui-state=dialog")) {
        // don't pass back button action
        if (webView.canGoBack()) {
            webView.goBack();
        }
    } else {
        // pass back button action
        super.onBackPressed();
    }
}

Answer: Add setCancelable(false) to stop the back button from closing a dialog box.
For example :
AlertDialog.Builder builder = AlertDialog.Builder(this)
Dialog dialog = builder.create()
dialog.setCancelable(false)
dialog.setCanceledOnTouchOutside(false)

This will prevent the user from canceling the dialog when they press the back button or touch outside the dialog window
Answer: Go ahead with this one:
 ProgressDialog progressDialog = new ProgressDialog(ChatActivity.this);
    progressDialog.setMessage("sending video...");
    progressDialog.setCanceledOnTouchOutside(false);
    progressDialog.setCancelable(false);
    progressDialog.show();

Answer: for Kotlin you can simply do this:
alertDialog.setOnKeyListener(DialogInterface.OnKeyListener { _: DialogInterface?, keyCode: Int, _: KeyEvent? -> keyCode == KeyEvent.KEYCODE_BACK })


Programmatically set view header

Question: I know there is a post on how to set a view header/footer value here,
but how do I set a view header/footer without having to create it through views UI first?
The reason why I want to implement a view header programmatically is because (a) I want to write php code in it, by leveraging the Drupal's API, something that is not so convenient in a textarea field, like the one that the views UI provides -and any other textarea field- plus the fact that some functions may never get invoked and (b) because I want to conditionally set/unset the view header/footer.
Answer: After some research I managed to answer my own question by implementing the hook_views_pre_view in my custom module. The method set_item is used to set the configuration of an item (field/sort/filter/etc) on a given display. The $print variable bares the content to be rendered in the view header, it is just an example and it can be replaced by anything. Apparently now I can take advantage of the Drupal API or even set/unset any view item conditionally.
/**
 * Implementation of hook_views_pre_view.
 */
function my_module_views_pre_view(&$view, &$display_id, &$args) {

  $path = $_GET['q'];
  // Construct the print link.
  $print = l(t('Display a printer-friendly version of this page'), '/print/' . $path . '/print-friendly',  array(
    'attributes' => array(
      'class' => array('print-friendly'),
      'target' => '_blank',
      'title'=> t('Display a printer-friendly version of this page.'),
      ),
    )
  );

  if ($view->name == 'my_view_name' && $display_id == 'my_view_display') {
    // View's header declaration.
    $item = array(
      'id' => 'area',
      'table' => 'views',
      'field' => 'area',
      'relationship' => 'none',
      'group_type' => 'group',
      'ui_name' => '',
      'label' => '',
      'empty' => 0,
      'content' => $print,
      'format' => 'filtered_html',
      'tokenize' => 0,
    );
    // Render the header.
    $view->set_item($display_id, 'header', 'area', $item);
  }
}

Comment: Please use the edit link on your question to add additional information. The Post Answer button should be used only for complete answers to the question. - [From Review](/review/low-quality-posts/89517)
Comment: @ShawnConn I really appreciate your words but I don't understand what do you mean by complete answer, can you guide me please? Did you try that code snippet and didn't work ?
Comment: I take @ShawnConn is saying it's not clear this is the answer for the question. It seems more additional information for the question. Maybe you should remove the part telling why you want to do it programmatically and not using the UI; that part is for the question.
Comment: @kiamlaluno Thanks for the clarification. I hope that is more clear now, but if someone still thinks that the answer is incomplete, ambiguous or inappropriate kindly let me know. I just am trying to share my findings.
Comment: @mchar So-called "code only" answers aren't generally considered to be great for Q+A. There's no explanation of _how_ you solved the problem, just a dump of code that purports to do so
Comment: @Clive Half of the answers across the SO sites are so-called "code-only" or one-liners because words are needless when the code speaks for itself. I don't have any intention to argue with anybody, I defended my part as much as I could, but I still haven't received any input on how to improve my answer except kiamlaluno's comment. Anyway, you have to admit that I really tried ;)
Comment: Yeah I didn't clarify that so well did I...I was speaking very generally, not really about your original answer specifically. I'd agree that with the comments, it was already pretty self-explanatory. Still, the paragraph you added does improve it too IMO so there is that...
Comment: Got this working in 8.9.10 with `$view->setHandler($display_id, 'header', 'area', $item);`
Answer: Just as a second option, you could always use a preprocess function to override the theme hook.
For starters, turn on theme_debug in your settings.php file, clear your site cache and navigate to the page that contains the view display that you'd like to alter.
Open your browser's developer tools (e.g. Chrome: Ctrl+Shift+I, or right click and choose "Inspect") and find the display's markup within the source code. You should see something similar directly above the element.

Next, inside template.php of your theme, write a preprocess function that calls the same theme hook:
function THEMENAME_preprocess_views_view(&$vars) {
    //logic
}

The $vars variable is an array that contains the view object. Use a debug tool like devel to introspect the render array. Then set the header and footer attribute by assigning it a value.
/**
 * Implements template_preprocess_views_view().
 */
function THEMENAME_preprocess_views_view(&$vars) {
    //logic
    $vars['header'] = "Something Special";
}

Source: template_preprocess_views_view

Programmatically set view header


Rake test expects for the table name defined as model name?

Question: I have an MS SQL db table (dbo.MEXICAN_FLOWERS), used by a model Flower. In order to write test cases, I wrote a dummy migration file for that model, and then modified the migration file with the column names that the db has, and ran:
rake db:migrate

Also I tried:
$RAILS_ENV=test rake db:migrate

and verified that everything looks great. When I try to do:
$ rake test

it raises an error such that a table with flowers is not found:
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: flower: DELETE FROM "flower"

Why is this happening?
I also ran:
rake db:migrate

Answer: When you run tests, Rails doesn't look at your regular database. Instead, it looks at your fixtures.
You need to write fake data in test/fixtures/flowers.
Cheers!
Comment: I already have fixtures like this: /test/fixtures/flower.yml file. Is it wrong?
Comment: I can tell you that all of my fixture files are plural: scores.yml, seminars.yml, users.yml, etc. Maybe that has something to do with it?


How to format Dataweave sample data to LinkedHashMap

Question: I have this LinkedHashMap and LinkedHashMap$Entry payload
{box=
   {
     0={plate=false, id=8269999, knife=1},
     1={plate=true, id=8260118, knife=1}
   }
}

I want to apply this structure to my Dataweave transformation sample data. I came up with this but the transformation fails during runtime, while preview shows it is a correct transformation...
%dw 1.0
%output application/java
---
[{
  "box": {
    "0": {
      "plate": {
        plate: false
      } as :object {
        class : "java.util.Object"
      },
      "id": {
        id: 8269999
      } as :object {
        class : "java.util.Object"
      },
      "knife": {
        knife: 1
      } as :object {
        class : "java.util.Object"
      }
    } as :object {
      class : "java.util.Object"
    },
    "1": {
      "plate": {
        plate: true
      } as :object {
        class : "java.util.Object"
      },
      "id": {
        id: 8260118
      } as :object {
        class : "java.util.Object"
      },
      "knife": {
        knife: 1
      } as :object {
        class : "java.util.Object"
      }
    } as :object {
      class : "java.util.Object"
    }
  } as :object {
    class : "java.util.Object"
  }
} as :object {
  class : "java.util.LinkedHashMap"
}]

Comment: You can remove all the `as :object {class : "java.util.Object"}` also can you paste the execption, add runtime information (version of mule you are using).
Answer: java.util.Object doesn't have fields like knife or plate so it would not make any sense to cast to it. What you want is to just remove all the 'as :object...' in your script and DataWeave will return maps as needed.
Also usually the entries in a map (ie LinkedHashMap$Entry) are not referenced directly at all. They are an implementation detail of the specific map implementation.
Just think in terms of the Map interface, not a specific implementation like LinkedHashMap.


Consequences of violation of independence assumption in ANOVA test

Question: Can you please explain me what is the consequences of violation of independence assumption in ANOVA test?
I couldn't visualize it.
Does Cochran Theorem relates to independence assumption ?
Answer: The independence assumption allows us to use simple statistical concepts to quantify the evidence for/against the null hypothesis. That is, independence (among the other assumptions) allows us to say that the errors from the mean are normally distributed. Then we can use the Cochran Theorem to quantify the p-value (how extreme the actual data is given the null hypothesis), which we then use to make a decision.
The Cochran Theorem is the workhorse theorem for ANOVA and requires independence, so yes there is a very strong relation.
Comment: If our model violates independence assumption, can we decompose the total variability?
Comment: If there is no independence (i.e. there is some underlying structure to the errors), then there might be a way to extend Cochran's theorem. However, if that were to exist, then it would be on a case-by-case basis.

A more useful approach would be to generalize ANOVA to regression. A lot of work has been done on making regression work with messy error (residual) structures.


Long Running Apps on Android Wear

Question: The Android Wear ecosystem seems to be built around quick tasks which a user will interact with, and then close.  This works great for most applications, but what about one which covers a long running task, and should not be automatically closed when the watch sleeps?
My specific case: Swing by Swing Golf GPS.  The preferred operation would be to have the application remain active, and shown when the screen wakes due to user action.  And the life-time of a single use will be between 2 to 4 hours.
What are some methods to go about keeping an application front and center on the Android Wear device for periods longer than a single use?
Answer: So, here is what I have come up with as a solution:
Build a notification with a PendingIntent to open the main Activity.  Also pass it an intent for the delete action, so we know if the user has dismissed it.
public class SbsNotificationHelper {
    private static final String NOTIFICATION_DELETED_INTENT = "sbs.notificationDeleted";
    private static boolean _isNotificationActive = false;

    /** Public static methods */

    public static NotificationCompat.Builder buildRoundInProgressNotification(Context context) throws Throwable {
        Intent viewIntent = new Intent(context, SbsRoundActivity.class);
        PendingIntent viewPendingIntent = PendingIntent.getActivity(context, 0, viewIntent, 0);

        context.registerReceiver(_broadcastReceiver, new IntentFilter(NOTIFICATION_DELETED_INTENT));
        _isNotificationActive = true;

        Intent deleteIntent = new Intent(NOTIFICATION_DELETED_INTENT);
        PendingIntent deletePendintIntent = PendingIntent.getBroadcast(context, 0, deleteIntent, 0);

        NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.circle_button, "", viewPendingIntent).build();

        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.bottom_bg);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.iphone_57x57)
                .setLargeIcon(bitmap)
                .setContentTitle("Golf GPS")
                .setContentText("Swing by Swing")
                .addAction(action)
                .setDeleteIntent(deletePendintIntent)
                .extend(new NotificationCompat.WearableExtender()
                        .setContentAction(0));

        return notificationBuilder;
    }

    public static boolean isNotificationActive() {
        return _isNotificationActive;
    }

    /** BroadcastReceiver */

    private static final BroadcastReceiver _broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            _isNotificationActive = false;
        }
    };

}

Use onStop() as opposed to onPause() to issue the notification.  This way, if you have multiple activities in your app, you can present them (only causing onPause() of the main Activity).
@Override
protected void onStop() {
    super.onStop();

    int notificationId = 001;
    NotificationCompat.Builder notificationBuilder = SbsNotificationHelper.buildRoundInProgressNotification(context);

    NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
    notificationManagerCompat.notify(notificationId, notificationBuilder.build());
}

Also use the notification inside of your WearableListenerService if you communicate with an app on the handheld.  Thus a notification can be popped and easily accessed when your app is opened.
@Override
public void onMessageReceived(MessageEvent messageEvent) {
    super.onMessageReceived(messageEvent);

    try {
        if (SEND_MESSAGE_PATH.equalsIgnoreCase(messageEvent.getPath())) {
            if (!SbsNotificationHelper.isNotificationActive()) {
                int notificationId = 001;
                NotificationCompat.Builder notificationBuilder = SbsNotificationHelper.buildRoundInProgressNotification(sbsApplication);

                NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
                notificationManagerCompat.notify(notificationId, notificationBuilder.build());
            }
        }
    }
    catch (Throwable throwable) {
        //Handle errors
    }
}

Comment: One thought: Does `OnStop()` reference the device turning off the screen? As far as I'm aware, the concept of Android Wear includes stopping all running apps, save for a message ticker and the clock, when the device sleeps.
Answer: the OnPause() method is called whenever the device is put to sleep or dialogue appears over the application. One or two activities can be done here, but they should be kept reasonably lightweight to prevent elongated user wait times.
Comment: So you are saying that a best practice would be to add a notification when the watch is headed for sleep?  And from that notification users would reenter our application?
Comment: @TerrenceGiggy
Not necessarily. That is an option, yes, but bear in mind that a lot of the heavyweight stuff needs to be done by the associated device. You can use the `OnPause()` method to send the associated device a notification, then use `NotificationCompat.Builder` to create a waking notification for your device, which will initiate the app on the Wear device again. You'll need a method to send the app's data back to the device.
Comment: @TerrenceGiggy

So:
Step 1: user initiates app
Step 2: App looks for a completed motion (The golfer's swing).
Step 3: The app sends the data to the android device.
Step 4: The Wear device goes to sleep.
Step 5: The user reviews the swing.

Remember that the 2-4 hours of wakefulness would murder the Wear battery life, which is why I'm suggesting this method.
Answer: I've had no problem doing a "extends Service" app on Wear device that works perfectly fine.
Basically: In your Wear app - decouple your GUI and app logic. Keep the app logic inside the service.  I keep a class object that holds all the GUI data and pull it static from the service when Activity starts.
You could extend wearable service, but I use just the generic service as the center of my app and that worked perfectly fine (app runs for days without trouble).

Long Running Apps on Android Wear


Variável Calendar atualiza a outra quando a segunda é atualizada?

Question: Olá, estive mexendo com a classe GregorianCalendar e me deparei com o seguinte problema:
Tinha que percorrer de um ponto no calendário até o outro, depois setar o primeiro ponto como o segundo, logo em seguida, "resetar" o segundo campo e percorrer de volta. basicamente o seguinte:
GregorianCalendar gc1=new GregorianCalendar();
GregorianCalendar gc2=new GregorianCalendar();
gc1.setTime(meuTempo1);
gc2.setTime(meuTempo2);
while(!gc2.equals(variavel)){//eu tinha que voltar a gc2 até um determinado ponto
//que não necessariamente é igual a gc1.
//percorre o tempo, tirando o tanto de gc2
}
gc1=gc2;//aqui está o problema
gc2.setTime(meuTempo2);

Basicamente, percorri de volta um determinado, dei um gc1=gc2e setei novamente o gc2 como ele era antes. O problema, é que quando eu dava o gc2.setTime(meuTempo2); a variável gc1 também recebia aquele parâmetro, ou seja, os atributos do gc1 também mudaram, como se eu tivesse colocado uma segunda linha gc1.setTime(meuTempo2);.
Foi fácil resolver isso, bastou substituir gc1=gc2 por gc1.setTime(gc2.getTime()); mas eu fiquei na dúvida, se eu instanciei uma variável nova, ela não deveria pegar os atributos e depois ficar independente da segunda? Se não, em quais casos isso pode acontecer? E se possível, como tratar esse problema?
Comment: Não tinha lido o final da pergunta. O que acontece é que você está passando a referencia do objeto(endereço de memória), e não seu valor. Outra coisa, para comparar datas e tempo, se você estiver usando JDK8, é recomendável que utilize as classes do pacote java.time, essas classes antigas tem vários problemas quanto a comparação.
Comment: Entendi, mas como eu perguntei, como contornar isso em outras classes?usando os setters todos? nesse caso ainda tem o `setTime`, mas tenho classes que tem mais de 30 atributos, vou usando `setAtributo(getAtributo())` em todos?
Answer: Fazer gc1=gc2 não copia os valores dos atributos de gc2 para gc1. Ao fazer isso, você está copiando a referência de gc2 para gc1. Em um nível mais baixo, significa que gc1 e gc2 apontam agora para o mesmo endereço de memória aonde está o objeto do tipo GregorianCalendar. Portanto, qualquer alteração no atributo que seja feita por meio do gc1 e do gc2 está afetando o mesmo objeto.
No caso do GregorianCalendar, você pode copiar os valores dos atributos utilizando o método clone. Algo dessa maneira:
gc1 = (GregorianCalendar)gc2.clone();

Note que o código acima está atribuindo um novo objeto GregorianCalendar para gc1 com os valores clonados de gc2.
Comment: @ThomasBrazPinto, não. Você precisa implementar o seu método clone e dizer como você quer clonar. Geralmente, o que faço é usar reflection para facilitar essa clonagem. Portanto, não faço atributo por atributo, uso reflection para fazer um loop em meus atributos, copiando os valores. Entretanto, tem uma série de questoes, como: e se o seu objeto tiver uma Collection, você vai clonar a Collection tb? Por isso, o Clone é feito caso-a-caso.
Comment: @ThomasBrazPinto, creio que você deva mudar a maneira de pensar. Conceitos de ponteiro são fundamentais para que você entenda referência no Java (Java usa ponteiro, mas ele abstrai boa parte do desenvolvedor). Ao fazer gc1=gc2, você está fazendo com que gc1 aponte para o mesmo endereço de memória de gc2.  Esse endereço de memória que gc1 e gc2 referenciam, contém o objeto propriamente dito, nesse caso uma instância de GregoriaCalendar. Por isso, não é uma questão de "ver" a alteração, a questão é que ambas as duas variáveis apontam para o mesmo objeto.
Comment: isso funciona para outras classes também? Digamos, uma entidade que eu mesmo criei para o banco de dados por exemplo
Comment: Entendi, Obrigado pela ajuda!
Comment: É preciso implementar a interface Cloneable para usar o método Clone, ver aqui: https://docs.oracle.com/javase/7/docs/api/java/lang/Cloneable.html
Comment: fiquei pensando aqui, e fiquei com outra dúvida, se eu deixasse do jeito inicial, e fizesse a alteração na variável `gc1` a alteração seria "vista" na `gc2` também?


Proving a natural map is open

Question: This actually have been asked and answered here. I still have question for proving that the natural map $p$ is open and i can't comment since my reputation is not enough yet, so i make a new question.
Henno suggests to prove that $p^{-1}(p(O)) = [0,1]$ so that since [0,1] is open in $I$, then $p^{-1}(p(O))$ is open in $I$, implying $p(O)$ is open in $I/\sim$. I have tried to prove it by showing that $p^{-1}(p(O)) \subseteq [0,1]$ and $[0,1] \subseteq p^{-1}(p(O))$. The former is obvious, so i focused on the latter. We have that
$$
\begin{equation}
x \in p^{-1}(p(O)) \Leftrightarrow p(b) \in p(O) \Leftrightarrow \exists y \in O \ni p(x) = p(y) \Leftrightarrow \exists y \in O \ni [x] = [y].
\end{equation}
$$
Let $a \in [0,1]$. Since $O$ is open in $I$, then it contains rational and irrational numbers.  If $a$ is rational, then i can choose any rational $b$ in $O$ so that $[a] = [b]$, since all rational in [0,1] have the same equivalence class. This proves that every rational number in [0,1] is also in $p^{-1}(p(O))$.
I have been struggling when $a$ is irrational. Here is my work.
If $a$ is irrational, then $a$ is either in $O$ or not. It is obvious that if $a \in O$, then $a \in p^{-1}(p(O))$. I am stuck when proving for $a \notin O$. Is my approach correct or is there a better way to prove this?
Note: i use the same book as the asker in the question i linked.
Answer: Let $O$ be a nonempty open subset of $[0,1]$, our goal is to prove that $p^{-1}(p(O)) = [0,1]$.
The quickest way is to show that for every $x \in [0,1]$, the equivalence class of $x$, i.e. $p ^{-1}(p(x))$ or $\{x+\mathbb{Q}\}\cap[0,1]$, is dense in $[0,1]$. Since $\mathbb{Q}$ is dense in $\mathbb{R}$, $x+\mathbb{Q}$ is also dense in $\mathbb{R}$. This is actually a bit tricky, but I suppose you know that any open subset of $\mathbb{R}$ is the disjoint union of countably many open intervals, or that the open intervals form a basis for the topology of $\mathbb R$.

Let $(a,b)$ be any nonempty open interval in $\mathbb{R}$, then $a-x<b-x$, and there exists some $q \in \mathbb{Q}$ such that $a-x<q<b-x\implies a<x+q<b$. Therefore, $x+\mathbb{Q}$ is dense in $\mathbb{R}$.

Now since a continuous function maps dense subsets to dense subsets, $\{x+\mathbb{Q}\}\cap[0,1]$ is dense in $[0,1]$. We conclude that $p ^{-1}(p(x))$ intersects every open subset $O$ of $[0,1]$, thus there exists some $y \in O$ satisfying $p(x)=p(y)$.
Answer: For each $x \in [0,1]$ we have $p^{-1}(p(x)) = (x + \mathbb Q) \cap [0,1]$.
Consider any $a \in [0,1]$.
Pick any  $a' \in O' = O \setminus \{0,1\}$ (note that $O'$ must be non-empty because otherwise $O \subset \{0,1\}$ which is impossible for an open set).
There exists $\epsilon > 0$ such that $(a'- \epsilon, a' + \epsilon) \subset O$. There exists a rational number $d$ such that $a - a' - \epsilon < d < a - a' + \epsilon$. Then $a' - \epsilon = a  - (a -a' + \epsilon) < a - d  < a - (a - a' - \epsilon) = a' + \epsilon$, hence $a - d \in (a'- \epsilon, a' + \epsilon) \subset O$. Therefore $a \in ((a-d) + \mathbb Q) \cap [0,1]) = p^{-1}(p(a-d)) \subset p^{-1}(p(O))$.

Proving a natural map is open


Multilingual content Migration

Question: I have Multi-Language website, I need this website to migrate new Drupal website.
I can use node export module for export the content; however, I have a multi-language site, how should I handle those translation nodes ?
Comment: Is the "new" Drupal, Drupal 8 or another Drupal 7 website ? What type of translation are you using ? Node translation ?
Comment: I have used "internalization" module, and am going to migrate New Drupal 7 website
Answer: It is much easier to create an xml view of your content in each language and import it with feeds module and xpath. Or if it is easier for you, you can export to csv with views data export and import to your new drupal with feeds csv parser. It is much easier and more reliable as you have total control of your content. Though be careful with the delimiters if using csv. XML is safer.
Comment: is it possible to export multi language contents
Comment: Yes there is a Node translation filter. Another solution is to do it programmatically using the global $language  variable. And finally you can always check this old patch too: https://www.drupal.org/node/1330332
Comment: i have asked about content migration.. hope you not get my point
Comment: Explain it better and I can help you as I have migrated multilingual content many many times with feeds

Multilingual content Migration


passing command line arguments between classes in Java

Question: I have a Java program in which I need to accept the command line arguments in an array as input in the main method, and then need to pass the array to a constructor of another class in the same program. I need to know how to declare the array globally and then how to pass it and take it in the constructor.
Thanks
Comment: Don't consider using global variables. As to passing information into a constructor, you give the accepting class's constructor a parameter that will accept the data, and you pass it in when calling this constructor.
Comment: Why do you think you need to declare the array globally (in java its `public`) to pass it in any constructor? Since you will be invoking the `constructor` from the main method itself, you can pass the array that you get as commandline argument, to the constructor.
Answer: public class Example{

  Example(String s[])
  {
   AnotherClass ac = new AnotherClass(s);
  }
  public static void main(String[] args){
  int num=args.length;
  String s[]=new String[num];
  Example ex = new Example (s);`
  }
}

And you can create AnotherClass
public class AnotherClass{
  AnotherClass(String s[])
  {
   // array argument constructor
  }
}

You can run using
javac Example.java
java Example
Comment: I cannot call the AnotherClass from the Main() method but I need to call it from the constructor of Example class and I have 2 arrays. So Do you first want me to pass the 2 arrays from the main() method to the constructor of the Example class and then from the constructor call the AnotherClass with the arrays? If possible, can you please show me the way to do it
Answer: class SomeOtherClass{
   public SomeOtherClass(String[] args){
       this.arguments = args;
   }
   private String[] arguments;
}
class YourMainClass{

 public static void main(String[] args){
     SomeOtherClass cl = new SomeOtherClass(args);
    //fanny's your aunt
  }
}

This is how you can pass the arguments to SomeOtherClass's constructor.
Answer: In your class that contains the main method, you could have a class variable like:
String[] cmdLineArgs;

then in the main method:
cmdLineArgs = new String[args.length];
this.cmdLineArgs = args;

and then just implement a getter that will return cmdLineArgs. Then to call another constructor:
YourObject x = new YourObject(yourFirstClass.getCmdLineArgs());

(you don't need all those steps if you're calling this other constructor from the main method of course, you can just call the constructor with args directly)


Midpoint between two lines

Question: I have that problem: "Given two secant lines $r,s$ in the plane and a point $P\notin r,s $, find a geometric method for obtain two points $R\in r, \; S\in s $ such that P is the midpoint of $RS$."
I know how to solve this problem analytically with the coordinates of $P$ and the equations of $r,s$, but I have nothing and I should use a geometric method, with "ruler and compass".
Thanks!
Comment: Just intersect $s$ with the symmetric of $r$ with respect to $P$ (or the opposite, $r$ with the symmetric of $s$ with respect to $P$).
Comment: I do not understand the terminology "secant line".
Comment: In some languages, the nomenclature for "intersecting lines" involves a word related to "secant."
Comment: I would say that the lines $r,s$ intersect in one point i.e. $r,s$ are not parallel
Comment: By "secant" line did he mean a "skew" line ?
Answer: Let $Q = r \cap  s$.

Draw the line $QP$ and take point $T$ on $QP$ so that $QP = TP$ i.e. $P$ is the midpoint of $QT$;
Draw the lines $r'$ and $s'$ though point $T$ so that $r'$ is parallel to $r$ and $s'$ is parallel to $s$;
Let $R = r\cap s'$ and $S = s \cap r'$;

The segment $RS$ passes through $P$ and $P$ is its midpoint. The reason for that comes from the fact that by construction $QRTS$ is a parallelogram and as such, the diagonals $QT$ and $RS$ intersect at a common point which is a midpoint for both  $QT$ and $RS$. However, by construction, $P$ is the midpoint of $QT$ so $P$ should also lie on $RS$ and should be its midpoint.
Comment: Thanks you very much! Very clear answer
Answer: Construct the reflection $r'$ of line $r$ through point $P$. (This can be done by selecting any two points on $r$, constructing their reflections through $P$, and then drawing a line through the reflections.) The intersection of $r'$ and $s$ is the required point $S$. Then $R$ is obtained as the intersection of $PS$ and $r$.
This may, depending on how the construction is carried out, be the same answer as Futorologist's, but it gives a different interpretation of the construction.
Answer:
It took me some time to draw the whole picture, so I'm a bit late regarding other answers, anyway here is my step by step solution.
I think credit should go to @Jack D'aurizio who was the quickest to give the hint.
Given lines $(r),(s)$, their intersection point $O$ and a point in the plan $P$ we can:

trace line $(OP)$
trace the circle $(\mathcal C)$ of center $P$ passing through $O$, it intersects $(OP)$ in $O\,'$ which is the symetrical of $O$ with respect to $P$.
it also intersects $(r),(s)$ in respectively $A$ and $B$
trace lines $(AP),(BP)$, they intersect $(\mathcal C)$ again in respectively $A\,'$ and $B\,'$ which are symetrical of $A,B$ with respect to $P$
trace lines $(O\,'A\,')=(r\,')$ and $(O\,'B\,')=(s\,')$ which are symetrical of $(r),(s)$ which respect to $P$
now $R=(r)\cap(s\,')$ and $S=(s)\cap(r\,')$ are the points requested in the question.

The fact the $P$ is middle of $[RS]$ is because by constructing $(r'),(s')$ we have built a parallelogram $(SORO\,')$ and their diagonals in blue $[OO\,']$ and $[RS]$ intersects in their middle.

Midpoint between two lines


Get an error called Uncaught TypeError: Cannot read properties of undefined (reading 'className') className.replace property

Question: I try create a website and i write a function. Whit This fuction Clicking on the icons will change the active icon class. But I get Cannot read properties of undefined (reading 'className') error. I have shared the function below. What do you think is the problem?
This is my function;
function PageTransitions(){
    // Button click activa class
    for (let i = 0; i < sectBtn.length; i++){
        sectBtn[i].addEventListener('click', function(){
            let currentBtn = document.querySelectorAll('.active-btn');
            currentBtn[0].className = currentBtn[0].className.replace("active-btn", "")
            this.className += 'active-btn'
        })
    }
}

What do you think is the problem?
Comment: So clearly `currentBtn[0]` did not find an element. You really should be using classList
Answer: You have no button that is selected so you do not find one and it throws an error. So make sure the element exists before using it. And use classList
const currentBtn = document.querySelector('.active-btn');
if (currentBtn) currentBtn.classList.remove('active-btn');
this.classList.add('active-btn');

Answer: Probably document.querySelectorAll('.active-btn'); returns empty array, because of that your currentBtn is empty and currentBtn[0] is undefined.
This causes currentBtn[0].className to fail


Woocommerce create_product_cat hook has no thumbnail_id / image information attached for product categories

Question: I have written code to hook into the creation of a category on Woocommerce. This code gets me all of the information except the "displayType" and "thumbnail_id". When hooking into the 'edited_product_cat' these fields are present.
My question is if there is a way/code to get the thumbnail_id on creation as well, or if there is a different hook that makes this possible?
Current code looks like the following:
function loader() {
        add_action('create_product_cat', [$this, 'onCategoryCreated'], 10, 2);
        add_action('edited_product_cat', [$this, 'onCategoryCreated'], 10, 2);
}

function onCategoryCreated ($categoryId){
        $cat = get_term_by( 'id', $categoryId, 'product_cat', 'ARRAY_A' );
        $catMeta = get_term_meta( $cat["term_id"] );
        $thumbnailId = get_term_meta( $cat["term_id"], 'thumbnail_id', true );
        $imageUrl = wp_get_attachment_url( $thumbnailId );

        error_log(json_encode($cat));
        error_log(json_encode($catMeta));
        error_log($thumbnailId);
        error_log($imageUrl);
}

which prints out the following for a create:
-> {"term_id":52,"name":"create","slug":"create","term_group":0,"term_taxonomy_id":52,"taxonomy":"product_cat","description":"create desc","parent":0,"count":0,"filter":"raw"}
-> {"order":["0"]}
->
->

and the following for update:
-> {"term_id":35,"name":"update","slug":"update","term_group":0,"term_taxonomy_id":35,"taxonomy":"product_cat","description":"update desc","parent":0,"count":0,"filter":"raw"}
-> {"order":["0"],"display_type":[""],"thumbnail_id":["7"]}
-> 7
-> http://localhost:8888/myWebsite/wp-content/uploads/2021/11/6ac25e82-9d4c-3f59-ad83-a06f7966a0fd.jpg

Comment: Use created_product_cat instead of create_product_cat :)
Answer: Use created_product_cat instead of create_product_cat
function loader() {
        add_action('created_product_cat', [$this, 'onCategoryCreated'], 10, 2);
        add_action('edited_product_cat', [$this, 'onCategoryCreated'], 10, 2);
}

function onCategoryCreated ($categoryId){
        $cat = get_term_by( 'id', $categoryId, 'product_cat', 'ARRAY_A' );
        $catMeta = get_term_meta( $cat["term_id"] );
        $thumbnailId = get_term_meta( $cat["term_id"], 'thumbnail_id', true );
        $imageUrl = wp_get_attachment_url( $thumbnailId );

        error_log(json_encode($cat));
        error_log(json_encode($catMeta));
        error_log($thumbnailId);
        error_log($imageUrl);
}

Comment: This did indeed solve it, stupid mistake. Thank you!


How to interpolate a 3D image with different interpolation methods in python

Question: I am quite new in python. I have a 3D Brain image in NIFTI format (.nii.gz) and I wanna interpolate it with different methods( nearest neighbor, bilinear, Spline, ...) and compare the results. voxel size of image is 1*0.45*0.45 and I wanna make it 0.45*0.45*0.45.
I know It is quite easy task. what i have done and the problems is that: In Scipy the functions only get points but here I have an Image. and the functions which are available to get input as image, only work for 2D images. Do you have any Solution?
Comment: Have a look at [`scipy.reference.ndimage`](https://docs.scipy.org/doc/scipy/reference/ndimage.html) (maybe [`scipy.ndimage.zoom`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.zoom.html)?)
Answer: Here you go:
<code>def rescale(data,affine):
    #compute rescaling coef
    original_resolution = [abs(affine[0,0]),abs(affine[1,1]),abs(affine[2,2])]
    target_resolution = [0.45,0.45,0.45]
    rescaling_coef = np.divide([float(i) for i in original_resolution],[float(i) for i in target_resolution])

    # X and Y dimension
    data = skimage.transform.rescale(data, (rescaling_coef[0],rescaling_coef[1]), order=1, preserve_range=True)
    # Z dimension
    #flip axes first
    data = np.swapaxes(data,0,2)
    data = skimage.transform.rescale(data, (rescaling_coef[2],1), order=1, preserve_range=True)
    data = np.swapaxes(data,0,2)

    return data, rescaling_coef
</code>


Partial Class Confliction in Asp.NET MVC

Question: I have a Data Models--created by Linq2SQL Class Diagram tool--in another assembly (Class Library Project) and I created another one
Here it is:
public partial class Customer : INotifyPropertyChanging, INotifyPropertyChanged
{

    private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
    private int _ID;
    private string _FirstName;
    private string _LastName;
    private string _Email;
    private System.DateTime _DOB;
    private string _PhoneNumber;
    private bool _Activated;
    private bool _Suspended;
            //..
}

In my Web Project, I created another one with the same name as partial:
  public partial class Customer
  {
    //It will have MetadataTypeAttribute for validation.
  }

I am using same namespace for them so they should be fine however, when I make View as Strongly typed using Customer object:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Customer>" %>

I get this error:

[System.Runtime.CompilerServices.CompilerGlobalScopeAttribute()] Line
  184:    public class views_register_registrationformcontrol_ascx :
  System.Web.Mvc.ViewUserControl {

Detailed Error Screen Shot: https://i.stack.imgur.com/SlZ4p.png
Answer: The problem is that you cannot have partial classes across multiple assemblies:
Check this answer
Is it possible to have two partial classes in different assemblies represent the same class?
Comment: Well I think this is the answer. Thanks.


Back propagation neural network data input advice

Question: I am currently doing a project which involves pothole detection and neural networks. So far, I have an Android phone that reads Accelerometer readings and writes the X,Y,Z Axis aswell as the Amplitude and current timestamp into a CSV file. The data is then normalized using min-max normalization and uses the Y axis readings from the CSV file. The problem I am facing for the neural network to learn a pothole is the fact that what data should I feed to the Back Propagation Neural Network? Shall I set a threshold and when the Y axis reaches this point, get the 5 previous points and 5 points after and then feed the network with 11 inputs? I don't want to overtrain the network nor feed it with data in different positions each time.
Training - I am also starting to gather the data collected and create a training dataset - should I put things such as readings for normal/bumpy roads/speed bumps as well as potholes? How large should a training set be? or is 'the more data the better it is' actually true?
This is what the pothole data looks like.

This is how the speedbump data looks like.

A sample of the data collected:
<code> X-Axis     Y-Axis    Z-Axis   Timestamp

-0.371827, 8.513097, 5.441484, 165401
-0.601749, 7.976613, 5.326523, 165601
-0.333506, 8.053253, 5.441484, 165801
-0.256866, 8.206534, 5.364844, 166001
0.049697, 8.398136, 5.364844, 166202
-0.371827, 8.436457, 5.211563, 166400
-0.256866, 8.551417, 5.709726, 166601
-0.256866, 8.513097, 5.403164, 166801
-0.333506, 8.474776, 5.709726, 167000
-0.563428, 8.628057, 5.594766, 167201
-0.563428, 7.401808, 4.713398, 167402
-1.981280, 5.447472, 4.406836, 167602    POTHOLE
-0.180225, 5.600753, 5.403164, 167800    POTHOLE
-0.984952, 8.053253, 4.445156, 168001
-1.214874, 8.666378, 5.671406, 168201
-0.525108, 7.210207, 3.870352, 168401
-1.138233, 7.286847, 5.824687, 168600
-0.601749, 10.045910, 5.288203, 168801
-0.180225, 8.206534, 5.173242, 169001
0.279619, 7.861651, 5.518125, 169200
0.202978, 8.934620, 5.824687, 169401
-0.065264, 8.321495, 5.364844, 169601
-0.065264, 8.628057, 5.709726, 169800
-0.716710, 8.014933, 5.748047, 170001
-0.141905, 8.513097, 5.441484, 170200
-0.026944, 8.206534, 5.594766, 170401
-0.601749, 8.168214, 5.058281, 170601
</code>
Algorithm
My proposed algorithm is to set a certain threshold such as line 12 on the sample data when the Y axis hits a certain threshold such as <7 then pass the previous 5 points and the 5 points after that to the NN.
Comment: How accurate do you think your simple threshold approach is? That is, is the method of simply looking for extreme Y deviation ( < 7 ) already 90% accurate, say?
Comment: I have several pothole data graphs and the Y axis goes below 7 at all times.  I'm not sure how accurate it is so far since speedbumps can also hit <7 which is why I am using Neural Nets to help for pattern recognition to tell the difference between a pothole and a speed bump.
Comment: On the graphs you've given, what is the X axis? Is it time or x-axis acceleration. The two graphs seem to have  have dissimilar scales?  Out of interest what is the orientation of the accelerometer, is the X axis oriented left/right across vehicle and the Y front to back, with Z vertical?
Answer: Given your comment, I am guessing that what distinguishes a pothole from a speed bump is largely the vehicle's speed going into the event. I think your idea of looking for outlier Y positions and then passing a surrounding window of data is a great place to start. What this means then is that your training data set will have to have 11 values for each known pattern you have.
If your neural network library has a softmax activation function for the output layer, you can perhaps use a single network to learn and identify potholes, speedbumps, and normal roads.
Alternatively, you can train two separate networks: one network would learn/identify good vs potholes, the other good vs speedbumps. Each new pattern would be given to both networks and you'd consider the output pairs (ideally [0,1] or [1,0]).
As for how large the training set needs to be, start small (e.g. 10 examples of each case), assess out of sample accuracy (so you'll need to reserve some additional known patterns as a hold out set), and then iteratively improve by adding more training patterns and/or changing the network layout and optimization settings. If you happen to be coding this in Python, PyBrain has some nice example documentation.
Answer: I'll address your question about the amount of training data.
You seem to have a 2 or 3 class classification problem, does this instance of data belong to pothole, speedbump or perhaps normal road.
Given a finite number of samples, you want to have an estimate of the accuracy of your prediction algorithm. To make this estimate you need to reserve some samples that your algorithm has not been trained on and on which you can measure the accuracy of the classification algorithm you have produced, this is commonly known as the test set.
The more data you use for training the less is available for testing the algorithm's accuracy. Consequently   variance of the estimate of accuracy on a small test set will potentially be quite high.
In general, a single partition of the data into training and test sets is unlikely to give an unbiased estimate of accuracy.
This is a well trodden path so some standard approaches for producing more reliable estimates exist.
Probably the two most popular are n-fold cross validation, where the whole dataset is partitioned into n disjoint training and test sets. Models are then trained on the training data  and tested on the test data for each of the  n partitions. Typically n is set to 10, the resulting accuracies from the n trials are then average to produce an overall accuracy figure. Cross Validation.
The second method is repeated hold out, where all the data is randomly  partitioned in to two parts, typically 50%/50%, models trained and then tested. Then the resulting accuracies are averaged.
If you are't familiar with them already, toolkits like WEKA  or R will have methods for estimating these accuracies and for building neural network and other models ready for you to just use out of the box.
Once you've decided on you're approach to subsampling the time series data you might want to consider comparing performance of other modeling approaches such as random forests or Generalised Linear Models ( GLMs ) which require very little tuning in comparison to neural networks and can give very good performance. A toolkit such as WEKA will make this very easy to experiment with alternate algorithms.WEKA.
I'm not sure if the other samples in your data support these observations, but one would imagine that a pothole would be characterised by a sharp negative z axis acceleration ( z-axis aligned perpendicular to the road surface )followed by a sharp positive z axis acceleration with little time inbetween. A speed bump would be the reverse, sharp +ve z axis followed by sharp -ve z-axis acceleration, with probably a slightly longer duration between the 2 events and a less steep acceleration profile. For the speed bump, the timing of the accelerations will be dependent on the profile of the bump, some have long plateaus, do you have information on the type of humps the data is from?
As you suggest there may well be an accompanying deceleration (in the  y-axis, orientation front to back of car ? ) in the case of the speed hump as the driver may have been aware of it and slowed accordingly.
This is less likely in the case of a pot hole, but not unknown.
In selecting the region of the time series to use for training you might want to combine the likelihood of the driver decelerating with the z-axis acceleration profiles for the two types of road obstruction to help you choose good regions. It seems likely that framing the correct samples consistently will significantly increase accuracy.
Answer: Not as much as an answer but a question first.  I take it the car in the resting state segment is the baseline averaged with your "bumps" potential.  I had a problem in anaysing evoked potential data where artifacts, or worse "missing data", were present. SPSS would assign 0 to missing data and bmdp just did a general mean average, therefore with assistance from the math guy in the department we / he designed an algorithm of a zero to next peak analysis. It was not that simple, but pretty close.  I will check back later this may not be applicable to your situation.
Comment: Welcome to the site, @LX_Gould. We appreciate your help with answering questions here. You may want to read our [FAQ](http://stats.stackexchange.com/faq), which contains information on site policies & how to best help with answering questions.


increasing and one one function

Question: If we are given a function f(x)=$x^3$$+$$3x$ for all x belong to real number .
Now as the derivative of function is always positive so the function should be increasing function and if it is always increasing function then it should be one one function also .
But when i tried , I got different result . Why ?
my try is on  https://i.stack.imgur.com/J28rp.jpg
Comment: Sorry , I cannot post image as I don't have enough reputations
Answer: You obtained a contradiction because you put $x_1=x_2$ into the equality AFTER you divided it by $x_1-x_2$ !

increasing and one one function


Show that $G$ = $(\mathbb Z_3 × \mathbb Z_4, +)$ is cyclic

Question:
Let $G$ = $(\mathbb Z_3 × \mathbb Z_4, +)$ with the operation defined somewhat like vector
  addition: for $a, a'$ ∈ $\mathbb Z_3$ and $b, b'$ ∈ $\mathbb Z_4$,
$(a, b) + (a', b') = (a +_3 a', b +_4 b')$. For example, $(2, 2) + (1, 3) = (0, 1)$.
Show that $G$ is cyclic.
Note: convince yourself that G is indeed a group and that $|G| = 12$.

I know that for $x$ in $G$, the smallest subgroup of $G$ that contains $x$ is $\langle x \rangle = \{\ldots,x^{-3},x^{-2},x^{-1},1,x,x^2,x^3,\ldots\} $
And so we say $G$ is cyclic if $\langle x \rangle$ = $G$ for some $x$.
And \begin{align}\mathbb Z_3 × \mathbb Z_4 &= \{(0,0),(0,1),(0,2),(0,3),(1,0),(1,1),(1,2),(1,3),(2,0),(2,1),(2,2),(2,3)\}\\ &= \mathbb Z_{12}\end{align}
But how can I apply this definition in my problem? I mean in my case, do I have to show that $\langle(a +_3 a', b +_4 b')\rangle$ = $G$? And if so, how do I do that? Any help please?
Answer: Hint: What is the order of $([1]_3, [1]_4)$ ?
Comment: Please don't downvote perfectly appropriate answer.
Comment: I know that it has to be of order $12$, because $(1,0)$ has order $3$ and $(0,1)$ has order $4$. But how can I show that $(1,0)$ has order $3$ and $(0,1)$ has order $4$?
Answer: you can see that, $Z_3\times Z_4=<(1,1)>$
Comment: why is it so? and how can this help me?
Comment: use definition of cyclic subgroup generated by an element, $$
Comment: and how can I find <$(1,1)$> ? I don't know how to apply the definition having 2 components  which are 1,1
Comment: Let $x=(1,1)$. Let $d$ be its order. Then $d\mid 12$ sicne the order of the group is 12. If $d$ was less than $12$, you can see that you would have either $x^3=0$ or $x^4=0$ (exercise, tell me if you have a problem with this). But neither is true, $x^3=(0,3), x^4=(1,0)$. Therefore, $d=12.$
Comment: I know that $(1,1)$ has to be of order $12$, because $(1,0)$ has order $3$ and $(0,1)$ has order $4$. But how can I show that $(1,0)$ has order $3$ and $(0,1)$ has order $4$?
Answer: Try to show that your group is generated by $(1,1) \in G$, i.e. $G = \langle (1,1) \rangle$.
The group $\langle (1,1) \rangle$ consists of all multiples (we have additive groups here) of $(1,1)$. Thus, if you want to work very elementary, you can just compute them:
$2(1,1) = (2,2),\; 3(1,1) = (0,3),\; 4(1,1) = (1,0)$, ...
Just pay attention that you are using the addition mod $3$ in the first argument and mod $4$ in the second arguement. You will manage to get all elements from your group $G$ in that way, which shows that $G \subset \langle (1,1) \rangle$. As we also have $\langle (1,1) \rangle \subset G$, we have an equality, such that $G$ is cyclic.
Comment: yes, thank you, I get that. but how can I show that $(1,0)$ has order $3$ and $(0,1)$ has order $4$? And hence $(1,1)$ would have order $12$
Comment: Just compute the mulitples of $(1,0)$ and $(0,1)$. Then you will see that the smallest positive number $m$, such that $m(1,0) = (0,0)$ will be $3$ and respectively $4$ for $(0,1)$. That just relies on the orders of $1$ in $\mathbb{Z}/3\mathbb{Z}$ and $\mathbb{Z}/4\mathbb{Z}$.


Questions regarding equinumerousity

Question: If $f:A \to B$ and $g:C \to D$ are one-to-one, onto functions, $A$ and $C$ are disjoint, and $B$ and $D$ are disjoint, then $f \cup g$ is one-to-one, onto function from $A \cup C$ to $B \cup D$.
Intuitively, I understand what the question asks for, since that both pairs $A$ and $C$, $B$ and $D$ are disjoint and their respective functions are one-to-one and onto, it is logically that $f \cup g$ is one-to-one, onto too. But I don't know how to put the proof in right words.
To prove that $f \cup g$ is one-to-one means that to show it is not the case that $(f \cup g)(a_1) = (f \cup g)(a_2)$ and $a_1$ not equal to $a_2$, but other than stating this, I don't know how to continue the proof. Please provide some hint or guides.
I am currently studying Daniel J. Velleman's brilliant book: How to Prove It. But I am not quite able to follow it for I have scanty knowledge regarding set theory, especially for the later chapters. Hope anyone here can provide some other book for references. Thanks in advance.
Answer: I'll continue from where you left off:
Suppose $(f \cup g)(a_1) = (f \cup g)(a_2)$. Since $B$ and $D$ are disjoint, it follows that $(f \cup g)(a_1)$ and $(f \cup g)(a_2)$ are either both in $B$ or both in $D$. Without loss of generality, suppose they are both in $B$. Then $a_1$ and $a_2$ are in $A$. Since $f: A \to B$ is one-to-one, $a_1 = a_2$.
You can do something similar for onto. Good luck!
Answer: Define $f\cup g:A\cup C\rightarrow B\cup D$ as follows
$$(f\cup g)(x)=
\begin{cases}
f(x), & \text{if }x\in A \\
g(x), & \text{if }x\in C
\end{cases}$$
Now you can use the bijectivity of $f$ and $g$ and the disjointness of the sets to argue the bijectivity of $f\cup g$.
Note that $f\cup g$ is also well defined because $A$ and $C$ are disjoint

I'll do surjectivity.
Take $y\in B\cup D$. Then either $y\in B$ or $y\in D$ but not both since $B\cap D=\emptyset$.
If $y\in B$ then there exists a unique $a\in A$ such that $f(a)=y$ by the bijectivity of $f$. Hence $(f\cup g)(a)=y$ by definition.
The argument for $y\in D$ is analogous.
Comment: So the complete proof for injectivity will be(with reference to @hlf guide): Suppose (f∪g)(a1)=(f∪g)(a2), then (f∪g)(a1) and (f∪g)(a2) are either both in B or both in D. WLOG, suppose they are both in B, then f(a1)=f(a2) so a1=a2 by bijectivity of f.
Comment: Indeed. That is how to proceed.

Questions regarding equinumerousity


A question about prime ideals in the ring of continuous functions

Question: Let $R$ be the ring of continuous functions on $[0,1]$ and let $I=\{f \in R\mid f(1/3) = f(1/2) = 0\}$. Then $I$ is an ideal but is not prime.
Please help me prove this, thank you.
Comment: Why do you want other people to do your homework? You have already asked about 4 homework questions in just a few hours and haven't even mentioned why you're having problems with the exercises.
Comment: Basically you're just posting all of your homework problems and asking "Please do my homework for me". That does not seem very nice of you. The people in here are using their time to help others and to learn, but you need to do your homework by yourself. There are some other persons who actually ask homework problems after having tried them, but this does not seem to be the case with you.
Comment: Dear user8917, I'm closing this question for now; please see the FAQ for how to ask a homework question.
Comment: I have tried it out, but the steps which I have aren't so good
Comment: This is what I have so far: If f, g are elements of Ideal I, and h an element R, then (hf - g)(1/3) = 0 and (hf-g)(1/2) = 0, and I is an ideal.
Comment: However, I don't know how to show that I is not prime
Comment: @user8917: If you know what a *prime ideal* is, you just have to check $I$ satisfies the definition. **Hint**: Use the *zero-product rule*.
Comment: Is this really tooo localized!
Answer: Hint: Let $f$ and $g$ be elements of $I$. What is $(f+g)(1/3)$? How about $(f+g)(1/2)$? How about for $hf$ instead of $f + g$, where $h$ is an arbitrary function in $R$?. You should be able to use this information to show that $I$ is an ideal.
As for proving that the ideal is not prime, note that $f\in R$ only if $f$ vanishes at both $1/2$ and $1/3$. Try to think of two functions $f,g\in R$ such that this is true for $fg$ but not $f$ or $g$.


O que está errado no código javascript?'

Question: Estou tentando fazer com que o código calcule a area e o perímetro de um retângulo, alguém pode me dizer onde estou falhando.
let retangulo = {
    largura: parseInt(prompt('Informe a largura do retângulo:')),
    comprimento: parseInt(prompt('Infomr o comprimento do retângulo'))
}

function calcularArea(){
    let aera;
    area = largura * comprimento;
    return area;
}

function calcularPerimetro(){
    let perimetro;
    perimetro = 2*(largura + comprimento)
    return perimetro;
}

Comment: Qual o erro que estás tendo? O código parece ok...
Answer: Você está usando variáveis que não existem, que na verdade são propriedades de um objeto. Idealmente, passe o objeto como parâmetro e acesse a propriedade do objeto. Assim:

let retangulo = {
    largura: parseInt(prompt('Informe a largura do retângulo:')),
    comprimento: parseInt(prompt('Infomr o comprimento do retângulo')),
}

function calcularArea(rect){
    return rect.largura * rect.comprimento;
}

function calcularPerimetro(rect){
    return 2*(rect.largura + rect.comprimento)
}

console.log(calcularArea(retangulo))
console.log(calcularPerimetro(retangulo))


How to decide the "Par" for each hole

Question: How is the "average number of strokes" decided for each hole?
While watching golf competitions, the majority of players are far below the par.
Shouldn't it then be adapted? If 90% of players are doing an eagle on a Par 5, why isn't it converted to a Par 3?
It should work as long as you don't try to compare from year to year if there has been a change in-between.
Answer: The par for a hole is primarily based on the length of the hole, but other factors can also affect its value; most noticeably the type of terrain and any potential obstacles (water, hills, buildings etc). Wikipedia article for Par
The USGA lays out the following guidelines for par computation;

To quote their advice on par computation;

Yardages for guidance in computing par are given below. The effective playing length of a hole for the scratch golfer determines par. (See Section 13-3b.) These yardages may not be applied arbitrarily; the configuration of the ground and the severity of the obstacles should be taken into consideration.
Authorized golf associations are empowered to adjudicate questions of hole par. (See Decision 16/1.)
Comment: Holes can also be less than the recommended yardage for a particular par. This is less common than a longer par, but can happen when a hazard, dogleg or fairway feature makes the "ideal" shot for the given distance unwise. For instance, take a 460-yard level hole with a nice big pond across the entire fairway from 260 yards to 320. The ideal tee shot for 460 yards would be a nice long drive (275 or better), but to make that work here your drive better *carry* 320+ yards in the air. Instead, the smart play is the 3-wood for two shots and a wedge to approach, making it a par-5.
Comment: Of course, PGA Tour events often exceed the guidelines. See the [528-yard par 4](http://tourreport.pgatour.com/2011/05/26/longest-par-4s-on-pga-tour/) for instance.
Answer: I worked on a golf app many years ago that helped map out courses in the midwest region and offer golfers help on the course - and for them to see the holes on their phone.
We had TONS of statistical data available to us and actually had a pro that was also a stats major and he found some really interesting things.

length of the hole is not a great indicator for difficulty.  There was very little correlation.
most courses (not all) based their par based on what someone who shoots 75-80 would average on that hole.  If a hole had a lake to shoot over for example, you could have a par 4 that was 265 that averaged 4.9 because there was such a severe penalty for going in the water.  Same for bunkers, tight fairways, lots of trees and so on.  Probably the reason that you see so many pros do well compared to par on some courses is because they have the ability to hit over the obstacles or not bad enough to hit into them.  If joe average players that averages a 78 and loses 4 strokes per 18 because of these things, that is quite an advantage on par for the pro golfer.
"pro" courses will usually rate their courses based on a scratch golfer.
par ratings mean almost nothing.  We got data on over 1000 golf courses and the average scores ranged from 79-84.  If you can shoot a 75 on one course consistently but only an 81 on another, it probably has more to do with the first course having easier holes than your performance there.
the two most heavily correlated factors that we had for a holes difficulty (par rating) was the size of the green and the slope of the green.  It wasn't even close.   You could probably create a par 5 that was at 180 yards with a 15 foot green that had a 30 degree slope and it might average well over 5.
courses want to have 18 holes work out to 70-72.  If they have a course estimated out at 67 they can try to make some holes harder or just bump up three holes.  There is nothing governing this.
some courses cater to good scores to drive business.  I always play a local course once a year that sucks but is really easy just so I can see the 80s.

Note: I am just a guy that saw a lot of data.  I am sure someone with more golf knowledge could clarify how they deduce holes at nice courses.  I am sure it has just as much to do with marketing as it does with taking statistical analysis.

How to decide the "Par" for each hole


custom validation with javascript in mvc3

Question: I'm new to MVC3. I have problem in custom validation, for example
In my BasicInfoViewModel.cs,
[Required]
    [Display(Name = "State", ResourceType = typeof(Resources.Global))]
    public string State { get; set; }

    [Display(Name = "City", ResourceType = typeof(Resources.Global))]
    public string City { get; set; }

In my BasicDetailsView.cshtml,

@Application.Resources.Global.State
 @Html.DropDownListFor(m => m.State, (List<SelectListItem>)ViewData["State"])

@Application.Resources.Global.City
@Html.DropDownListFor(m => m.City, (List<SelectListItem>)ViewData["City"])

If the state property returns true, then only "City" is required. If not, City is not required, then the textbox should be diabled.
I'm not using EditorFor, using DropDownListFor because i'm using plain html. Can anyone help me to solve this issue?
Thanks...
Comment: `I'm not using EditorFor, using TextBoxFor` - Where is this `TextBoxFor`? I can't see it in the code you have shown. All I can see is 2 dropdown lists (which by the way are wrong because you are using the same property name for both the value and the items).
Comment: @DarinDimitrov, corrected. How can we do this?
Comment: @DarinDimitrov my ViewData["city"] has a collection of SelectItem which has a different id, value for each.
Comment: But then you should not use `City` as first argument of your DropDown. Or rename the value in your ViewData to `ViewData["cities"]`.
Answer: MVC Foolproof is a set of validation data annotations that extend the existing ones and provide additional functionality. For example the [RequiredIfNotEmpty] attribute from this package is quite suitable for your scenario as it allows for conditional validation.
[Display(Name = "State", ResourceType = typeof(Resources.Global))]
public string State { get; set; }

[RequiredIfNotEmpty("State")]
[Display(Name = "City", ResourceType = typeof(Resources.Global))]
public string City { get; set; }

Now the State property is optional. But if it has some value then the City property is required.
Answer: You might want to look at RequiredIfAttribute. To make your city dropdownlist disabled - use jquery. For checking if data is valid you have js method $("selector").valid() which returns 0 or 1 and also shows validation message for specified field


How to reformulate this model in standard form?

Question: How to reformulate the following linear programming model into an equivalent model that is a linear program in standard form?:
Maximize $-e^T |x|$
subject to $Ax \geq b$
x unrestricted
where e = (1, 1,...,1)
and |x| = abs(x)
Standard form in this case would be:
$min_x$ $c^Tx$
Ax = b
x $\geq$ 0
Comment: Suppose you have $4$ (decision) variables is then your objective function $-|x_1|-|x_2|-|x_3|-|x_4|$?
Comment: I guess so, I also find it an odd formulation. It is mainly about the formulation. I have a hunch that the absolute value in the objective can be exchanged with the $\geq$ in the standard form.
Answer: You can tranform the variables $|x_j|=x_j^++x_j^-$ and $x_j=x_j^+-x_j^-$ , with $x_j^+,x_j^-\geq 0$
For 2 decision variables and 2 constraints we get
$\texttt{max} \ \ -x_1^+-x_1^--x_2^+-x_2^- $
$a_{11}\cdot \left( x_1^+-x_1^-\right)+a_{12}\cdot \left( x_2^+-x_2^-\right)\geq b_1$
$a_{21}\cdot \left( x_1^+-x_1^-\right)+a_{22}\cdot \left( x_2^+-x_2^-\right)\geq b_2$
$x_1^+,x_1^-,x_2^+,x_2^-\geq 0$

Maximizing $f(\textbf x)$ is equivalent to minimizing $-f(\textbf x)$
And we have to subtract surplus variables ($s_i$) for each
$\geq$-constraint to get equations.

$\texttt{min} \ \ x_1^++x_1^-+x_2^++x_2^- $
$a_{11}\cdot \left( x_1^+-x_1^-\right)+a_{12}\cdot \left( x_2^+-x_2^-\right)-s_1=b_1$
$a_{21}\cdot \left( x_1^+-x_1^-\right)+a_{22}\cdot \left( x_2^+-x_2^-\right)-s_2= b_2$
$x_1^+,x_1^-,x_2^+,x_2^-,s_1,s_2\geq 0$
This is what you wanted.
Comment: You also need $s_i \ge 0$.
Comment: And subtract $s_i$ instead of adding.
Comment: @RobPratt 100% right. No idea why I´ve witten it this way.
Comment: Looks good now.
Comment: what would be a numbered example?
Comment: / for $^+_1,^−_1,^+_2,^−_2,_1,_2$
Comment: Just replace the coefficient by some numbers. For instance: $a_{11}=1,a_{12}=2,a_{21}=3,a_{22}=1, b_1=-1, b_2=7$
Comment: but are $x^- and x^+$ opposites, like -4 and +4?
Comment: Not really. One of them will be $0$ at the optimal solution. Note that both are non-negative. If the solution is $x^{-}=4$ and $x^{+}=0$ then $x=-4$


How to process SharePoint 2010 publishing page content before rendering?

Question: In SharePoint 2010 is there a way to process the content of a Publishing Page before it is displayed? I would like to use "shortcodes" (eg: [tab], [accordion]), in the content, then parse it into html before it is rendered to the page.
Answer: This site may point you in the right direction. He created a master page with a code behind.  You could possibly creaet a custom publishing page with a code behind file that alters the contents of your page.


Uniqueness of canonical conjunctive normal form

Question: Could someone explain me why is there for each formula one and only one equivalent canonical conjunctive normal form? Like, I understood how to derive one by using the truth tables but I'm still asking myself how to prove this statement in a formal way.
Answer: Think about it this way: two statements are equivalent if and only if they have the same truth table, and there is exactly one canonical conjunctive form for every truth-table.
It follows that there is exactly one canonical conjunctive form that is equivalent to a given statement.
The key then, if you want to prove it formally, is to do the following two things:

for an arbitrary truth-table, find a canonical conjunctive normal form with that truth table
given that two canonical conjunctive normal forms have the same truth table, show that the expressions must be identical.
Comment: thanks, it makes a lot of sense!
Comment: @Omnomnomnom, can I convert two boolean expressions into their canonical SOP/POS form to prove their equivalence? If canonical form is unique they should match, right?
Comment: @Samik correct.${}{}{}$
Comment: @Omnomnomnom - Do you have a reference for the uniqueness? It seems to me [this post](http://cs.stackexchange.com/q/55182/21921) contradicts the uniqueness. What am I missing? Thanks in advance!
Comment: I don't see how the first is in CNF
Comment: Thanks for your answer! I haven't been alerted and saw it by chance. (It might be more prudent to use the @ sign.) If I understand correctly, you're saying that you don't see how $A\land B$ is in CNF. This is the fourth example in [this Wikipedia subentry](https://en.wikipedia.org/wiki/Conjunctive_normal_form#Examples_and_non-examples).
Comment: You can also look at [this WolframAlpha link](http://www.wolframalpha.com/input/?i=A+and+B&rawformassumption=%7B%22C%22,+%22A%22%7D+-%3E+%7B%22Variable%22%7D&rawformassumption=%7B%22C%22,+%22and%22%7D+-%3E+%7B%22MathOperator%22%7D).
Comment: @Pierre-YvesGaillard my apologies for leaving it out the @. In any case, it seems that (according to your links) I misunderstood the definition of CNF back when I answered this; my understanding was that the CNF was necessarily was expanded to include all "maxterms".  That is, I would have said that $A \wedge B$ is in *a conjunctive form* but not in *the canonical conjunctive form* as neither $A$ nor $B$ are maxterms.  That is, was thinking of CCNF, i.e. [canonical conjunctive form](https://en.wikipedia.org/wiki/Canonical_normal_form).
Comment: @Pierre-YvesGaillard in fact, looking at the question, he is indeed asking specifically about the *canonical* CNF, so I was accidentally right.
Comment: @Pierre-YvesGaillard It is well known that CNFs are not unique.  In fact, the problem of finding a *minimal* CNF (i.e. with the fewest terms) is important in electrical engineering and can be solved using [Karnaugh diagrams](https://en.wikipedia.org/wiki/Karnaugh_map).
Comment: I also missed the "canonical". Sorry! Now everything is clear. Thanks!


Proving that $N,K,O$ are collinear.

Question: Consider the square with centre $O$ below: $X$ is a point chosen on $AD$ and a circle is inscribed in $\Delta ABX$. $N,K$ are the tangent points. Prove that $N,K,O$ are collinear.

My try:
I have chosen points $E,F$ on $AD,BC$ such that $AN=DE=CF$ and I created a rectangle $EFGN$ shown below. Obviously $O$ is the Centre of square and rectangle. It is enough to prove that $NK$ extended passes through $O$. I started with contradiction that let $NK$ does not pass through $O$, so let $NK$ extended meets $BC$ at $T \ne F$ and $EG$ at $R$.

Any help from here?
Answer:
Extend $NO$ to intersect $BC$ at $M$. Note that $NO$ might not pass through $K$ at this point. Connect $AC$, which passes through $O$. Label point $L$.
Since $CM=NA=AL$, we have $BM=BL=BK$. Also since $XN=XK$ and $\angle NXK=\angle KBM$ we have isosceles triangles $NXK$ and $KBM$ similar (connect $NK$ and $KM$ here) and the linearity of $N,K,M$ follows which implies linearity of $N,K,O$.
Answer:
We can prove that $N, K, O $ are collinear by showing that $\angle NKB+ \angle BKO=180^o$
Proof:
Note that $O_1$ is the in-center of $\Delta ABX$.
We can assume that $\angle YBO_1= \angle KBO_1=\alpha$
$\therefore \angle AXB=90^o-2 \alpha$ and $\angle HXK=45^o-\alpha$
$\because \angle XHK=90^o$
$\therefore \angle NKB = 90^o+45^o-\alpha$
$\color{red}{ \angle NKB = 135^o-\alpha}$ ----- (1)
Next we consider $\angle BKO$.
$\because \angle O_1KB=90^o$ and $\angle O_1OB=90^o$
$\therefore \angle O_1KB = \angle O_1OB$
Hence $O, K, O_1, B$ are concyclic.
$\therefore  \angle BKO= \angle OO_1B$
But $\angle OO_1B=45^o+\alpha$
$\therefore \color{red}{\angle BKO=45^o+\alpha}$ ---- (2)
(1) and (2) $\implies $$\angle NKB+ \angle BKO=180^o$
Hence $N, K, O$ are collinear.

Proving that $N,K,O$ are collinear.


React Native - How to set blurRadius onto a selected image

Question: My app displays images and other info getting data from a JSON, and I want to set a blurRadius on the selected image when the unblur function is called.
My code is the following:
const [blur, setBlur] = useState(160);
const unblur = () => {
if(blur == 160){
    setBlur(0);
}
}

{isLoading ? <ActivityIndicator/> : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
    <>
    <Text style={{ textAlign: "left", color: 'white', fontSize: 24 }}>
        <Image style={{ alignSelf: "center" }} source={{uri: item.profile_picture, width: 48, height: 48}} />
        {item.username}
    </Text>
    <TouchableOpacity onPress={() => unblur()}>
        <Image style={{ alignSelf: "center" }} blurRadius={blur} source={{uri: item.picture, width: 400, height: 320}} />
    </TouchableOpacity>
    <Text style={{ textAlign: "left", color: 'white', fontSize: 24 }}>
        ID {item.id}
    </Text>
    <Text>
        {'\n'}{'\n'}
    </Text>
    </>
)}
/>
)}

I want to change the {blur} value for a given image when I tap the TouchableOpacity component of the image I want to unblur. Right in this moment when I tap an image, all the images in the list are getting unblurred.
Answer: You should add the blur values inside your items like this. Create a new components called Items. Then, add the blur state inside it. (not inside Main).
const Main = () => {
  if (isLoading) {
    return;
    <ActivityIndicator />;
  }

  return (
    <FlatList
      data={data}
      keyExtractor={({ id }, index) => id}
      renderItem={({ item }) => <Item item={item} />}
    />
  );
};

const Item = ({ item }) => {
  const [blur, setBlur] = useState(160);
  const unblur = () => {
    if (blur == 160) {
      setBlur(0);
    }
  };

  return (
    <>
      <Text style={{ textAlign: "left", color: "white", fontSize: 24 }}>
        <Image
          style={{ alignSelf: "center" }}
          source={{ uri: item.profile_picture, width: 48, height: 48 }}
        />
        {item.username}
      </Text>
      <TouchableOpacity onPress={() => unblur()}>
        <Image
          style={{ alignSelf: "center" }}
          blurRadius={blur}
          source={{ uri: item.picture, width: 400, height: 320 }}
        />
      </TouchableOpacity>
      <Text style={{ textAlign: "left", color: "white", fontSize: 24 }}>
        ID {item.id}
      </Text>
      <Text>
        {"\n"}
        {"\n"}
      </Text>
    </>
  );
};

Also, may I suggest you can use 'onPressIn'. That way, image will unblur when the finger tap the image, not press the image. But that was your decision.


Binomial Coefficients Proof Help

Question: I'm having trouble doing these proofs. So far I've changed the N choose R into its factorial form and have simplified but I'm stuck.
$\left( \begin{array} { c } { n } \\ { r } \end{array} \right) = \frac { n - r + 1 } { r } \cdot \left( \begin{array} { c } { n } \\ { r - 1 } \end{array} \right)$
$\left( \begin{array} { l } { n } \\ { r } \end{array} \right) = \frac { n } { n - r } \cdot \left( \begin{array} { c } { n - 1 } \\ { r } \end{array} \right)$
$n \left( \begin{array} { c } { n - 1 } \\ { r } \end{array} \right) = ( r + 1 ) \left( \begin{array} { c } { n } \\ { r + 1 } \end{array} \right)$
Comment: Just use the definition: [Binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient)
Answer: You have the well-know formula
$${n\choose k} = \frac{n!}{k!(n-k)!}$$
So, for the first equality :
$${n\choose r} = \frac{n!}{r!(n-r)!} = \frac{n! \times (n-r+1)}{(r-1)! \times r \times (n-r+1) !} = \frac{n-r+1}{r} {n \choose r-1}$$
You can do the two others in the exact same way !
Comment: The first formula  is certainly not by definition. It requires a proof.
Comment: You are right that it is not the most elegant way to define binomial coefficients ; but I guess that anyone who knows binomial coefficient knows this formula.
Comment: Sure, but saying it's a well-known formula would be more accurate.
Comment: Ok, I edit my answer then !
Answer: $\frac{n-r+1}{r}\binom{n}{r-1}=\frac{n-r+1}{r}\frac{n!}{(r-1)!(n-r+1)!}=\frac{n!}{r(r-1)!(n-r)!}=\frac{n!}{r!(n-r)!}=\binom{n}{r}$
That was the first identity. Can you do the other two now? Exactly the same idea.

Binomial Coefficients Proof Help


Viewing the loopback interface on Solaris 10 (using snoop or another tool)

Question: I am trying to use snoop on solaris 10 to detect traffic between a client and server both located on my machine.  Question: I just want to verify that I should use the loopback interface for this.
So now for the real question.
I have found a few posts that suggest that you cannot use snoop on Solaris to listen to a loopback interface.  Can someone verify this for me.  I have found a few threads that seems to suggest this but most of them are fairly old (see links at bottom).
Has this problem been solved?  Is there a way to listen to a loop back interface on Solaris 10?  (Using snoop or another method.  My assumption is that if snoop will not work something like wireshark will not work either).
This is what I have tried:
% sudo snoop -d lo0

Which results in this:
snoop: cannot open "lo0": DLPI link does not exist

Thanks

Links
http://forums.sun.com/thread.jspa?threadID=5252240
http://firstname.lastname@example.com/msg01860.html
http://www.derkeiler.com/Mailing-Lists/securityfocus/focus-sun/2002-08/0007.html
http://opensolaris.org/jive/thread.jspa?messageID=175240
Answer: I realize that this is an old thread, but in case someone stumbles across it, it is worth noting that this appears to now be possible in Solaris 11:
http://docs.oracle.com/cd/E23824_01/html/821-1453/gexkw.html#gexnc
There is now a '-I' option that allows snoop to work with IP-layer devices.
Comment: It's OK to add information to old questions, especially when it solves the problem.
Answer: The posts are correct, you cannot snoop loopback traffic on solaris.  You can't tcpdump it, you can't wireshark it.  You can't dtrace it.  Many have tried.
OpenSolaris supports it (via the clearview project).
Answer: I vaguely recall some problems with snoop on the loopback interface (something about snoop requiring a real piece of harware which is why you get that DLPI message -- there's no Data Link Provider Interface for loopback b/c it's a virtual device).
You may want to try Wireshark or plain-ol-tcpdump, but you might be out of luck Re: lo0.  As an alternative you could connect one of your physical interfaces to a dead-end hub with nothing else & send your traffic over that interface.
Comment: tcpdump fails with a similar error message. "tcpdump: lo0: No such device exists"  "(lo0: No DLPI device found)"
Answer: https://blogs.oracle.com/seb/entry/observe_loopback_and_inter_zone
Seems like OpenSolaris has this feature (or will)
Answer: I'm no expert in the use of Dtrace, but there may be a way to use it to capture the data.
Answer: i have captured traffic in solaris 10 using Opnet ...
however, you cannot capture from a zone, you must use global zone, unless you are assigning dedicated IO cards to the zones under the global...


Saving a views sql query

Question: I am using Drupal 6, and Views 2.0; I need to create a node where one of the fields is a filterable view. I then need to store the final SQL query of the view in the database.
How would I add the block view to a node creation page?
Comment: Welcome to Drupal Answers. You are describing the basic operation of the Views module. Watch the video series [Taming the Beast](http://%20http://dev.nodeone.se/en/taming-the-beast-learn-views-with-nodeone) to get a handle on how to use views.
Comment: The OP said, "I need to create a node where one of the fields is a filterable view." It doesn't seem that is one of the basic operations of the Views module.
Comment: yes, basically on node/create I would like for the user to "filter" a specified view and when clicking save I would like to store the views sql query. Have you seen this being done before? I could not find any reference to anyhting like this...
Answer: Unfortunately I wasn't able to solve this issue, so I did a little bit of a work around.
What I did was built a content type where the user could specify what data he/she needed by use of a form and fields.
I then took the user input and built a dynamic sql query to output the required data.
Its a pretty dirty way of doing it... but until I find another solution, I'll have to use it.

Saving a views sql query


Errors fitting a Penalized Linear Model in R

Question: I am trying to reproduce the results from this answer in CrossValidated with no luck. I keep getting an error when calling:
print("Fitting Penalized Linear Model")
GLMmodel <- train(X,Y,method='glmnet',trControl=myCtrl,tuneLength=10)

Here is the error:
[1] "Fitting Penalized Linear Model"
Error in { :
  task 1 failed - "arguments imply differing number of rows: 1264, 736"
In addition: There were 50 or more warnings (use warnings() to see the first
 50)

The full code is below:
#Setup
rm(list = ls(all = TRUE))
set.seed(1)

#Generate an input matrix with 10,000 values
#2,000 rows, 5 columns
X <- data.frame(replicate(5, rnorm(2000)))

#Construct Y using X
Y <- runif(1)*X[,1]*X[,2]^2+runif(1)*X[,3]/X[,4]

#Convert Y to binary
Y <- as.factor(ifelse(sign(Y)>0,'X1','X0'))

#Create bootstrap samples for fitting models
library(caret)
print("Creating bootstrap samples")
tmp <- createResample(Y,times = 25)
myCtrl <- trainControl(method = "boot", index = tmp, timingSamps = 10)

#Fit models
print("Fitting Random Forests")
RFmodel <- train(X,Y,method='rf',trControl=myCtrl,tuneLength=1)

print("Fitting SVM")
SVMmodel <- train(X,Y,method='svmRadial',trControl=myCtrl,tuneLength=3)

print("Fitting Penalized Linear Model")
GLMmodel <- train(X,Y,method='glmnet',trControl=myCtrl,tuneLength=10)

print("Fitting Nearest neighbors")
KNNmodel <- train(X,Y,method='knn',trControl=myCtrl,tuneLength=10)

print("Fitting Neural Network")
NNmodel <- train(X,Y,method='nnet',trControl=myCtrl,tuneLength=3, trace = FALSE)

#Assess re-sampled (out of sample) accuracy
print("Assessing re-sampled (OOB) accuracy")
resamps <- resamples(
        list(   RF = RFmodel,
                SVM = SVMmodel,
                GLMnet = GLMmodel,
                KNN = KNNmodel,
                NN = NNmodel
                ))
print("Summarizing resamps")
summary(resamps)

print("Plotting accuracy")
dotplot(resamps, metric = "Accuracy")

#Assess run-time (in seconds)
print("Assessing timings")
resamps$timings

I am relatively new to R so I can't tell what's wrong with that line. Did the package GLM change since the time of that post? Is this a possible bug with GML?
For reference. I am running the latest version of R (2.15.2) with the latest stable version of caret (5.15-052)
Comment: The glmnet method for `caret` requires the `glmnet` package.  The `glmnet` package require `Matrix`.  They were probably both installed when you installed caret.  Type `sessionInfo()` to see which versions you are running, and upgrade if needed.
Comment: The above code runs fine for me with `caret_5.15-052`, `glmnet_1.8-5`, `Matrix_1.0-10` and `R-2.15.2` on windows. I will try on my mac later this evening.  I just copied and pasted it into a fresh R session.  Are you doing the same?
Comment: Although, I have to admit I've seen `"arguments imply differing number of rows: ..."` a lot in my caret models recently, and had just chalked it up to sleep-deprivation.  If you figure out the conditions that cause the error, perhaps you'll isolate a bug.
Comment: Hi Zach, yes. I am doing the same. Hmm, I don't think I manually installed `glmnet` or `Matrix`. Are they needed by GLM and not by the other packages? I am surprised it didn't prompt me to install those packages.
Answer: I was missing the package glmnet. The error message:

Error in { :
  task 1 failed - "arguments imply differing number of rows: 1264, 736"
In addition: There were 50 or more warnings (use warnings() to see the first
 50)

misled me to think there was problem with the input, not that I was missing a package.


VPN laptop as proxy gateway for Intranet computers truss bridge/bypass

Question: I have a Windows 7 Enterprise VPN laptop to access my client's VPN network. During VPN session the laptop can not accept any request from my Intranet even if I open any door using Windows Firewall Inbound Rules. However, during VPN session the laptop can connect anywhere inside my Intranet using direct local IP:port.
Here's the thing:
I want to use my client's VPN laptop as a proxy for other non-VPN computers inside my Intranet.
Installing a proxy didn't work since other Intranet computers can not access any port during VPN session on the VPN laptop. Is there any kind of proxy tunneling with server/client support in Windows, Java or Linux?
I was thinking some kind of app in the VPN laptop connecting to one of my Intranet's PCs, then use this PC as a proxy server and forward requests from Intranet to VPN.
Do I make sense? Is there something ready to use?
Comment: Talk with your client. It's likely they configured their VPN this way for a reason.
Comment: For sure they did! But still I need more access :)
Answer: Your scenario describes the exact use case for SSH with reverse gateway port forwarding. Here's one possible example of its implementation:
1) Setup a Linux computer on your intranet and install OpenSSH server there (IIRC, it must be fresh enough to support SSHv2).
2) Configure SSHd to enable gateway ports by setting line "GatewayPorts yes" in /etc/ssh/sshd_config. Don't forget to restart sshd.
3) Install PuTTY SSH client to your VPN laptop.
4) To enable connection to particular port $Port of VPN laptop from other intranet computers, create a tunnel by running this command on VPN laptop:
putty $LinuxIP -R $Port:localhost:$Port -N
Your Linux gateway will listen on the first port from -R option then forward it to the second port from -R option of your VPN laptop. In my example both ports are the same for simplicity. -N option prevent putty from running shell after creating the tunnel.
If you need multiple ports to forward, supply multiple -R options in the same format. I also recommend to wrap this command by .BAT script loop to restore the tunnel automatically upon broken network links.
Comment: Thank you Van! Looking forward to test it. I have everything you describe.
Comment: It worked! Van... I Love You! Own you lot of beers :)


Fire ManipulationStarted manually in WP7

Question: I have a webscrollview in WP7, which initially does not have focus ( the content is hittestVisible, therefore takes away the scrollviewers hittestvisibility ). When I set its content's visibility to false, I can scroll the scrollviewer, but only after lifting my finger, and placing it back again. I would really like the focus to shift, and after this re-apply the focus so that I can slide after the scrollview gains focus, not wait for the next manipulationStarted event to fire.
Here is my code:
<UserControl
x:Class="WTFApp.Resources.ViewControllers.DetailedItemContentControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:EiBaseApi.Animation;assembly=EiBaseApi"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
shell:SystemTray.IsVisible="True" >

<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="10"/>
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.Resources>
        <Storyboard x:Name="MediatedListBoxContentAnimator">
            <DoubleAnimation x:Name="MediatedAnimation"
                             Storyboard.TargetName="WebScrollViewMediator"
                             Storyboard.TargetProperty="ScrollableWidthMultiplier" >
            </DoubleAnimation>
        </Storyboard>

    </Grid.Resources>

    <ScrollViewer x:Name="Scroller"
                  HorizontalScrollBarVisibility="Auto"
                  VerticalScrollBarVisibility="Disabled"
                  ManipulationMode="Control"
                  Grid.Row="1"
                  Grid.RowSpan="2" >
        <StackPanel Name="WebScrollView" Orientation="Horizontal">
            <UserControl Name="LeftContentControl"   MinWidth="480" />
            <UserControl Name="MiddleContentControl" MinWidth="480" />
            <UserControl Name="RightContentControl"  MinWidth="480" />
        </StackPanel>
    </ScrollViewer>
    <local:ScrollableItemAnimationMediator x:Name="WebScrollViewMediator"
                                           ScrollViewer="{Binding ElementName=Scroller}"/>
</Grid>

in C#:
protected override void TouchFrameDelta( object sender, TouchFrameEventArgs e )
    {
        if ( UserManipulating == ManipulationState.ManipulationStopped )
        {
            UserManipulating = ManipulationState.ManipulationStarted;
            ManipulationStartingPoint = e.GetPrimaryTouchPoint( null ).Position;
        }
        //if we are already manipulating the scrollviewer, we do nothing
        if ( UserManipulating != ManipulationState.ManipulationStarted )
        {
            return;
        }
        TouchPoint touchPoint = e.GetPrimaryTouchPoint( null );
        float differenceStart = ( float )( touchPoint.Position.X - ManipulationStartingPoint.X );
        if ( Math.Abs( differenceStart ) >= 25 )
        {
            if ( BrowserListIsHitTestVisible )
            {
                BrowserListIsHitTestVisible = false;
                MiddleContentControl.Focus( );
                MiddleContentControl.UpdateLayout( );
                return;
            }

            float differenceDelta = ( float ) ( touchPoint.Position.X - ManipulationDeltaPoint.X );
            if ( touchPoint.Action == TouchAction.Up )
            {
                UserManipulating = ManipulationState.ManipilatingScrollViewCompleted;
                OnManipulationCompleted( differenceDelta );
            }
        }
        ManipulationDeltaPoint = touchPoint.Position;
    }

The TouchFrameDeltais a Touch.FrameReported event.
Does anyone have a n idea why this does not work, and how to fix it?
Thanks in advance
Comment: To clarify, the end goal is to have a horizontally scrolling panel, with the contents being three user controls stacked horizontally?

If so, would the default scrollviewer behavior not work for this (set IsHitTestVisible on the scrollviewer back to true)?
Comment: The problem is, that when I set the IsHitTestVisible, or any other user-input layout change, gets handled after the user releases and replaces their finger. This having something to do with the manipulation started event, I guess. When the browser claims hittestvisibility, the scrollviewer's manipulationstartedevent does not get fired, and only on the next manipulationstarted event will it catch and handle this. So even when I scroll horizontally, update the layout, do all kinds of weird update stuff, the browser is still hittestvisible and remains so until I release and reapply input
Comment: Is it possible to provide the actual xaml that you are using for the page? That way we can try to reproduce the issue more accurately.
Answer: Just to clarify for you, ManipulationStarted (and Completed) cannot be fired manually, as their EventArgs are sealed without any public constructors.
What you're asking for, isn't something I would consider possible. Since your child item doesn't support any interaction initially, the events wouldn't be bubbled down to it, even after you set IsHitTestVisible before you performed yet another event.
I can't see what you're exactly trying to archive here, but messing with scrolling and the WebBrowser is not something I would recommend for 7.0/7.5, as the control have very limited functionality.