With a 'review' node type and a node reference to a 'product ' node type limit number of user reviews to one

Question: In a product node type with a review node type that has a reference field to it, how do I only permit one review per user per product node? Do I use the Rules module and if so how do I configure the rule? Do I make a custom query and then unset the Add Review button/link on the product node in a custom module or in template.php?
(edit) Take the example of product reviews on Amazon or muffler repair reviews on Yelp. The user who makes the review  gets one review per listing or item. After they create the review, they can edit it but can't make another one for that listing or item. Seems logical. Likewise the Fivestar rating widget only allows one vote per item so having several reviews for an item will not permit more than just one Fivestar rating.........
Unless somebody has a better solution, I'm going to test -- since the Fivestar widget makes the database query anyway -- if it has been set by the user on the node view. If true then I will disable the Node Reference URL widget button in the links area. If I need more security, I will create code or a Rue that tests on the Node Add page if the Fivestar widget has already been set to disable the Node Add page and redirect the user back to the product.
Comment: What do you mean with "only permit one review per user"?
Answer: You might need to try a custom module for this.  Rules are too generic as you can only control a user's right to create a type of content.  If I was to write a module for this, it would go something along these lines:
• Use hook_form_alter to add an extra validation function to your Review node form
• Check if the user has submitted a review before in the db
• Throw an error if a record exists in the database
Something like the following code should work, but this is untested.
Edited to note that this is Drupal 6 code but if you use it as a template it shouldn't be too far away.
<?php

function MYMODULE_form_alter($form_id, &$form) {
    // If the form is a "review" node form
    if ($form_id == 'review_node_form') {
        // Add an extra validation function
        $form['#validate'][] = 'MYMODULE_user_node_limit';
    }
}

// Validation function
function MYMODULE_user_node_limit($node) {
    // Get our logged in user's details
    global $user;
    // Run a database query (something like this)
    $sql = "SELECT {node}.uid \n"
    . "FROM {content_type_review}, {node} "
    . "WHERE {content_type_page}.field_node_ref_nid = {node}.nid "
    . "AND {node}.nid = %d"
    . "AND {node}.uid = %d";
    $result = db_query($sql, $node->nid, $node->uid);
    if ($result === FALSE) {
        // Throw error
        drupal_set_message('You have already submitted a review of this item.', 'error');
    }
}
?>

Edited to answer additional comment by asker
Regarding the comment made by Adam S - you could use the code I have already posted in conjunction with the Drupal 7 equivalent of Drupal 6's hook_nodeapi. Here is a list of Drupal 7's node hooks for you to have a look at.  Also, have a look at Eric London's Drupal 6 example of a problem similar to yours of limiting a user's node writing privileges.  Apologies for not providing an exact Drupal 7 example but if you follow the basic premise of Eric London's link but modify it in conjunction with my code, you should be able to solve your problem.
Comment: Although it doesn't solve the problem of the link from the node reference URL widget being shown on the page it does validate the node to force only one review in case some crafty person wanted to place several reviews of their product from the same user. So I'll just unset the link and validate the form with this. However, it might be better to validate before they receive the form and redirect back to the page.
Comment: I have amended my answer to answer your comment, Adam.
Answer: For what it's worth, I took a slightly different approach that might be useful.  It isn't perfect, but works very well for me.  I borrowed heavily from the solution here:
How to limit a user to one vote when using Fivestar?
But I didn't like changing my theme.  I wanted to to it in the form alter, as I wanted to control things before they got to the browser (so other #validate solutions weren't right for me).  Anyway, here is my approach:
<?php
function MYMODULE_form_alter($form_id, &$form, $form_id) {
    switch($form_id) {
        case 'comment_node_product_form':  //Modifications to the voting for five star on comment forms
            MYMODULE_fivestar_limit_votes($form);
            break;
    }
}

/**
 * Function to limit votes on a particular node to one per user.  Also requires users to be logged in to vote.
* This assumes that you are passing in a node as the entity for which the vote is recorded.  That little bit would
* of course be more flexible if done differently.
*
* @param unknown $form
* @param string $voteTag
* @param string $entityType
*/
function MYMODULE_fivestar_limit_votes(&$form, $voteTag = 'rating', $entityType = 'node') {
    $path = drupal_get_path('module', 'fivestar');
    // These are likely added already, but no harm done just in case
    drupal_add_js($path . '/js/fivestar.js');
    drupal_add_css($path . '/css/fivestar.css');
    $replacement = false;
    $is_login = user_is_logged_in();
    $nid = $form['#node']->nid;

    $rating = votingapi_select_single_result_value(array(
        'entity_id' => $nid,
        'entity_type' => $entityType,
        'tag' => $voteTag,
        'function' => 'average',
    ));
    $lang = $form['field_product_rating']['#language'];
    $widget = $form['field_product_rating'][$lang][0]['rating']['#widget'];
    if ($is_login) {
        if (isset($rating)) {
            $voting_message = "
You have already rated this.
";
            $replacement = theme('fivestar_static', array('rating' => $rating, 'stars' => 5, 'tag' => $voteTag, 'widget' => $widget)) . $voting_message;
        }
        // The 'else' here is to leave the form alone.
    }
    else {
        $fivestar_links = l('Login', 'user/login') . ' or ' . l('Register', 'user/register');
        $voting_message = "
Only registered user can rate this content type.
$fivestar_links to rate this content type.
";
        $replacement = theme('fivestar_static', array('rating' => $rating, 'stars' => 5, 'tag' => $voteTag, 'widget' => $widget)) . $voting_message;
    }
    if ($replacement) {
        $form['field_product_rating']['#type'] = 'markup';
        $form['field_product_rating']['#markup'] = $replacement;
        $form['field_product_rating']['#tree'] = false;
        unset($form['field_product_rating']['und']);
    }
?>


Swift iOS : Find parse users via UISearchBar and dysplay results in a table view

Question: i trie to find parse users via UISearchBar and display results in a table view.
When i heat search, nothing happened...
My idea was to use the searchText.text as a query to PFUser.
Should i try to use searchBar with search display controller instead ?
Any idea ?
import UIKit

  class AllFriendsTableViewController: UITableViewController, UISearchBarDelegate,      UISearchDisplayDelegate {
@IBOutlet var SearchDisplay: UISearchDisplayController!

var userList:NSMutableArray = NSMutableArray()

 func searchBarShouldBeginEditing(searchBar: UISearchBar!) -> Bool {
    return true
}

func searchBarShouldEndEditing(searchBar: UISearchBar!) -> Bool {
    return true

}

func searchBar(searchBar: UISearchBar!, textDidChange searchText: String!) {
    loadUser()
}

@IBOutlet var searchText: UISearchBar!

func loadUser () {

    userList.removeAllObjects()
    var findUser:PFQuery = PFUser.query()
    findUser.whereKey("username", equalTo: searchText.text)

    findUser.findObjectsInBackgroundWithBlock { (objects:[AnyObject]!, error:NSError!) -> Void in
        if !(error != nil) {
            // The find succeeded.
            println("succesfull load Users")
            // Do something with the found objects
            for object  in objects  {
                self.userList.addObject(object)
                println("users added to userlist")
            }
            self.tableView.reloadData()
        } else {
            // Log details of the failure
            println("error loadind user ")
            println("error")
        }

    }
}

override func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
    return 1
}

override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
    if tableView == searchDisplayController.searchResultsTableView {
        return userList.count
    }
    else {
        return 0
    }
}

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {

    let cell: AllFirendsTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)as AllFirendsTableViewCell

    let users:PFObject = self.userList.objectAtIndex(indexPath!.row) as PFObject

    var findUserName:PFQuery = PFUser.query()
    findUserName.whereKey("username", containsString: searchText.text)

    findUserName.findObjectsInBackgroundWithBlock{
        (objects:[AnyObject]!, error:NSError!) -> Void in

        if !(error != nil) {

            if let user:PFUser = users as? PFUser {
                cell.userNameTextField.text = user.username
                println("user exist")
                // define avatar poster

                if let avatarImage:PFFile = user["profileImage"] as? PFFile {
                    avatarImage.getDataInBackgroundWithBlock{(imageData:NSData!, error:NSError!)-> Void in

                        if !(error != nil) {

                            let image:UIImage = UIImage(data: imageData)

                            cell.avatarImage.image = image as UIImage
                            cell.avatarImage.layer.cornerRadius = 24
                            cell.avatarImage.clipsToBounds = true

                        }

                    }

                }
                else {
                    cell.avatarImage.image = UIImage(named: "Avatar-1")
                    cell.avatarImage.layer.cornerRadius = 24
                    cell.avatarImage.clipsToBounds = true
                }
            }

        }

    }

  return cell

}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true)
    navigationController.navigationBar.hidden = false
    loadUser()

}

override func viewDidAppear(animated: Bool) {

}

override func viewDidLoad() {

    // Do any additional setup after loading the view, typically from a nib.
}

}
Comment: You should search for users when search button is tapped, but currently you do it in a cellForRow method. This is wrong. There is an article about searchbar at raywenderlich.com, read it.
Comment: thanks but i ve allready read this tuto. If i do it like raywenderlich.com, i have to download all parse user and then filter the result. I would prefer to download only the users who matches the searchText.text.
Comment: Sorry, I was wrong. I checked your code and it looks OK.
Comment: ok but i can't see any results  in the table view. Something is going wrong.
Answer: I suspect this might be due to you attempting to reload the tableview from the background thread that your network request occurs on.  UI updates should happen from the main thread.
In your loadUser() function try doing your tableview reload from the main thread, as follows:
NSOperationQueue.mainQueue().addOperationWithBlock({
    self.tableView.reloadData()
})

That may fix your issue.
Comment: Those withBlock: methods from parse run the block on the main thread.


Jenkins: SmokeTest answer success, but 1 Test is failure

Question: We have in our System SmokeTests on Jenkins. In the log, I see:
<code>[ERROR] Tests run: 170, Failures: 1, Errors: 0, Skipped: 17
</code>
Jenkins give it out as successful. What can be the problem?
Answer: I have found the oroblem. The instance of the jenkins had not enogh memory to catch all. So i reduced the debugmode to write less informations. Know it run without a problem


Help solving volume equation

Question: I'm working on some ecological data that uses the following equation to calculate volume (V) of timber logs in cubic metres per hectare based on surveys along a transect.
$$ V=\frac{\pi^2\Sigma d^2}{8L}$$
where L is length of transect, and d is diameter of the log.
My question is do square all the individual diameters, then add them, then add  $\pi^2$
or do I sum all diameters, square them, then add $\pi^2$?
Bonus points for explanations! Thanks in advance.
Comment: Is $\sum_{k=1}^{n}d_k^{2}$ or $\sum_{k=1}^{n}d^{2}$?And you multiply $\pi^2$.
Answer: Remember the order of operations:

parentheses
exponents
multiplication and division from left to right, with multiplication and division (which is multiplication by the multiplicative inverse of the divisor) taking equal precedence
addition and subtraction from left to right, with addition and subtraction (which is addition of the additive inverse of the subtrahend) also taking equal precedence

