primefaces qr code not shown?

Question: I am using primefaces to develop a web app.I am trying to show the bar code on mhe webpage.All coders are shown except the QR code.I have read that two jar files are required for this

barcode4j: 2.1
qrgen: 1.4

I have added these jar files in the lib folder & try running it.In this way i get 404 error when i add qrgen in lib folder.
I tried doing it using maven i added the depedency as follows:
<dependency>
    <groupId>net.glxn</groupId>
    <artifactId>qrgen</artifactId>
    <version>1.4</version>
</dependency>
<dependency>
    <groupId>net.sf.barcode4j</groupId>
    <artifactId>barcode4j-light</artifactId>
    <version>2.1</version>
</dependency>

but i get error for second dependency so i copied the barcode4j in lib folder but i can't print the QR code.please help me out.
code for xhtml
<!DOCTYPE html>

    <h:head>
        <title>login</title>
    </h:head>
    <h:body>

    <h:outputText value="Interleaved 2 of 5" />

    <h:outputText value="Codabar" />

    <h:outputText value="Code39" />

    <h:outputText value="Code128" />

    <h:outputText value="EAN-8" />

    <h:outputText value="EAN-13" />

    <h:outputText value="UPC-A (PNG)" />

    <h:outputText value="UPC-E (Vertical)" />

    <h:outputText value="PDF417" />

    <h:outputText value="DataMatrix" />

    <h:outputText value="Postnet" />

    <h:outputText value="QR" />

    </h:body>

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.prime</groupId>
    <artifactId>primedemop</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>primefaces</name>
    <dependencies>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>5.1</version>
        </dependency>
          <dependency>
        <groupId>net.glxn</groupId>
        <artifactId>qrgen</artifactId>
        <version>1.4</version>
    </dependency>

    </dependencies>![smaple][2]
</project>