The summation symbol acts like a set of parentheses, so we do what is inside first.  Recall that
$$\sum_{k = 1}^n a_k = a_1 + a_2 + \cdots + a_n$$
In your example, $a_k = d_k^2$, so we obtain
$$\sum_{k = 1}^n d_k^2 = d_1^2 + d_2^2 + \cdots + d_n^2$$
Since exponentiation takes precedence over addition, we first square each $d_k$, then add.  If we wanted to represent the square of the sum, we would instead write
$$(d_1 + d_2 + \cdots + d_n)^2 = \left(\sum_{k = 1}^n d_k\right)^2$$
Once we have performed the addition, we have a product of three factors:
\begin{align*}
\frac{\pi^2\sum_{k = 1}^n d_k^2}{8L} & = \pi^2 \cdot \sum_{k = 1}^n d_k^2 \cdot \frac{1}{8L} && \text{since division is multiplication by the reciprocal}\\
& = \pi^2 \cdot \frac{1}{8L} \cdot \sum_{k = 1}^n d_k^2 && \text{since multiplication is commutative}\\
& = \frac{\pi^2}{8L}\sum_{k = 1}^n d_k^2 && \text{multiply from left to right}
\end{align*}
In answer to your question, we first square each $d_k$, add the squares, then multiply the sum by $\pi^2$, and divide the result by $8L$.  Note that multiplying by $\pi^2$, then dividing by $8L$ is equivalent to multiplying by $\dfrac{\pi^2}{8L}$.
Answer: I can't speak as to the validity of the equation, but what it means in this form is to square each of the $d$s, add them, and then multiply by $\dfrac{\pi^2}{8L}$. So for example if you had $d_1=1$, $d_2=2$, and $d_3=3$ for $3$ different logs, you would get
$$\frac{\pi^2}{8L}\times\left(1^2+2^2+3^2\right)$$
Comment: Thanks for the response. I see this gives a different outcome to the answer below. Can you explain to me why the $\frac{\pi^2}{8L}$ multiplied by the sum of the squared diameters, when $\pi^2$ and $\Sigma d^2$ are both together above the division line?
Comment: @DHunter Please see N.F. Taussig's answer which covers the details, but basically dividing first or dividing at the end in this case doesn't matter.
Answer: From what I can guess the question is how to compute
$$\pi^2 \sum_{i=1}^N d_i^2 = \pi^2 (d_1^2 + d_2^2 + d_3^2 + \ldots + d_N^2)$$
This means we first sum the squares of all diameters and then multiply the result (not add) by $\pi^2$.

Help solving volume equation


Odd behavior of Windows thread

Question: I am combining GTK+, WinAPI and Winsock to create a graphical client-server interface, a waiting room. nUsers is a variable that determines the number of clients successfully connected.
Within a Windows thread, created by:
CreateThread(NULL, 0, action_to_users, NULL, 0, NULL);

I use the do-nothing while loop so that it freezes until a user connects.
while(!nUsers);

However, it never passes through the loop as if nUsers never becomes > 0.nUsers counts the number of clients connected properly, as I constantly monitor it and use it in a variety of different functions.
To prove my point, something even stranger happens.
If I make the loop
while(!nUsers) { printf("(%i)\n", nUsers); }

To spam the console with text printed out (doesn't matter what text as long as it is not an empty string) it works as intended.

What could be possibly going on here...
Comment: Mark `nUsers` `volatile`.
Comment: @orhtej2 You are genuis. It worked.. but why..
Comment: I mean I am a qualified C programmer, I know where to use volatile, but now it didn't look like the situation I know of
Comment: 'while(!nUsers);' a room heater.  Windows has plenty synchro options that require less A/C, (and does not completely waste a core).
Comment: @MartinJames what do you mean?
I should admit that I am new to windows threading. I rely on the function reference.. and I have entirely read it.
Comment: @Corelation You 'do nothing' loop does something.  It uses 100% of a complete execution core, and it uses up inter-core memory bandwidth while 'doing nothing'.  Besides wasting CPU/memory resources that would be better used 'doing somethig useful', is uses a lot of power and you may well hear your cooling fans speed up a notch, in the manner of a fan heater:(   Perhpas not unsurprisingly, your OS provides synchronization mechanisms to allow efficient inter-thread signaling without CPU-looping.  You shoud search MSDN/Google for 'events and 'semaphores'.
Comment: Incidentally. while it worked 'for you' in this case, 'volatile' is not guaranteed effective even for the (bad) polling operation/s you are doing.  Google/MSDN for 'CriticalSection'.
Answer: Regarding the original problem: compiler is free to cache the value of nUsers since the variable is not modified within this loop. Marking the variable volatile prevents this optimization as described here.
Regarding what you're trying to achieve - it looks like a producer-consumer pattern, where the thread(s) handling the sockets are producers and your GUI thread is a consumer. You can slow down your consumer loop to only loop when new data is available using:

semaphores as showcased here - producer thread increments count on semaphore while consumer decrements it upon dequeing work item.
Events like here - producer thread signals an event while consumer thread waits for it to become signalled. You can queue the work in some queue to allow more than one item being processed.
Condition variables (XP+) - here a variable you're waiting for gets signalled upon meeting certain criteria.
Comment: 'where the thread(s) handling the sockets are producers and your GUI thread is a consumer' - if that is the case, then neither the OP's original 'loop doing nothing' or our suggestions of events'semas/condvar waits are useful - one cannot wait in a GUI event handler.  The go-to API for comms in that case is PostMessage(), or possibly PostThreadMessage().

Odd behavior of Windows thread


Vários if em uma condição SQL

Question: Estou tentando usar 2 ifs porém o resultado sempre retorna vazio, quando eu utilizo somente um if ele vai.
SELECT aci_codigo, aci_valor_pagamento, bai_fk_pes_codigo,
       aci_tipo_pagamento, aci_fk_ftm_codigo, aci_nosso_numero,
       ftm_descricao, ftm_codigo, bai_fk_bor_codigo,
       bor_tipo,bai_data_cadastro
FROM acordo_item
INNER JOIN baixa ON bai_fk_aci_codigo = aci_codigo
INNER JOIN bordero ON bor_codigo = bai_fk_bor_codigo
LEFT JOIN financeiro_tipo_movimentacao ON ftm_codigo = aci_fk_ftm_codigo
WHERE aci_status = 'B'
AND
IF(aci_tipo_pagamento = "PE", bai_data_cadastro, bor_data_criacao) >= '2016-11-22 00:00:00'
AND
IF(aci_tipo_pagamento = "PE", bai_data_cadastro, bor_data_criacao) <= '2016-11-22 00:00:00'
GROUP BY aci_codigo

Comment: Qual é o objetivo da restrição por aci_tipo_pagamento? Observe que construiu algo como "A >= x and A <= x". A restrição somente será verdadeira se A = x. Isto é, somente se a data selecionada for 22/11/2016.
Answer: ...
AND
(
IF(aci_tipo_pagamento = "PE", bai_data_cadastro, bor_data_criacao) >= '2016-11-22 00:00:00'
AND
IF(aci_tipo_pagamento = "PE", bai_data_cadastro, bor_data_criacao) <= '2016-11-22 00:00:00'
)
GROUP BY aci_codigo

Comment: Como é que estes parêntesis resolvem o problema???
Comment: Mas resolveram ?
Answer: Consegui resolver da seguinte maneira
AND  IF(aci_tipo_pagamento = 'PE', bai_data_cadastro >= '{$dataI} 00:00:00', bor_data_criacao >= '{$dataI} 00:00:00')
                AND  IF(aci_tipo_pagamento = 'PE', bai_data_cadastro <= '{$dataF} 23:59:59', bor_data_criacao <= '{$dataF} 23:59:59')

Vários if em uma condição SQL


Do we need preprocessing before applying a sophisticated undersampling method?

Question: My question is around applying undersampling methods to an imbalanced, and highly dimensional dataset, with mixed data. Lets say as an example, I have 150 features, also a highly imbalanced binary target variable.
I want to apply a sophisticated undersampling method, not random undersampling. Lets say something like OSS, Tomek, CNN from Imblearn.
I have 2 questions for applying undersampling to this dataset:
1-) Do I need to run PCA to reduce number of 150 features before undersampling?
2-) Do I need preprocessing? Like scaling to numerical features and one-hot encoding to categorical ones etc?
Thanks
Comment: [Are you sure you need to undersample at all?](https://stats.stackexchange.com/q/357466/1352)
Answer: First, you probably do not need to do anything about the class imbalance. Much of the apparent issue with class imbalance comes from using improper scoring rules like accuracy that depend on a (typically arbitrary) threshold. If you are sick of your imbalanced problem returning that all or almost all of the predictions belong to the majority category, the first thought should be to change the threshold instead of the data. (Probably even better would be to consider one of the proper scoring rules discussed in the link, but if you must use a threshold, I suspect you can change it to suit your needs.) Further, downsampling to fix what is likely a non-problem is probably the worst idea of all. Aside from issues of experimental design, before you collect data, which is discussed in the excellent answer by Dikran Marsupial to the linked question, downsampling discards precious data to solve a non-problem. (Perhaps there could be computational reasons for downsampling to allow your dataset to fit into memory or to run in a reasonable amount of time, though the better plan might be to upgrade your hardware.)
However, even when an idea is a poor one, it can be helpful to know how it would fit into a reasonable workflow, even if that is just to show its drawbacks.
I see arguments in favor of either order.

Fiddle with the data to create new data. Then you have your synthetic data that you are treating as if they were real, and you do the rest of the modeling as if the synthetic data were real.

Do your preprocessing on the real data. Then synthesize new data based on the preprocessed real data, since the undesirable features of the data will have been removed.

The former makes the most sense to me. You are doing the rest of the modeling as if the synthetic data were real. Why not pretend the synthetic data were real when it comes to the preprocessing? This also has the advantage of assuring that your synthetic data adhere to the properties you want, whereas the latter idea allows for nastiness to creep in that you then are unable to preprocess away.
However, I do believe you can treat this as a hyperparameter and go with whatever leads to the best performance.
Overall, though, the best move is probably not to undersample (or even oversample) at all, and to use proper statistical methods on data that represent the reality of your situation.
Comment: Thanks for your detailed answer on a different perspective I didn't thought before. I will dig deeper into your suggestion.


Google gson handle json with different types

Question: I have following json to prase and convert to POJO.
{
    "name" : "test",
    "parameters":[
    {"key":"p1","value":["array of strings"]},
    {"key":"p2","value": "some string value"}
    ]
}

As you can see the parameters key is an array of objects(key value pair) where "value" can be of two types (an array or string).
My POJO for key value pair object looks like this -
public class KeyValuePair {
    private String key;
    private Object value;
}

This works great when all objects in "parameters" array are of string type but it breaks if I get an array of string with error:

Expected a string but was BEGIN_ARRAY at line 1 column 261 path $.parameters[0].value

How can I handle both types?
Answer: You can check value's value type while parsing.
Like this...
if (value instanceof JSONArray) {
// It's an array
// store in arrray
} else if (value instanceof JSONObject) {
// It's an object
// store in object
} else {
// It's something else, like a string or number
}

Hope this helps. :)
Comment: So I need to do manual parsing? I was hoping if there was way to handle this automatically when using like gson.fromJson("json", MyPojo.class)
Comment: As you have used "Object" for value is the only way to store String or Array which is not working as you have mentioned. Then one way left that is manual parsing according to me.
Answer: This Pojo has problem and Gson couldn't parse it  use this POJO
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class KeyValuePair {

@SerializedName("name")
@Expose
private String name;

@SerializedName("parameters")
@Expose
private List<Parameter> parameters = null;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public List<Parameter> getParameters() {
return parameters;
}

public void setParameters(List<Parameter> parameters) {
this.parameters = parameters;
}

 }
-----------------------------------com.example.Parameter.java-----------    ------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Parameter {

@SerializedName("key")
@Expose
private String key;

@SerializedName("value")
@Expose
private String value;

public String getKey() {
    return key;
}

public void setKey(String key) {
    this.key = key;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

}

or using this site to generate POJO based on your json JsonToPojo
Answer: Bigoloo has the right approach. However it is enough to just change the POJO as:
@Getter @Setter
public class MysticalObject {
    private String name;
    private Collection<Object> parameters;
}

and then:
MysticalObject mo = new Gson().fromJson( json, MysticalObject.class );

so you should not need to create any Parameter class. Just when getting the value from Collection parameters check if it is of type String or String[].
Parameters will be a Map - LinkedTreeMap in my case - so you can get parameters from it also by keys p1 and p2.


Solution of the Cauchy problem $xu_x + yu_y = 0$, $u(x,y) = x$ on $x^2 +y^2 =1$

Question: The Cauchy problem $xu_x + yu_y = 0$, $u(x,y) = x$ on $x^2 +y^2 =1$ has

a solution for $x ,y \in \Bbb R$

a unique bounded solution in $\{x ,y \mid (x,y) \neq (0, 0)\}$

an unique solution in $\{x ,y \mid (x,y) \neq (0, 0)\}$ but not bounded.

I have tried to solve this problem. Can anyone please check and tell me how to proceed further and which option(s) will be right?
Answer: Let $$v(r,\theta) = u(r\cos \theta, r\sin \theta)$$
Then $$u_x = v_r\cos\theta - v_\theta r \sin \theta \\
 u_y = v_r\sin\theta + v_\theta r \cos \theta $$
$$xu_x + yu_y = v_r r\cos^2\theta - v_\theta r^2 \sin \theta \cos\theta \\
 +  v_r r\sin^2\theta + v_\theta r^2 \cos \theta \sin \theta$$
$$
0 = xu_x + yu_y = r v_r
$$
Therefore $v_r = 0$ everywhere except possibly at the origin, and
$$
v(r, \theta) = f(\theta)
\\ u(x,y) = f(\mbox{atan2 } (y/x) ) $$
where the atan2 function is the usual quadrant-aware arctangent (atan2 is in the third quadrant if $x$ and $y$ are both negative, etc).
Now if we impose the boundary conditions, the unique solution is
$$
u(x,y) = f(\cos\left(\mbox{atan2 } (y/x) \right)
$$
This is a bounded function, but it is not defined at $(x,y) = (0,0)$ because on an arbitrarily small circle around the origin, ($u(x,y)$ takes on all values in $[-1,1]$.
So the answer is 2 - bounded everywhere but domain does not include the origin.
Comment: You could write the solution more conveniently as $u = \cos\theta = \frac{x}{\sqrt{x^2+y^2}}$
Comment: Can you please check my answer once again? I have made some changes. I really did not get what you have told. Can you please check and tell me what to do next?@Mark Fischler
Comment: Can you please check my answer once again? I have made some changes.  Can you please check and tell me what to do next?@Dylan
Answer: From your notes, it's not quite clear (to me) what you have actually done, but what the PDE says is that $u$ must be constant on rays (half-lines) from the origin. Together with the given values on the unit circle, that should tell you anything you need to know about $u$.
Comment: I have applied the Cauchy's method for solving First order Pde.@Hans Lundmark
Comment: Can you please check my answer once again? I have made some changes. I really did not get what you have told. Can you please check and tell me what to do next?@Hans Lundmark
Answer: Taking
$$
xu_{x}+yu_{y}=0\text{ with } u(x,y)=x \text{ on }x^{2}+y^{2}=1
$$
Due to the contour conditions we will consider the change of variables
\begin{align}
x & = r\cos\theta\\
y & = r\sin\theta
\end{align}
with
\begin{align}
dx & = dr\cos\theta-r\sin\theta d\theta\\
dy & = dr\sin\theta+r\cos\theta d\theta
\end{align}
we have
\begin{align}
u_{x} & = u_{r}\frac{dr}{dx}+u_{\theta}\frac{d\theta}{dx}\\
u_{y} & = u_{r}\frac{dr}{dy}+u_{\theta}\frac{d\theta}{dy}
\end{align}
Here from the characteristic curves
$$
\frac{dx}{x}=\frac{dy}{y}\implies\frac{dy}{dx}=\frac{y}{x}=\tan\theta
$$
so we obtain
$$
xu_{x}+yu_{y}=0\iff2ru_{r}=0\implies u(r,\theta)=C+\Phi(\theta)
$$
Note that
\begin{align}
\frac{dr}{dx} & = \frac{1}{\cos\theta}\\
\frac{dr}{dy} & = \frac{1}{\sin\theta}\\
\frac{d\theta}{dx} & = 0\\
\frac{d\theta}{dy} & = 0
\end{align}
Now with the boundary conditions
$$
u(1,\theta)=\cos\theta\implies\Phi(\theta)=\cos\theta\text{ and }C=0
$$
and finally
$$
u(r,\theta)=\cos\theta
$$
or in $(x,y)$ coordinates, $$du(x,y)=\frac{x}{\sqrt{x^{2}+y^{2}}}$$
Comment: I don't think the $C$ is necessary here, since a constant is also a function of $\theta$. Hence the general solution $u(r,\theta) = \Phi(\theta)$ is sufficient.
Comment: Can you please check my answer once again? I have made some changes. I really did not get what you have told. Can you please check and tell me what to do next?@Cesareo
Comment: Can you please check my answer once again? I have made some changes. I really did not get what you have told. Can you please check and tell me what to do next?@Dylan
Comment: As far as could see $\frac{x^2}{y^2}=u^2(1+\frac{x^2}{y^2})\Leftrightarrow x^2=u^2(x^2+y^2) \Rightarrow u = \pm\frac{x}{\sqrt{x^2+y^2}}$


Android 10 Vivo funtouch Os killed my foreground service on swipe?

Question: I am working on app in which i start count for long period of time , for this i have startforeground service the service is working fine in all devices except few devices like android 10 vivo funtouch Os. in which when you swipe notification it kills foregorund service , so to resolve this issue  , only few devices behaving like that thanks
<code>   class MyCountdownService : Service(){

@RequiresApi(Build.VERSION_CODES.O)
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

    Log.i("Boot","intent is ${intent?.action}")

    showNotification()

    wakeLock =
        (getSystemService(Context.POWER_SERVICE) as PowerManager).run {
            newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "EndlessService::lock").apply {
                acquire()
            }
        }

    println("intent ${intent }")
    isServiceStarted =true

  if(intent!=null) {
      val action = intent?.action

      when(action){

          MyCountdownService.ADD_SERVICE ->{
              val countdown = intent.getParcelableExtra<CountDown>(Add_kEY)
              schedule(countdown !!)

          }

          else ->{

              Log.i("Boot","Service boot ")
              serviceScope.launch(Dispatchers.IO) {
                  smsScheduler.reSchedule()
              }

          }

      }

  }else{

      serviceScope.launch(Dispatchers.IO) {
          smsScheduler.reSchedule()
      }

  }

    return START_STICKY } }
</code>
//Manifest file
<code>    <uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

    <service android:name=".service.MyService"

        />
</code>
Answer: Please Follow the Steps to enable foreground service in Android 10 Vivo funtouch Os Device.
Settings < Battery < Background Power Consumption Management < Your Application < Select Don't restrict background power usage.
More details


Decision boundaries and Gaussian density functions

Question: This is for my hw, and if anyone can solve the first part of the question it will be great.
Here is the question:
Assume a two-class problem with equal a priori class probabilities and Gaussian class-conditional densities as follows:
$$p(x\mid w_1) = {\cal N}\left(\begin{bmatrix} 0 \\ 0 \end{bmatrix},\begin{bmatrix} a & c \\ c & b \end{bmatrix}\right)\quad\text{and}\quad p(x\mid w_2) =
{\cal N}\left(\begin{bmatrix} d \\ e \end{bmatrix},\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}\right)$$
where $ab-c^2=1$.

Find the equation of the decision boundary between these two classes
in terms of the given parameters, after choosing a logarithmic
discriminant function.
Determine the constraints on the values of a, b, c, d and e, such
that the resulting discriminant function results with a linear
decision boundary.
Comment: I see a study group forming...
Comment: Should this question be re-opened since the one that it duplicates has been removed voluntarily by the author, or should the author be asked to consider removing this one too?
Comment: i don't understand what you mean but, if this is the exact duplicate of a question asked before, i can't see the question or answer. Where can i find?
Comment: See the link to "[Possible duplicate](http://stats.stackexchange.com/questions/18300/how-to-compute-mean-vector-and-covariance-matrix-of-equal-distributions)" at the top of this question?
Comment: @Dilip: Under the circumstances, I would agree it should probably be reopened.
Answer: I will use $(X,Y)$ for the observation.  Given $w = w_1$, we have that the variances of $X$ and $Y$ are $a$ and $b$ respectively, while the covariance is $c$.
Thus, the correlation coefficient $\rho = \frac{c}{\sqrt{ab}}$ and so
$1-\rho^2  = 1 - \frac{c^2}{ab} = \frac{1}{ab}$. The two conditional (joint) densities are joint normal densities given by
$$\begin{align}
f_1(x,y) &= \frac{1}{2\pi \sqrt{ab(1-\rho^2)}}\exp\left[-\frac{1}{2(1-\rho^2)}\left(\frac{x^2}{a} - 2\rho\frac{xy}{\sqrt{ab}} + \frac{y^2}{b}\right)\right]\\
&= \frac{1}{2\pi}\exp\left[-\frac{ab}{2}\left(\frac{x^2}{a} - 2\frac{c}{\sqrt{ab}}\frac{xy}{\sqrt{ab}} + \frac{y^2}{b}\right)\right]\\
&= \frac{1}{2\pi}\exp\left[-\frac{1}{2}\left(bx^2 - 2cxy + ay^2\right)\right],\\
f_2(x,y)
&= \frac{1}{2\pi}\exp\left[-\frac{1}{2}\left((x-d)^2+(y-e)^2\right)\right]\\
\end{align}$$
The decision boundary is the set of all $(x,y)$ for which $f_1(x,y) = f_2(x,y)$, and so the decision boundary is the conic section specified by
$$bx^2 -2cxy +ay^2 - \left((x-d)^2 + (y-e)^2\right) = 0.$$
Edit: As pointed out in the comment by whuber,
this conic section can be a hyperbola as well as an ellipse or
parabola (including as a special case a straight line).
The discriminant $c^2-(a-1)(b-1) = (a+b)-2$ (since we are
given that $ab-c^2=1$)
can be positive, negative, or zero depending on the variances
$a$ and $b$.
I suspect that this will be work out to be
either an ellipse or a parabola (but not
a hyperbola) depending on
the parameters $a,b,c,d,e$, including, as a special case of parabola,
a straight line.  A specific example of a straight-line decision
boundary is when $c = 0$ and $a = b = 1$ so that the
only difference between the two conditional distributions is the means:
$X$ and $Y$ are conditionally independent unit-variance
normal random variables under either hypothesis.  In this instance,
the decision boundary is the perpendicular bisector of the
straight line segment with end-points $(0,0)$ and $(d,e)$.
What puzzles me, though, is a hyperbola as a decision boundary
since a hyperbola partitions the plane into three regions
(two of which are congruent). The joint density surfaces are
a (possibly) flattened bell and a circular bell, and
so one of these bells subsumes the other in two non-contiguous regions
of the plane: I just can't visualize it.  Perhaps someone will
create a nice illustration....
Comment: Re the visualization: Imagine the intersection of a spherical bowl with a bowl that is so long and shallow (but with steep sides) that it looks almost like a folded piece of paper. That is what things look like when $b=2/a$ and $c=1$.  The steep sides of the paper rise above the bowl's sides, but the valley along the center of the paper falls below the bowl's sides.  Thus, the region where the paper is higher consists of two separate areas delimited by the arcs of the hyperbola.
Comment: Good beginning! I fixed a subtraction error in the final formula. As a result, you might want to revisit your speculations in the last paragraph. To get started, note that the equation is linear if and only if all the quadratic coefficients are zero, which is equivalent to $a=1$, $b=1$, and $c=0$. (There is another special case where the equation represents a *pair* of lines.) Whether the locus is elliptical or hyperbolic depends on the sign of the determinant $(a-1)(b-1)-c^2$; both signs are possible.
Comment: @whuber cool visualisation