Comment: [This question](http://stackoverflow.com/questions/29993696/maven-depedency-not-working-in-primefaces/) specifically resolves the issue around Maven dependencies. What you need to do is 1) Prove that your source code compiles while using libraries from the QR code package and 2) Show us in your source code where you attempt to use these libraries. What we're seeing here doesn't appear to be a problem with the dependency management, but something else. Without the full picture, nobody can help you.
Answer: I guess you're doing all ok.But you missed on one thing.The qrgen-1.4 you are using are further having dependencies as zxing-core-2.0 & zxing-javase trying including these two jar files into your build path these might work well.
Answer: Try:

        <dependency>
            <groupId>io.nayuki</groupId>
            <artifactId>qrcodegen</artifactId>
            <version>1.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces.extensions</groupId>
            <artifactId>barcode4j-light</artifactId>
            <version>2.3.0</version>
        </dependency>

Comment: This depends on the PrimeFaces version you are using. The io.nayuki dependency was added later. It will not work with PF 5.1.
Answer: You should check the dependencies page of the documentation. There you can find which dependencies are needed for the barcode and QR-code to work. Note though that these dependencies will not be the same for each version for PrimeFaces, so make sure to check if the version of the documentation is matching your PrimeFaces version. The link I've added here points to 13.

primefaces qr code not shown?


Getting error `Do you want to add protocol stubs?

Question: I added the ImageView Protocol. What can be done to remove the error

Do you want to add protocol stubs?

CardsViewController
import UIKit

protocol ImageViewProtocol{
    func sendImageToViewController(theImage: UIImage)
}

class CardsViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, ImageViewProtocol {
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var nameTextField: UITextField!
    @IBOutlet weak var locationTextField: UITextField!
    @IBOutlet weak var imageView: UIImageView!

    @IBAction func goToViewController2Action(_ sender: Any)
    {
        let viewcontroller2 = storyboard?.instantiateViewController(withIdentifier: "viewController2") as! ViewController2
        viewcontroller2.delegate = self
        self.navigationController?.pushViewController(viewcontroller2, animated: true)
    }

    func chooseImagePickerAction(source: UIImagePickerController.SourceType) {
        if UIImagePickerController.isSourceTypeAvailable(source) {
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.allowsEditing = true
            imagePicker.sourceType = source
            self.present(imagePicker, animated: true, completion: nil)
        }
    }

    @IBAction func saveButtonPressed(_ sender: UIBarButtonItem) {
        if nameTextField.text == "" || locationTextField.text == "" || textField.text == "" {
            print("Not all fields are filled")
        } else {
            if let context = (UIApplication.shared.delegate as? AppDelegate)?.coreDataStack.persistentContainer.viewContext {
                let card = Card(context: context)
                card.name = nameTextField.text
                card.location = locationTextField.text
                card.number = textField.text
                if let image = imageView.image {
                    card.image = image.pngData()
                }
                do {
                    try context.save()
                    print("Cохранение удалось!")
                } catch let error as NSError {
                    print("Не удалось сохранить данные \(error), \(error.userInfo)")
                }
            }

            performSegue(withIdentifier: "unwindSegueFromNewCard", sender: self)
        }
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        imageView.image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        dismiss(animated: true, completion: nil)
    }
}

ViewController2
import UIKit

class ViewController2: UIViewController {
    var filter : CIFilter!
    var delegate: ImageViewProtocol!

    @IBOutlet weak var select: UISegmentedControl!
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var barcodeImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        barcodeImageView.image = UIImage(named: "photo")
    }

    @IBAction func saveButtonAction(_ sender: Any) {
        if textField.text == "" {
            print("Not all fields are filled")
        } else {
            delegate.sendImageToViewController(theImage: barcodeImageView.image!)
            self.navigationController?.popViewController(animated: true)
        }
        performSegue(withIdentifier: "unwindSegueFromViewController", sender: sender)
    }

    @IBAction func tappedEnter(_ sender: Any) {
        if textField.text?.isEmpty ?? true {
            return
        } else {
            if let texttxt = textField.text {

                let data = texttxt.data(using: .ascii, allowLossyConversion: false)

                if select.selectedSegmentIndex == 0
                {
                    filter = CIFilter(name: "CICode128BarcodeGenerator")
                } else {
                    filter = CIFilter(name: "CIQRCodeGenerator")
                }

                filter.setValue(data, forKey: "inputMessage")
                let transform = CGAffineTransform(scaleX: 5, y: 5)
                let image = UIImage(ciImage: filter.outputImage!.transformed(by: transform))
                barcodeImageView.image = image
            }
        }
    }
}

Comment: You added a Protocol indeed, but no one is implementing its method.
Answer: This error comes because you implemented protocol (ImageViewProtcol) but you haven't add required methods of your protocol (in your case sendImageToViewController(theImage: UIImage)). All methods of your protocol are required by default. If you want to change it, you can look here.
It's the same as when you're implementing UITableViewDataSource, you also need to add required methods like number of items etc.
To fix this, add this method to your CardsViewController:
func sendImageToViewController(theImage: UIImage) {
    // do something with image
}


Examples in Machine Learning with Non-Differentiable Objective Functions

Question: I was reading the following lecture notes on Gradient Descent and came across the following note:

Supposedly, there are some instances in machine learning where the objective function is non-differentiable.  I was trying to think of some instances in Machine Learning where the Objective Functions are non-differentiable. After doing some thinking and reading about this online, I think one of the instances where this is true is in L1 Regularization (i.e. the absolute value of the model parameters introduces discontinuities):

My Question: Can someone please tell me if my understanding of this concept is correct? In L1 Regularization, the absolute value of the model parameters will likely result in the objective function not being differentiable in the classical sense - and as a result, some alternate method of Gradient Descent will be required to optimize such types of objective functions: thus, we use Subgradient Methods.
Is this correct?
Thanks!
References:

https://raghumeka.github.io/CS289ML/gdnotes.pdf
https://machinelearningcompass.com/machine_learning_math/subgradient_descent/
Comment: It seems you are correct. Apart from L1 regularization, another example is SVM with Hinge loss. https://machinelearningcompass.com/machine_learning_math/subgradient_descent/
Answer:
In L1 Regularization, the absolute value of the model parameters will likely result in the objective function not being differentiable in the classical sense - and as a result, some alternate method of Gradient Descent will be required ...

You statement is not accurate.

for non-differentiable functions, in many cases, we still can have analytical solutions. Gradient descent is not required for all cases.

non-differentiable is for specific points. Gradient descent needs the function to be differentiable to runb BUT it does not need the function to be differentiable everywhere. This is because for functions not differentiable at certain points, the only thing we are missing is we do not know how to update x at that point. But nothing prevent us to update x on other points where gradient can be calculated.

Examples: suppose we just want to minimize $f(x)=|x|$. We have an analytical solution of it ($x^*=0$). So gradient descent is not required.
If we want to optimize it using gradient descent, we need the gradient to update the $x$ value in each iteration, so we need the function to be differentiable at a given point.
We have gradient for the function, which is $f'(x)=1, \text{ when } x>0$ and $f'(x)=-1 \text{ when } x<0$. The function is differentiable everywhere except at 0. And we are using it to run the gradient descent.

Here is an additional example in 2D. We have a function $f(x_1,x_2)=|x_1-1.23|+1.7*|x_2-3.21|$, looks like this

It is convex and has global minima at $(1.23, 3.21)$.
The function is NOT differentiable everywhere, but gradient decent works just fine. Following plot shows the gradient decent iterations over time.


Is the time complexity of this mergesort implementation O(nlogn)?

Question: In this online textbook https://runestone.academy/runestone/static/pythonds/SortSearch/TheMergeSort.html they give the following code for mergesort:
def mergeSort(alist):
    if len(alist)>1:
        mid = len(alist)//2
        lefthalf = alist[:mid]
        righthalf = alist[mid:]

        mergeSort(lefthalf)
        mergeSort(righthalf)

        i=0
        j=0
        k=0
        while i < len(lefthalf) and j < len(righthalf):
            if lefthalf[i] <= righthalf[j]:
                alist[k]=lefthalf[i]
                i=i+1
            else:
                alist[k]=righthalf[j]
                j=j+1
            k=k+1

        while i < len(lefthalf):
            alist[k]=lefthalf[i]
            i=i+1
            k=k+1

        while j < len(righthalf):
            alist[k]=righthalf[j]
            j=j+1
            k=k+1

In the analysis the online book makes they write:

Recall that the slicing operator is O(k) where k is the size of the slice. In order to guarantee that mergeSort will be O(nlogn) we will need to remove the slice operator.Again, this is possible if we simply pass the starting and ending indices along with the list when we make the recursive call.

So my first question is:
1- Can you guys tell me of a scenario where the slice operators would ruin the time complexity of the algorithm?
I wrote the code to do it without a slice operation below:
def mergeSort2(alist, l, r):
    if r - l >= 1:
        mid = l + (r - l)//2

        mergeSort2(alist, l, mid)
        mergeSort2(alist, mid+1, r)

        i = l
        j = mid+1
        k = 0
        temp_list = [None]*(r-l+1)
        while i < mid+1 and j < r+1:
            if alist[i] <= alist[j]:
                temp_list[k] = alist[i]
                i=i+1
            else:
                temp_list[k] = alist[j]
                j=j+1
            k=k+1

        while i < mid+1:
            temp_list[k] = alist[i]
            i=i+1
            k=k+1

        while j < r+1:
            temp_list[k] = alist[j]
            j=j+1
            k=k+1

        n = 0
        for index in range(l,r+1):
            alist[index] = temp_list[n]
            n += 1

As you can see the loop at the bottom of the code could be replaced with a slice.
Question 2:
2- The way I see it instead of doing 2 slices that take k time before the recursive calls we are now initialising temp_list in k time and then copying the sorted temp_list into our result in k time. So the time complexity of the algorithm has not changed?
Comment: The slices are fine. They're not hurting the time complexity at all.
Comment: What about my rewrite, what would be the advantage/con of doing it the way I did ?
Answer: Slicing shouldn't affect the time complexity at all in terms of it's order of magnitude. The constant factor is another discussion.
The key part of understanding how the time complexity is unchanged is here:
def mergeSort(alist):
    if len(alist)>1:
        mid = len(alist)//2
        lefthalf = alist[:mid]
        righthalf = alist[mid:]

        mergeSort(lefthalf)
        mergeSort(righthalf)

So let's break it down step by step:
Here we copy the entire list. This is O(N)
lefthalf = alist[:mid]
righthalf = alist[mid:]

This part calls mergeSort on the left and the right, leading to recursive slicing.
mergeSort(lefthalf)
mergeSort(righthalf)

mergeSort(lefthalf) and mergeSort(righthalf) together will slice the entirety of the array, and the sum of their recursive children will do so as well. The thing is the number of times the array is sliced in it's entirety is log N, since you keep dividing the array by 2 and you can only do that log N times. This gives you O(N) slice times O(log N) times you do the slice resulting in O(NlogN)
To summarize:

No if the slicing is implemented correctly. Obviously you can add random slices and mess up the time complexity.
Slicing won't change the magnitude of your time complexity - still O(NlogN)


How to prove $ \frac{1}{A+B} = \frac{1}{A} - \frac{1}{A} B \frac{1}{A} + \frac{1}{A}B \frac{1}{A}B \frac{1}{A} + \cdots $?

Question: For matrix $A$ and $B$
\begin{align}
\frac{1}{A+B} = \frac{1}{A} - \frac{1}{A} B \frac{1}{A} + \frac{1}{A}B \frac{1}{A}B \frac{1}{A} + \cdots
\end{align}
How can prove above identity holds?
Comment: Is $\frac{1}{A}$ notation for $A^{-1}$?
Comment: Have you tried multiplying the right side with $A+B$?
Answer: Recall Neumann's series. If $\rho(C) < 1$, we have
$$ \def\I{\mathrm{Id}}(\I - C)^{-1} = \sum_{k=0}^\infty C^k $$
apply this to $C = -BA^{-1}$, giving
$$ (\I + BA^{-1})^{-1} = \sum_{k=0}^\infty (-1)^k (BA^{-1})^k $$
and multiply by $A^{-1}$:
$$ (A + B)^{-1} = \bigl((\I + BA^{-1})A \bigr)^{-1}
  = A^{-1}(\I + BA^{-1}) = \sum_{k=0}^\infty (-1)^k A^{-1}(BA^{-1})^k
$$
note that this only holds if $\rho(BA^{-1}) < 1$.
Comment: Except for a left/right-hand bias, it appears that we posted the same answer within a minute of each other. :)
Answer: A fundamental identity for the inverse of a matrix is $$(I-A)^{-1} = \sum_{n=0}^\infty A^{n}$$ when the matrix norm of $A$ is less than 1.
Using this identity we have $$(A+B)^{-1} = (A(I-(-A^{-1}B)))^{-1} = (I-(-A^{-1}B))^{-1} A^{-1} = \left( \sum_{n=0}^\infty (-1)^n(A^{-1}B)^n \right) A^{-1}$$
Hence $$(A+B)^{-1} = \sum_{n=0}^\infty (-1)^n(A^{-1}B)^n A^{-1}.$$ Note that this holds only when the matrix norm of $A^{-1}B$ is less than 1, just like with the classical geometric series.


Check if div-container has more than one div-inner no jQuery

Question: I need a if else function that checks if div_container has more than one div_inner inside of it with Javascript only.
Here's my example code:

var inner = document.querySelector('.inner')
var container = document.querySelector('.container').innerHTML;
if(container > '1') {
  container.classList.add('test');
}
else {
  // do nothing
}
.test {
  color: red;
}

Test

Test

Test

I only want to use Javascript. No jQuery at all.
Comment: Give your outer div and id so you can use getElementById, then you can iterate through the returned childNodes and use nodeName to determine if its a div.
Comment: So select the `container` elements, loop over the collection, check to see if it has elements with that class inside.
Comment: `div_container.querySelectorAll('.inner').length`
Answer: You have to use querySelectorAll() to get all the container and loop through them to check the inner div's length:

var container = document.querySelectorAll('.container');
container.forEach(function(el){
  var inner = el.querySelectorAll('.inner').length;
  if(inner > 1) {
    el.classList.add('test');
  }
  else {
    // do nothing
  }
});
.test {
  color: red;
  background-color: lightgray;
}

Test

Test

Test

Answer: You can use querySelectorAll()

for (const container of document.querySelectorAll('.container')) {
  if (container.querySelectorAll('.inner').length > 1) {
    container.classList.add('test');
  }
}
.test {
  color: red;
}

Test

Test

Test


How do I import local po files?

Question: There is no /admin/config/regional/translate/import page in Drupal 9 now, which exists in Drupal 7. So I don't know how to import manually translated PO files.
Answer: You must have forgot to enable the Interface Translation core submodule, which provides Interface Translation Import at <code>/admin/config/regional/translate/import</code>.
D9 and D7 have a nearly identical UI for translation import that works the same way.
Comment: Thank you for your tip! I did enalbe the Interface Translation module. It turned out there was a CSS sinppet which hide the second secondary tab in my administration theme. :-(

How do I import local po files?


centos7 - named starts manually, but systemctl reports timeout

Question: named starts and runs fine if I start it manually ("/usr/sbin/named -u named"), but when I start it with systemctl, it fails:
# systemctl start named
Job for named.service failed because a timeout was exceeded. See "systemctl status named.service" and "journalctl -xe" for details.

The status just shows normal named messages, however a "ps alx" while it's still running makes it look like it's looking for password input somewhere, which it shouldn't be doing, but maybe that's a default systemctl thing and a red herring:
4     0 18608 28440  20   0 134824  1296 poll_s S+   pts/1      0:00 systemctl start named
0     0 18609 18608  20   0  15428   824 poll_s S+   pts/1      0:00 /usr/bin/systemd-tty-ask-password-agent --watch
0     0 18610 18608  20   0 294680  3056 poll_s Sl+  pts/1      0:00 /usr/bin/pkttyagent --notify-fd 5 --fallback
5    25 18624     1  20   0 294512 146616 sigsus Ssl ?          0:06 /usr/sbin/named -u named -c /etc/named.conf

Anyway, hopefully someone knows what's going on...
Comment: What does the log say when you try to start it through systemd?
Comment: After I delete all the loading zone messages, they are identical whether starting with systemd or manually, aside from systemd giving up and killing it: 30 seconds after named is started there is "systemd: named.service start operation timed out. Terminating." and named shutting down log messages.
Comment: What changes did you make to `/etc/sysconfig/named` and to the named.service unit?
Comment: None, and I did a yum update as well (which did update named)
Answer: You can test your named.conf configuration with the named-checkconf command.
named-checkconf /etc/named.conf

If there's no output from that command, your named.conf configuration is good.
If there's an error, you'll see some reference to the error.
Comment: If it were a named configuration problem, it wouldn't start up manually.
Answer: The problem turned out to be that systemd was looking for the process pid in a different place than named.conf was putting it:
May  3 16:04:59 ns2 systemd: PID file /run/named/named.pid not readable (yet?) after start.

options {
        directory       "/var/named";
        pid-file        "/var/run/named/pid";
}


save the value of a custom form in the database

Question: Why isn't the code saving values in the database?
module_load_include('inc', 'firstform', 'firstform_node_form_alter');

function firstform_menu() {
$items = array();

$items['submit_driven_ajax'] = array(
    'title' => 'send your email',
    'page callback' => 'drupal_get_form',
    'access callback' => TRUE,
    'weight' => 3,
);
return $items;

}
function firstform_intro() {
$markup = t('The AJAX example module provides many examples of AJAX including forms, links, and AJAX commands.');
return $markup;}

function firstform_form($form, &$form_state) {
$form['box'] = array(
    '#type' => 'markup',
    '#prefix' => '
',
    '#suffix' => '
',
);
$form['email'] = array(
    '#type' => 'textfield',
    '#required' => TRUE
    , '#description' => "Please enter your email name.",
    '#ajax' => array(
        'callback' => 'firstform_text_driven_callback',
        'wrapper' => 'box',
        'name' => 'email1',
    ),
);
$form['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
        'callback' => 'firstform_submit_driven_callback',
        'wrapper' => 'box',
        'name' => 'submit1',
    ),
    '#value' => t('Submit'),
);

return $form;}

function firstform_submit_driven_callback($form, $form_state) {
$element = $form['box'];
$element['#markup'] = "your email ({$form_state['values']['email']}): " . date('c');
return $element;}

function firstform_text_driven_callback($form, $form_state) {
$element = $form['box'];
$element['#markup'] = "your email ({$form_state['values']['email']}): " .date('c');
return $element;}

 function firstform_block_info() {
$blocks = array();
$blocks['firstform'] = array(
    'info' => t('Form mail'),
    'weight' => 0,
);
return $blocks;}

function firstform_block_view($delta = '') {
module_load_include('inc', 'node', 'node.pages');
switch ($delta) {
    case 'firstform':
        $block['subject'] = t('');
        $form = drupal_render(node_add('firstform'));
        $block['content'] = $form;

        break;
}
return $block;}

  function firstform_node_insert($node){
  db_insert('firstform_node_form_alter')
->fields(array(
  'nid' => $node->nid,
  'email' => $node->firstform['email'],
  'date' => $node->firstform['date'],
))
->execute();}

function firstform_node_update($node) {

 if (db_select('firstform_node_form_alter', 'a')->fields('a')->condition('nid', $node->nid, '=')->execute()->fetchAssoc()) {
db_update('firstform_node_form_alter')
  ->fields(array(
    'email' => $node->firstform['email'],
    'date' => $node->firstform['date'],
  ))
  ->condition('nid', $node->nid)
  ->execute();
  }  else {
firstform_node_insert($node);}}

    function firstform_node_delete($node) {  db_delete('firstform_node_form_alter')
->condition('nid', $node->nid)
->execute();}

When I add firstform.install, the firstform_node_form_alter table is not created.
function firstform_schema() {
 $schema['firstform_node_form_alter'] = array(
'description' => 'Stores email settings for nodes.',
'fields' => array(
  'nid' => array(
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
    'default' => 0,
    'description' => 'The {node}.nid to store settings.',
  ),'email' => array(
    'type' => 'varchar',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Node Form Example 1 textfield',
  ),
  'date' => array(
    'type' => 'int',
    'length' => 256,
    'not null' => FALSE,
    'default' => '',
    'description' => 'Node Form date textfield',
  ),
),
'primary key' => array('nid'),
'foreign keys' => array(
  'dnv_node' => array(
    'table' => 'node',
    'columns' => array('nid' => 'nid'),
  ),
),
 );
return $schema;
}

Comment: You need uninstall and then install module again to make Drupal run firstfom_schema()
Comment: You can use devel for quick module reinstalling. Or as other option write hook_update and add new table/fields
Comment: You can use **drush dre firstform -y** to have uninstalling and re-enabling your module all in one command.
Answer: hook_schema is called at install and unistall, so make sure your actually installing the module and not just turning it on.
If you've already had your module running on your site, switched it off at /admin/modules and then switched it back on, drupal doesn't recognize this as an uninstall/install event. Rather, you need to fully remove it from the DB by going to admin/modules/uninstall after switching the module off.
Comment: Enabling the module for the first time is treated as an installation by Drupal, so it fires the install and schema hooks.  If you've added code to those hooks after the module has already been installed, then the module must be disabled, uninstalled, and then enabled again.  That entire process is essentially a "reinstall" of the module.


Why is "kicked ball" a violation in basketball?

Question: This may be opinion-based, but can anybody explain why "kicked ball", i.e. striking the ball with any part of the leg, is a violation in basketball? I've always thought it seemed like a fair play, not much different from striking the ball with your arms or hands. Kicked ball violation calls slow down the game, and at least in the NBA, adds an additional element of judgement as to whether the kicking was intentional or not, although it always seems to be called regardless.
Comment: Are you asking why you're not allowed to kick the ball? What reason is needed beyond, that's not the kind of game Basketball is (or they want it to be)?
Comment: Striking the ball with your hands is the same violation, though.
Comment: @Joe How so? Striking it with your fist is a violation, but I don't think I've ever seen that called.
Comment: Your fist is your hand, no?  The point is that it's clearly not an attempt to control the ball - it's just being disruptive.
Comment: @Joe Sure, but any other contact with your hands is fine, so I'm not sure what you're getting at.
Comment: @komodosp Like I said, it may be opinion-based, but it seems odd to slow down the game for a violation that doesn't seem to give an unfair advantage, and even if it was legal I don't think we'd see it happen significantly more.
Comment: I suppose technically any rule wouldn't give an unfair advantage as long as both teams are allowed do it. But (non-safety related) rules of games are usually guided by the type of game they want to play - e.g. why in Soccer are you not allowed to handle the ball, or in rugby to throw it forward. Allowing kicking would completely change the complexion of the game. "I don't think we'd see it happen". I think we would! e.g. Ball is bouncing low or rolling and your opponent is about to pick it up, I think taking a swing with your foot to boot it down the court or to a team-mate would happen a lot!
Comment: @komodosp Fair point although I think you could modify the rules to allow what currently occurs anyway (using your leg/foot to deflect a pass) without an infraction + shot clock reset, while still prohibiting the kinds of things you mentioned.
Comment: It's the nature of the game. Why is a handball in futbol/football/soccer a violation (even if accidental)? Calling it slows the game down and might even reward the penalized team if gives the defense a chance to get back when they weren't to start with.
Answer: Whenever the basketball is intentionally hit by the leg/foot, a violation will be called. If a player uses a foot to prevent the ball from going out of bounds, it is a violation. If a cross-over hits the leg of an opponent intentionally, it is a violation. So, if the ball is blocked or hit intentionally by the leg or foot a violation might be called, no matter if you are defensive or offensive.
Not sure why more ball players do not use this to an advantage...it is much like being a goalie on the basketball court.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://sports.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://sports.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/25383)
Answer: For a foot / leg infraction to be whistled voluntary is the first requirement. To be a foot violation it is necessary that whoever touches the ball with his leg does so as a result of a voluntary gesture. For example, if I am standing or making a legal defensive move, and you hit my leg trying to make a ground pass, there is no violation.
Once the voluntariness of the gesture has been clarified, then the concept of "advantage" can also be applied, although on the foot violation it is quite rare. For example: you pass the ball, I touch it with my foot but the ball still reaches your teammate unmarked under the basket. There would be a violation, but there is no booing so as not to dare an advantage to those who committed it.


Can we conclude from $MM^T=I$ that $M^TM=I $ over $\mathbb F_2$

Question:
Let $M$ be nonsingular real matrix, dimension $n$. If we know that $$MM^T=I,$$ where $I$ is identical matrix. Is it true that $M^TM=I$ too. And it is all over $\mathbb F_2$ field, which is field that consists only of $0,1$.

My first thoughts was that it is not necessary true, but then:

If we multiply our main equation by $M$ on the right we get: $$MM^TM=M $$
If we multiply our main equation by $M^T$ on the left, we have: $$M^TMM^T=M^T $$

So, can we conclude from here, that $M^T=I?$ Or there can exist other matrix $A\neq I$ such that $AM^T=M^T$ and $MA=M?$
Comment: This is a special case of a more general fact: The unique left inverse of an invertible square matrix is also its (unique) right inverse.
Comment: But does this stay in $F_2$?
Comment: Yes, as $GL(n, 2) = GL(n, \Bbb F_2)$ is (still) a group.
Answer: Hint: What does $MM^T=I$ tell you about $M^{-1}$?
Answer: Yes. The right inverse of a matrix is equal to the left inverse. If $MM^T=I$, $M^T$ is the right inverse of $M$. So it is also the left inverse and $M^TM=I$.
Answer: Yes, because for square matrices, a right inverse is automatically a left inverse.


checkbox not showing at view time in datagrid of material-ui

Question: Some main code related to datagrid
  const apiRef = React.useRef(null);
  const [gotApiRef, setGotApiRef] = useState(false);
  const [gotApiRef2, setGotApiRef2] = useState(false);
  console.log("apiRef.current: ", apiRef.current);
  const ObjRef = React.useRef({
    dataRe: {
      columns: [],
      rows: [],
    },
    tempRe: {
      rows: [],
    },
  });

const columns = [
    { field: "lenderName", headerName: "Lender Name", width: 200 },
    { field: "endpoint", headerName: "Endpoint", width: 250 },
  ];

// filling row data with props

useEffect(() => {
    if (props.data.docs) {
      props.data.docs.map((row) => {
        let temp = {
          id: row._id,
          lenderName: row.name,
          endpoint: row.endpoint,
        };
        ObjRef.current.tempRe.rows.push(temp);
      });
      console.log("2. ObjRef.current.tempRe.rows:", ObjRef.current.tempRe.rows);
    }
  }, [props.data]);

// ====================== Checkbox Selection useEffect =========================
useEffect(() => {
    if (gotApiRef) {
      console.log("entry in useEffect");
      //console.log("1. ObjRef.current.dataRe: ", ObjRef.current.dataRe);
      console.log("In useEffect apiRef.current: ", apiRef.current);
      const dataRe = {
        columns,
        rows: ObjRef.current.tempRe.rows,
      };
      counterRef.current.renderCount += 1;
      // console.log(
      //   "3 counterRef.current.renderCount:",
      //   counterRef.current.renderCount
      // );

      ObjRef.current.dataRe = dataRe;

      const rowModels = apiRef?.current?.getRowModels();
      if (rowModels != undefined) {
        console.log("5 ObjRef.current.dataRe:", ObjRef.current.dataRe);
        console.log("in rowModel not undefined..");
        console.log("5. rowModels*:", rowModels);
        if (apiRef.current) {
          console.log("in apiRef.current*", apiRef.current);
          setGotApiRef2(true)
          apiRef.current.setRowModels(
            rowModels.map((r) => {
              console.log("in rowModels.map");
              r.selected = true;
              return r;
            })
          );
        }
      }
    }
  }, [gotApiRef]);

//in return

            <DataGrid
              rows={ObjRef.current.dataRe.rows}
              columns={ObjRef.current.dataRe.columns}
              // {...ObjRef.current.dataRe}
              checkboxSelection
              onSelectionChange={(newSelection) => {
                setSelection(newSelection.rows);
              }}
              components={{
                noRowsOverlay: (params) => {
                  console.log(
                    "in noRowOverlay ObjRef.current.dataRe:",
                    ObjRef.current.dataRe
                  );
                  console.log("params in noRowsOverlay**:", params);
                  if (!apiRef.current) {
                    apiRef.current = params.api.current;
                    console.log(
                      "apiRef.current in noRowOverlay:",
                      apiRef.current
                    );
                    setGotApiRef(true);
                  }
                  return
No rows
;
                },
              }}
            />

I read somewhere that use Layout Effect is used with use Ref, even tried that but no help
this question is work after this question with this name
"Can I initialize the checkbox selection in a material-ui DataGrid?"
Can I initialize the checkbox selection in a material-ui DataGrid?
I am getting data in apiRef.current
I am setting data in ObjRef.current.dataRe
after setting I should get data in rowModels ,but I am getting rowModels as null
Answer: this is solved, i just used a boolean state to make component render and removed dependency from useEffect.
upon some hit and trial it runs.


Python Flask not displaying Javascript

Question: I'm trying to display a javascript file in a python flask project. I'm using blocks in the html file which is calling the javascript file.  It is just not displaying on the webpage.
If I remove the base.html part of the project and just put everything into the snake.html file it runs fine, which says to me the Javascript is fine, I'm just misunderstanding the Flask parts.
Any assistance you could give me, would be greatly appreciated.
base.html

    {% if title %}
    <title>{{ title }}</title>
    {% else %}
    <title>Unseen Arcade</title>
    {% endif %}
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    {% block scripts %}{% endblock scripts %}

Unseen Arcade: Home

    {% block content %}{% endblock content %}

snake.html
{% extends "base.html" %}
{% block scripts %}

{% endblock %}

{% block content %}

 Snake Game:

Use the keys W, A, S, and D to control the direction of the snake, if you get onto the leaderboard with a score above 50 you will receive a hint on the locations of other secret arcades in London.$

{% endblock %}

folder layout:
FlaskApp/
FlaskApp/
    forms.py
    __init__.py
    routes.py
    static/
      p5.min.js
      addons/
        p5.dom.min.js
        p5.sound.min.js
      snake/
        snake.js
    templates/
        base.html
      snake/
        snake.html
  flaskapp.wsgi

Comment: Are you receiving any errors in the JS console?
Comment: Some of the files you have in your `base.html` aren't in your specified folder layout
Comment: Sorry, I edited it to include those files, they are in there, just didn't think to check.  I'm also referencing them without url_for, that's not an issue right?
Comment: I'm sshing into a rapsberry pi hosting this, so I don't really have a js console for it.
Comment: How are you viewing the webpage? If inside a browser you should be able to view the JS console....
Comment: Oh, such an obvious thing and I was too dumb to think of it.  This is what I get for branching from my area.  Thank you so much Kstullich.  I'll post an answer pointing out that I merely used url_for inside base.html and it solved it.
Answer: Thanks to Kstullich I found out that the path I was using in base.html was incorrect, and swapped the script paths to use url_for.  Also didn't think about viewing the js console in the browser.

Python Flask not displaying Javascript


Matching jumbled strings and returning corresponding column value in R

Question: Below is a data frame with two columns of character data type in R. My requirement is that suppose if I have a jumbled string "FB,AI,IT,GE", I want to test if this jumbled string exists in the "a2 column", then return the corresponding "a1 column" value. Clearly, the first "a2 column" value is what matches with the jumbled string above, I need the corresponding "a1" value to be returned. I would appreciate is using "if-else" is avoided.
<code>a1 = c("B1","B2","B3","B4","B5")
a2 = c("IT,GE,FB,AI","GE,AI","FB,IT,AI","GE,IT,FB","AI")
a12 = data.frame(a1,a2)
a12$a1 = as.character(a12$a1)
a12$a2 = as.character(a12$a2)
</code>
Comment: "FB,AI,IT,GE" should be an exact match? No values extra or less?
Comment: @RonakShah, Thank you so much for replying, absolutely exact, nothing less, nothing more.
Comment: Something like : `a12$a1[sapply(strsplit(a12$a2, ","), function(x) all(strsplit(val, ",")[[1]] %in% x))]`. Don't think this is an efficient method though.
Comment: @RonakShah, it works, but as I said, nothing less, nothing more, I tried using other strings like "AI", it is returning multiple "a1" values, need a little tweak here, kindly check.
Comment: @RonakShah, Also, I would greatly appreciate, if this can be achieved without using function, as it has the possibility of slowing down the process on large data, I suppose.
Comment: @AdamShaw I'd recommend asking this question on the https://community.rstudio.com/ to get a good response
Answer: <code>#string to be matched
match_str <- "FB,AI,IT,GE"

idx <- sapply(strsplit(as.character(a12$a2),","),
              function(x) setequal(unlist(strsplit(as.character(match_str),",")), unlist(x)))
a12$a1[idx]
</code>
Output is:
<code>[1] "B1"
</code>
<code>#sample data
> dput(a12)
structure(list(a1 = c("B1", "B2", "B3", "B4", "B5"), a2 = c("IT,GE,FB,AI",
"GE,AI", "FB,IT,AI", "GE,IT,FB", "AI")), .Names = c("a1", "a2"
), row.names = c(NA, -5L), class = "data.frame")
</code>
Comment: very nice, still, I would be very thankful if this can be achieved without using a function, like say if my string is "IT,GE,FB,AI", a12$a1[a12$a2 == "IT,GE,FB,AI"], this will solve the problem. I know this is the exact string, but if something like this can be done for jumbled too, thanks and kindly suggest.
Comment: Above solution is the vectorized one and it's not going to slow your processing. I don't think you can achieve it without splitting your string either on `''` or `','`.
Comment: Sure, thanks a lot for your help, still if you can find a fix, please let me know.


Python NoneTypeDataType while posting data to Flask with Ajax

Question: I'm trying to figure out how to make ajax data post to my flask controller,

Without ajax, it works just find :

This is the form in my html template :
<form  method=post action="{{ url_for( 'editreals', id=realist.index(row), name='head') }}">

In my view.py, get the index 'id' and cast it :
i = int(request.args.get("id")

With ajax, I'm using a jquery plugin (http://www.appelsiini.net/projects/jeditable) to edit in place :

{{ row["rubric"] }}

In return I get a 500 error
I don't understand why the controller always send back that error :
TypeError: list indices must be integers, not NoneTypeDataType :

From the web debugger the data I sends seems ok to me :
FormData :
  rubric: datasubmitted
  id: 0

Those field are just Strings, nop ? Why python says they are NoneTypeDataType ?
[EDIT-1]
Headers :
Request URL:http://<Server-IPAddress>:5000/editskills
Request Method:POST
Status Code:500 INTERNAL SERVER ERROR
Request Headersview source
Accept:text/html, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:25
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:session=eyJsb2dnZWRfaW4iOnRydWV9.BcMSfg.j5SaVklwzSzTdttCciYL_9dqZNg
DNT:1
Host:<Server-IPAddress>:5000
Origin:http://<Server-IPAddress>:5000
Referer:http://<Server-IPAddress>:5000/competences
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)           Chrome/32.0.1700.76 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
rubric:1Réseaux
id:0
Response Headersview source
Connection:close
Content-Type:text/html; charset=utf-8
Date:Thu, 23 Jan 2014 20:52:19 GMT
Server:Werkzeug/0.9.4 Python/2.7.3
X-XSS-Protection:0

Preview :
File "/home/noa/virtualenv/folio/foliodev/portfolio/views.py", line 39, in editskills
v = liste[i]
TypeError: list indices must be integers, not NoneType

Sorry I made a mistake, there is the code which cause the error:
i = request.args.get("id", type=int)
v = liste[i]

If I try this instead :
i = int(request.args.get("id"))

It breaks directly to the cast :
i = int(request.args.get("id"))
TypeError: int() argument must be a string or a number, not 'NoneType'

Which make me focus on why does the data I send are 'NoneType'
Thank you very much for your time.
Comment: In the working code you are using `ind` (which is what you are looking for in your view), but the data you are sending via ajax is sending `id` ... shouldn't it be `ind`?
Comment: Yes it is, I edited the view to request the id and not ind, sry I forgot to specify it in my question.
Comment: Can you provide the *full* stack trace?
Comment: Hello, do you need more info ?
Answer: The issue is that in your working form example you are sending the id in the query string (which makes it available to request.args).  jEditable is sending the id in the response body as part of the POST - Flask exposes this data under request.form.  Change i = int(request.args.get("id")) to i = int(request.form.get("id")) and things will work.
Comment: It work, thank you very much, I wasn't clear about this 2 ways to post data.


Tem como alterar a ordem vertical de divs por CSS?

Question: Eu tenho o seguinte layout de uma página gerada automaticamente:

Eu gostaria de trazer a Fonte, para junto da Data (logo abaixo). Mas eu não posso mudar disposição dos elementos gerados. Só posso alterar um template com os elementos HTML externos, uma div por fora de todo esse conteúdo, CSS. Essa página será enviada por email como um Newsletter, então acredito que Javascript não seria uma boa ideia.
Tem como fazer isso somente com CSS?
ver no JSFiddle
Comment: André, é isto que quer? __http://jsfiddle.net/e54eZ/1/__ Até pode funcionar, mas vai ser dificil garantir que tudo fica "onde você quer"
Comment: @Sergio muito obrigado pela luz. Eu tive a ideia de mexer por `position:absolute` e ficou assim: http://jsfiddle.net/andretf/e54eZ/! Pode postar como uma resposta para eu poder dar a pergunta como resolvida?
Comment: @Sergio Corrigindo o link do comentário anterior: http://jsfiddle.net/andretf/e54eZ/3/
Answer: Caso você não tenha problemas com browsers antigos, você pode utilizar Flexbox.
Supondo que você tenha um elemento pai destes três outros blocos, ficaria assim:
.elemento-pai {
  display: flex;
  flex-direction: column;
}

.d2 {
  order: 3;
}

.d3 {
  order: 2;
}

Desta forma trocando os elementos de posição e preservando a dinâmica deles (um continua empurrando o outro pra baixo, etc).
Exemplo: FIDDLE
Comment: Boa resposta, mas o css ainda não funciona em todos os navegadores (IE8, IE9..).
Comment: Atualizei pra ter esta resposta como a aceita, já que hoje em 2016 ela é [amplamente aceita](http://caniuse.com/#feat=flexbox) pelos navegadores atuais.
Comment: Ótimo exemplo. CSS esta se tornando um canivete suíço.
Comment: @AndreFigueiredo pois é, é uma feature relativamente nova (CSS3), por isso destaquei na primeira frase que só deve ser usado caso navegadores antigos não sejam problema.
Answer: Você pode forçar os elementos a posicionarem-se onde quer. Se tomar este caminho o melhor é que todos os elementos estejam posicionados, e que tenha controlo sobre as suas dimensões para não cruzarem uns por cima dos outros.
Aqui fica uma sugestão: http://jsfiddle.net/e54eZ/1/
.d1, .d3 {
    color: #cc9900;
    font-family: Arial;
    font-size: 11px;
    position: absolute; # para os poder mover livremente

}
.d2 {
    margin-top: 20px; # para deixar espaço para os outros elementos
    font-family: "Segoe UI", Arial, Helvetica, Verdana, sans-serif;
}
/* PArte nova */
.d3 {
    top: 5px;
    left: 120px;
}
.d1 {
    top: 5px;
    left: 7px;
}


Create custom (equally spaced) bins in ggplot for data with gaps

Question: I have data with large degrees of separation between "clusters/groups" of values that I hope to make a histogram with, but dividing the bins into equal sized groups has been difficult. I'd like for zero (0) to have it's own bin, the total number of equally spaced bins be < 8 (ideally, to avoid crowding the plot) with an extra empty bin for "..." signifying the large gaps in-between the data values. The actual dataset has 800+ zeros with maybe 5% data >0. Naturally the zeros will over-shadow the rest of the data, but a log transform will fix that. I just can't figure out the best way to break-up the data...
Data looks like this:
set.seed(123)

zero <- runif(50, min=0, max=0)
small <- runif(7, min=0, max=0.1)
medium <- runif(5, min=0, max=0.5)
high <- runif(3, min=1.5, max=2.5)

f <- function(x){
  return(data.frame(ID=deparse(substitute(x)), value=x))
}

all <- bind_rows(f(zero), f(small), f(medium), f(high))
all <- as.data.frame(all[,-1])
names(all)[1] <- "value"

My attempt:
bins <- all %>% mutate(bin = cut(all$value, breaks = c(0, seq(0.01:0.4), Inf), right = FALSE)) %>%
  count(bin, name = "freq") %>%
  add_row(bin = "...", freq = NA_integer_) %>%
  mutate(bin = fct_relevel(bin, "...", after = 0.4))

But I get this error:
Error in `mutate()`:
! Problem while computing `bin = fct_relevel(bin, "...", after = 0.5)`.
Caused by error:
! `idx` must contain one integer for each level of `f`

This is not equally spaced, but I'm looking for something like this as labels for my plot:
levels(bins$bin) <- c("0", "0.01-0.05", "0.05-0.1", "0.1-0.2", "0.2-0.3", "0.3-0.4", "...", "2.0+")

ggplot(bins, aes(x = bin, y = freq, fill = bin)) +
  geom_histogram(stat = "identity", colour = "black")

Answer: You can use cut directly inside ggplot
ggplot(all, aes(cut(value, breaks = c(0, 0.25, 0.5, 3), inc = TRUE))) +
  geom_bar() +
  scale_y_log10() +
  labs(x = "value")

Answer: This worked for me (using my own data):
bins <- WET %>% mutate(bin = cut(den, breaks = c(0, seq(0.001, 0.225, 0.15), 0.255, 0.3, Inf), right = FALSE)) %>%
count(bin, name = "freq") %>% # build frequency table, frequency = freq
add_row(bin = "...", freq = NA_integer_) %>% # add empty row for NA
mutate(bin = fct_relevel(bin, "...", after = 3)) # Put factor level "..." after 3! (the 3rd position)
levels(bins$bin) <- c("0", "0.001-0.15", "0.15-0.255", "...", "0.3+")

# fct_relevel(f, "a", after = 2), "..., after = x, x must be an integer! (2nd position)

ggplot(bins, aes(x = bin, y = freq, fill = bin)) +
  geom_bar(stat = "identity", colour = "black") +
  geom_text(aes(label = freq), vjust = -0.5) +
  scale_y_continuous(limits = c(0, 800), expand = expansion(mult = c(0, 0.05))) +
  scale_fill_brewer(name = "Density", palette="Greys", breaks = c("0", "0.001-0.15", "0.15-0.255", "0.3+")) +
  # Only show these legend values (exclude "...")
  labs(title = "Wet seasons - Pink shrimp density (no./m2)",x = "Density range", y = "Frequency") +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(axis.text = element_text(size = 9, face = "bold")) +
  theme(axis.title = element_text(size = 13, face = "bold")) + # Axis titles
  theme(axis.title.x = element_text(vjust = -3)) +
  theme(panel.border = element_rect(color = "black", fill = NA, size = 1)) +
  # Adjust distance of x-axis title from plot
  theme(plot.margin = margin(t = 20,  # Top margin
                             r = 50,  # Right margin
                             b = 40,  # Bottom margin
                             l = 10)) # Left margin


Field is validated when loosing focus

Question: I'm doing validation of a textbox with RequiredFieldValidation.
I want it to validate the textbox only when a button is clicked, not when textbox loses focus.
Now, every time when I click anywhere else on a page it shows an error message.
Here is a code:
<code> <asp:TemplateField HeaderText="Email">
      <ItemTemplate>
     <asp:TextBox runat="server" ID="txtEmail" Text='<%#Eval("CustEmail") %>' />
      <asp:RequiredFieldValidator ControlToValidate="txtEmail"
          ValidationGroup="grpEmail"
          ErrorMessage="Must enter Email Address" runat="server"></asp:RequiredFieldValidator>
       <asp:Button Text="Update Email" ButtonType="Button" CommandName="UpdateEmail"
           ValidationGroup="grpEmail"
           CausesValidation="true"
           Visible="true" runat="server"/>
     </ItemTemplate>
 </asp:TemplateField>
</code>
I just need it to be validated when button is clicked. That's it.
What am I doing wrong?
Answer: Setting the attribute CausesValidation of the Textbox to false should do the trick.

Field is validated when loosing focus


How to tell if an image was updated

Question: I'm using images generated by Drupal (drupal 7) to feed an application. I'm then caching those images in the app. I'm trying to figure out a way to determine if the image has been updated since the last download, is there anyway to access this information about an image, without actually loading the image?
Answer: You can use ETags - when the app receives an image, there will be an HTTP header that looks like:
ETag: "686897696a7c876b7e"

Whenever the app wants to check for a new image, perform a GET request with this header:
If-None-Match: "686897696a7c876b7e"

If the file is unchanged, your web server will respond with HTTP 304 Not Modified status.
Comment: got it to work, just an fyi for anyone trying to do this you need to pass the quotes ie; '"686897696a7c876b7e"'

How to tell if an image was updated


Input em javaFx

Question: Tenho o seguinte programa que desenha uma ilusão de Pogendorff mas preciso que antes de ele executar peça o numero de rectangulos e por ventura de linhas. Ou seja, o N_BARS ser posto por input previo a execução do programa.Deixo o codigo:
import javafx.application.*;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import javafx.scene.shape.*;
import javafx.embed.swing.*;
import javafx.application.*;
import javafx.scene.text.*;
import java.util.*;
import javafx.scene.paint.Color;

public class Ilusao  {
 private Pane pane;
private void start(Stage primaryStage)
{
    primaryStage.setOnCloseRequest(
        e -> Platform.runLater( () -> {Platform.exit(); System.exit(0);} ) );

    // WRITE YOUR CODE HERE
    // TODO

    // https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/Pane.html
    this.pane = new Pane();
    this.pane.setPrefSize(900, 600);
    primaryStage.setScene(new Scene(this.pane, Color.WHITE));
    primaryStage.show();

    Label label1 = new Label("Name:");
    TextField textField = new TextField ();
    HBox hb = new HBox();
    hb.getChildren().addAll(label1, textField);
    hb.setSpacing(10);

    this.drawIlusion();
} // END start
/**
 * Add shape to pane
 */
public void addShape(Shape shape)
{
    Platform.runLater(() -> this.pane.getChildren().add(shape));
}

/** execute this method to start the program
 * executing the code in method start(Stage primaryStage)
 */
public static void start()
{
    Ilusao drawingApp = new Ilusao();
    drawingApp.launch();
}

public void launch()
{
    // Initialises JavaFX:
    new JFXPanel();
    // Makes sure JavaFX doesn't exit when first window is closed:
    Platform.setImplicitExit(false);
    // Runs initialisation on the JavaFX thread:
    Platform.runLater(() -> start(new Stage()));
}

public Ilusao()
{
    super();
}

private void drawIlusion()
{
    final int N_BARS = 14;
    for(int i =50; i <=N_BARS*50;i+=100)
    {
        Rectangle rectangles = new Rectangle(i,50,30,300);
        rectangles.setStrokeWidth(0.5);
        rectangles.setStroke(Color.BLACK);
        rectangles.setFill(Color.YELLOW);
        pane.getChildren().add(rectangles);
    }
    int k =50;
    for(int j = 0;j<=N_BARS*50;j+=100)
    {
        Line lowerLine = new Line (j,350,k,267);
        lowerLine.setStrokeWidth(0.5);
        lowerLine.setStroke(Color.BLACK);
        pane.getChildren().add(lowerLine);
        k+=100;
    }
    int m = 150;
    for(int l = 80;l<=N_BARS*50;l+=100)
    {

        Line upperLine = new Line(l,218,m,100);
        upperLine.setStrokeWidth(0.5);
        upperLine.setStroke(Color.BLACK);
        pane.getChildren().add(upperLine);

        m+=100;
    }

    // Line testLine = new Line(0,350,180,50);
    // testLine.setStrokeWidth(0.5);
    // testLine.setStroke(Color.BLACK);
    // pane.getChildren().add(testLine);
    // END class World

   }
}

Answer:
Você pode tornar N_BARS atributo da classe, podendo ser alterado de qualquer método de Ilusao antes do método drawIlusion ser chamado para desenhar os elementos. Outra solução é parametrizar o método drawIlusion para receber como argumento o número que irá substituir N_BARS, qualquer uma das opções funcionará.
A parte de ler a entrada pode ser feita utilizando a classe TextInputDialog:
TextInputDialog dialog = new TextInputDialog();
dialog.setHeaderText("Nº de Barras");
dialog.setContentText("Digite o número de barras a serem criadas:");

// para só aceitar números.
dialog.getEditor().textProperty().addListener((observable, oldValue, newValue) -> {
   if(!newValue.matches("\\d*"))
      dialog.getEditor().setText(newValue.replaceAll("\\D+", ""));
});

Optional<String> value = dialog.showAndWait();
if(value.isPresent()){
   try {
       int bars =  Integer.parseInt(value.get());
       this.drawIlusion(bars);
   } catch(NumberFormatException ex){
      // Seja legal e trate as exceções. :)
   }
}

Ficando:
import javafx.application.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import javafx.scene.shape.*;
import java.util.*;
import javafx.scene.paint.Color;

public class Ilusao extends Application {

    private Pane pane;

    @Override
    public void start(Stage primaryStage) {

        this.pane = new Pane();
        this.pane.setPrefSize(900, 600);
        primaryStage.setScene(new Scene(this.pane, Color.WHITE));

        Label label1 = new Label("Name:");
        TextField textField = new TextField();
        HBox hb = new HBox();
        hb.getChildren().addAll(label1, textField);
        hb.setSpacing(10);

        TextInputDialog dialog = new TextInputDialog();
        dialog.setHeaderText("Nº de Barras");
        dialog.setContentText("Digite o número de barras a serem criadas:");

        dialog.getEditor().textProperty().addListener((observable, oldValue, newValue) -> {
            if(!newValue.matches("\\d*"))
                dialog.getEditor().setText(newValue.replaceAll("\\D+", ""));
        });

        Optional<String> value = dialog.showAndWait();
        if(value.isPresent()){
            try {
                int bars =  Integer.parseInt(value.get());
                this.drawIlusion(bars);
            } catch(NumberFormatException ex){
                // Seja legal e trate as exceções. :)
            }
        }
        primaryStage.show();
    }

    private void drawIlusion(int bars){
        for (int i = 50; i <= bars * 50; i += 100) {
            Rectangle rectangles = new Rectangle(i, 50, 30, 300);
            rectangles.setStrokeWidth(0.5);
            rectangles.setStroke(Color.BLACK);
            rectangles.setFill(Color.YELLOW);
            pane.getChildren().add(rectangles);
        }
        int k = 50;
        for (int j = 0; j <= bars * 50; j += 100) {
            Line lowerLine = new Line(j, 350, k, 267);
            lowerLine.setStrokeWidth(0.5);
            lowerLine.setStroke(Color.BLACK);
            pane.getChildren().add(lowerLine);
            k += 100;
        }
        int m = 150;
        for (int l = 80; l <= bars * 50; l += 100) {

            Line upperLine = new Line(l, 218, m, 100);
            upperLine.setStrokeWidth(0.5);
            upperLine.setStroke(Color.BLACK);
            pane.getChildren().add(upperLine);

            m += 100;
        }
    }
}

Comment: Boas,testei seu codigo e o numero inserido nao corresponde ao numero de barras que aparece? Nao consigo identificar o erro.
Comment: @Phil testei seu código anterior e ele também não exibe o número correto. Não é problema de lógica do teu código? A única alteração que fiz foi deixar com que o valor de `N_BARS` fosse especificado via input.

Input em javaFx


Transposing trombones and tubas from bass clef to treble clef

Question: I'm a new boy at transposition school(!). (I play piano so am familiar with which note is which in the two clefs.)
I play clarinets, Bb and A. We only use treble clef, so it's a simply process of raising the key by a two semitones (Bb clarinet) or three semitones (A clarinet) to accompany our trio who play in concert pitch.
However, my other band needs help transposing trombones and tubas from bass clef to treble clef. I have read the instructions above, but I need to understand the 'why' before I can help the band, and spot if I am transposing the tuba or trombone correctly. Obviously I don't need to understand brass instrument fingering, or trombone positioning, but must grasp what happens for the change from bass clef to treble clef.
I used to think that, if a brass instrument should play a 'C' in bass clef, then, (after using Musescore to transpose), the instrument should play a C in the treble. Not so, it seems. That is my mystery.
Any pointers for my now-addled brain would be most welcome.
Comment: This leaves several important points unclear. Why do you want to have tubas notated in the treble clef although they play in a deep register? Why do you think that a 'C' becomes something else when notated in a different clef? Changing a clef should only ever involve moving everything on the staff around by as many lines/gaps as the difference between the two clefs warrants.
Comment: If tubas and trombones are having trouble *transposing*, even an octave , then aren't they going to have more trouble reading in treble clef, when they're used to bass or tenor clef dots?
Comment: I'd start by asking them to see what they usually play and comparing that to the score to find out how this is usually handled.  My guess is that they'd read just like a Bb bass clarinet.
Answer: Orchestral trombones and tubas typically read from bass clef and are treated as concert pitch (non-transposing) instruments. So when they perform a written bass-clef C the sounding note is concert C. Orchestral trombonists also have to read several other clefs too, but those are less common.
In some non-orchestral ensembles (e.g. UK Brass band) trombones are written in treble clef and treated as Bb transposing instruments. So when they perform a written treble-clef C the sounding note is concert Bb.
UK brass bands notate all instruments (apart from bass trombone) as transposing instruments in treble clef (even the basses!). All instruments are treated as Bb transposing apart from Soprano cornet, tenor horn and Eb bass, which are Eb transposition.
If you're using a package like Sibelius, it's very straightforward to create a treble-clef transposing stave for your trombone or Eb bass or Bb bass and then copy an existing concert pitch line into that stave, and it will be transposed automatically.  I expect Musescore can do something similar.
If you're doing it manually rather than via software (or if you want to check what the software has produced), remember that Bb instruments are written one tone higher than the desired sounding concert pitch (perform written C, produce sounding concert Bb)  And Eb instruments are written a minor third lower than sounding concert pitch (perform written C, produce sounding concert Eb).
Comment: @Brian THOMAS Not Big Band.  Those trombones stay firmly in bass clef, even when the number of 'telegraph poles'  makes tenor clef a more obvious choice!   VERY occasionally a high solo passage will be written in (untransposed) treble clef.   But this gets mentioned in textbooks al lot more than it actually happens!
Comment: I didn't know that about UK bands using treble clef for everything! With assumed one-octave-down? or would it be two for the bass trombone, tuba, etc? That explains a lot.

BTW, @Clive, just to clarify, your original assumption is *normally* correct: Clefs in and of themself don't usually imply anything about *transposition*; A "C" in bass clef is a "C" in treble, just one with an impractical number of ledger lines below the staff barring any assumption of 8vb.
Comment: @Andy Bonner In British Brass Band notation, Bass Trombone is the exception.  It is written the same as orchestral bass trombone, concert pitch bass clef.  Even when the obsolete 'G Bass Trombone (the one with a handle on the slide) is being used.
Comment: I mentioned Bass Trombone in the third paragraph. And I've removed Big Band from the second para.
Answer: In British brass bands and certain other types of ensemble the low brass are written as transposing instruments (with the appropriate key signature change) and in treble clef.

Tenor trombone, baritone horn and euphonium are B-flat instruments and are written a major ninth higher than they sound.
E-flat tuba is written a major thirteenth higher than it sounds.
B-flat tuba is written two octaves and a second higher than it sounds.
Bass trombone is not transposed and stays in bass clef.
Answer: The reason is that most people who learned trombone in an old-school English brass band will have learned it as a Bb instrument. The Bb euphonium and Bb horn in brass bands are written just like your Bb clarinet parts (except raised up an octave to place the notes inside the staff so that they are readable). Therefore middle C on a piano ends up being notated as D second line from the top in treble clef on a euphonium part.
To make life easier, they traditionally taught the trombone players off the same music because they have a similar range. So a trombone player like that will see D treble clef on the page, will call it D, and will play a note that is actually concert C.
Ditto tuba, except they will have raised the treble clef notation two octaves to make it readable.
Except bass trombone, which is a relatively new addition to brass bands and is always bass clef, concert pitch.
Comment: WAY back, local bands doubtless used a serpent or ophicleide, with bass clef notation.  But once the Brass Band line-up became established, it was pretty much always a G bass trombone - the one a bit longer than the Bb instrument, with an extension handle to reach the further positions!  The valved instruments, from BBb Bass to Eb Soprano Cornet all read treble clef, and all fingered the written notes in the same way. Pick up any instrument - no need to learn new fingerings.  If a Soprano Cornet player 'lost his chops' he could descend through Bb cornet, tenor horn, baritone, bass :-)
Comment: Yes the other advantage for the band is the trombone player can read & play euphonium or baritone parts if need be (e.g. if someone doesn't turn up) or move permanently to those instruments if that's what the band needs more. Or vice versa.


Linear Regression: Expectation Proof

Question: I found the following proof in my notes:
$E(Y_i) = E[\beta_0 + \beta X_i + \varepsilon_i] =\cdots= \beta_0 + \beta X_i$.  This does not seem right to me, however.  Why would $E(\beta_1 X_i) = \beta_1 X_i$?  I wonder if i might have written it down incorrectly, with the actual proof meaning to be for the estimated value Yi hat (I don't know how to code this unfortunately).  Does anyone recall this property of linear regression?
Comment: Perhaps you meant $\beta_i E X_i$? Your question needs some context...
Comment: It seems like what we are trying to show is that the expectation of a linear regression is a linear function of expectations but we may also be trying to show the proof shown on page 4 here: http://web.njit.edu/~wguo/Math644_2012/Math644_Chapter%201_part2.pdf
Comment: That proof shows the expectation of $Y_{i}$ is equivalent to the expectation of its estimate Yi hat
Comment: I actually think my answer is a bit more complete than the "accepted" one.
Answer: If $Y_i=\beta_0+\beta X_i+\epsilon_i$, where $\beta_0$ and $\beta$ are constants and $\epsilon_i$ is an "error" random variable with mean $0$, then $E(Y_i)=\beta_0+\beta E(X_i)$.
Comment: This is what I thought, and what copper-hat mentioned above.  It seems likely I missed the E.  Thank you very much.  While I'm here, could I also ask: Why is it that the error has to be 'centered' or mean zero, and what is the importance of this property?  Do you think it is just to say 'remember, linearity of expectation works here too'?
Comment: If there is a systematic error, we would probably incorporate it in the $\beta_0$ term. Linearity of expectation would work in any case, we just use $E(\epsilon_i)$.
Comment: That makes sense, thanks.  My other final question is: why in the linked document above, or in general, is E(Y) = E(Y'), that is, the estimated Y's expectation is the same as Y's expectation?  Is it that the variance is what's changing not the mean?
Comment: The least squares estimator is *unbiased*. That takes some proving.
Comment: Ohh, so that's what's meant by unbiased essentially.  The expected value of the estimate is unchanged.
Comment: An *estimator* is a random variable (like sample mean, or sample standard deviation) which is used to estimate a population parameter. The estimator is *unbiased* if it has expectation the population parameter. Unbiasedness is in general a desirable quality, though there are exceptions. For example, when we are estimating the variance of a normal, the population variance version that has $n-1$ in the denominator is unbiased, but the one with $n$ in the denominator has smaller variance (it is on average closer to the truth).
Comment: Thank you, that was very helpful. I'm somewhat curious as to why you received a negative vote by the way.
Comment: If the voter left a comment, that could be helpful.
Comment: I've down-voted this answer but I'll up-vote it after the error is corrected: $E(Y_i)$ appears where $E(X_i)$ should be.
Comment: Thanks for identifying the typo. Fixed.
Comment: @user78504 : "Unbiased" doesn't mean the expected value of the estimator is "unchanged" (whatever that means$\ldots$); rather it means the expected value of the estimator is equal to the thing to be estimated.  Unbiasedness is at least somewhat overrated by the masses.  In some circumstances unbiasedness is a very bad thing.
Answer: In this sort of regression problem, $X_i$ may be random in the sense that if you take another sample, all the $X_i$ values change, but one behaves as if one seeks the conditional expected value of $Y_i$ given $X_i$, so that in effect $X_i$ is treated as if it were constant rather than random.  And the $\beta$s are also being treated as constant.
Comment: Right, so in fact I was correct since it is in effect being treated as a constant.  I misunderstood before.

Linear Regression: Expectation Proof


Android view position animation

Question: E.g
<RelativeLayout>

    <View1/>

    <View2
    above:view1/>

</RelativeLayout>

I have a relativeLayout, and view2 is setup as above view1
Now I want to animate view2 to position blow view1
how Do I do that? is the animation has to use absolutely X/Y?
Answer: Add this to your relative layout:
android:animateLayoutChanges="true"

And then, in your code you could try this:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)view2.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.view1);

view1.setLayoutParams(params);

Comment: It does changes the layout but without animation.
android:animateLayoutChanges="true" seems not working
Comment: Can you use a LinearLayout instead of a RelativeLayout? If so, I can give you another alternative.
Comment: no, cause have some other components need to be in different layer and overlaped

Android view position animation


Solution Verification - Area between a Curve

Question: Conflicted on whether I did this correctly. Any suggestions are appreciated!
Answer: Your initial calculation of $\frac{1}{3}+\frac{49}{3}=\frac{50}{3}$ was correct for the two green areas
Your revised calculation of $5$ is correct for the purple area
What I do not know is whether the question is asking for the two green areas of $\frac{50}{3}$, or just the darker green area of $\frac{49}{3}$, or the purple area of $5$
Comment: Thanks! I updated my answer. Does that look better?
Comment: @Eight8 - All your calculations of areas have been correct, both initial and revised.  I am not certain precisely which area you actually being asked for
Answer: I think you've shaded the wrong region.  Here is a plot of the three curves in question:

The only region that is bounded by all three curves and no others, is the one between $x = 1$ and $x = 4$, and from $y = 1$ to $y = 16$.  Note you are not asked for the region below $y = \sqrt{x}$.
Therefore, the desired area is $$\int_{x=1}^4 x^2 - \sqrt{x} \, dx.$$ I leave the computation as an exercise.
Comment: Eight8 did that calculation as $\frac{49}{3}$.  Also the earlier small loop as $\frac{1}{3}$
Comment: Thanks! I updated my answer. Does that look better?
Answer: If you want to find the area of the purple shaded region, that is not what you have.
That area would be $\int_0^1 x^2 \ dx + \int_1^4 \sqrt x$
But it is not clear that you in fact do want the that shaded area.  That would would include the boundary $y= 0$ which is not mentioned in the instructions.
My picture looks like:

Eventually the parabola will hit the line, but I truncated the picture.
Which is what your work shows.
You have an unexplained sign change at the last step.  It is not wrong, but I would get in front of it, rather than flipping a sign with no explanation.
$\int_0^4 |\sqrt x - x^2| \ dx =  \int_0^1 \sqrt x - x^2 \ dx + \int_1^4 x^2-\sqrt x \ dx$
Comment: Thanks! I updated my answer. Does that look better?


GCD divisibility of LCM

Question: Show that the following conditions are equivalent:
i) There exist positive integers $a,b$ such that $\gcd(a,b)=d$ and $\operatorname{lcm}(a,b)=m$.
ii) $d∣m$
The first direction is very straightforward but for the second direction we start with so little I wrote $d = mq$ for some $q$ in the integers but I'm confused as to where to go next
Comment: It should be $m=dq$ for some $q$. To prove the other direction, let $a=dq$, $b=d$.
Comment: A much more interesting (but not difficult) question is the following.  Given positive integers $d$ and $m$, how many pairs $(a,b)$ of positive integers are there such that $\gcd(a,b)=d$ and $\text{lcm}(a,b)=m$.
Answer: If you have $d|m$, you immediately get $gcd(d,m)=d$ and $lcm(d,m)=m$, so the pair $(d/m)$ does the job completing the proof of the other direction.
Answer: We know that $$\gcd(a,b) | ax + by$$ So, the GCD divides any linear combination of $a$ and $b$. Isn't the LCM a linear combination of $a$ and $b$? $LCM = ka + 0\cdot b$ for some $k$.

GCD divisibility of LCM


Is running GNU Screen suid root the only way to make multiuser mode work?

Question: I'm running Ubuntu 11.10 and GNU Screen version "4.00.03jw4", and I'm trying to use multiuser mode.
The following process works for me:
as user "first_user"
> sudo chmod u+s /usr/bin/screen
> sudo chmod 755 /var/run/screen

and only after that can you do
> screen -S session_name
or if you've already created a screen session,
> screen -r session_name

and inside of screen:
>^A:multiuser on
>^A:acladd second_user "#?"

and if you want second_user to only be an observer
>^A:aclchg second_user -w "#?"

now you can, as user "second_user", do
> screen -x first_user/
to connect

when you're all done, do
> sudo chmod u-s /usr/bin/screen
> sudo chmod 775 /var/run/screen

because running screen suid root is a security risk

This is depressing. I've been searching diligently, but I can't find a better way. Is there one?
Update:

There is a bug in screen 4.06. Users can connect to a shared session, but can't send a command over it like: screen -S shared_session_name -X stuff "comands\n".
In the screen 4.09 it is fixed
Comment: An update on this: I just got a little more information from "twb" on freenode #screen: "On debian/ubuntu, /usr/share/doc/screen/README.Debian, last para"
Still says I'll need suid root, though. He also recommended tmux.
Answer: You are right. This is the only way to get multiuser screen running.
However, unless your box is very exposed, I don't think that leaving the suid bit on is a huge security risk.
Comment: Thanks Ben. For other reasons I've switched to tmux, and I wrote a blog post on how to do something similar with it that I find satisfying. http://danielpcox.org/remote-tmux-observation
Comment: @danielpcox your link is dead, is there another place for it? or a different solution after all this time?


changeing only pixels that are predominantly red, rather than removing the red component of all pixels

Question: Please I want to change only pixels that are  predominantly red, rather than removing the red component of all pixels. (I am using python 3.5) What might be wrong with my code.
from cImage import *
def removeRed(imageFile):
    myimagewindow = ImageWin("Image Processing",1000,500)
    oldimage = FileImage(imageFile)
    oldimage.draw(myimagewindow)

    width = oldimage.getWidth()
    height = oldimage.getHeight()
    newim = EmptyImage(width,height)

    for col in range(width):
        for row in range(height):
            old_pixel = oldimage.getPixel(col,row)
            new_pixel = Pixel(0, old_pixel.getGreen(), old_pixel.getBlue())
            newim.setPixel(col, row, new_pixel)
    newim.setPosition(width+1,0)
    newim.draw(myimagewindow)
    myimagewindow.exitOnClick()
removeRed("red.gif")

Comment: what is the problem?
Comment: I want to change only pixels that are predominantly red, rather than removing the red component of all pixels.
Comment: What do you want to replace your red pixels with?
Answer: if you define "predominant" by "highest value of R,G,B is R" then just compare values and set to 0 only if red is higher than both green and blue:
for col in range(width):
    for row in range(height):
        old_pixel = oldimage.getPixel(col,row)
        if old_pixel.getRed() > old_pixel.getGreen() and old_pixel.getRed() > old_pixel.getBlue():
            new_pixel = Pixel(0, old_pixel.getGreen(), old_pixel.getBlue())
            newim.setPixel(col, row, new_pixel)
        else:
            newim.setPixel(col, row, old_pixel)

Comment: For example I have a picture of a rose flower with a white background. This being the case, I would like to remove the red color from the rose flower without doing any other change to any color present in the picture. In short, I want the red color gone.
Comment: Predominant, in the sense that there is a part of the picture in red, so I want to remove that part alone,but because the background of the picture is white and there is a bit of red color in white, the background changes to cyan.In short I want to remove the red color from that specific pixel than removing it from the whole pixel
Comment: Have you tested my answer?
Comment: not working like what? I have tested it and if R is > B and > G, it removes the R component from the pixel.


Possible to password-protect a subdomain in web2py?

Question: Is there a way to password-protect a subdomain for a web2py-based page by using the routes file or other means? For instance, if you have mydomainname.com, can you make the main page public while password-protecting sub.mydomainname.com? Thanks.
Answer: You wouldn't use routes.py to do the password protecting, but you can use it to route sub.mydomainname.com to a particular application or controller within an application.
From that point, all you have to do is use the standard Auth checks to require login for access to the sub.mydomainname.com application or controller. To protect an entire application, somewhere in a model file after Auth has been defined, you can do something like:
<code>if (not auth.user and
    not (request.function == 'user' and request.args(0) == 'login')):
    redirect(URL('default', 'user', args='login'))
</code>
If you just need to protect a controller, you can put similar code at the top of the controller (though you don't need to check for the /default/user/login URL if it isn't the default.py controller).


which K3S ports should (not) be exposed on a public interface

Question: The K3S documentation explains which ports are required for this kubernetes distribution to work.
What it does NOT explain is, which of these ports are OK to be open on a public interface.
K3S seem to deal with the following ports
<code>Master
6443/tcp nodes
8472/udp flannel
10250/tcp kublet (metrics)
10251/tcp controller-manager
10255/tcp kublet (readonly)

Worker
10250/tcp kublet (metrics)
10255/tcp kublet (readonly)
30000-32767/tcp nodeports
</code>
Given the cluster nodes share their own subnet. It seems to make sense to bind the ports to the subnet interface (instead of the public interface). Unfortunately this is not exactly painless with K3S.
So before jumping through hoops:
Which of the ports above should be hidden from the public interface?
Which of the ports above are secured and maybe even required to available via public interface (e.g. access to the cluster via kubectl)?
Answer: Remember to prioritize security over convenience when deciding port exposure on your k3s cluster.
Ports that should not be accessible from the public interface:

6443/tcp (Master): This port is the primary communication port for the Kubernetes API server and should not be directly exposed to the public internet. Instead, consider using a VPN or secure tunneling to access it. That way, you've got a secret handshake before letting anyone in.

8472/udp (Master): You must restrict this port to internal cluster communication. The Flannel networking overlay uses it, and it handles communication between nodes.

10251/tcp (Master): Designed for internal communication, this port is used by the controller-manager and should not be exposed directly to the public.

Ports that can be safely accessed through the public interface:

10250/tcp (Master and Worker): This port is used by the kubelet for metric collection and monitoring. While it can be exposed, it's crucial to secure it properly, considering TLS encryption and proper authentication mechanisms to restrict access.

10255/tcp (Master and Worker): Similar to port 10250, it should be secured with proper authentication and encryption if exposed. The kubelet uses this port for read-only access.

30000-32767/tcp (Worker): These ports are used for NodePort services. While you can expose these ports, you must ensure that only necessary services are bound to them and that you have security measures (like firewalls or network policies) in place.
Answer: If you need to access your cluster with kubectl you only need the port 6443 exposed, anyways as the official docs indicates, there are some risky ports regarding flannel and vxlan:
k3s inbound ports


How can I denominate levels of lists in R?

Question: I would like to denominate the levels of a list, as with rownames() or colnames() when denominating rows and columns of matrices.
Example:
a<-matrix(rep(1,4),2,2)
b<-matrix(rep(2,9),3,3)
list<-list(a,b)
print(list)

Instead of returning [[1]] at the first level I want the list to use some string like 'matrix a' instead. Maybe this is simple to do.
Comment: +1 for to-the-point question and reproducible example.
Answer: Just use names:
names(list) = c("A","B")

> list
$A
     [,1] [,2]
[1,]    1    1
[2,]    1    1

$B
     [,1] [,2] [,3]
[1,]    2    2    2
[2,]    2    2    2
[3,]    2    2    2

list[["A"]]
     [,1] [,2]
[1,]    1    1
[2,]    1    1

Note that in general it is not good practice to use R reserved words such as list as variable names.
Comment: As with a lot of things in life :)


Getting the return address of a function in C

Question: I have some C code that essentially looks something like
double* my_function(double* input) {
    double* output = (double*) malloc(...);
    // Do some stuff to output based on input
    return output;
}

Assuming that I have already built an array called my_var_in, my main code has something like
double* my_var_out = my_function(my_var_in);

This creates new memory, which my_var_out points to; most of the time that's exactly what I want to happen. However, sometimes I just want to update the already existing memory. If I write
double* my_var = ... ; // allocate and fill my_var as desired
my_var = my_function(my_var);

Then I lose the pointer to the previously existing memory since my_var now points to the newly allocated memory. I've played around with several different ideas for how to get around this.
1) I know I can get this to work by changing the function style to something like
void my_function(double* destination, double* source) {
    // Check if destination == source and update based on this

I've previously developed with this style of passing the destination pointer as an input argument and updating it there; it works great functionally, but I like the style of outputting pointers better and want to keep developing with it.
2) Based on here and here, it seems that the __builtin_return_address function could be of some use. I think I can use this function to compare the input address with the output address and allocate/update based on that. After reading the documentation here, I wrote the following test
int* just_testing(int* in) {
    void* ptr = __builtin_return_address(0); // the return address of just_testing
    printf("Input address: %p\n", in);
    printf("From function: %p\n", ptr);

    return in;
}

int main(int argc, char** argv) {

    int* out = (int*) malloc(sizeof(int));
    out[0] = 2;
    printf("From main before call: %p\n", out);
    out = just_testing(out);
    printf("From main after call: %p\n", out);

    return 0;
}

This gives me the output
From main before call: 0x19b2010
Input address: 0x19b2010
From function: 0x4011f1
From main after call: 0x19b2010

Unfortunately, the results from __builtin_return_address don't match the address of the variable that receives the return from the function, which I did not expect.
Why aren't the addresses the same? I also welcome any constructive suggestions on a different approach besides the two I've listed here.
Comment: That's not what "return address" means, and what you want is impossible, sorry. Just continue passing the destination pointer as an argument; it's quite standard.
Comment: After trying out a few different implementations, it seems like this really is the best way to accomplish what I want. Thanks for the advice.
Answer: The cleanest solution is to have two separate functions:
#include <stdlib.h>
#include <string.h>

void compute_inplace(double *data) {
    data[0] *= 2;
}

double *compute_copying(const double *input) {
    double *output = malloc(sizeof *output * N);
    if (output == NULL)
        return NULL;

    memcpy(output, input, sizeof *output * N);
    compute_inplace(output);
    return output;
}

Note that the copying function takes its argument as a pointer to const, which helps if you accidentally pass a read-only memory area to it.
Comment: I think that the second function should still return the pointer. Apart from that two functions is the best solution because it is known at compile time what the programmer wants.
Answer: Other possible solution could be to have following definition:-
double* my_function(double* input, bool alloc)
{
   double* output = input;

   if(alloc)
   {
       //allocate new memory
       double* output = ( double*)malloc(...);
   }
   //else work with input memory

   //do modifications here

   return output;
}

Comment: Good suggestion. I just implemented it and included varargs so that it only needs the extra argument if it is updating. Still not as clean as I would like, and there's still a possibility of losing the pointer.


JavaScript Custom Alert Box

Question: I'd Like to make a custom alert box, usually an alert box would have OK, but i want to add more buttons like 'yes', 'no' or 'hit that guy', right now I only know how to make alertboxes, confirmboxes and promptboxes.  I want it to look like on chrome when the page is not responding you can choose to wait or kill the pages.  Here is a picture of what I am trying to do. I only want to use JavaScript or jQuery, and no other languages please.Thanks for helping.P.S. Sorry for the wall of text and not much code.
Comment: http://ninodezign.com/free-awesome-jquery-plugin-for-custom-alert-box/
Answer: The system alert dialog is as-is. You can't change it. You seem to know that you can use a custom dialog message, but don't want to because they don't look nice? You know you can customize the look, or use a pre-defined style. Take a look at jQuery UI "themeroller" for additional styles:
http://jqueryui.com/themeroller/
Answer: You can define your own dialogs like this:
$("
Test message
").dialog();

If no, you can define your own function to use.
custom_alert();
custom_alert("Display Message");
custom_alert("Display Message", "Set Title");

function custom_alert(output_msg, title_msg)
{
    if (!title_msg)
        title_msg = 'Alert';

    if (!output_msg)
        output_msg = 'No Message to Display.';

    $("

").html(output_msg).dialog({
        title: title_msg,
        resizable: false,
        modal: true,
        buttons: {
            "Ok": function()
            {
                $( this ).dialog( "close" );
            }
        }
    });
}

Comment: That is if the OP is using jQuery UI...
Comment: @epascarello seems he was using it at all... ;)

JavaScript Custom Alert Box


What are surface elements?

Question: would somebody please help me out with surface integrating? While calculating flux, there is the integrand $F\cdot n$ however in the definition of surface integration I am reading about $|| r_{u} \times r_{v}||$. Thanks very much. I do not remember why I keep having to change $d\mathbf{S}$ into $\mathbf{n} dS$.
Answer: I would say $d\mathbf{S}$ is the vector element of surface area and $dS$ is the scalar element of surface area.  So $d\mathbf{S} = \mathbf{N} dS$ where $\mathbf N$ is the unit normal to the surface.
Which normal?  The one chosen according to the rules you are using!  Technically, you are integrating over an oriented surface, and $\mathbf{N}$ is determined by the orientation.

added
Note if $\mathbf r(u,v)$ is a parametric description of the surface, then at each point of the surface, $\frac{\partial\mathbf r}{\partial u}$ and $\frac{\partial\mathbf r}{\partial v}$ are tangents to the surface,
$\frac{\partial\mathbf r}{\partial u}\times \frac{\partial\mathbf r}{\partial v}$ is a normal to the surface.  The norm $\|\frac{\partial\mathbf r}{\partial u}\times \frac{\partial\mathbf r}{\partial v}\|$ is the length of that normal vector.  Then think of $dS = \|\frac{\partial\mathbf r}{\partial u}\times \frac{\partial\mathbf r}{\partial v}\|\;du\;dv$, where $\|\frac{\partial\mathbf r}{\partial u}\times \frac{\partial\mathbf r}{\partial v}\|$ is the area of a paralellogram with sides $\frac{\partial\mathbf r}{\partial u}$ and $\frac{\partial\mathbf r}{\partial v}$.  And $d\mathbf S = (\frac{\partial\mathbf r}{\partial u}\times \frac{\partial\mathbf r}{\partial v})\;du\;dv$ is a vector with magnitude $dS$ and perpendicular to the surface.
Comment: I could not see why the to multiply by the magnitude $\displaystyle || \dfrac{dx}{du} \times \dfrac{dx}{dv}||$....
Comment: unless they are just analogs to the multiplication as in spherical and cylindrical coordinates, etc.

What are surface elements?


Can these equations be considered as differential equations?

Question: Consider a differential equation with  a term containing $y(x_0)$, for example $$y'' - 2y' + y = y(x_0)$$ $x_0 \in \mathbb{R}$ is a constant. My question is, does such equations fall under the category of differential equations? I have never studied any equation with such a term. If its a differential equation, then $y(x_0)$ can be considered a constant coefficient?
Comment: There could be multiple terms like $y(x_0), y(x_1),y(x_2)$ too.
Comment: But $y(x_0)$ is assumed to be a constant.
Comment: @Dr.SonnhardGraubner : it is not independent of $y$. It depends on the solution.
Comment: Think that $y(x_0) =\int \delta(x-x_0) y(x) dx$. After that you can solve the linear DE using the Laplace Transform.
Comment: @Cesareo : differential equations with distributions? Any theory available on this?
Comment: I remember seeing such kind of a distribution term as impulse in the field control theory
Answer: Although the term $y(x_0)$ depends on the solution $y$ it is still a constant as it doesn't depend on $x$.
Let's try to solve your equation $y'' - 2y' + y = C,$ where $C=y(x_0).$ One solution is $y(x) = C.$ The solutions of the homogeneous equation are $y(x) = (Ax+B) e^x.$ Therefore the general solutions are
$$y(x) = (Ax+B) e^x + C.$$
To get $y(x_0) = C$ we must have $A=B=0.$ Thus there is only the constant solution
$$y(x) = C = y(x_0).$$
Comment: You can also have constants $A, B$ with $Ax_0+B=0$ so that the general solution is $$y(x) = A(x-x_0)e^x+B$$ (replaced $C$ with $B$).


What is the value of s?

Question: This is something I came up with a day. I tried a procedure but later I found it was incorrect. So here it is:
$$2^s = 2s + 2 $$
Comment: This usually requires the use of [Lambert's W function](https://en.wikipedia.org/wiki/Lambert_W_function#Solving_equations); in particular, the example linked to is $3^x=2x+2$, almost exactly your equation.
Comment: Why do you expect this to have a clean solution?  Very quickly, mixing exponentials and polynomials you will enter the realm of "*[non-elementary](https://en.wikipedia.org/wiki/Elementary_function#Non-elementary_functions)*" solutions.  This probably will only be solvable using things like Lambert-W functions or using numerical methods
Comment: (*In response to someone noting that $3$ is a simple solution to the equation*)
 *A* simple solution, which can be spotted by inspection... It is implied that the OP is looking for an algebraic approach that doesn't rely on luck or a flash of inspiration to find the answer but a process.  It missed other solutions such as one near $-0.690093$ which you will not be so lucky as to write without using Lambert-W functions
Comment: There is no explicit solution for this equation.
Answer: As the commentators have written,
the solution involves
the Lambert W-function.
Look it up.
The explicit solution
according to Wolfy
 is
$s = -\dfrac{W(-\log(2)/4) + \log(2)}{\log(2)}
$.
The numeric values
for the two branches
of the W-function are
$s≈-0.690093
$
for the main branch and
$s = 3$
for the -1 branch.
Yep -
$2^3 = 2\cdot 3 + 2$.
Comment: It's a fun one. $W(y)$ solves $xe^x = y$ for $x$.
Comment: Ok, Thanks, that is a function I had no notion before. On my agenda to study it.

What is the value of s?


Proving the set of all monotonic increasing sequences is closed in $\ell_2$

Question: The following is a homework question, therefore tips on solutions are also kindly welcome.
Let $X=\ell_2$ be the set of all infinite sequences with $\sum_{n=1}^\infty x_n^2 < \infty$, with the metric:
$d(x_n,y_n)=\sqrt{(\sum_{n=1}^{\infty}(x_n-y_n)^2}$.
We define $A\subseteq X$, where $A$ is the set of all sequences such that for all $n$, $x_n \leq x_{n+1}$ (monotone increasing).
Prove that $A$ is a closed set.
My remark:
Since $x_n \in \ell_2$ then $\sum_{n=1}^\infty x_n^2 < \infty $, therefore $\lim_{n \to \infty} x_n^2 = 0$. So I think that the points in $A$ are all the sequences such that $x_n =0$ for all $n>N$ for some $N \in \mathbb{N}$.
I.e $x_n \in A \iff x_n = 0 \;\;\forall n>N$
Does is help? Is it true?
Comment: What about the sequence $(-\frac{1}{n})$?
Comment: As a tip for a solution: what is your/a common strategy to check whether a set is closed?
Comment: Either to check if the complement is an open set- which in this case seems, at least at a first glance rather difficult. The second option is to check if for every convergent sequence of elements in the set, the limit is also an element of the set.
Comment: Yes, the second approach should work. Note that here we have a sequence where each element is a sequence itself.
Comment: You can use that each of the linear functionals $x\mapsto x_{n+1}-x_n$ is continuous.
Comment: So a sequence $(x_n)_m$ of increasing sequences converges to some sequence $(y_n)$. You need to show that $(y_n)$ is increasing. But if $(x_n)_m$ converges to $(y_n)_m$ then for any fixed $N$ the sequence $(x_N)_m$ converges to $y_M$. So all that you need to show is that if $a_n\leq b_n$ then $\lim a_n\leq \lim b_n$ which is rather fundamental.
Answer: From the comment from Jonas Lenz it is. Lear that any element in $A$ is a sequence with  non positive values that in increase to $0$. Suppose $(\boldsymbol{x}_m: m\in\mathbb{N})$ is a sequence in $A$ which converges in $\ell_2$. Then, for any positive integers $m,n$
$$ |\boldsymbol{x}_m(n)-\boldsymbol{x}(n)|\leq\|\boldsymbol{x}_m -\boldsymbol{x}\|_2$$
From this we see that
$$\lim_{m\rightarrow\infty}\boldsymbol{x}_m(n)=\boldsymbol{x}(n)$$
Since
$$\boldsymbol{x}_m(n)\leq\boldsymbol{x}_m(n+1)\leq0$$
We can conclude that
$$\boldsymbol{x}(n)\leq \boldsymbol{x}(n+1)\leq0$$
Answer: I'll add an answer based on a different approach..
It suffices to show that the complement $A^c$ of $A$ is open in $\ell_2$; to show this, for any $x\in A^c$, we need to find some radius $\epsilon>0$ such that, if $\|y-x\|_2<\epsilon$, then $y\in A^c$.
Indeed, if $x\in A^c$, then (by the definition of $A$) there exists some $n$ with $x_n>x_{n+1}$. Let $\epsilon=(x_n-x_{n+1})/2>0$. If $\|y-x\|_2<\epsilon$, then $|y_n-x_n|,|y_{n+1}-x_{n+1}|<\epsilon$. So
$$y_n-y_{n+1}>(x_n-\epsilon)-(x_{n+1}+\epsilon)=x_n-x_{n+1}-2\epsilon=0.$$
So, $y$ is not a monotonic increasing sequence, and $y\in A^c$, as desired.
Answer: The approach you pointed out makes sense to me! It just needs a few extra steps.
Since $\lim_n x^2_n=0$, then $\lim_n|x_n|=0$. Since the sequence is monotone increasing, this implies that $\sup_n x_n=0$ (can you see why?). A similar reasoning applied to $-x_n$ shows that $\inf_n x_n=0$.
The only thing left now is to show that $\{0\}$ is a closed set, but perhaps you can provide the details of that :).
Comment: One cannot apply similar reasoning to $-x_n$, as the condition that a sequence is monotone increasing is not preserved under negation.