Different theme of Media module audio player in Firefox and IE and chrome

Question: I installed Media module, and there is a content type for audio files. The Manage display of the audio field is Audio. But the player has different themes in different browsers. This is what Firefox displays

This is for IE

and it is chrome

What is the problem? why do they have not the same theme?
thanks
Answer: If I am not mistaken, these are the native displays for the HTML5 <audio> element in different browsers. I don't think the Media module has anything to do with it, it probably only displays the markup without adding any theming.


How to respond to 'attach' from Gmail? Responding to intent with attachment

Question: I am writing an android application. This app is built on top of Gmail. I want to add the ability to attach files from other apps. The first app I am working on doing this with is a custom Box app (made with the box sdk). I can currently send an intent, open an activity in the Box app, pick an attachment, and return. However, in my Box-SDK app, once an item is selected, I have no idea how to turn it into data that I can properly send back to my Gmail app (or any original sender of the intent). I also do not know how to send that data back to the originator of the intent.
I know setResult() is involved, but I am not sure where to put it or how to properly use it to carry the data chosen in box into the email app.
What's currently happening is it just goes back into gmail without an attachment and says that the download has finished.
Here is the code I currently have:
    private void onFileSelected(final int resultCode, final Intent data) {
        if (Activity.RESULT_OK != resultCode) {
            Toast.makeText(this, "fail", Toast.LENGTH_LONG).show();
        }
        else {
            final BoxAndroidFile file =     data.getParcelableExtra(FilePickerActivity.EXTRA_BOX_ANDROID_FILE);
            AsyncTask<Null, Integer, Null> task = new AsyncTask<Null, Integer, Null>() {

                @Override
                protected void onPostExecute(Null result) {
                    Toast.makeText(MainActivity.this, "done downloading", Toast.LENGTH_LONG).show();
//                    Intent result2 = new Intent();
//                    result2.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + ));
//                    setResult(Activity.RESULT_OK, result2);
////                    setResult(resultCode, data);
                    super.onPostExecute(result);
                    finish();
                }

                @Override
                protected void onPreExecute() {
                    Toast.makeText(MainActivity.this, "start downloading", Toast.LENGTH_LONG).show();
                    super.onPreExecute();
                }

                @Override
                protected Null doInBackground(Null... params) {
                    BoxAndroidClient client = ((HelloWorldApplication) getApplication()).getClient();
                    try {
                        File f = new File(Environment.getExternalStorageDirectory(), file.getName());
                        Intent result2 = new Intent();
                        result2.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + f.getAbsolutePath()));
                        setResult(Activity.RESULT_OK, data);
//                        setResult(resultCode, data);
                        System.out.println(f.getAbsolutePath());
                        client.getFilesManager().downloadFile(file.getId(), f, null, null);
                    }
                    catch (Exception e) {
                    }
                    return null;
                }
            };
            task.execute();

        }
    }

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == AUTH_REQUEST) {
        onAuthenticated(resultCode, data);
    }
    else if (requestCode == UPLOAD_REQUEST) {
        onFolderSelected(resultCode, data);
    }
    else if (requestCode == DOWNLOAD_REQUEST) {
        onFileSelected(resultCode, data);
    }
}

Comment: I managed to figure it out, by setting the result to a new intent with the file uri as the extra

Intent result2 = new Intent();
            result2.setData(Uri.parse("file://" + f.getAbsolutePath()));
            getActivity().setResult(Activity.RESULT_OK, result2);
Answer: Try using a file provider:
https://developer.android.com/reference/android/support/v4/content/FileProvider.html#ServeUri
From the page:
"There are a variety of ways to serve the content URI for a file to a client app. One common way is for the client app to start your app by calling startActivityResult(), which sends an Intent to your app to start an Activity in your app. In response, your app can immediately return a content URI to the client app or present a user interface that allows the user to pick a file. In the latter case, once the user picks the file your app can return its content URI. In both cases, your app returns the content URI in an Intent sent via setResult()"
From another stackoverflow answer:
public void showCameraScreen(View view) {
// BUILT IN CAMERA
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(this)) );
this.startActivityForResult(camera, 1);

}

private File getTempFile(Context context) {
// it will return /sdcard/MyImage.tmp
final File path = new File(Environment.getExternalStorageDirectory(), context.getPackageName());
if (!path.exists()) {
    path.mkdir();
}
return new File(path, "MyImage.tmp");
}

@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
    final File file = getTempFile(this);

    byte[] _data = new byte[(int) file.length()];
    try {
        InputStream in = new FileInputStream(file);
        in.read(_data);
        in.close();
        in = null;
        //DO WHAT YOU WANT WITH _data. The byte array of your image.
    } catch (Exception E) {

    }
}
}

We can modify this code, where it says //Do What you want with the _data, just call
public final void setResult (int resultCode, Intent data)


Zoom do browser não funciona com meu CSS

Question: Tenho dentro da tag body 3 divs com altura definida em pixels e largura em porcentagem.
Quando a pessoa digita CTRL+ os navegadores dão zoom até 500%.
O meu problema é que o zoom não funciona.
Tentei definir, na tag body e nos 3 ids definidos nas 3 divs: topo, corpo e rodapé.
No meu caso eu defini o overflow-y como scroll e as divs com min-width e width de 100 e max-width de 500% porém não está resolvendo.

CSS:
/*
    Created on : 31/05/2014, 23:25:56
    Author     : willian
*/

body {
    margin: 0;
    padding: 0;
    min-width: 100%;
    width: 100%;
    max-width: 500%;
    overflow-x: scroll;
}

#todo {
    margin: 0;
    padding: 0;
    min-width: 100%;
    width: 100%;
    max-width: 500%;
    overflow-x: auto;
}

#topo {
    margin: 0;
    padding: 0;
    height: 200px;
    min-width: 100%;
    max-width: 500%;
    background: #fefcda;
    overflow-x:auto;
}
#corpo {
    margin: 0;
    padding: 0;
    height: 800px;
    min-width: 100%;
    max-width: 500%;
    background: #faf9ed;
    overflow-x: auto;
}
#rodape {
    margin: 0;
    padding: 0;
    height: 300px;
    min-width: 100%;
    max-width: 500%;
    background: #fefcda;
    overflow-x: auto;
}

Comment: Posso perguntar qual a intenção do seu código? Eu sei o problema que você quer resolver, mas tem algumas coisas no seu CSS que eu não entendi. OBS: O zoom funcionou normalmente aqui: Chrome Version 34.0.1847.137
Answer: Via CSS não tens controlo sobre a capacidade do navegador fazer ou deixar de fazer ampliação da página.
Esse tipo de indicações são passadas aos navegadores por meio de META TAGS colocadas na secção  onde podemos dar instruções do género:
<meta name='viewport'
      content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' />

Aqui sim, podes indicar que a página começa à escala de 1 e o máximo até onde pode ir é 1, desabilitando assim a função de zoom no navegador.
Nota:
user-scalable=0  (não deixa o utilizador fazer zoom)
user-scalable=1  (deixa o utilizador fazer zoom)


Problems with creating primary keys in sql

Question: I have table that has null type of data and it need to be null
replacement parts 0,m-> Repair
So replacement parts can be part of repair but every repair don't need to have replacement parts and when I am creating tables I putted for replacement parts id null, but problem is when I am creating primary key it can be only with not null. What to do?
Comment: use a unique key instead. thats allows to have **NULL**
Comment: So Like this; Replacement parts (Id unique, date date, description nvarchar(255))???
Comment: You proabably need a many to many relationship between repairs and parts.
Comment: it need to be 0,m . School project and they said need that
Comment: MySQL and SQL Server are different products. Wrong tags might lead to answers that don't work for you.
Comment: Typically you might have a table of parts, a table of repairs, and a table identifying which part goes with which repair, so, what's the problem with that idea?
Answer: The question describes only one half of the relation between repairs and replacement parts.
You stated that a repair may consist of zero ore more replacement parts.
But (1) can the same replacement part be taken in zero or more repairs, or (2) is a replacement part consumed by a repair such that it can occur only zero or one time in a repair?
It is necessary to make this clear, because (1) and (2) lead to different database schemes:
(1) is a many - to - many relationship and leads to a separate table connecting parts and repairs:
create table part (
    partId int primary key
);

create table repair (
    repairId int primary key
    );

create table part_repair (
    partId int references part (partId),
    repairId int references repair (repairId)
    primary key (partId, repairId)
    );

(2) part may be used in zero or one repair; store repair-id in part:
create table repair (
    repairId int primary key
    );

create table part (
    partId int primary key,
    repairId int references repair(repairId)
);

Note that repairId in part may take on NULL values for those parts that are not assigned to a repair.
Hope that helps a bit.
Comment: Hm - @Strawberry: Why do you think so?
Comment: Because I mis-read. The first part is fine. The second idea is decidely unlikely, but I think you said as much


Django: Improperly configured url: unbalanced parenthesis

Question: I'm developing a website ina VM on my Mac which then gets deployed to a remote UAT server.  The VM is set up with the same OS and software stack as the UAT and live servers.  I'm getting the following error when attempting to access the UAT version of my website:
"^accounts/update-user-group/(?P<pk>\d" is not a valid regular expression: unbalanced parenthesis

On first look it seems pretty obvious what's wrong: The given URL pattern is incomplete. However, my urls.py file has the correct full url:
# -*- coding: utf-8 -*-

from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.conf.urls import patterns, url

from views import UserGroupList, UserGroupDetail
from views import UserGroupCreate, UserGroupUpdate, UserGroupDelete
from views import UserDeletedGroups, RecoverDeletedGroup

urlpatterns = patterns('',
    url(_(r'^accounts/create-user-group/$'), UserGroupCreate.as_view(), name='user_group_create'),
    url(_(r'^accounts/update-user-group/(?P<pk>\d+)/$'), UserGroupUpdate.as_view(), name='user_group_update'),
    url(_(r'^delete/(?P<pk>\d+)/$'), UserGroupDelete.as_view(), name='user_group_delete'),
    url(_(r'^accounts/user-group-deleted/$'), UserDeletedGroups.as_view(), name='user_group_deleted_list'),
    url(_(r'^recover/(?P<pk>\d+)/$'), RecoverDeletedGroup.as_view(), name='user_group_recover_deleted'),
    url(_(r'^accounts/user-group-details/(?P<pk>\d+)/$'), UserGroupDetail.as_view(), name='user_group_detail'),
    url(_(r'^accounts/user-group-list/$'), UserGroupList.as_view(), name='user_group_list'),
)

So the error seems to be getting generated by the second regex in the urlpatterns.  However, If I change the regex to this:
url(_(r'^accounts/update-user-group/(?P<pk>[\d]+)/$'), UserGroupUpdate.as_view(), name='user_group_update'),

Then the error moves on to the next line.  All I've done here is add square brackets round the \d
for the pk argument. How can this simple difference be the cause of the error? And why would it only be happening in my UAT environment and not local development?
Comment: Why are you wrapping your regex strings with ugettext?
Comment: Because its an international site and translatable URLs is one of the requirements.  We've been doing this for a year and it hasn't been causing any problems previously
Comment: It turns out that this wasn't causing a problem due to the fact that we didn't have a translation for that URL in our PO file. Now we do and it is incomplete. Thanks Daniel, your question pointed me in the right direction
Comment: @hellsgate add your solution as an answer and accept it - it might help someone in the future who comes across this
Comment: @TimmyO'Mahony thanks, i need to wait 2 days before I can accept my own anser though
Answer: Daniels question pointed me in the right direction for this. The translation for the problem URL in my PO file was incomplete so ensuring that was correct sorted my problem.


How to use telebot module to create an inline button in bot window, which if clicked will work very similar to 'Create poll' button found in groups?

Question: I am relatively new to python and I am trying to create a telegram bot using telebot, which will create a quiz-like game, and each user can create their own quiz-like game also. During the step by step process of creating this quiz by the user, at one point, I need them to send me a poll, just like how they create a new poll in a group. But there is no create poll button inside telegram bot as these buttons are generally found in groups and not in one-one chats.
So I need to create an inline keyboard button, which upon clicking will let the users create a poll and send it to the bot. I have gone through the documentation in github and couldn't find anything useful for this.
This similar thing is implemented by telegram's own "Quizbot". I'll attach the screenshots from that bot for clarity. Please help me identify how to implement it in my bot.

If 'Create question" button is clicked:

I am a noob to python and coding, so please help me with this problem.
edit: I can send a poll to the bot if I am using telegram desktop and not from the phone. I want to know how to enable to use it in the phone.
Comment: Sorry, can't help you here. I'm not actually familiar with the library. Search the documentation for "poll", if it is missing- it's likely not supported.
Comment: @AndrewMorozko I guess it's missing. But I can send poll from desktop app. So for now I can continue with the project. Thank you
Comment: @AndrewMorozko sorry for disturbing you again. https://stackoverflow.com/questions/63951583/lamda-funtion-in-bot-message-handler-not-working-properly-in-telebot-python
Could you please take a look at this question?
Answer: By using telebot we can do this. This gives us the opportunity to create poll from phone apps also.
<code>import telebot
from telebot.types import ReplyKeyboardMarkup,KeyboardButton,
                          KeyboardButtonPollType,ReplyKeyboardRemove

bot=telebot.Telebot(token='your bot token')
poll_markup=ReplyKeyboardMarkup(one_time_keyboard=True)
poll_markup.add(KeyboardButton('send me a poll',
                request_poll=KeyboardButtonPollType(type='quiz')))
#from my experience, only quiz type and regular type polls can be send.

remove_board=ReplyKeyboardRemove()
bot.send_message(chat_id,text,reply_markup=poll_markup)
#some other code here

#this can be used to remove the replykeyboard when you no longer need it.
bot.send_message(chat_id,text,reply_markup=remove_board)

</code>


How to get Fragment value from url in Drupal 8?

Question: I need to get the Fragment value from url like: admin/config/system/meta_custom?query=test#abc=xyz in Drupal 8.
Need value of abc - ideally using Drupal's API, rather than doing my own Url Parsing.
Comment: I was looking for such answer and haven't found anything useful. Right now I'll use parse_url function from php https://www.php.net/manual/ru/function.parse-url.php, but if I find something in Drupal API I'll let you know
Answer: You could use it like this:
$path = \Drupal::request()->getpathInfo();
$arg  = explode('/',$path);
It gives:
Array
(
    [0] =>
    [1] => node
    [2] => add
    [3] => application
)
Comment: \Drupal::request()->getpathInfo() only gets url and get params, but not fragments with #, so I think I does not the solution author looking for


Can't override Tomcat default file size limit in UAT profile environment

Question: For some reason I am not able to override Tomcat's settings about the file size limit when working with the UAT profile environment (everything works smoothly on SIT)
I am using Spring Boot 2.2 and i am adding these properties to the configuration file:
spring.servlet.multipart.max-file-size=25MB
spring.servlet.multipart.max-request-size=25MB

However when i run my application on the Eclipse IDE (clean install and profile UAT) it gives me errors when I try to upload files which are greater than 1MB (which AFAIK is the default Tomcat's file limit size).
A couple more things to point out:

Both the application-sit.properties file and the application-uat.properties have all of the instructions placed in the same order.
When I try to upload file whose size is lower than 1MB i get another error which is UnsupportedMediaType and so I was wondering whether the problem was in my Angular front-end or in my Spring Boot back-end application.

Oh... and I run my SIT application locally while the UAT application is run in a VM (it wouldn't surprise me if it is something that has to do with the VM).
Thank you all in advance for the help, I'm open to answer if you need more informations.
Have a nice day.
UPDATE
As requested by @PiotrP.Karwasz I am including the Angular and Spring code I used to make the upload service:
upload() in upload-service.service.ts
  upload(file: File)  {
    const formData: FormData = new FormData();
    formData.append('file', file);

    return new Observable(((observer: Observer<any>) => {
      const xhr = new XMLHttpRequest();

      xhr.onreadystatechange = _ => {
        if (xhr.readyState === 4) {
          if(xhr.status === 200) {
            observer.next(xhr.response);
            observer.complete();
          }
          else {
            observer.error(xhr.response);
          }
        }
      };

      ///environment.baseUrl changes based on the active profile config
      let url = environment.baseUrl + constants.REST_UPLOAD_FILE;
      xhr.open('POST', url, true);
      xhr.send(formData);
    }));
  }

save() in FileStorageService.java
@Override
public void save(MultipartFile file) {
    try {
        String filename = FilenameUtils.removeExtension(file.getOriginalFilename())
                                        + " - "
                                        +  new SimpleDateFormat("dd꞉MM꞉yyyy HH'h'꞉mm'min'꞉ss's'")
                                            .format(new Date())
                                            .toString()
                                            .replaceAll("[^a-zA-Z0-9.-⁄꞉]", "_")
                                        + "." + FilenameUtils.getExtension(file.getOriginalFilename());

        Files.copy(file.getInputStream(), this.root.resolve(filename));
    } catch (final Exception e) {
        throw new RuntimeException("Non posso salvare il file. Errore: " + e);
    }
}

Note that as far as I understood by making tests printing stuff on the Eclipse console it seems like it doesn't even get to the point of reaching the Spring Boot save() method and I've actually also tried printing things on the controller method (whose code will be linked below) that manages the incoming requests but it doesn't show anything either way so seems more like it's never reaching the controller too.
The controller method who takes care of the upload request is available at https://pastebin.com/EMZStXJw
Comment: How do you upload the file: is it through a HTML form? What `enctype` are you using? `multipart/form-data` or the default `application/x-www-form-urlencoded`?
Comment: @PiotrP.Karwasz I am using Angular FormData to upload the file with a Drag and Drop area, you can check the HTML code here: https://pastebin.com/i83TV0CA

Here's the related component: https://pastebin.com/H0Xbhnpw

Also, if it can be helpful, my Angular code is based on this guide (I've just made a few changes to implement drag and drop and used XMLHttpRequest instead of the usual HttpClient to make the request since it gave me ambigous Cross Origin issues): https://www.bezkoder.com/angular-spring-boot-file-upload/
Comment: That covers the interface, but how is `uploadService.upload` implemented and the handler method on Spring's side? Can you add them to your question?
Comment: @PiotrP.Karwasz first of all thank you for trying to help me out, I'm spending days at work just to solve this issue. I've updated my question as you requested. Since it does not print things on screen when I make a request to the controller method but it gives me specific exceptions related to the file size or the media type my best guess at this point is that when I deploy the .war application it misses something. I've also tried making the requests with Postman to the correct URL but same results.
Comment: The code you posted should work: check in your browser debug tools if the `Content-Type` of the XHR request is `multipart/form-data`. Are there any proxies between your browser and Tomcat that might change the `Content-Type`?
Comment: @PiotrP.Karwasz I am not sure about the proxies, is there a way to check it out...?

BTW here you go, the Content-Type does NOT change on the HTTP Headers and this is the same one I get on my local environment so it should work, am I wrong?

`Content-Type` [here](https://ibb.co/tbrRXdb)
and `Response` [here](https://ibb.co/JjxDFfn)
Answer: Okay, after extracting the .war file of my front-end build I finally got it and I'll put this here for anyone who may need it.
The thing is that my environment.baseUrl (see the upload() method in upload-service.service.ts file) was pointing to an invalid endpoint (I still have to figure out why the endpoint was behaving like that and why it was there in the first place) and so when I tried making the request i got ambigous errors that had nothing to do with the actual one.
Modifying the UAT configuration file was enough to make it work.
TLDR;
Make sure you are pointing to the right URL endpoint in your UAT configuration file and extract the .war to check your application.properties files.


Images show up once, then have to clear styles folder to see again?

Question: So I'm trying to get a site setup with a template (global news), which requires Drupal 7.x, so I'm using 7.41. Anyway, I have all the modules set up and the general layout as it should be. However, I'm having a problem with getting the images to render.
It seems as though if I delete the /default/files/styles folder, the images will generate and show up on the website, however if I refresh the page the images fail to load until I delete the folder again. If I don't delete the folder I get a 403-forbidden for each image I'm trying to load.
It's weird, and I've almost driven myself crazy trying to get this figured out.
Any advice?
Comment: Sounds like a web server configuration issue. When the images are regenerated they get served by Drupal, but once generated they should be served directly from the filesystem. Look at your .htaccess files (if using Apache).
Comment: Hey @AlfredArmstrong thanks for the response. All of the .htaccess files should be stock from the install. I'm trying to transfer a previous version that I made on a different server (my own personal) to a client's hosted (justhost) shared server. I've double checked that all of the permissions are correct.
Comment: Turns out there was a deny all in the .htaccess that was throwing everything off. Thanks again for the help
Answer: The fact that derived images can be fetched when they are absent from the filesystem but not when they are present indicates this is a webserver configuration issue.
The webserver rules are normally be set up so that any non-existent paths are routed to Drupal. When image thumbnails are generated they get served by Drupal, but once on disk they should be served directly from the filesystem. Check your .htaccess files (if using Apache) and somewhere there is likely to be an rule denying access to that area of the filesystem.


tcpdump http request/responce Wireshark

Question:
sudo tcpdump -i enp2s0 -n dst port 8080 -w test_tcpdump.dump

I'm using this command on a linux to simply dump everything that goes through port 8080..
But why can I only see the request from HTTP and not the response?
Answer: dst port 8080 - this captures traffic with destination port 8080 only.
The response packets have soruce port 8080, but the destination port will be some random port selected by the client.
Change the filter to port 8080 and you will see packets coming from/to port 8080 (i.e. both directions)

tcpdump http request/responce Wireshark


Modifying SSL / TLS certificates for local use

Question: I am currently developing some applications on my local 'serverfarm'.
I have set up ZendServer with Apache2 and PHP, which works very fine, and nothing unwanted happened until now:
Now I wanted to manage my MySQL databases with phpMyAdmin, because Sun's MySQL SQL tool seems to cause problems creating valid batches.
Working with PMA is not the problem, I am extremely used to work with PMA, if I could access it.
And this is my actual problem: My Firefox wants to tell me that he can not open a 'self-signed certificate'.
I tried to work-around that by editing Firefox's ssl configurations, but it did NOT seem to work.
Now I have to change the servers' certificates, but I did not where to find the specific file, because I never had to worry about ssl or tls configurations.
Answer: When Firefox, or any other browser, has a problem with a certificate (expired, self-signed, invalid domain, etc) there is a dialog where you can add a security exception.  You should be able to add a permanent exception for the warning.
If you continue to have issue, why not disable SSL?  If it's just local development, what's the risk?
Comment: The problem is, that PMA is only reachable via https:// . This is ZendServer's security standard.
Comment: and by the way, I am sorry, but if I add localhost or any internal ethernet ip to the exceptions firefox still kicks me.
Comment: I'm not suggesting to add it to any exceptions list in the options, but when you actually hit the page.  In my firefox (3.0.x on Linux) it says:

"Secure Connection Failed
The certificate is not trusted because the issuer certificate is unknown.
etc.."

At the bottom is a blue link "Or you can add an exception..." - Is this what you are doing?
Comment: No, it says: (US) http://bit.ly/3Be37B (EU) http://imagr.eu/upload/issuer.png "self-signed etc. etc."
Answer: This is the correct solution.
I found this solution while cruising through stackoverflow.com
Thank you anyway.


MVC Code First Publish

Question: I have created a code first MVC application and I am having issues with a certain part of the publish.
I am getting the error message of

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: SQL
  Network Interfaces, error: 26 - Error Locating Server/Instance
  Specified)
SQLExpress database file auto-creation error:
The connection string specifies a local Sql Server Express instance
  using a database location within the application's App_Data directory

Now, my connection string is pointing to the correct server, and everything about the connection string is fine. I am not using a local db inside the App_Data folder.
I am at an utter stand still.
Answer: I know you said the connection string is fine, but you should double check. With the credentials and server path on your connection string can you connect by sql management for example ? If yes, your problem probably is database permission

MVC Code First Publish


apt-get upgrade and update will break an old Rails app with dependencies?

Question: I am running a Rails 2.3.8 app on my server, with other depended gems, which usually require old version instead of the new version which supports Rails 3.
I have not been running apt-get update and apt-get upgrade on my VPS. I am afraid that running either may upgrade my Rails and other gems to latest version, which will then break my app.
I just wanna update my Ubuntu system, such as security updates and such, without touching any applications.
So, what should I run?
Thanks.
Answer: If you want to ensure that your gems don't upgrade during the server update/upgrade, you can add the specific gem version to your environment.rb file.
As an example; rather than just declaring the gem name you can add the version number:
config.gem 'delayed_job', :version => '~>2.0.4'

The above line will ensure the delayed_job gem is installed but only the specific version of 2.0.4.
I notice you said that you don't want to touch the applications. I don't think you can achieve a server-wide update without first manually adding the gem version numbers as I explained above.
Once you have added the version numbers you should be able to run both 'apt-get update' and 'apt-get upgrade' without fear that your applications would break. AFAIK when you update/upgrade the server it will install the newest version of RoR but it won't remove version 2.3.8.
Answer: If anything breaks on your system as a result of installing security updates (which is correctly done with apt-get upgrade), then in general it would be a bug in the upgraded package.
Of course, this is assuming that you're not doing oddball things like mixing distribution releases, or using third-party repositories -- in that case, all bets are off and you're totally on your own.  So don't do that.
Comment: Did you even *read* my answer?
Comment: So now which line I should run?


What does it mean for a formula to be a truth functional component/compound of another formula?

Question: I'm reading Fine and Schurz's "Transfer Theorems for Multimodal Logics" in Logic and Reality: Essays on the Legacy of Arthur Prior edited by J. B. Copeland (Clarendon Press, 1996, pp. 169-213) and I've met the following definitions in page 177:

The set of truth-functional constituents$^1$ TC($\phi$) of a given formula $\phi$ is the set of all constituents of $\phi$ which are truth-functional components of $\phi$.

Finally, B($\Delta$) is the set of all Boolean, or truth-functional, compounds of formulae in $\Delta$.

$^1$ Consider this to mean formulas which are atomic.
Neither of which I can make sense of. I understand that truth-functionality relates to the  connectives of propositional logic, that the modal operators are not truth-functional and that component formulae usually mean formulae which are contained in another, bigger, formula, but I can't understand what the words "component" and "compound" may mean in this context, nor how they are different from one another.
While researching for this, I've found a paper by D. H. Sanford titled "What is a Truth-Functional Component" (free to read on site) which, although the title may sound convenient, was not of great help. Any help would be appreciated, and references to books/papers which explain these concepts would be great.
Comment: I think you are right: presumably they are sub-formulas of $\phi$ that are not in the scope of a modal-operator.
Answer: Let us dwell on the question a bit longer.
Modal logic is an intensional logical system. Some people equate intension in this technical sense to meaning. However, this is a far too simplistic view of such a comprehensive concept as meaning. It is more appropriate to regard intension as a mode of meaning that stipulates how a statement relates to an extension (also a mode of meaning).
Hence in intensional systems of logic, there is at least one operator that puts statements into an intensional context which cancels truth-functionality, that is, we cannot set down a table with columns of statements as input and a column of truth-values as output. Thus, two propositions $P$ and $Q$ may have the same truth value, but $\Box P$ and $\Diamond Q$ diverges radically in their consequences - contrast them, for example, with the behaviour of negation $\neg$. Notice that being truth-functional or not is actually an attribution of logical operators.
The standard modal propositional logic is unimodal (a.k.a., monomodal); it has one modal (non-truth-functional) operator as primitive, either $\Box$ or $\Diamond$, the other one is defined by the one taken as primitive. The rest of the operators are truth-functional.
In the cited article, Fine and Schurz investigate stratified multimodal systems. For the sake of simplicity, they consider a bimodal system with modal operators $\Box_{1}$ and $\Box_{2}$ which do not interact logically.
By components, we take a synthetic point of view; we put together components to form an object. The logical systems $L_{l}$ and $L_{2}$ and formal languages $\mathscr{L}_{l}$ and $\mathscr{L}_{2}$ induced by $\Box_{1}$ and $\Box_{2}$, respectively, are the components of the logical system $L$ , the minimal normal bimodal logic containing both of them and and the associated formal language $\mathscr{L}$.
Constituents of an object give us an analytic view of it; we set apart constituents of an object to see the way it is built up. There is a distinction between the constituents of a formula $\phi$ and the subformulas of it. Keeping with the cited article, $SF_{1}(\phi)$ is the set of all $1$-subformulas of $\phi$ viewed as an $\mathscr{L}_{1}$-formula which are all formulas having an occurrence in $\phi$ which does not "properly lie in the scope of" a $\Box_{2}$-operator, because $\mathscr{L}_{1}$ does not have a syntactic rule to prefix $\Box_{2}$ to a formula. Thus, $\Box_{2} q$ cannot be a subformula in $\mathscr{L}_{1}$, but $\Box_{1}\Box_{2} q$ can. $1$-constituents form a set of formulas $\Sigma_{1}$ defined by $\mathbb{P}\,\cup\,\{\Box_{2}\phi\mid\phi\in\mathscr{L}\}$, where $\mathbb{P}$ is the set of propositional variables.
Notice that  $\Sigma_{1}$ is virtually the set of the atomic variables (i.e., not compound formulas) of $\mathscr{L}$ as seen relative to $\mathscr{L}_{1}$. $C_{1}(\phi)$ is the set of all $1$-constituents of $\phi$ which are the $1$-subformulas of $\phi$ which are $1$-constituents. Therefore, $C_{1}(\phi) = SF_{1}(\phi)\cap\Sigma_{1}$. Mutatis mutandis, we can define the same notions for $\Box_{2}$, and for $\mathscr{L}$ combine them, as $\Sigma = \Sigma_{1}\,\cup\,\Sigma_{2}$ and so on, in particular, $SC(\phi)$, the set of all subconstituents of $\phi$ in $\mathscr{L}$, defined by $SC(\phi) = SF(\phi)\,\cap\,\Sigma$.
It may be helpful to remark that $\Sigma=\mathbb{P}\,\cup\,\{\Box_{1}\phi\mid\phi\in\mathscr{L}\}\,\cup\,\{\Box_{2}\phi\mid\phi\in\mathscr{L}\}$, hence, the set of all constituents in $\mathscr{L}$ consists of truth-functional, non-compound formulas and non-truth-functional, compound (viz., modal) formulas. So, we see that $\Sigma$ is the set of all $\mathscr{L}$-formulas which are not truth-functionally compound.
Let us look into identification of the set of truth-functional constituents of a formula $\phi$, $TC(\phi)$ going over the authors' example on pp. 176-177:
$$\phi\equiv\Box_{2}q\wedge\Box_{1}\neg\Box_{1}\Box_{2}p$$
$SF_{1}(\phi) =\{\Box_{2}q, \Box_{1}\neg\Box_{1}\Box_{2}p, \neg\Box_{1}\Box_{2}p, \Box_{1}\Box_{2}p, \Box_{2}p\}$ since $\mathscr{L}_{1}$ has a syntactic rule to prefix $\Box_{1}$. Then, $C_{1}(\phi) =\{\Box_{2}q, \Box_{2}p\}$, the atomic formulas occurring in $\phi$.
$SF(\phi) =\{\Box_{2}q, \Box_{1}\neg\Box_{1}\Box_{2}p, \neg\Box_{1}\Box_{2}p, \Box_{1}\Box_{2}p, \Box_{2}p, p, q\}$ since $\mathscr{L}$ has a syntactic rules to prefix both $\Box_{1}$ and $\Box_{2}$.
$SC(\phi) =\{\Box_{2}q, \Box_{1}\neg\Box_{1}\Box_{2}p, \Box_{1}\Box_{2}p, \Box_{2}p, p, q\}$. Notice that we have omitted $\neg\Box_{1}\Box_{2}p$ from $SF(\phi)$ to obtain $SC(\phi)$, since a negated formula is a truth-functionally compound formula with respect to both $\mathscr{L}_{1}$ and $\mathscr{L}_{2}$. Consequently, $TC(\phi)=\{p, q\}$.
Suppose $\theta\equiv\Box_{2}q$ and $\psi\equiv\Box_{1}\neg\Box_{1}\Box_{2}p$, so that their conjunction gives the formula $\phi$ in the authors' example.
Let $\Delta=\{\theta, \psi\}$. Then $B(\Delta)=\{\neg\theta, \neg\psi, \theta\wedge\psi, \theta\vee\psi\ldots\}$. So, $\phi\in B(\Delta)$.


Total de Subregistros - MySql

Question: Em meu banco de tenho várias tabelas, mas vou fazer um exemplo simples do que quero fazer:
Supondo duas tabelas:

Tabela 1

id | loja | data

Tabela 2

id_2 | id_tab1_2 | produto

Percebam que o id_tab1_2 é uma chave estrangeira, ligado ao campo id da tabela 1.
O que eu quero é EM UMA ÚNICA QUERY trazer todos os registros da Tabela 1 e a quantidade de sub registros da Tabela 2, ex:
SELECT * FROM tabela_1 ...
E o resultado fosse algo parecido com isso:
id | loja |   data     | quant_tab_2
1  |   X  | 23/07/2018 |      2
2  |   Y  | 23/07/2018 |      1
3  |   Z  | 23/07/2018 |      0
No campo quant_tab_2 vem a quantidade se sub registros na Tabela 2 de cada registro da Tabela 1
Não que tenha que vir uma coluna com o nome quant_tab_2, é só um exemplo, eu não quero ter que fazer pra cada registro da Tabela 1, uma nova query pra saber quantos sub registros dela há na Tabela 2, é possível fazer isso? Alguém pode me ajudar?
Answer: Com base na sua suposição, a query ficaria dessa forma:
SELECT
tabela_1.id,
tabela_1.loja,
tabela_1.data,
COUNT(tabela_2.id_2) as quant_tab_2
FROM tabela_1
LEFT JOIN tabela_2 ON (tabela_1.id = tabela_2.id_tab1_2)
GROUP BY tabela_1.id

Comment: É isso msm, obrigado!!!
Answer: Você pode fazer algo do tipo:
select t1.*, count(t2.produto) from tabela1 as t1
inner join tabela2  as t2 on t2.id_tab1_2 = t1.id
group by t2.id_tab1_2

Total de Subregistros - MySql


NTLM Kerberos support for Identity server which set behind nginx server (not working for IE)

Question: I have Identity server 4 which reside behind ngnix proxy. and it support Azure AD.  now if I SSO on https then it is not working for IE browser but work properly in other browser due to IWA/NTLM/Kerberos .
So change need to do in ngnix to support that.
Comment: This was due to http2 setting in. Nginx.
Comment: If you could please provide your answer in the answer section, that would be beneficial for future readers who might experience a NGINX issue similar to this. Thanks!
Comment: What is the issue here? Is it that it doesn't work with IE or is there something missing? Because you say that it's working in other browsers, so it seems like your auth backend setup is working properly.
Answer: we have  default setting in nginx like this :
<code>   listen 443 ssl http2 default_server;
   listen [::]:443 ssl http2 default_server;
</code>
Then I have removed  http2
<code>    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;
</code>
so IE has issue with SSL + http2


Inplicit Function to Explicit

Question: Can someone explain me, how can I transform this implicit function into that explicit? I thought it was impossible and resolved the exercise as it was an implicit, but as you can see in the solutions of the exercise they can transform it!
Answer: Generally, the implicit function theorem makes no promises as to being able to represent the implicit function explicitly (in terms of elementary functions, that is). However, there's also nothing to imply that it couldn't be done in specific cases. Here, for example, you have a quadratic equation in $x$, admitting the standard solution.
Comment: Don't you know $x=(-b\pm\sqrt{b^2-4ac})/(2a)$ for $ax^2+bx+c=0$?
Comment: But how can I transform the implicit to explicit? In this case, at least?
Comment: As mentioned, the quadratic equation $a(t)x^2 + b(t)x + c(t)=0$ has the two (usually distinct, and possibly complex) solutions $\frac{1}{2a(t)}\left(-b(t)\pm\sqrt{b(t)^2 - 4a(t)c(t)}\right)$.
Comment: Oh ok, it was to easy I was thinking to far ahead to see the basic!
Comment: How am I supposed to choose between the solution with + or - before the square root?
Comment: @FranciscoGonçalves that part depends on context. Here, for example, you're looking for an implicit function such that $x(t_0)=x_0$ for some $t_0,x_0$, so that should give you the answer.

Inplicit Function to Explicit


AWK Regex pattern matching

Question: I have a text file, and I need to identify a certain pattern in one field. I am using AWK, and trying to use the match() function.
The requirement is I need to see if the following pattern exists in a string of digits
??????1?
??????3?
??????5?
??????7?

ie I am only interested in the last but one digit being a 1, 3, 5, or a 7.
I have a solution, which looks like this;
    b = match($23, "[0-9][0-9][0-9][0-9][0-9][0-9]1[0-9]")
    c = match($23, "[0-9][0-9][0-9][0-9][0-9][0-9]3[0-9]")
    d = match($23, "[0-9][0-9][0-9][0-9][0-9][0-9]5[0-9]")
    e = match($23, "[0-9][0-9][0-9][0-9][0-9][0-9]7[0-9]")

    if (b || c || d || e)
    {
            print "Found a match" $23
    }

I think though I should be able to write the regex more succinctly like this;
b = match($23, "[0-9]{6}1[0-9]")

but this does not work.
Am I missing something, or are my regex skills (which are not great), really all that bad?
Thanks in anticipation
Comment: Is it definitely field 23 that you're interested in? Can we see a whole line of data? Does the rest of your script transform the line in any way?
Answer: The regex delimiter is /.../, not "...". When you use quotes in an RE context, you're telling awk that there's an RE stored inside a string literal and that string literal gets parsed twice, once when the script is read and then again when it's executed which makes your RE specification that much more complicated to accommodate that double parsing.
So, do not write:
b = match($23, "[0-9]{6}1[0-9]")

write:
b = match($23, /[0-9]{6}1[0-9]/)

instead.
That's not your problem though. The most likely problem you have is that you are calling a version of awk that does not support RE-intervals like {6}. If you are using an older version of GNU awk, then you can enable that functionality by adding the --re-interval flag:
awk --re-interval '...b = match($23, /[0-9]{6}1[0-9]/)...'

but whether it's that or you're using an awk that just doesnt support RE_intervals, the best thing to do is get a newer version of gawk.
Finally, your whole script can be reduced to:
awk --re-interval '$23 ~ /[0-9]{6}[1357][0-9]/{print "Found a match", $23}'

Change [0-9] to [[:digit:]] for locale-independence if you like.
The reason why RE intervals weren't supported by default in gawk until recently is that old awk didn't support them so a script that had an RE of a{2}b when executed in old awk would have been looking for literally those 5 chars and gawk didn't want old scripts to quietly break when executed in gawk instead of old awk. A few release back the gawk guys rightly decided to take the plunge an enable RE intervals by default for our convenience over backward compatibility.
Comment: Thanks for your comments, deleted my answer and upvoted yours—I don't know AWK's regex flavor and was offering a few ideas hoping the syntax would be compatible.
Comment: Great answer. Thanks
Unfortunately I am stuck with the version of awk that I have, the server is not mine to administer.
Comment: Are you sure there's only 1 awk version on your server? Solaris, for example, comes with 3 (/usr/bin/awk, /usr/bin/nawk, and /usr/xpg4/bin/awk). Do you happen to know which awk version you are running (try `awk --version` and/or just tell us the OS)?
Answer: Here is one awk solution:
awk -v FS="" '$7~/(1|3|5|7)/' file

By setting FS to nothing, every character becomes a field.  We can then test field #7.
As Tom posted.
awk -v FS="" '$7~/[1357]/' file

Comment: This doesn't take into consideration the fact that the input contains many fields, only one of which is to be matched. It would make more sense to use `/[1357]/` anyway.

AWK Regex pattern matching


Weierstrass's M-test example for uniform convergence and switching Sum and Integral.

Question: How would I go about finding $M_n$ in
\begin{equation}
\sum_{n=1}^{\infty} \int_{0}^\infty x^{\frac{s}{2}-1}e^{-\pi n^{2}x}dx
\end{equation}
to show that it is uniformly convergent?
UPDATE:
Just coming back to this and having trouble understanding this. Without relating this integral  to the zeta and gamma functions, how do I show the sum has uniform convergence ( Weierstrass)? For $Re(s) > 1$. And can therefore swap integral with summation by fubinis theorem?
Comment: Hint: link the integration with $\Gamma$ function.
Comment: uniformly convergent where?
Comment: I changed my answer below to give a proof without using properties of the  gamma or zeta function.
Answer: You may observe that, using a standard integral representation of the gamma function, we have
$$
\int _0^{\infty }x^{s/2-1}e^{-\pi n^2x}dx=\frac{1}{n^s}\pi^{-s/2}\Gamma(s/2)
$$ then your series rewrites
$$
\sum_{n=1}^{\infty} \int_{0}^\infty x^{\frac{s}{2}-1}e^{-\pi n^{2}x}dx=\pi^{-s/2}\Gamma(s/2)\sum_{n=1}^{\infty} \frac{1}{n^s}=\pi^{-s/2}\Gamma(s/2)\zeta(s)
$$ and the convergence of the series is uniform on each $[a,b] \ni s$, $1<a<b$, since
$$
\left|\frac{1}{n^s}\right|\leq\frac{1}{n^a}, \quad n\geq1.
$$
Comment: No, the series does not converge uniformly on $[a,\infty), $ simply because each of those integrals $\to \infty$ at $\infty.$ We do get uniform convergence on each $[a,b], 11$.  So, we need to restrict $s$ in this problem such that $\text{Re}(s)>1$.
Comment: @zhw. Assume $s>0$. Please, I think you are not right saying that each integral $\to +\infty$, we rather have $\displaystyle \int _0^{\infty }x^{s/2-1}e^{-\pi n^2x}dx=\frac{1}{n^s}\pi^{-s/2}\Gamma(s/2) \to 0$, as $n \to +\infty$, or I'm missing something...
Comment: So $M_n$ is $\frac{1}{n^{a}} $ here? does $a$ have to be less than s?
Comment: for each $n,$ $ \lim_{s\to \infty} \int _0^{\infty }x^{s/2-1}e^{-\pi n^2x}dx = \infty.$ No series of functions, each of which is unbounded on a set, can converge uniformly on that set.
Comment: @zhw.You are talking about $s \to +\infty$ (not $n \to +\infty$), you are then right! I will edit my answer, thanks.
Comment: @OlivierOloa would this then mean I can interchange sum and integral?
Answer: Lemma: For any fixed $a>0,$
$$\lim_{p\to \infty}\int_0^\infty x^pe^{-ax}\, dx = \infty.$$
Proof: The integral is greater than
$$\int_1^2 x^p e^{-ax}\  dx \ge e^{-2a}\int_1^2 x^p\ dx = e^{-2a}\cdot\frac{2^{p+1}-1}{(p+1)}.$$
The last expression $\to \infty$ as $p\to \infty.$
In your problem, let $f_n(s)= \int_0^\infty x^{s/2-1}e^{-\pi n^2x}\,dx.$ You wonder  if $\sum_n f_n(s)$ converges uniformly on $(1,\infty).$ It doesn't. Why? The lemma shows each $f_n(s) \to \infty$ as $s\to \infty.$ So each $f_n$ is unbounded on $(1,\infty).$ Elementary fact: No series of unbounded bounded functions on a set can converge uniformly on that set.
Now you also bring up the question of whether sum and integral can be interhanaged in this problem. They can. A simple way to see that is the monotone convergence theorem, a corollary of which says, to be brief: If each $f_n$ is nonnegative, then $\sum_n \int f_n = \int (\sum_n f_n).$
Comment: The exponent on $x$ is fixed and doea not approach infinity in the original post.
Comment: How did you arrive at that? It certainly wasn't stated. The OP asks whether the sum converges uniformly. The $n$th summand should then be a function. Of what? Of $s$ of course.
Comment: I don't see a limit on the parameter $s$.  Am working on a "smart phone" so apology if I missed something.


Cascade entity reference in a content type

Question: I have two content types parts and maintenance.
Parts has 3 fields.

Oven type
Oven Part
Parts price

In maintenance i have a entity reference field with autocomplete that points to parts.
So now when a user types in a part the autocomplete show a list of possible matches.
The problem is that 2 different ovens can have the same parts but the price is different.
So I would like it to be a cascade so that a user can first select the oven and then select the part for this oven.

select the oventype

show the parts that fit this oven
Answer: It sounds like you want to try to use Reference Field Option Limit:

Example 1:
countries and cities Suppose you want to label articles (or
  products, or businesses, etc) by both city and country so both can be
  used for filtering and searching. You could use a hierarchical
  taxonomy with city terms as children of country terms, but that
  doesn't make sense when you come to set up Views filters.
With this module, create two separate taxonomies for country and city
  (or content types, or whatever entity you want to use). Then add a
  reference field so that each city points to its country: eg, the term
  'Paris' has a reference to 'France'.
Then when editing an article, selecting 'France' in the country field
  will cause the city field to update to show only cities in France.

How you denote the different parts based on their price. I dunno. But you can look at this module and if need use it as a starting point to extend or create javascript behaviors or alter sql queries it's using.


dynamic naming of UIButtons within a loop - objective-c, iphone sdk

Question: As it may seem obvious I am not armed with Objective C knowledge. Levering on other more simple computer languages I am trying to set a dynamic name for a list of buttons generated by a simple loop (as the following code suggest).
Simply putting it, I would like to have several UIButtons generated dynamically (within a loop) naming them dynamically, as well as other related functions.
button1,button2,button3 etc..
After googling and searching Stackoverlow, I haven't arrived to a clear simple answer, thus my question.
<code>- (void)viewDidLoad {
    // This is not Dynamic, Obviously
    UIButton *button0 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button0 setTitle:@"Button0" forState:UIControlStateNormal];
    button0.tag = 0;
    button0.frame = CGRectMake(0.0, 0.0, 100.0, 100.0);
    button0.center = CGPointMake(160.0,50.0);
    [self.view addSubview:button0];
    // I can duplication the lines manually in terms of copy them over and over,  changing the name and other related functions, but it seems wrong. (I actually know its bad Karma)

    // The question at hand:
    // I would like to generate that within a loop
    // (The following code is wrong)

    float startPointY = 150.0;
    //
    for (int buttonsLoop = 1;buttonsLoop < 11;buttonsLoop++){

        NSString *tempButtonName = [NSString stringWithFormat:@"button%i",buttonsLoop];

        UIButton tempButtonName = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [tempButtonName setTitle:tempButtonName forState:UIControlStateNormal];
        tempButtonName.tag = tempButtonName;
        tempButtonName.frame = CGRectMake(0.0, 0.0, 100.0, 100.0);
        tempButtonName.center = CGPointMake(160.0,50.0+startPointY);
        [self.view addSubview:tempButtonName];
        startPointY += 100;
    }

}
</code>
Answer: Where you're going wrong is in trying to come up with a different variable name for the button each time through the loop. You don't need to do that, and it makes things harder than they ought to be. If you do:
<code>for(i=0;i<4;i++) {
    UIButton *button = //...
</code>
then you will have a different button each time through the loop as you require.
Comment: Hey Graham, Thank you kindly for the answer.
I never expected it to be so simple, you opened my mind and made me fall in love (even more) with Objective-C
Thank you.


Shared Preferences differences

Question: 1) What is the difference between
PreferenceManager.getDefaultSharedPreferences(context)

and
getSharedPreferences(name, mode)

2) And what does each of them do?
3) And how can I make a  setting screen (Activity)?
Answer: 1) You can have multiple SharedPreference files (so they are called SharedPreferences). The argument name of method getSharedPreferences(name, mode) specifies the the name of SharedPreference file to handle.
PreferenceManager.getDefaultSharedPreferences(context) returns the default SharedPreference file having default name and mode. Default name is based on your app's package name (as packagename_preferences.xml) and default mode is MODE_PRIVATE.
If you just want to use a single SharedPreferences file, PreferenceManager.getDefaultSharedPreferences(context) is concise to use.
2) With SharedPreferences you can save some key-value data.
3) Your last question: how to make a setting screen? is too wide topic to answer here. However, I suggest that using PreferenceActivity or PreferenceFragment you can manage a SharedPreferences without handling SharedPreferences directly.

Shared Preferences differences


How To Dispatch Two Related Events In a Re-frame Application?

Question: I'm working on a game with inventory system. Right now, the characters equipment and inventory are separate values in my DB. My problem, is when a user equips an item I need to both remove the item from the inventory and add it to the character.
I have something like this right now:
(defn equip-item [item idx]
  (re-frame/dispatch [:equip-item {:position :off-hand :item item}])
  (re-frame/dispatch [:remove-item-from-inventory idx]))

(re-frame/reg-event-db
  :equip-item
  (fn [db [_ itemObj]]
    (update-in db [:character :equipment] merge {(:position itemObj) (:item itemObj)})))

(re-frame/reg-event-db
  :remove-item-from-inventory
  (fn [db [_ idx]]
    (update-in db [:inventory :main] handle-remove idx)))

This works perfectly fine so far, but I'm wondering if there's a better way to handle dispatching multiple events like this? I know there's an ability to create an effect with a :dispatch-n key, but I'm not sure if that's appropriate here.
In any case, I'm also concerned about one event failing with the other succeeding. These should behave sort of like a transaction in that if one fails they both should fail.
Answer: Instead of using reg-event-db, use reg-event-fx. This returns a hash of effects.
One of these effects can be :fx, which is a list of other effects to call. These effects can be, for example, to dispatch an event. Some code:
(rf/reg-event-db
 :print1
 (fn [db]
   (.log js/console "print1!")
   db))

(rf/reg-event-db
 :print2
 (fn [db]
   (.log js/console "print2!")
   db))

(rf/reg-event-fx
 :test-two-dispatch
 (fn [{:keys [db]} _]
   {:db db
    :fx [[:dispatch [:print1]]
         [:dispatch [:print2]]]}))

Answer: The best approach would be to extract those update-in to separate regular functions, create the necessary third event, and call those functions in there via e.g. ->. Of course, you would call those functions in the original events instead of update-in as well.


Rendering Color Data to a Window, Win32

Question: So I am able to create an array of color data (projecting 3d models in case you are wondering), but I need to display them in a Win32 window. I know I could draw it pixel by pixel, but that is really slow. I know that I probably need BitBlt(); I would need it anyway if I am to use double buffering. I have seen how to render a .bmp to the window, but I don't have a .bmp. I guess I could MAKE a .bmp, but I'm going for speed here.
Is there any way to directly (probably not directly, but still quickly) access the pixel data of the hDC? How do graphics libraries do it so quickly?
Comment: Consider migrating this question to Stack Overflow
Comment: Why not take a look at [SDL](http://www.libsdl.org/). Just search the sources for the parts you need.
Answer: To copy your buffer to the DC, you should construct a BITMAPINFO, then use SetDIBitsToDevice() with the screen hDC, the pointer to your buffer and the constructed BITMAPINFO.
You can find a good starting-point for double buffering here.
Comment: If the pixel format of array of color data can be expressed in a BITMAPINFO, this is the fastest way to go.  If the color data is in an unusual format, (e.g., floating point values or has weird alignment), you might need to make an intermediate copy.
Answer: Render to a MemoryDC (which is quicker for pixel-by-pixel access), then copy that to your window DC.

Rendering Color Data to a Window, Win32


Model binding for float fails

Question: I'm trying to send window's position to the server. But model binding for top always fails. My action method is as below:
public void winClosed(Window position)

And the window model:
public class Window
{
    public decimal Left { get; set; }
    public double Top { get; set; }
}

In this picture you can see sample values:

And finally the JavaScript code:
var position = this.wrapper.offset();
$.post("@Url.Action("winClosed", "Home")", position);

The first line is relative to Kendo Window. I've already tried double, and float types in the model.
Comment: Is your ajax method hit the controller and do you write the JavaScript at the view or an JavaScript file?
Comment: Yes, it hits the action and I'll get the `left` just fine. And this call is from the `_Layout`.
Comment: What is the culture on the server (is the decimal separator a `.` (dot) or a `,` (comma)?
Comment: Culture is `fa-IR`, I don't know the separator. But it seems to be `.`
Comment: I think the decimal separator for farsi-Iran is `/`. Try initially setting `var position = { top: 93/3666, left: 210 };` to see if it binds.
Comment: Please post the answer Stephen so I can select it. I'm changing the separator like this: `position['top'] = position['top'].toString().replace('.', '/');`
Answer: The decimal separator for your culture (fa-IR) is / (forward slash) character. You will need to replace the . character with a / character. For example
var offset = this.wrapper.offset();
var l = offset.left.toString().replace('.', '/');
var t = offset.top.toString().replace('.', '/');
$.post("@Url.Action("winClosed", "Home")", {left: l, top: t });

Comment: I just figured out that there is a funny thing about kendo window, its `position` accepts just `int`! So you can simply use `parseInt`.

Model binding for float fails


Show $(\mathbb{R},0,+,-)$ has infinitely many automorphisms

Question: Show $(\mathbb{R},0,+,-)$ has infinitely many automorphisms :
My idea is that if $\phi:(\mathbb{R},0,+,-) \rightarrow (\mathbb{R},0,+,-)$ is an automorphism. Then since here we don't have the order relation. For any $x_1, x_2, y_1, y_2 \in \mathbb{R}$, $(x_1,x_2 ) \rightarrow (y_1, y_2)$ will be an automorphism. In another words, any we can always map an open interval to another open interval to have automorphism.
Could someone let me know if my thinking is correct?
If not, could you let me know what went wrong, and how should I fix it?
Any hints or ideas will be appreciated!
Thanks!
Comment: I assume "automorphism" means that it preserves the given operations... $\phi(0)=0$, $\phi(x+y) = \phi(x)+\phi(y)$, $\phi(-y) = -\phi(y)$.  Can you think of such functions?  Infinitely many of them?
Comment: Correct.  You get one map $x \mapsto ax$ for each multiplier $a$.  But which of these are bijective?
Comment: Other than the identity function, we can just multiply any $x \in \mathbb{R}$ by any constant. Would that work?
Comment: Prime? no.  $x \mapsto \sqrt{2}\;x$ will work.
Comment: $a$ has to be prime, is that right?
Answer: The answer you propose in the comments is correct: For any non-zero $r\in \mathbb{R}$, the function $x\mapsto rx$ is an automorphism of $(\mathbb{R},0,+,-)$. I'll leave it to you to check the details.
On the other hand, what you've written doesn't make any sense to me. You say "$(x_1,x_2)\to (y_1,y_2)$ will be an automorphism". What function $\mathbb{R}\to \mathbb{R}$ do you have in mind here? It's not true that any open interval can be  mapped to any other open interval by an automorphism. For example, $(-1,1)$ can't be mapped to $(1,2)$, since the first interval contains $0$, the second does not contain $0$, and any automorphism maps $0$ to $0$.
Answer: Hint: $\mathbb R$ is an infinite-dimensional vector space over $\mathbb Q$.
Comment: But this result is not needed for the question.
Comment: See also https://en.wikipedia.org/wiki/Cauchy%27s_functional_equation
Comment: Expanding on @GEdgar's comment, it's not just overkill - it actually proves a *weaker* result. $\mathsf{ZF}$ (= set theory without choice) does **not** prove that $\mathbb{R}$ has a basis as a $\mathbb{Q}$-vector space, and indeed "Every vector space has a basis" is equivalent to the full axiom of choice. The "scaling" solution is not only simpler, it also doesn't need any set-theoretic hypotheses.
Comment: @NoahSchweber, indeed. Thanks.