Fail2Ban unblock ipaddress

Question: I am trying to unblock an IP address without restarting Fail2Ban each time, what is the best way of doing this? Or can you point me in the direction of a useful guide?
As you can see below the IP address I am trying to remove is: 89.31.259.161
# iptables -L -n

    Chain INPUT (policy DROP)
    target     prot opt source               destination
    fail2ban-apache-badbots  tcp  --  0.0.0.0/0            0.0.0.0/0           multiport dports 80,443
    fail2ban-httpd  tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80
    fail2ban-sasl  tcp  --  0.0.0.0/0            0.0.0.0/0           multiport dports 25,465,143,220,993,110,995
    fail2ban-SSH  tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:22
    fail2ban-httpd  tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:443
    fail2ban-httpd  tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80
    fail2ban-vsftpd  tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:21
    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           multiport dports 80,443,25,465,110,995,143,993,587,465,21,20,2855
    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:54000

    Chain FORWARD (policy DROP)
    target     prot opt source               destination

    Chain OUTPUT (policy ACCEPT)
    target     prot opt source               destination

    Chain fail2ban-SSH (1 references)
    target     prot opt source               destination
    RETURN     all  --  0.0.0.0/0            0.0.0.0/0

    Chain fail2ban-apache-badbots (1 references)
    target     prot opt source               destination
    RETURN     all  --  0.0.0.0/0            0.0.0.0/0

    Chain fail2ban-httpd (3 references)
    target     prot opt source               destination
    DROP       all  --  89.31.259.161        0.0.0.0/0
    DROP       all  --  89.31.259.161        0.0.0.0/0
    RETURN     all  --  0.0.0.0/0            0.0.0.0/0
    RETURN     all  --  0.0.0.0/0            0.0.0.0/0
    RETURN     all  --  0.0.0.0/0            0.0.0.0/0

Chain fail2ban-sasl (1 references)
target     prot opt source               destination
RETURN     all  --  0.0.0.0/0            0.0.0.0/0

Chain fail2ban-vsftpd (1 references)
target     prot opt source               destination
RETURN     all  --  0.0.0.0/0            0.0.0.0/0

I was able to run: iptables -D fail2ban-httpd -s 89.31.259.161 -j DROP although this only deleted one of the lines.
Comment: See http://serverfault.com/questions/285256/how-to-unban-an-ip-properly-with-fail2ban
Answer: Use the --line-numbers option to iptables to get a listing which shows the line numbers for the rules in a chain e.g.
iptables -L fail2ban-SSH -v -n --line-numbers
Chain fail2ban-SSH (1 references)
num   pkts bytes target     prot opt in     out   source              destination
1       19  2332 DROP       all  --  *      *     184.108.40.206      0.0.0.0/0
2       16  1704 DROP       all  --  *      *     220.127.116.11       0.0.0.0/0
3       15   980 DROP       all  --  *      *     220.127.116.11      0.0.0.0/0
4        6   360 DROP       all  --  *      *     220.127.116.11      0.0.0.0/0
5     8504  581K RETURN     all  --  *      *     0.0.0.0/0           0.0.0.0/0

Then use iptables -D chain rulenum to remove the ones you don't want e.g.
iptables -D fail2ban-SSH 1

would delete the
1       19  2332 DROP       all  --  *      *     126.96.36.199      0.0.0.0/0

line from the example above. Note that everything is renumbered so you can run the same command again to remove the new rule 1 in the chain.
Comment: This will work - UNTIL you restart the server or fail2ban. The answer from @Ndianabasi is better.
Answer: From my experience with Fail2ban, unbanning an IP address directly through IPTABLES will result in the IP being banned again by Fail2ban if the Fail2ban service is restarted within the Ban Time.
That being said, the most effective and clean way of unbanning an IP address banned by Fail2ban is using the fail2ban-client.
Step 1: Take note of the Jail Name by checking the Fail2ban log
sudo zgrep 'Ban' /var/log/fail2ban.log

Sample output:

2017-11-03 04:30:14,509 fail2ban.actions        [25091]: NOTICE
  [nginx-badbots] Ban 188.8.131.52 2017-11-03 04:37:29,597
  fail2ban.actions        [27065]: NOTICE  [nginx-badbots] Ban
  126.96.36.199 2017-11-03 04:37:30,124 fail2ban.actions        [27065]: NOTICE  [nginx-badbots] Ban 18.104.22.168 2017-11-03 04:37:30,364
  fail2ban.actions        [27065]: NOTICE  [nginx-badbots] Ban
  220.127.116.11 2017-11-03 04:38:06,754 fail2ban.actions        [27065]: NOTICE  [vsftpd] Ban 126.96.36.199

If we are interested in unbanning the IP address - 184.108.40.206 - then the Jail name is vsftpd.
Step 2: Unban the IP address using fail2ban-client. The general format is:
sudo fail2ban-client set [JAIL] unbanip [xx.xx.xx.xx]

Now, run:
sudo fail2ban-client set vsftpd unbanip 188.8.131.52

Sample output:

184.108.40.206

Step 3: Confirm unban from Fail2ban log
sudo tail -f /var/log/fail2ban.log

Sample output:

2017-11-03 04:38:13,332 fail2ban.actions        [27065]: NOTICE
  [vsftpd] Unban 220.127.116.11
Comment: This should be the accepted answer.

Fail2Ban unblock ipaddress


Why there is theta in index of gradient symbol in gradient descent update formula for MAML?

Question: In this MAML paper, they use following formula of gradient descent update (see page 3, algorithm 1):
$$
\varTheta '\ =\varTheta \ −\ \alpha \nabla _{\varTheta }\mathcal{L}_{\mathcal{T}_{i}}( f_{\varTheta })
$$
My question is, what is the reason of having theta in subscript after gradient (nabla) ?
Specifically, why is it not like this:
$$
\displaystyle \varTheta '\ =\varTheta \ −\ \alpha \nabla \mathcal{L}_{\mathcal{T}_{i}}( f_{\varTheta }) \
$$
In other words why is not enough to tell it like just gradient of loss function?
Answer: That means gradient with respect to $\theta$. In the context, there is little uncertainty and probably anyone reading the paper can understand that it is gradient wrt $\theta$ even if they hadn't used the subscript notation but there is no harm in being precise, especially in published work.
It's like writing $\frac{\partial f}{\partial \theta}$, instead of $f'$.


Kotlin: how to pass array to Java annotation

Question: I want to use @OneOf annotation from package io.dropwizard.validation;
Java usage:
@OneOf(value = {"m", "f"})

Kotlin usage: ???
I've tried this:
 @OneOf(value = arrayOf("m", "f"))

and this:
 @OneOf(value = ["m", "f"])

(EDIT: this example works since Kotlin 1.2, it supports array literal in annotation, thanks @BakaWaii)
All i get is :

Type inference failed. Expected type mismatch:
required: String
found: Array<String>

Kotlin version: 1.1.2-2
Comment: To pass an array as a vararg parameter, use spread (*) operator. `@OneOf(value = *arrayOf("m", "f"))`
Answer: The value parameter is automatically converted to a vararg parameter in Kotlin, as described in http://kotlinlang.org/docs/reference/annotations.html#java-annotations.
The correct syntax for this particular case is @OneOf("m", "f")
Answer: In Kotlin 1.2, it supports array literal in annotation. So the below syntax becomes valid in Kotlin 1.2:
@OneOf(value = ["m", "f"])

Answer: As an example from Kotlin docs
// Kotlin 1.2+:
@OneOf(names = ["abc", "foo", "bar"])
class C

// Older Kotlin versions:
@OneOf(names = arrayOf("abc", "foo", "bar"))
class D

Comment: any idea how to pass this as a variable?
like, val someArray = arrayOf("abc", "foo", "bar")
I tried it below way and its giving me `should be compile time constant exception`
1)
@OneOf(names = someArray)
2)
@OneOf(names = *someArray)
Answer: Example of annotation parameters other than value. Non-literals can also be passed inside []
@RequestMapping(value = "/{isbn}", method=[RequestMethod.GET])
fun getBook(@PathVariable isbn: String) : Book = bookRepository.findBookByIsbn(isbn)


Do I need to run Captcha and Mollom simultaneously?

Question: Just wondering if I have Mollom installed and running successfully on a D7 site, if I still need to keep Captcha enabled?
I'm getting double captcha forms with both enabled.
Comment: The only possible answer is "it depends". Do you have any reason to believe Mollom will fail to recognize some threats? If so, you need other layer. If no, no.
Comment: No. There is no need to have both enabled.
Answer: If you're satisfied with the Mollom module, then I don't think it makes sense to also leave the Captcha module enabled/installed.
However, if you're looking for some kind of extra protection/layer but without those double captcha forms, then you may want to consider replacing Captcha with the Honeypot module. Because of the technique used by Honeypot, you don't risk to have double captcha forms in that case.
Some more details about the Honeypot module (from its project page):

... uses both the honeypot and timestamp methods of deterring spam bots from completing forms on your Drupal site (read more here). These methods are effective against many spam bots, and are not as intrusive as CAPTCHAs or other methods which Punish the user.

Note: even if you don't want to consider using the Honeypot module (for whatever reason), keep "the message" in mind about what that link quoted from its project page (Punish the user) is trying to explain whenever your researching similar modules.
Comment: I've had captcha disabled for the last 24+ hours and so far, no spam post on my webforms...


How I deploy my libgdx project to HTML/JS using TeaVM

Question: I recently created a libGDX project using vis-runtime version 0.3.4. As due to long build times and requirement for separate runtime-gwt project, GWT support was dropped in 0.3.3 version of vis-runtime.
Maybe TeaVM can be used as web backend, so I am looking for integration of TeaVM with vis-runtime library ?
Take a look of this project (integration of libgdx with teaVM) that uses Maven as build system not Gradle.
Any help would be greatly appreciated.
Answer: I created TeaVM backend for libGDX as a prototype. I have no time to maintain it and thought someone from libGDX community becomes interested and picks this project. No one did, so backend is not maintained anymore. You can ask question on libGDX community forums and may be you find someone who is interested in developing my prototype. From my side I can help with fixing bugs in TeaVM and telling how this or that thing works in TeaVM.
Regarding Gradle, there's no official support, but 3rd party plugin is available: https://github.com/edibleday/teavm-gradle-plugin. You can examine source code and see that it's easy to write one. You can even write your own Gradle plugin if you are not satisfied with this one. However, I think that supporting Gradle is a little more complicated task than just wring Gradle plugin. For example, IDE integration is also needed (i.e. IDE must import and setup project from build.gradle).
Comment: Thanks for support as well as your suggestion, I will forward it to libGDX community.
Comment: Hello, @alexey-andreev perhaps you have some idea to run TeamVM JUnit test on IntelliJ? https://stackoverflow.com/questions/52025648/run-junit-test-with-intellij


trim(both) doesnt not trim the leading character

Question: Table qqq:
|**type**  | **ColB** |

-+-----------+-----------+-
| A     | 0030-0000     |
| A     | 0234-0001     |
| A     | 0001-0003     |

type is Varchar,
ColB is Varchar
I would like to trim all zeroes in leading and trailing poisition. The expected outcome is :
|**type**  | **ColB** |

-+-----------+-----------+-
| A     | 30-        |
| A     | 234-0001   |
| A     | 1-0003     |

This is query I wrote:
select type, TRIM(both '0' FROM colB) From qqq
where type = 'A';
However, my output is:
|**type**  | **ColB** |

-+-----------+-----------+-
| A     | 0030-         |
| A     | 0234-0001     |
| A     | 0001-0003     |

the trim (both does not working out...
Comment: Presumably you have another character before the first `0`.
Comment: Nope. I've checked @GordonLinoff
Comment: BOTH is optional here, as per https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_trim
Comment: Stabbing in the dark here, but have you tried testing it with a string that does not have a -?
Comment: Even if i use 'TRIM(leading` it does not working out too @toonice
Comment: Does not have hyphen? @toonice
Comment: That's what I meant.  I have since gotten my copy of MySQL up and running and been able to test that theory.  It's not the hyphen.  I'll keep looking.
Comment: any possible alternatives? @toonice
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/139430/discussion-between-toonice-and-user6308605).
Answer: After much diagnosis via chat I began to suspect that there was a leading space in the strings.  I suggested the following as an answer...
SELECT TRIM( '0' FROM TRIM( fieldName ) )
FROM tableName;


The proof concerning morphism between varieties in T. A. Springer's book

Question: The Theorem 1.9.5 in T. A. Springer's Linear Algebraic Groups (page 19) states that:

Let $\phi: X \rightarrow Y$ be a morphism of varieties. Then $\phi X$ contains a non-empty open subset of its closure $\overline{\phi X}$.

(Here, a variety is defined as a quasi-compact ringed space to have an open cover by affine subsets along with being separated.)
The first line of Springer's proof wrotes:

Using a covering of $Y$ by affine open sets, we reduce the proof to the case that $Y$ is affine.

I wonder how such reduction proceeds, particularly whether the preimage of a affine open subset of $Y$ is a subvariety of $X$. (Initially I wrongly claim that the preimage of a affine open subset of $Y$ is not necessarily quasi-compact.)
Hope for an answer, thanks in advance!
Comment: [This answer](https://math.stackexchange.com/questions/1721223) is helpful.
Answer: Actually, $\phi$ is a quasi-compact map.
Indeed, let $B$ be an affine base scheme, so that $X,Y$ are separated quasicompact over $B$.
Then $\phi$ is the composition of $\phi_1: X= X \times_Y Y \rightarrow X \times_B Y$ and $\phi_2: X \times_B Y \rightarrow Y$.
$Y \rightarrow B$ is separated so $\phi_1$ is a closed immersion so is quasi-compact. But $\phi_2$ is a base change of $X \rightarrow B$ which is a quasi-compact map so is quasi-compact. So the composition $\phi$ of $\phi_1$ and $\phi_2$ is quasi-compact.
Answer: Actually, the map $\phi:X\to Y$ is quasi-compact, so the preimage of any quasi-compact set (like an affine open set of $Y$) is again quasi-compact. The key result is the following:

Lemma (Stacks Project 03GI): Let $f:X\to Y$ and $g:Y\to Z$ be morphisms of schemes. If $g\circ f$ is quasi-compact and $g$ is quasi-separated, then $f$ is quasi-compact.

In our situation, we take $Z=\operatorname{Spec} k$, $g$ the structure morphism, $f=\phi$, and then we have that $g\circ\phi$ is equal to the structure morphism $X\to \operatorname{Spec} k$ by assumption that $\phi$ is a map of $k$-schemes. As a separated morphism is quasi-separated, we have that $g$ is quasi-separated, and because $X$ is quasi-compact and $\operatorname{Spec} k$ is a point, we have that $g\circ f$ is quasi-compact. Thus your situation satisfies the assumptions of the lemma and we may conclude that $\phi$ is quasi-compact.
(I do not have a copy of this book in front of me right now, but I remember that some of these algebraic groups texts are notorious for not doing things correctly from a modern algebraic-geometry perspective. If it's doing some wacky thing like only taking closed points, do not fear: these geometric objects embed as subspaces with the induced topology of the schemes in question, and the maps between the not-quite-schemey versions are exactly the restrictions of the scheme maps to these subspaces and everything is okay.)
Comment: May I ask that utilizing the method above, whether we can prove the preimage of a subvariety is still a subvariety?
Comment: @WembleyInter What do you mean? What parts of that claim are tripping you up? This shows quasi-compactness, and any locally closed subscheme of a separated scheme is again separated, so that would seem to do it by your definitions.
Comment: Ah... Now I get it. Thanks!
Comment: @WembleyInter if this resolves your issues, please consider [accepting the answer](http://meta.math.stackexchange.com/questions/3286/). If not, is there something you feel is missing from the answer?


AJAX callback not added using form_alter

Question: I want to perform a AJAX callback to check the value of a custom field during user registration. Because the form is already built, I need to use hook_form_alter.

But, no callback is added using hook_form_alter. Maybe it is overwritten later on? Therefore, I tried $form['#after_build'].
But that fails too for the AJAX property. Adding another form element works perfectly fine.

The code:
/**
 * Implements hook_form_alter().
 */
function member_id_check_v2_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id){
    case 'user_register_form':
    case 'user_profile_form':
      $form['#after_build'][] = '_member_id_check_v2_ajax';
      break;
    default:
      break;
  }
}

function _member_id_check_v2_ajax($form, &$form_state) {
  $form['member_id_check_v2_callback_wrapper'] = array(
    '#type' => 'textfield',
    '#title' => t("The default value will be changed"),
  );

  $form['custom_field']['#ajax'] = array(
    'callback' => '_member_id_check_v2_callback',
    'wrapper' =>  'member_id_check_v2_callback_wrapper',
  );

  return $form;
}

function _member_id_check_v2_callback() {
    watchdog(WATCHDOG_DEBUG,'Callback worked!');
}

What am I missing? Thanks in advance!
Answer: You need to do the AJAX callback on #process callback as #after_build callback is too late to inject AJAX.
Check out the this link and the example code:
/**
 * Implements hook_form_alter()
 */
function kf_link_form_alter(&$form, &$form_state, $form_id) {
  if ('example_node_form' == $form_id) {
    //$form['field_link'][$language]['#after_build'][] = '_kf_link_field_link_after_build';
    $form['field_link'][$language][0]['#process'] = array('link_field_process', '_kf_link_field_link_process');
  }
}

/**
 * Custom form api process function
 */
function _kf_link_field_link_process($element, &$form_state, $form) {
  $element['url']['#description'] = '

';
  $element['url']['#ajax'] = array(
    'callback' => 'kf_link_ajax_callback',
    'wrapper' => 'example-link',
  );
  return $element;
}

/**
 * Custom ajax callback function
 */
function kf_link_ajax_callback(&$form, $form_state) {
  $values = $form_state['values'];
  $field_link = $values['field_link'];
  $language = $values['language'];
  $url = $field_link[$language][0]['url'];
  $duplicate_nodes = _kf_link_get_url_nid($url);
  foreach ($duplicate_nodes as $duplicate_node) {
    if (isset($duplicate_node->nid) && ($duplicate_node->nid != $values['nid'])) {
      drupal_set_message(t('This URL already exists in !title', array('!title' => $duplicate_node->title, '!url' => "node/{$duplicate_node->nid}")), 'error');
    }
  }
  $commands = array();
  $commands[] = ajax_command_html(NULL, theme('status_messages'));
  return array(
    '#type' => 'ajax',
    '#commands' => $commands,
  );
}


Log all http responses with an error code >=400

Question: The application in question uses connexion, which wraps flask, to take care of the web-server. The API is specified with swagger. Is there an easy and straight forward way to get somewhere into the code where http responses are formulated from the web-server?
If possible, I would like to avoid writing 200 errorhandlers, or the 10 most popular and crossing my fingers.
api.py
import connexion
app = connexion.App(__name__,
                specification_dir='../swagger/',
                swagger_ui=False,
                validator_map={
                    'body': connexion.decorators.validation.RequestBodyValidator
                })
app.add_api('swagger.yml', strict_validation=True)

# If I had to use app.error_handler decorators to implement the special
# treatment of http responses with error codes, I would put it here

swagger.yml
swagger: '2.0'
info:
  title: My Minimal Working Example
consumes:

  - application/json
produces:
  - application/json

basePath: /api/v1
paths:
  '/do_something':
    post:
      tags:
        - MyTag
      operationId: entrypoint.do_something
      summary: Do something on request
      parameters:
        - name: data
          in: body
          schema:
            $ref: '#/definitions/data'
      responses:
        '200':
          description: Success!
          schema:
            $ref: '#/definitions/Response'
        '400':
          description: Error!
          schema:
            $ref: '#/definitions/Response'
        '403':
          description: Not Authorized
          schema:
            $ref: '#/definitions/Response'
# a lot more stuff and "definitions"

Answer: I solved the problem by subclassing the Flask object, as davidism suggested. The short version is this:
app.py
import logging.config
import yaml

logging.config.dictConfig(yaml.load(open('logging.conf', 'r')))
logger = logging.getLogger("mainLogger")

class LoggingFlask(Flask):
    def make_response(self, rv):
        rv = super(LoggingFlask, self).make_response(rv)
        if int(rv.status_code) >= 300:
            logger.warn("Request failed with error code %s." % rv.status_code)
        return rv

app = LoggingFlask(__name__)

session.log
./app.py
[2017-10-10 11:38:19,564 - werkzeug - INFO]:  * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[2017-10-10 11:38:19,566 - werkzeug - INFO]:  * Restarting with stat
[2017-10-10 11:38:19,690 - werkzeug - WARNING]:  * Debugger is active!
[2017-10-10 11:38:19,691 - werkzeug - INFO]:  * Debugger PIN: 211-310-838

# issues a good request
[2017-10-10 11:38:25,179 - werkzeug - INFO]: 127.0.0.1 - - [10/Oct/2017 11:38:25] "GET /todo/api/v1.0/tasks HTTP/1.1" 200 -

# issued a bad request
[2017-10-10 11:38:28,646 - mainLogger - WARNING]: Request failed with error code 404.
[2017-10-10 11:38:28,646 - mainLogger - WARNING]: Request failed with error code 404.
[2017-10-10 11:38:28,647 - werkzeug - INFO]: 127.0.0.1 - - [10/Oct/2017 11:38:28] "GET /todo/api/v1.0/task HTTP/1.1" 404 -

If someone knows how to access the request that triggered the current response, feel free to drop a comment so that I can include it in this answer as well.


Fitting lyrics to multiple rhythms with ossia stave

Question: I'm trying to transcribe a song with a slightly different different number of syllables in different verses. To indicate this I'm using an ossia stave since writing the verses out multiple times would make the whole thing pretty long. However, the lyrics of the verse with changed rhythm are fitted to the rhythm of the original melody. Is there a way to associate lyrics with an ossia stave?

\version "2.20.0"

melody = \relative c' {
    << { a4 e' e a, | \noBreak b4 e8( d) d2 | \noBreak c4 e e c | \noBreak d4 fis g fis | }
        \new Staff \with {
            \override VerticalAxisGroup.default-staff-staff-spacing =
                #'((basic-distance . 4.5)
                   (padding . -10))
            \remove "Time_signature_engraver"
            alignAboveContext = #"3"
            \magnifyStaff #2/3
            \hide Clef
        }
        { \stopStaff s4 s s s | \startStaff c4 e e8( d) d4 | \stopStaff s4 s s s | \startStaff d4 fis fis2 }
    >>
}

verse_one = \lyricmode {
    A -- A A A A -- A A,
    A -- A A A A A -- A -- A,
}

verse_two = \lyricmode {
    B -- B -- B B -- B -- B BB,
    B -- B -- B B B -- B -- B ,
}

\score {
\new Staff = "3"
    << \new Voice = "Lead" {
        \melody
    }
    \new Lyrics \lyricsto "Lead" {
        <<
        { \set stanza = "1." \verse_one }
        \new Lyrics { \set stanza = "2." \set associatedVoice = "Lead" \verse_two }
        >>
    }
    >>
}

Answer: There isn't a way to do it, I'm afraid (or at least a practical way).
However, your problem can be solved by a trick that is very handy in complex situations like these. Just add a NullVoice into your staff, so you will have something like
\new Staff
<<
        \new Voice = "lead" { \melody }
        \new NullVoice = "lyricguide" { \lyricguide }
        \new Lyrics \lyricsto "lyricguide" {
                A a a,
                B b b.
        }
>>

The NullVoice is just a dummy voice that you can put anything into but nothing is ever rendered. So you can come up with any rhythm you want, put that into the NullVoice (the notes themselves do not matter, so you can write just a4 4 4 4 | 4 4 4 4 etc.) and align the lyrics to that voice, as shown in the bit of code above.
In this way, you can align the lyrics to any rhythm you want (it doesn't even need to have anything in common with the rest of the voices). You can see this mostly in choral settings where all voices sing sort of the same lyrics most of the time, with some exceptions, but those "common lyrics" actually don't align to any of the voices.


Regex not as greedy as expected /^(\d+)[^_]/

Question: Regex: /^(\d+)[^_]/gm
Test String: 12_34
I'd expect this regex not to match on test string, because \d+ is greedy eating the digits 1 and 2 and [^_] fails on _.
But it unexpected matches with only 1 in Group1. Where am I wrong?
I try to find a regular expression that matches the digits in test strings "12" or "12xx" but does not match on "12_xx"
Sample:
https://regex101.com/r/0QRTjs/1/
Dialect: In the end I'll use Microsoft System.Text.RegularExpressions.
Comment: You should read about [Backtracking](https://stackoverflow.com/q/9011592/8967612) and [Atomic Groups](https://stackoverflow.com/q/14411818/8967612). Basically, "greedy" means "as much as possible **with backtracking allowed**". The behavior that you were expecting can be achieved with an atomic group.
Comment: As to your particular example, you can just use a negative Lookahead since you probably don't need to include the character after the digits in the match: `^(\d+)(?!\d|_)`. See [this demo](https://regex101.com/r/Lt7Zhg/1).
Comment: OK, so the feature **Backtracking** leads to my "unexpected behaviour", because the regexp does more than I thought. And I can use **Atomic Groups** to avoid the Backtracking. `^((?>\d*))[^_]` seems to do the trick. Thank you Ahmed!
Comment: `^((?>\d*))([^_]|$)` to correctly match my digit-only line.
Answer: \d+ will match with one or more digits.
Since you append [^_], it can only be followed by a non _ character.
Therefore \d+ cannot match 12 because it is followed by _.
1 is the first matching group because it is followed by 2 which is not _.
If you want to match lines with digits only there is a very simple expression:
^(\d+)$

Answer: \d+ has the ability to reduce the number of matches if that results in an overall match. By backtracking then 2 satisfies the match of [^_] and 1 is captured.
See HERE
You can use a negative lookahead at the start of the match:
/^(?!\d+_)(\d+)/

See HERE
Or you can use an atomic group that disallows backtracking:
/^((?>\d+))(?:[^_]|$)/

See HERE
Or use a possessive quantifier of ++ which disallows backtracking:
/^\d++([^_]|$)/

See HERE
The possessive quantifier is likely the fastest...
Comment: `(?!=_)` is not enough and "12" will still be matched in "12_". You need `(?![_\d])`. Also, I'm guessing the `=` is a typo?
Comment: `/^((?>\d+))[^_]/` does wrong on the digit-only line. I corrected my answer in the comments. Best seems to be @41686d6564 answer `^(\d+)(?!\d|_)?`


Continuous mapping $D^2 \to S^1$

Question: It is a well known result in algebraic topology that there is no retraction of $D^2$ onto $S^1$.
Does anyone know any continuous maps $D^2 \to S^1$ which are not constant?
Comment: I have to ask: how does one get to the point where one knows what a retraction is and, well, that algebraic topology is something, and is not able to construct a non-const. cont. function like that? :/
Comment: $e^{i\pi|z|}{}$
Comment: In particular, a map $f:S^1\rightarrow S^1$ can be extended to all of $D^2$ if and only if $f$ is homotopy-equivalent to a constant.
Comment: There are no continuous maps of $D^2$ to $S^1$ that are the identity on $S^1\subset D^2$.
Comment: Since Mariano's comment was up voted so many times I feel compelled to respond! I was trying to come up with a map from D^2 to S^1 which when restricted to the boundary has degree 2. I couldn't think of one which is why I asked the question. I probably should have been more explicit. Thomas answered this question though...
Comment: @Dbr: Your map would be a map $S^1\to S^1$ which factors through $D^2$. Since $D^2$ is contractible, your original map is null, hence degree 0.
Answer: How about the map that sends $$(x,y)\in D^2=\{(x,y)\in\mathbb{R}^2\mid x^2+y^2\leq 1\}$$ to $$(\textstyle\sqrt{1-y^2},y)\in S^1=\{(x,y)\in\mathbb{R}^2\mid x^2+y^2=1\}$$
Answer: If you can think of a path $\gamma\colon I \to S^1$, then you get a continuous map $D^2 \to S^1$ by first collapsing $D^2$ to the interval $I$ and then composing with your path.
If your path $\gamma$ was not constant, then the resulting map $D^2 \to S^1$ will not be constant.

Continuous mapping $D^2 \to S^1$


"Time ago" from "date end" in views

Question: How to print Date Field in Views in format "time ago" for "end dates"?
If I config field in views like:
Display: End date only,
Formatter: Time ago.
I get duration form Start date :(
Example for today (7 jun 2014).
date field values: start 1 jan 2013, end 1 jan 2014.
I wanna get: Expired - 5 mounths and 7 days.
But views printing: Expired - 1 year, 5 mounths and 7 days.
Answer: You can write this in javascript to avoid caching issues and use the users machine time.
https://drupal.org/project/timeago
http://momentjs.com/
http://timeago.yarp.com/
otherwise there is a patch here: https://drupal.org/node/2026545
Comment: Thanks for the idea of conversion using js.

I looked module "timeago". Great module, but it is impossible translate the strings (plurals strings). And there is a problem with the date fields if option "all day" is enabled.

I'll try a custom js whit Drupal.formatPlural() or will use momentjs.com (looks powerfully).

Sorry for my english.

"Time ago" from "date end" in views


How can percent increase of two products separately be greater than the percent increase of the whole?

Question: How can the percent increase in Product $A$ ($52\%$) and Product $B$ ($75\%$) each be greater than the combined increase ($47\%$)?
In $2015$, I have $\$1.1$M revenue of Product $A$ with $1,000$ units sold for an average price of $\$1,100$ per unit.  In $2016$, I have $\$1$M revenue of Product A with $600 $ units sold for an average of $\$1,667$ per unit.  The increase in percent from $\$1,100$ per unit to $\$1,667$ per unit is $52\%$.
In $2015$, I have $\$0.6$M revenue of Product $B$ with $350$ units sold for an average price of $\$1,714$ per unit.  In $2016$, I have $\$0.3$M revenue of Product $B$ with 100 units sold for an average of $\$3,000$ per unit.  The increase in percent from $\$1,714$ per unit to $\$3,000$ per unit is $75\%$.
Combining the products, in 2015, I have $\$1.7$M revenue of both products with $1,350$ units sold for an average price of $\$1,259$ per unit.  In $2016$, I have $\$1.3$M revenue of both products with $700$ units sold for an average of $\$1,857$ per unit.  The increase in percent from $\$1,259$ per unit to $\$1,857$ per unit is $47\%$.
Restating the question, how can the percent increase in Product $A$ ($52\%$) and Product $B$ ($75\%$) each be greater than the combined increase ($47\%$)?
Comment: This is an example of 'Simpson's Paradox'.
Comment: The Wikipedia article on [Simpson's paradox](https://en.wikipedia.org/wiki/Simpson's_paradox) is a decent starting point.
Answer: To take an extreme case:
Suppose in year $1$ I sell $100$ units of $A$ for $\$1000$ each and $1$ unit of $B$ for $\$1$.  That's $101$ units sold for $\$100001$ so the unit price is $\$990.1089109$.
Suppose in year $2$ I sell $1$ unit of $A$ for $\$1100$ and $100$ units of $B$ for $\$1.1$.  That's $101$ units for $\$1210$ so a unit price of $\$11.98019802$.
Thus both products go up by $10\%$ but the unit price goes way down. Of course, that's because in year $1$ I sold lots of the expensive product and in year $2$ I sold lots of the cheap one.  That's what you did in your problem...in the first year you sold about three times as much $A$ as $B$, while in the second year that jumped to six times as much.


Rules triggering rules - how to enforce or disable it

Question: There are many situations in which a rule could trigger another rule.  For example, If I have a rule that reacts to a Node being created, I can trigger that rule with another rule that created a node.  The same should hold true for flagging nodes, but I have seen cases in which it does not.  I have written 'single flag enforcement' rules that are triggered by a node being flagged, which un-flag all nodes flagged by that user, then re-flag only the triggering node.  This rule should trigger itself over and over infinitely, but it does not.   How does Drupal's Rules handle these situation?  Is there a way to force rules to allow or disallow this form of cascading rule triggering (and potentially cause/prevent an infinite loop?)
Answer: It will not trigger recursively, Rules has inbuilt mechanism to prevent this. if you check the function rules_element_invoke_component you can see this.
<code>function rules_element_invoke_component($arguments, RulesPlugin $element) {
  ....
  // Handle recursion prevention.
  if ($state->isBlocked($component)) {
     return rules_log('Not evaluating @plugin %label to prevent recursion.',  $replacements, RulesLog::INFO, $component);
  }
  $state->block($component);
  ....
}
</code>
Comment: Yeah, as you said a rule cannot be called as a child process. But as per VBO, assume that we have a rule that triggers when a user is updated and we are performing bulk user update. Even though this is a bulk operation for us internally it is only loop. And after each updation if a rule is not triggering any other rule then it will unblock `$state->unblock($component);`, so it will trigger for the next update also.
Comment: Is that to say that a rule will not trigger itself, but it can trigger a different rule if the actions match triggers?
Comment: Yes, if you check the [rules.state.inc](http://drupalcontrib.org/api/drupal/contributions!rules!includes!rules.state.inc/7) file you can see `static protected $blocked = array();` where they are storing the rule id.
Comment: It looks like a rule can be called multiple times on a single page load, but not as a 'child process' of the same rule.
Comment: I don't think so, can you explain a scenario.
Comment: As Once a rule is called, it is added to the blocked array, which prevents it from being called later.  However, a rule can be called several times (by views bulk operations) on a page load, so it looks like the blocked array is reset at some point.


How to theme one tab of a node

Question: I have hook_menu() configured to show a tab for every node at node/%node/summary.  The callback for that page returns the correct content, but I'd like to add a bunch of HTML to the page.
I believe I need to create a .tpl.php file in my custom theme.  How do I know what to name the file and make sure that the template is used only on the correct pages?
Answer: In Drupal 6, this would be:
 page-node-summary.tpl.php

More information on Drupal 6 template suggestions can be found at http://drupal.org/node/1089642
In Drupal 7, this would be:
 page--node--summary.tpl.php

More information on Drupal 7 template suggestions can be found at http://drupal.org/node/1089656
In either case, I'd grab the default page.tpl.php of your theme as a basis for it.
Comment: @htoip please tag your questions with 6 or 7 so people don't need to answer both methods...
Answer: The theme developer module allows you to point and click on any part of your page. It shows you all called and possible theme functions and template names.

How to theme one tab of a node


JAPE rule Sentence contains multiple cases

Question: How can i check whether a sentence contain combinations? For example consider sentence.
John appointed as new CEO for google.
I need to write a rule to check whether sentence contains < 'new' + 'Jobtitle' >.
How can i achieve this. I tried following. I need to check is there 'new' before word .
Rule: CustomRules
(
    {
        Sentence contains {Lookup.majorType == "organization"},
        Sentence contains {Lookup.majorType == "jobtitle"},
        Sentence contains {Lookup.majorType == "person_first"}
    }
)

Comment: See following question. It alows you to limit a JAPE patern to match within a single sentece only. Then you can select the coreponding sentence using another JAPE. http://stackoverflow.com/questions/29198611/jape-file-to-find-the-pattern-within-a-sentence
Answer: One way to handle this is to revert it. Focus on the sequence you need and then get the covering Sentence:
(
  {Token@string == "new"}
  {Lookup.majorType = "jobtitle"}
):newJT

You should check this edge when the Sentence starts after "new", like this:
new

CEO

You can use something like this:
{Token ... }
{!Sentence, Lookup.majorType ...}

And then get the sentence (if you really need it) in the java RHS:
long end = newJTAnnots.lastNode().getOffset();
long start = newJTAnnots.firstNode().getOffset();
AnnotationSet sentences = inputAS.get("Sentence", start, end);


How to calculate 3D depth reconstruction of an image using a set of 3 similar images?

Question: I have tried asking this in computer science SE, but sadly get no answers. Since this is fundamentally mathematical, I hope someone could give pointers to an answer for this, please.
From a set of 2 similar images taken some small translation distance apart, we can calculate the depth of the a particular point, if we know the distance of a reference object in the frames. This is done by checking the disparity difference in the x pixel coordinates.

My question is about how to calculate depth of a particular point in the image, given 3 randomly translated/rotated/scaled images, without knowing anything about the camera movements?

What is the mathematical principle that allow us to calculate the depth of a particular point just by comparing these 3 normal/uncalibrated camera pictures?
Thank you.
Answer: Here you have two problems, the fist is to estimate the parameters of the cameras and then you can use this parameters to get the depht of a particular point.
The problem of estimating the parametes of multiple cameras when you have multiple images in which have been established correspondence between $n$ is called Structure from motion. The principles to solve this problem are epipolar geometry, two interesting books about this problem are "Three dimensional computer vision a geometric viewpoint" by O. Fagueras and "Computer Vision. A modern approach" by D. Forsyth and J. Ponce.
When you have recovered the parameters of the camaras you can just go as if you have two cameras but in this case checking the disparity difference in the x pixel coordinates in three images. Or you can give a different approach like using the third camera to check the correspondences made by the other two cameras.
Comment: thank you for your answer!


Webflow view-state model bean properties are not autowired

Question: I have a Spring 3.2.11 and Webflow 2.4.0 app using JSF2 for view rendering.
One of my pages uses a view-state model bean for validation but when the validatePasswordChange method is called, the bean properties have not been autowired so I get a NPE. I don't understand why they're null!?
Thank you for any suggestions.
Here's my bean validation method. Why is the passwordService property null?
public void validatePasswordChange(ValidationContext context) {

    MessageContext messages = context.getMessageContext();
    if (!confirmPassword.equals(newPassword)) {

        messages.addMessage(new MessageBuilder().error()
                .source("confirmPassword")
                .defaultText(
                        this.getMessage("kyn.password.change.validation.noMatch"))
                .build());
    };

    List<String> validationMessages = passwordService
            .validatePasswordPolicyCompliance(getUsername(),
            newPassword);
    if (validationMessages != null) {
        for (String message : validationMessages) {
            messages.addMessage(new MessageBuilder().error()
                    .source("confirmPassword")
                    .defaultText(message).build());
        }
    }
}

Here's a snippet from my flow.xml. I'm inserting passwordUpdateBean into the flowScope in the on-start and expecting the model attribute to use it:
<on-start>
    <evaluate expression="passwordUpdateBean" result="flowScope.passwordUpdateBean"></evaluate>
</on-start>

<view-state id="passwordChange" model="passwordUpdateBean">
    <transition on="proceed" to="update"/>
    <transition on="cancel" to="redirectCancel"  validate="false"/>
</view-state>

And here's my bean config xml:
<bean id="passwordUpdateBean"
    class="com.xyz.PasswordUpdateBean"
    scope="prototype"
    parent="abstractWebBean">
    <property name="passwordService" ref="passwordManagementService"/>
    <property name="appUserDetailsService" ref="appUserDetailsService"/>
    <property name="autoLoginAfterEnrollment" value="true"/>
    <property name="usernamePasswordAuthenticationProvider" ref="usernamePasswordAuthenticationProvider"/>
</bean>

Answer: beans will NOT auto wire inside your flow definitions. You have get have to explicitly retrieve the bean into the flow definition.
Note @Service class annotations are automatically accessible in flow files (i.e <evaluate expression="myService.getPasswordUpdateBean()" result="flowScope.passwordUpdateBean"/>)
<on-start>
    <evaluate expression="....getPasswordUpdateBean()" result="flowScope.passwordUpdateBean"></evaluate>

</on-start>


How to Bulk delete the document from solr without actually deleting the node?

Question: The scenario is to delete bulk documents from apache solr, without deleting the actual node from the database. I am aware that when the node is un-published it will be deleted from solr.
But as my node are very large containing 1000's of terms I don not want to use node-save to un-publish the node.
Is there any hook or function which un-publishes the node and deletes from solr by minimal load (definitely not node save)  ?
UPDATE:

Drupal Version : 7.15
Modules: Apachesolr
Answer: I found the answer on exploring the apache solr module,
STEP 1
Select the nodes from the node table alone or by joining the apachesolr index entities table,
<code>// Check for unpublished content that wasn't deleted from the index.
  $table = apachesolr_get_indexer_table('node');

 // Select the nids from the node table
  $query = db_select($table, 'aien')
    ->fields('aien', array('entity_id'))
    ->condition('n.nid', 0);
  $query->leftJoin('node', 'n', 'n.nid = aien.entity_id');
  $nodes = $query->execute()->fetchAllAssoc('nid');
</code>
STEP 2
Chunk it to some limit and call the apachesolr_index_nodeapi_mass_delete function
<code>      $node_lists = array_chunk($nodes, '100', TRUE);
  foreach ($node_lists as $nodes) {
    watchdog('Apache Solr', 'On cron running apachesolr_nodeapi_mass_delete() on nids @nids', array('@nids' => implode(',', array_keys($nodes))), WATCHDOG_WARNING);
    if (!apachesolr_index_nodeapi_mass_delete($nodes, $table)) {
      // Solr query failed - so stop trying.
      break;
    }
  }
</code>


Trying to write custom handler to extend views_handler_field_term_node_tid

Question: Edit: solved, see first reply for answer.
I am trying to write my views filter handler to extend the views_handler_field_term_node_tid class. I believe I have done everything correctly but I'm having no luck. In my module I have implemented hook_views_api()
/**
* Implements hook_views_api().
*/
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', mymodule') . '/views',
  );
}

Called the handler.inc file and the mymodule.views.inc in the module .info file:
files[] = views/mymodule.views.inc
files[] = views/mymodule_handler_field_term_node_tid.inc

This is the contents of that file:
class mymodule_handler_field_term_node_tid extends views_handler_field_term_node_tid {

  function option_definition() {
    $options = parent::option_definition();
    $options['convert_spaces'] = array('default' => FALSE, 'bool' => TRUE);

    return $options;
  }

  /**
   * Option to replace spaces with hyphens.
   */
  function options_form(&$form, &$form_state) {

    parent::options_form($form, $form_state);

    $form['convert_spaces'] = array(
      '#title' => t('Convert spaces in term names to hyphens'),
      '#description' => t('This allows links to work with Views taxonomy term arguments.'),
      '#type' => 'checkbox',
      '#default_value' => !empty($this->options['convert_spaces']),
    );

  }

  function render_item($count, $item) {
    return $item['name'];
  }

}

And finally I have implemented hook_views_data_alter() in the mymodule.views.inc
/**
 * Implements hook_views_data_alter()
 */
function mymodule_views_data_alter(&$data) {
  $data['node']['term_node_tid'] = array(
    'title' => t('Taxonomy terms on node'),
    'help' => t('Relate nodes to taxonomy terms, specifying which vocabulary or vocabularies to use. This relationship will cause duplicated records if there are multiple terms.'),
    'relationship' => array(
      'handler' => 'views_handler_relationship_node_term_data',
      'label' => t('term'),
      'base' => 'taxonomy_term_data',
    ),
      'field' => array(
      'title' => t('All taxonomy terms'),
      'help' => t('Display all taxonomy terms associated with a node from specified vocabularies.'),
      'handler' => 'mymodule_handler_field_term_node_tid',
      'no group by' => TRUE,
    ),
  );

}

So the weird issue is that running dpm($data); in my mymodule_views_data_alter function before I alter the $data['node']['term_node_tid'] brings up no reference to that data at all. That is being originally defined in taxonomy.views.inc and should be existing in the $data array because I have added the Content: All taxonomy terms field to my test view. I've been pulling out my hair for the last couple hours trying to figure this out with no luck.
Answer: You must adjust your module's weight so that it runs after views. Use hook_module_implements_alter or Modules weight
And then you can also change your code in MYMODULE.views.inc to something simpler:
function MYMODULE_views_data_alter(&$data) {
  $data['node']['term_node_tid']['field']['handler'] = 'MYMODULE_handler_field_term_node_tid';
}

Comment: Thank you so much, you were dead on about the weight thing. I guess that makes sense seeing as my module is extending an existing field/handler instead of creating my own from the module. It would have to execute after views to modify code from views. It's always something simple :) Thanks a million!


How to go about creating an interactive map in Android

Question: I need a section of my application to have an interactive map of a square area that consists of about 10 buildings. You have to be able to click on a building and receive some information about it. I know there are a couple of ways to go about this, but I'm hoping someone with some background in this can give me some tips.
Here are some ways that I can think about accomplishing this.
Google Maps
I already implemented Google Maps API and it works quite well, but doesn't really have the effect I was looking for. Google Maps requires an internet connection and gives you access to the entire map. I need it to be locked into one area.
Webviews
This seems like a great alternative. I'm sure I can come up with a simple image map that will give you more information when you click a certain building. The only problem with this is that you also need an internet connection.
OpenGL?
I've never really looked into this too much, but I heard it is difficult and a pain to implement. It would be able to run locally, but is it worth it?
Are there any other way to go about developing an interactive map? Something to keep in mind is that I would also like to someday port this over to iOS (if anyone has any experience with that as well)
Comment: you don't need an internet connection to populate a WebView. You can save the html file in the /assets/ directory and load it at runtime.
Comment: Using cache on Google Maps is forbidden by the Android Maps APIs Terms of Service (see section 8.2). #justsayin
Comment: Interesting... post that as an answer, and I'll also take other answers, and compare which method is "better" and then award the bounty. Thanks for the insight.
Answer: If you want full control and are comfortable using html and javascript, I would highly recommend using the open source OpenLayers library. You can create an html page, save it in assets and run it locally on the device. You can create your own set of map tiles or even use one single jpeg file and then 'map' the buildings you want on it and then use the simple but extensive OpenLayers API to allow for building selection and information display. It even has multi-touch functionality built in for panning and zooming. Works great on and off mobile.
You can see a list of examples here. Doing a simple view source on any of the examples will give you a very clear idea of what they are doing. You can also take a look at this example which plots a bunch of image thumbnails on the map area from flicker with the ability to click for more details. This example uses an online feed, but you can easily use a local one.. even one passed in from the app to the webview.
ps. I have no affiliation to OpenLayers other than actively using it for my projects.
Comment: Ton of great answers. Best one to fit my needs. Thanks
Answer: It might take 10 pages to answer your question from the start.

Let's look here first: https://developers.google.com/maps/documentation/android/hello-mapview
After you are able to use MapView, you just need to create your ItemizedOverlay Class.

Replace this class with HelloItemizedOverlay in the Tutorial.
public class GooglerMapItemizedOverlay extends ItemizedOverlay {

    private ArrayList<OverlayItem> mOverlayItems = new ArrayList<OverlayItem>();
    private Context mContext;
    private Paint rectPaint, textPaint;

    public GooglerMapItemizedOverlay(Drawable defaultMarker, Context context) {
        super(boundCenterBottom(defaultMarker));

        mContext = context;
        populate();
    }

    @Override
    protected OverlayItem createItem(int i) {
        return mOverlayItems.get(i);
    }

    public void addOverlayItem(OverlayItem overlay) {
        mOverlayItems.add(overlay);
        populate();
    }

    @Override
    public int size() {
        return mOverlayItems.size();
    }

    public void clear(){
        mOverlayItems.clear();
        populate();
    }

    @Override
    protected boolean onTap(int index) {
        // information goes here
      OverlayItem item = mOverlayItems.get(index);
      AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
      dialog.setTitle(item.getTitle());
      dialog.setMessage(item.getSnippet());
      dialog.show();
      return true;
    }
}

Hope this helps.
Comment: Why it doesn't ? he asking the way to plot some 10 buildings an can make interaction.

Google map provide enough for you to plot the location, with your custom icon (yes, also your building icon) and can make interaction by use onTab that i include in my code.

If you understand enough, it can make the camera view to make 3D look like, with out even using openGL :]
Answer: Google Maps

Will have the effect you want (custom location, cannot move, cannot zoom in or out)
But does not allow offline content

Here is how to do it (I did it and it works):

You center on the GPS coordinates that you want to restrict the area
You adjust the zoom level to restrict the area
You disable multitouch events to prevent zoom in or out
You disable dragging to prevent moving around
You handles click on the ItimizedOverlays that you created to handle actions

There are good answers on StackOverflow for each one of these steps.

1&2: https://developers.google.com/maps/documentation/android/reference/com/google/android/maps/MapView
3: Android and GoogleMaps: disable the mapView dragging
4: https://developers.google.com/maps/documentation/android/hello-mapview
Answer: If you need to display always the same map, you could just display the map as background of layout (make the map image) and handle touch positions to show popups for certain building.
Or use webview like stated in the comment and handle touch x,y to map position of building.


Is there any canonical way to find out the Lie group corresponding to a manifold?

Question: Lie groups are manifolds. But it is well known that not all manifolds are Lie groups. E.g. There are no Lie groups that correspond to the 2-sphere. More generally, the fundamental group has to be a freely generated Abelian group/have connected homeomorphic components, etc. cf. this post.
Given a manifold with the above-mentioned properties, one could look up the Cartan classification of semi-simple Lie groups with already-known manifold structures and find the corresponding Lie group, but if he doesn't find his manifold listed he can't comment that it has no Lie group structure. That is because a particular Lie group may have multiple manifold realizations and one of the realizations may not be given in the classification table. E.g. $U(2)$ is diffeomorphic to $S^3 \times S^1$ but this does not constitute an isomorphism of groups although homotopy equivalence is there. So the "canonical" manifold realization available for the semi-simple Lie groups may not always be the manifold whose corresponding Lie group is to be found.
Is there any canonical/algorithmic way to construct a Lie group given a differentiable manifold that actually admits a Lie group structure?
EDIT: If all of this sounds ill-defined I would like the answerer to explain why/how this is so (because atleast intuitively it makes sense to me if not absolutely rigorously: I am not trained in math) and possibly modify my question to something which is well-defined (and interesting to you).
Comment: Why? Lie groups are manifolds. Some manifolds are also Lie groups. I just wanted to find a Lie group associated with a given manifold. How is this an ill-defined question?
Comment: So the answer is non-unique---okay, but I would be happy to get one out of those infinite choices from a manifold. Suppose I am handed a complicated-looking manifold $M$ and there *might* exist only a finite number of Lie groups that have $M$ as its group manifold. Even if there are infinite, I want to get hold of *only* one of them via this construction I seek. Is this not a well-defined question? (Essentially I am looking for something like the Gram-Schmidt procedure which also gives a highly non-unique orthonormal basis set)
Comment: @Sanjana I doubt such a procedure would exist. I think that [this is relevant](https://math.stackexchange.com/questions/3481290/can-every-manifold-be-turned-into-a-lie-group)
Comment: @MarianoSuárez-Álvarez: it would be good if you could give a pointer to more information about the existence of uncountably many Lie group structures on $\Bbb{R}^n$ for large $n$.
Comment: If $G, H$ are compact simply connected Lie groups are homeomorphic as manifolds, then they are isomorphic as Lie groups. Thus, at least in the simply connected case (no compactness is needed), there is a canonical Lie group structure. However, I would not call this natural in any sense.
Answer: Here is an answer of sorts. I will interpret the undefined term "canonical" in the question as "as commutative as possible." This will still leave some ambiguity, but let's try. It also leaves out of the "canonical" list some of the most naturally occurring groups, such as $SL(n, {\mathbb R})$, so my definition is far from natural in any sense.
Given a Lie group $G$, I will use the notation $G^{can}$ for a "canonical" Lie group diffeomorphic to $G$ as a smooth manifold.
First of all, I will limit myself to connected Lie groups, otherwise, if $G$ is a Lie group with, say, countably many connected components and the connected component of the identity $G_0$, then I will take as $G^{can}$ the direct product $G_0^{can}\times {\mathbb Z}$.  (I am leaving it to you to work out the case of disconnected Lie groups with finitely many components.)
Now, given a conected Lie group $G$, let $K< G$ be a maximal compact subgroup (it is unique up to conjugation). The Cartan's theorem and Levi-Malcev decomposition of $G$ yields a diffeomorphism $G\cong K\times {\mathbb R}^n$ for some $n$. The group $K$ (as a manifold) is uniquely determined up to homotopy equivalence by the topology of $G$. I will ignore this ambiguity for a  moment and set $G^{can}=K^{can}\times {\mathbb R}^n$ (as a Lie group), in line with making $G^{can}$ as commutative as possible. Here ${\mathbb R}^n$ is understood as the unique simply-connected abelian Lie group, the additive group of the vector space ${\mathbb R}^n$.
Now, the problem is reduced to the setting of compact Lie groups (up to the issue of homotopy-equivalence). We will be helped by a theorem of Toda:
Toda, Hirosi, A note on compact semi-simple Lie groups, Jap. J. Math., new. Ser. 2, 355-360 (1976). ZBL0355.22007.
Toda proves that if $K_1, K_2$ are simply-connected compact Lie groups which are homotopy-equivalent as topological spaces (actually, one just needs isomorphisms of homotopy groups in matching degrees), then $K_1$ is isomorphic to $K_2$ as a Lie group. Thus, among simply-connected compact groups, each homotopy equivalence class contains a unique group, which will be our canonical choice. This leaves out the case of non-simply connected compact Lie groups $K$. The universal cover $\tilde{K}$ splits (as a Lie group) as the direct product of simple compact factors, denoted $\tilde{K}^{ss}$ (the semisimple part of $\tilde{K}$) and some ${\mathbb R}^m$. If there are no compact factors, then $K^{can}$ is again clear: It is the product of $m$ copies of $S^1$ (the group $K$ is again determined by its homotopy type). In general, $K$ will have a finite covering group of the form $\tilde{K}^{ss}\times (S^1)^m$. This one is canonical.
Uniqueness for $K$ will fail, for instance, the semisimple compact groups groups $SO(4)$ and $SO(3)\times Sp(1)$  are not isomorphic but are diffeomorphic. (In this case, $\tilde{K}=\tilde{K}^{ss}= Spin(4)= Sp(1)\times Sp(1)$.) Which of these is more "canonical"? The second one, $SO(3)\times Sp(1)$, is more commutative so maybe you will like it better. In any case, you get finitely many options to choose from and I leave it to you to decide which one is more canonical.


Identificar Visitante e Usuário no Wordpress

Question: Estou trabalhando em um plugin wordpress, e necessito alterar o nome do menu Login para Minha conta quando o usuário estiver logado.
Também necessito de alterar o titulo da página. Já tentei usar o filtro abaixo, mas acaba alterando todos os links do site.
add_filter('the_title', 'function_name');
e quanto alterar o nome do menu, não encontrei nada a respeito, alguém tem alguma sugestão sobre algo?
Obrigado desde já...
O CÓDIGO
Tentando adicionar um shortcode para ser usado da forma citada acima!
if ( !function_exists('custom_login_form') )
{
    function custom_login_form()
    {
        $args=array(
            "echo" => false,
            "label_log_in" => "Entrar",
            "remember"  => true,
        );
        if ( !is_user_logged_in() ){
            return wp_login_form($args);
        }else{
            return 'Logado em Minha conta!
' . wp_loginout('index.php');
        }
    }
}
add_shortcode('login_form', 'custom_login_form');

Isto funciona perfeitamente, gostaria agora fazer as alterações no menu e no titulo da página!
RESOLUÇÃO
Depois de muitas pesquisas conseguir encontrar uma solução para o problema, que por coincidência eu já tinha tentado e não funcionou de jeito nenhum.
Usando o seguinte filtro.
add_filter('wp_nav_menu_items', 'function_name', 10, 2);
function func_name_wp_nav($items, $args){
    return $items;
}

Então você adicionando items de acordo o menu, que geralmente é LI ele adiciona como último elemento, exemplo.
$item .= "
Item 1
";

Isto funcionou perfeitamente pra mim! Qualquer dúvida com relação ao post, comentem e tentarei responder no que souber.
Obrigado...
Answer: Você deve estar procurando usar a função is_user_logged_in(), se o usuário estiver logado o valor de retorno é verdadeiro, caso contrário é falso.
if ( is_user_logged_in() ) {
    // Fazer algo quando esse usuário estiver logado
} else {
    // Fazer algo caso seja um visitante
}

Sobre a segunda pergunta, a função the_title deveria funcionar, entretanto se preferir usar algo mais clean, use the_title_attribute, ambas tem praticamente o mesmo objetivo, porem, essa última tem um parâmetro a mais que é $post que permite especificar o ID ou objeto de uma postagem, podendo obter ou alterar, por padrão a postagem atual é buscada.
Para alterar o nome do menu, aqui (Changing Admin Menu Labels - WordPress Development SE) têm uma solução que talvez funciona para você.
Comment: **@QMechanic73** A função `is_user_logged_in()` está correta, eu já estava tentando com ela, porém o que não consigo é fazer que altere o menu e o titulo da página corretamente, quando alterado o titulo da página, é alterado todos os outros links também. E quanto alterar o link na barra principal, não consegui e o link que passou é referente aos menus da administração. Obrigado!
Comment: @ItaloIzaac Vamos por partes =D. O título, tente fazer uma expressão condicional usando [`in_the_loop()`](http://codex.wordpress.org/Function_Reference/in_the_loop) para verificar se o contexto de `the_title`(*já que `the_title_attribute` parece não ser preciso aqui*) está dentro do loop.
Comment: **@QMechanic** Usando o `in_the_loop()` funcionou perfeitamente modificando o titulo da página sem modificar outros links da mesma. Agora a segunda parte é "MACABRA", rsrs, obrigado desde já...
Comment: A mesma ideia passada pelo post é a mesma logica para essa aqui, porém a solução apresentada não funciona e aparentemente está incorreta.


how to run xcode 5 project on iphone 5 with ios 7.0.2

Question: Can any one tell me how can I rum my xcode project on real iphone 5 with ios 7 installed without developers account
Comment: Sure. Jailbreak the phone, install AppSync (or whatever it is called nowadays), and patch Xcode in order it not to require the developer cert for code signing.
Comment: To do so you nee to create provisioning profile.  Follow the [link to create provisioning profile][1]

  [1]: http://stackoverflow.com/questions/19293185/install-iphone-application-in-my-device/19293531#19293531
Comment: possible duplicate of [How can I deploy an iPhone application from Xcode to a real iPhone device?](http://stackoverflow.com/questions/246422/how-can-i-deploy-an-iphone-application-from-xcode-to-a-real-iphone-device)
Answer: There is no possible way of doing what you want to do without an Apple Developer Account and a registration of the iOS Developer Program.

Make an Apple Developer Account.
Sign up for iOS Developer Programme.
Create a Provisioning Profile for your device.
Run your
app on the device.

That is if you are attempting to run your app in a regular device.
I believe there are ways to achieve this if your device is jailbroken, however I advise you to refrain from doing so.


SQLite suddenly considers everything as not an error

Question: It started on an Android phone, simple create statement in a file inside the assets/migrations folder (I use a 3rd party library called ActiveAndroid and for 2 years it worked okay - I did not changed anything about that):
CREATE TABLE IF NOT EXISTS Car (Brand TEXT);

I get this exception:
04-07 15:31:36.683  15738-15738/? E/SQLiteLog﹕ (21) API called with NULL prepared statement
04-07 15:31:36.683  15738-15738/? E/SQLiteLog﹕ (21) misuse at line 63243 of [00bb9c9ce4]
java.lang.RuntimeException: Unable to create application com.activeandroid.app.Application: android.database.sqlite.SQLiteException: not an error (code 0)

at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4394)
            at android.app.ActivityThread.access$1300(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1294)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.database.sqlite.SQLiteException: not an error (code 0)
            at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method)
            at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:727)
            at android.database.sqlite.SQLiteSession.executeForChangedRowCount(SQLiteSession.java:754)
            at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:64)
            at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1665)
            at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1594)
            at com.activeandroid.DatabaseHelper.executeSqlScript(DatabaseHelper.java:185)
            at com.activeandroid.DatabaseHelper.executeMigrations(DatabaseHelper.java:155)
            at com.activeandroid.DatabaseHelper.onUpgrade(DatabaseHelper.java:78)
            at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:257)
            at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
            at com.activeandroid.Cache.openDatabase(Cache.java:104)
            at com.activeandroid.Cache.initialize(Cache.java:77)
            at com.activeandroid.ActiveAndroid.initialize(ActiveAndroid.java:43)
            at com.activeandroid.ActiveAndroid.initialize(ActiveAndroid.java:30)
            at com.activeandroid.app.Application.onCreate(Application.java:25)
            at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1000)
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4391)
            at android.app.ActivityThread.access$1300(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1294)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            at java.lang.reflect.Method.invokeNative(Native Method)

So I checked it on my computer with a Firefox addon called SQLite Manager and created a brand new file (the file is totally unrelated to the Android database).
I used this select and on the last error I get this:

It seems that every SQLite statement is a not an error statement.
Unfortunately, Android can't handle that.
What should I do?
Comment: `API called with NULL prepared statement` Can you show how do you query your table?
Comment: I use a 3rd party library, ActiveAndroid (and it works for 2 years now). Which method should I search for?
Comment: The one to which you are passing the null prepared statement. Typically a query.
Comment: @DerGolem I do not use queries, that's the point of ORMs. I simply use the `save` method of the model object and it is saved via ActiveAndroid. As I said, it's been working for 2 years and nothing is changed in it. The curious thing is that the Firefox addon _also shows not an error_. Why? Is it common?
Comment: This is why I hate 3rd party librares.
Comment: This 3rd party library has been working for 2 years without a problem and nothing has been changed in it (because it works). Can you explain why does the FF addon also show _not an error_ message?
Comment: No. I can't. I don't know the db structure. Maybe the db is cotrrupt. Maybe it lacks the master table, ....
Answer: It seems that the upgrade script in the assets\migration folder had some empty lines and that caused the not an error.
Comment: Ah, it was driving me insane. The same is valid for Sugar ORM. Much thanks!
Comment: @dVaffection Glad it could help :)
Comment: Thank you for answering this. It could really be a hard to find problem which your answer solved in 30s
Comment: @BugsHappen Glad that the answer was helpful :)
Comment: FYI, you can use the much improved SQL Parser that permits empty lines, comments and all sorts of stuff. As per: https://github.com/pardom/ActiveAndroid/pull/215#issuecomment-58227643
Comment: I ran into this issue because my sql file contained comments! I was following along this [tutorial](https://github.com/jgilfelt/android-sqlite-asset-helper) for upgrading a database with the sqliteassethelper utility.


Prove that not all elements of this recurrent sequence are primes

Question: This  question  is a part of my assignment on elementary number theory and I am unable to solve it.

Let a, b and $x_0$ be positive integers and $x_n = ax_{n-1} +b $ for n=1, 2,...,... Prove that not all $x_n$ can be primes.

I tried by assuming that let all $x_n$ be primes. Then I can put $x_i$'s recursively to get a, b, $x_0$ but I am not able to find any contradiction based on that.
Can you please help?
Answer: If $x_0$ is not prime, then there is nothing to prove.
If $a=1$, then $x_n=x_0 + n b$ and so is a multiple of $x_0$ for $n=x_0$.
If $a\ne1$, then
$$
x_n = x_0 a^n + b\frac{a^n-1}{a-1}
$$
and so $|x_n| \to \infty$ and $n \to \infty$.
If $x_n$ is always prime, then there is an $n$ such that $p=x_n$ does not divide $a$ or $a-1$. We can assume that $n=0$ by ignoring the previous terms. Then $a-1$ is invertible mod $p$. Moreover, if $m$ is a multiple of $p-1$, then $p$ divides $a^m-1$ and and so $p$ divides $x_m$, a contradiction.
Comment: @BarryCipra, don't delete your answer. Different people need different arguments. Or different renderings of the same idea.
Comment: I have half a mind to delete my own answer now, since it's essentially the same as yours but not nearly as clearly presented.
Answer: In order for all the $x_n$'s to be prime, we must have $\gcd(a,b)=1$, in which case $\gcd(a,x_n)=1$ for all $n\ge1$. Now consider the sequence $x_1\to x_2\to x_3\to\cdots$ mod $x_1$. We get
$$0\to b\to(a+1)b\to(a^2+a+1)b\to\cdots\to(a^k+a^{k-1}+\cdots+a+1)b\to\cdots$$
To be precise, $x_n\equiv(a^{n-2}+a^{n-3}+\cdots+a+1)b$ mod $x_1$ for $n\ge2$. But it's easy to show, using Fermat's little theorem, that $a^k+a^{k-1}+\cdots+a+1\equiv0$ mod $x_1$ for some $k$: If $a\equiv1$ mod $x_1$ the sum is clearly $0$ mod $x_1$ for $k=x_1-1$, while otherwise we have
$$a^k+a^{k-1}+\cdots+a+1={a^{k+1}-1\over a-1}$$
for which the numerator is $0$ mod $x_1$ for $k=x_1-2$. To be precise again, we find that if $x_1$ is prime, then it divides $x_n$ for $n=x_1+1$ if $a\equiv1$ mod $x_1$ and $n=x_1$ if $a\not\equiv1$ mod $x_1$. And since we clearly have $x_1\lt x_2\lt x_3\lt\cdots$ since $a$, $b$ and $x_0$ are all positive integers, that $x_n$ cannot be prime.
Answer: First I'll make a change of variables, and say that $n=k+1$, this way you have $x_{k+1}=ax_k + b$. Now consider what happens when you apply the expression M-times, for example, if you apply it twice you get:
$$x_{k+2}=ax_{k+1}+b = a(ax_k + b) + b = a^2x_k + b(a+1)$$
$$x_{k+2}=a^2x_k + b(a+1)$$
And you if apply it three times you get:
$$x_{k+3}=a^3x_k + b(a^2+a+1)$$
Then you can generalize, and prove by induction, that if you use the expression to get the (k+M)-th number in terms of the k-th the result is:
$$x_{k+M}=a^Mx_k + b\sum_{i=0}^{M-1}{a^i}$$
Since the summation term is a geometric progression, you can substitute the closed formula for it:
$$\sum_{i=0}^{M-1}{a^i} = \frac{a^{M-1}-1}{a-1}$$
Which result in:
$$x_{k+M}=a^Mx_k + b(\frac{a^{M-1}-1}{a-1})$$
You can multiply the term $b(\frac{a^{M-1}-1}{a-1})$ by $\frac{a}{a}$.
$$x_{k+M}=a^Mx_k + b(\frac{a^{M}-a}{a(a-1)})$$
Fermat's little theorem states that if $p$ is a prime number and $a$ is an integer, than $a^p-a$ is an integer multiple of $p$. In the expression we found for $x_{k+M}$ we'll say that $M=x_k$, which will happen at some point in the sequence.
$$x_{k+M}=a^{x_k}x_k + b(\frac{a^{x_k}-a}{a(a-1)})$$
Since we have a $a^{x_k}-a$ and $x_k$ is prime, we can say that $a^{x_k}-a=Cx_k$ where $C$ a an integer.
$$x_{k+M}=a^{x_k}x_k + b(\frac{Cx_k}{a(a-1)})$$
Now we have a couple of possibilities. Since $b(\frac{Cx_k}{a(a-1)})$ has to be an integer, as it's just a sum of integers and $x_k$ is prime, then:

$C$, or $b$ is a multiple of $a$, $a-1$ or both.
$x_k$ is exactly equal to $a$ or $a-1$
If the second option is true, than we can just choose a different $x_k$ from the sequence, since it is all prime. Then choosing a $x_k$ that is not $a$ or $a-1$ (which can always be done) we have:

$$x_{k+M}=x_k[a^{x_k} + b(\frac{C}{a(a-1)})]$$
That would mean that $x_{k+M}$ is a multiple of $x_k$ which is a contradiction.


Handling uploaded resources for local development

Question: With our Drupal site we develop locally, commit to svn and deploy to the live site. Some content gets uploaded on the live site (some images, videos etc). I am trying to sort out the best way to handle those uploaded resources.
Currently, we do daily database dumps, and use those for local development, but if someone has edited a page and added an image, it will 404 on the local since the image doesn't exist.
I rsync content down, but not all the team has ssh access (security). Should I tar up the uploaded assets at the same time as the database dumps? Or, is there a better way to handle this?
Basically; Whats the best way of getting uploaded content, for local development?
Comment: http://drupal.org/project/stage_file_proxy
Answer: Yes your database and files need to be kept in sync to avoid 404s as you describe.
With our setup all developers have access to a backed up copy of the database and files. The backups of both database and files are synchronised so together they're essentially a snapshot of the production site. I personally use a collection of Drush commands wrapped up in a shell script in order to restore this snapshot to my local machine.


Como construir um Layout Complex no JSF2?

Question: Preciso aplicar um tipo de Layout no meu sistema de maneira que fique o mais parecido com sistema de desktop, então procurei uns modelo de layout no site do PrimeFaces no site abaixo;
http://www.primefaces.org/showcase/ui/panel/layout/element.xhtml
E como vocês podem ver existem vários modelo de layout, porém o único que significativamente explica como fazer é o FULL, como mostra abaixo;
http://www.primefaces.org/showcase/ui/panel/layout/full.xhtml
Porém existe um em especifico que me chamou a atenção que é o layout   " Complex ", quando eu clico é direcionado para está pagina;
http://www.primefaces.org/showcase/ui/panel/layout/complex.xhtml
Mas essa pagina não mostra como criar o layout, como faço para saber como construir esse layout?
Answer:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <f:view contentType="text/html">

    <h:head>
        <h:outputStylesheet name="main/css/showcase.css" />
        <h:outputStylesheet name="main/css/sh.css" />

        </h:head>

        <h:body>

                    Bottom Content

                            <h:outputText value="Menu 2 Content" />

                            <h:outputText value="Menu 3 Content" />

                        <h:outputLink value="#{request.contextPath}/resources/demo/images/nature/nature1.jpg" title="Nature 1" style="margin-bottom:5px;">

                        </h:outputLink>

                        <h:outputLink value="#{request.contextPath}/resources/demo/images/nature/nature2.jpg" title="Nature 2" style="margin-bottom:2px;">

                        </h:outputLink>

                        <h:outputLink value="#{request.contextPath}/resources/demo/images/nature/nature3.jpg" title="Nature 3" style="margin-bottom:2px;">

                        </h:outputLink>

                        <h:outputLink value="#{request.contextPath}/resources/demo/images/nature/nature4.jpg" title="Nature 4" style="margin-bottom:2px;">

                        </h:outputLink>

                <h:outputText value="Resistance to PrimeFaces is futile!" />

        </h:body>

    </f:view>

Segue o link com o código do layout complex, aqui.


Views: Access CCK image delta for each image link

Question: I have a view that for each row, outputs the first 3 images of a CCK image field.
I would like to be able to Output a different link for each image in the format node/[nid]?image=[delta]
I don't mind writing a token for this purpose, although I'm not sure how I'd access the delta number in the first place, other that some convoluted loop that just increments and resets a static variable, and even then, would that even work or is there some sort of token caching that would break even that approach?
Answer: Depending on the views version you use, you have different options to render a multiple values field and the fields themselves.
The easiest thing in this case would be to create a special field formatter for the images. Field formatters are almost exactly same for both Drupal 6 and 7 and is what you could call a theme function for fields. In that theme function you would be able to handle the different deltas, as you will have that variable accessible.

This  post explains a bit about field formatters.
This post explains how to create a field formatter (D6).
Comment: Awesome worked very nicely, although I found the following link a little more helpful, simply because it was written with more of an example to go with it, but thank you very much for lighting the way :)

http://manueg.okkernoot.net/blog/200907/how-create-cck-formatter


We cannot write this function

Question: I'm a new user so if my question is inappropriate, please comment (or edit maybe).
If we accept axiom of choice, we can find a choice function for $\mathbb{R} / \mathbb{Q} $ , this is obvious. But we cannot find such a function "with hand and I think we should prove we cannot. My question is how can we prove such a thing or how can we define "writing with hand"? This question might be generalized but because I'm not so sure about it, I will stuck in that example.
I think my work for this question is unnecessary but I think I should share some of it.
First of all:
$ZFC$ $\Rightarrow$ Every $\alpha \in \mathbb{R} / \mathbb{Q} = \{ r + \mathbb{Q}: r \in \mathbb{R} \} $ there exists a set $X \subset \mathbb{R}$ such that $|\alpha \cap X| = 1 $
I tried to approach to question in such a manner but then I believed that proof or explanation must be in meta-mathematics. We can approach this by assuming that we can find such a function in $ZF\neg C$ and prove that we are pope. But I'm not satisfied with this strategy.
Most satisfiable and probable strategy that I thought is trying to show that if we want to write this function with hand (and not with technology like axiom of choice) we should use infinitely many characters.
Thanks for any help and please bear in mind that I cannot understand high-level explanations.
Comment: @tomasz: Proving you are not the pope usually requires an appeal to some large cardinals! ;-)
Comment: Just a language quibble: Axiom of choice doesn't let us "find" a function, it lets us assert the existence of a function. Knowing my car keys exist don't help me find them. :)
Comment: Proving that we are pope does not yield a contradiction until it's established that we are not, in fact, pope.
Comment: @AsafKaragila: That's no good; cardinals have a reputation of having asserted some rather dubious statements, so there's a high risk of a contradiction. ;)
Answer: When we have a statement "There is some object with property $\varphi$". Often we can prove this statement using the axiom of choice. When we say that "we cannot write a definition of such object by hand" we often mean that we cannot prove the existence of this object without some appeal to the axiom of choice. Yes, this is quite informal and ill-defined, but so are "by hand" and "explicitly".
There are two common methods to showing something like that:

The reduction to another problem. We prove that given such object, we can generate another object, which we may assume doesn't exist without some choice. For example, a non-measurable set. Another example is a linear ordering of $\Bbb{R/Q}$.
The problem with this approach is that it relies on previous knowledge, and the more extensive your knowledge of choice principles is, the easier or harder it can get.
Exhibit a model. We know from the completeness theorem that $\sf ZF$ can prove a statement if and only if it is true in all its models. We already know that in models of $\sf ZFC$ the statement is true, so now we need to check and see what happens in models where the axiom of choice fails. What you have to do here is to construct a model of $\sf ZF$ where our statement fails. Of course this implies that the axiom of choice must fail in the model as well (or else $\sf ZF$ was inconsistent to begin with).
Note that the failure of the axiom of choice is not necessarily equivalent to the failure of our statement. It is a byproduct of its failure. Since the statement is a consequence of the axiom of choice, the failure of choice is a consequence of the failure of our statement.
This method is difficult. It often employs advanced set theoretical methods such as forcing. It is, however, important to understand why this method works at all.

In the case of the statement "there exists a choice function from $\Bbb{R/Q}$" we can either rely on the construction of Solovay, or others, which proved that there are models in which the Lebesgue measure has properties which are incompatible with such choice function.
Or you can try and construct a model yourself.

Also related:

How do we know we need the axiom of choice for some theorem?
Comment: Can you elaborate on the last step?  Why does the failure of AC imply that $\phi$ is false?
Comment: You mean you look for a model where this particular $\phi$ is exactly equivalent to the axiom of choice?
Comment: I revised my answer completely. I hope this helps.
Comment: Thanks, I especially liked second method. For your third sentence's completeness should we also observe or prove that axiom of choice cannot give us a rule of function?
Comment: @KonformistLiberal: I'm not sure what do you mean by that.
Answer: One can show that such a function cannot be found not only in ZF but even in ZF+(countable choice), as follows.
For simplicity let's discuss a closely related problem where the space is not $\mathbb{R}$ but rather the circle $\mathbb{R}/\mathbb{Z}$. One approach that immediately comes to mind is to use the results of the following paper:
Solovay, R. A model of set-theory in which every set of reals is Lebesgue measurable. Annals of Mathematics (2) 92 (1970), 1--56.
If you had a way of specifying such a set $X$ without uncountable choice, in Solovay's model it would be measurable and one would then get a contradiction by considering two cases: (a) if the measure of $X$ is zero then one would use countable additivity of Lebesgue measure (which follows from countable dependent choice) to show that the measure of the circle is zero; (b) if the measure of $X$ is nonzero then the measure of the circle would be infinite.  In either case one gets a contradiction, allowing one to conclude that such a set does not exist.
Comment: You can't prove the Lebesgue measure countably additive without using the axiom of choice (a small fragment of it, anyway).
Comment: Of course there are ways. :-)
Comment: I think using subadditivity one can finish the argument.
Comment: I'm not 100% sure that it's countably-subadditive either. Think of the case where $\Bbb R$ is the countable union of countable sets.
Comment: Good point.  That particular example can be circumvented by requiring countable AC.  This may be enough to prove countable subadditivity as well.
Comment: Countable choice suffices to prove a lot more. It's still not enough to conclude a proof from $\sf ZF$ (or lack thereof).
Comment: If we can't find such a function in ZF+(countable choice), we certainly can't find it in ZF alone, either.  So if countable choice is enough to prove subadditivity of Lebesgue measure, this completes the argument.
Answer: A possible notion in set theory that may correspond to your "writing by hand" is that of ordinal definable sets. But then, the existence of ordinal definable choice function of $\mathbb{R} / \mathbb{Q} $ is independent over $ZFC$. For an elementary exposition to this notion start with Levy's "Basic set theory" and then maybe look at Jech, Kanamori or even better original papers of Solovay and Shelah.
Here are the references:
Solovay, Robert M. (1970), "A model of set-theory in which every set of reals is Lebesgue measurable", Annals of Mathematics. Second Series 92: 1–56
Shelah, Saharon (1984), "Can you take Solovay's inaccessible away?", Israel Journal of Mathematics 48 (1): 1–47
Comment: When someone writes "please bear in mind that I cannot understand high-level explanations", sending them to a paper by Shelah is just wrong. Solovay's paper is not difficult, but requires quite a lot of set theoretical background in order to understand properly.
Comment: I was not trying to explain anything but merely quoting some work that seemed relevant to the question.
Comment: Pointing to Shelah is the same as saying "papers in the fields of set theory, logic or model theory". He has over 1000 papers, and they still pile up. Solovay wasn't a one-hit wonder either. Referring someone to original papers should be precise, and especially when that person has written so much about so many different topics. Moreover, Shelah often "hides" results that he's not proud of in seemingly unrelated papers (e.g. the recent $\frak p=t$ proof is a corollary in a model theoretic paper).
Comment: I added detailed references.
Comment: Good. I should also add that Shelah's paper is quite difficult (technically, not just to read).

We cannot write this function


Como fazer um formulário que aceite upload de foto e salve no banco de dados

Question: Criei um banco de dados chamado Form e tabela com as seguintes informações
contatos (id int A.I, nome varchar(30), idade int(2), foto(blob)

Fiz aquele formulário padrão:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JS Bin</title>

   <form name="CadastroAlunos" type="text" method="post" enctype="multipart/form-data" action="upload.php">

  Nome: <input type="text" name="NomeAluno">

  Idade: <input type="text" name="IdadeAluno">

  Foto: <input type="file" name="image" />

    <input type="submit" value="Enviar" name="envia" />
  </form>

UPLOAD.PHP
<?php
     include_once 'conexao.php';

     $nome = $_POST['NomeAluno'];

     $idade = $_POST['IdadeAluno'];

     $foto = $_FILES['image'];

     move_uploaded_file ( string $foto , string $novoDestino );

     $sql = "INSERT INTO contatos (nome, idade, foto) values ('$nome', '$idade', $novoDestino");
?>

Como faço para gravar a foto junto com as de mais informações do formulário?
Comment: Eu recomendo que salve a imagem em uma pasta e em seu banco você grave o caminho para o arquivo, salvar o proprio arquivo no banco de dados não é uma das melhores praticas pois o seu banco pode ficar sobrecarregado e começar a apresentar lentidão.
Comment: Use `$_FILES` para manipular o arquivo, `$_POST` para informações do form e [move_uploaded_file](http://php.net/manual/en/function.move-uploaded-file.php) para transferiro o arquivo para o servidor.
Comment: Relacionado: [É errado gravar byte de imagens no banco de dados?](http://pt.stackoverflow.com/q/12687/91)
Comment: Entendi o que disse, só que estou com problema para implementar. Havia visto alguns códigos antes, só que a pessoa fazia upload da foto para uma pasta no computador. Quero que vá pro banco de dados. Vou editar minha pergunta e adicionar o php que fiz. Se puder dar uma olhada
Comment: Você precisa pegar o conteúdo do arquivo com [file_get_contents](http://php.net/manual/en/function.file-get-contents.php) isso retornara uma 'string' ai basta gravar no banco. Pode fazer um teste e imprimir o retorno de `file_get_contents()`.
Comment: @rray irei ver isso agora mesmo.
Comment: @RafaelAcioly então, quanto a isso nem preciso me preocupar tanto, porque esse projeto é acadêmico, irei fazer upload de algumas imagens só. Mas obrigado pela dica.
Answer: Utilize o tipo BLOB para a coluna foto que receberá o conteúdo do input type="file".
Seu código PHP para inserção no banco ficaria mais ou menos assim:
<?php
include_once 'conexao.php';

$nome = $_POST['NomeAluno'];
$idade = $_POST['IdadeAluno'];

$imagem = $_FILES['image']['tmp_name'];
$tamanho = $_FILES['image']['size'];
//$tipo = $_FILES['image']['type'];
//$nomeImagem = $_FILES['image']['name'];

if ( $imagem != "none" ) {
    $fp = fopen($imagem, "rb");
    $conteudo = fread($fp, $tamanho);
    $conteudo = addslashes($conteudo);
    fclose($fp);

    $sql = "INSERT INTO contatos (nome, idade, foto) values ('$nome', '$idade', '$conteudo')";

    mysqli_query($conexao, $sql) or die("Algo deu errado ao inserir o registro. Tente novamente.");

    echo 'Registro inserido com sucesso!';

    //header('Location: index.php');

    if(mysqli_affected_rows($conexao) > 0)
        print "A imagem foi salva na base de dados.";
    else
        print "Não foi possível salvar a imagem na base de dados.";

} else
    print "Não foi possível carregar a imagem.";
?>

Comment: Tentei implementar desta forma que enviou mas da erro nesta parte : `Parse error: syntax error, unexpected ''.png'' (T_CONSTANT_ENCAPSED_STRING) in C:\wamp\www\up\upload.php on line 11`. Porque será deste erro?
Comment: fiz uma edição no código, eu havia trocado o comando `$nomeFinal= time()'.jpg';` de posição. Verifique se o problema persiste, caso ainda ocorra tente fazer o upload de uma imagem .jpg.
Comment: Alterei e tentei fazer o upload de uma imagem .jpg mas o erro persiste nesta linha ainda `Parse error: syntax error, unexpected ''.jpg'' (T_CONSTANT_ENCAPSED_STRING) in C:\wamp\www\up\upload.php on line 9`
Comment: novamente alterado, o erro era na mesma  linha. Faltou um '.'
Comment: Agora passou dessa parte e parou em uma que parece ser mais complexa: `Warning: fopen(1443794568.jpg): failed to open stream: No such file or directory in C:\wamp\www\up\upload.php on line 15` e também

 `Warning: fread() expects parameter 1 to be resource, boolean given in C:\wamp\www\up\upload.php on line 15`
Comment: tentei outra abordagem, editei novamente a resposta.
Comment: Há um exemplo mais completo na documentação do PHP: http://php.net/manual/pt_BR/features.file-upload.php
Comment: Fiz pequenas edições no que me enviou agora e deu certo. Agradeço a paciência. Muito obrigado! :D @feresjorge
Comment: Edite a publicação com o código funcionando, pode servir para outra pessoa. Peço desculpas por não ter testado o código antes, não foi possível.
Answer: Acho mais recomendável salvar o caminho da imagem no banco, eu faria dessa forma:
<?php
include_once 'conexao.php';

$nome = $_POST['NomeAluno'];

$idade = $_POST['IdadeAluno'];

$foto = $_FILES['image']['tmp_name'];

$tamanho_permitido = 1024000; //1 MB
$pasta = 'uploads';

if (!empty($foto)){
    $file = getimagesize($foto);

    //TESTA O TAMANHO DO ARQUIVO
    if($_FILES['image']['size'] > $tamanho_permitido){
        echo "erro - arquivo muito grande";
        exit();
    }

    //TESTA A EXTENSÃO DO ARQUIVO
    if(!preg_match('/^image\/(?:gif|jpg|jpeg|png)$/i', $file['mime'])){
        echo "erro - extensão não permitida";
        exit();
    }

    //CAPTURA A EXTENSÃO DO ARQUIVO
    $extensao = str_ireplace("/", "", strchr($file['mime'], "/"));

    //MONTA O CAMINHO DO NOVO DESTINO
    $novoDestino = "{$pasta}/foto_arquivo_".uniqid('', true) . '.' . $extensao;
    move_uploaded_file ($foto , $novoDestino );

}

$sql = "INSERT INTO contatos (nome, idade, foto) values ('$nome', '$idade', $novoDestino";

echo $sql;
?>


Determine the composition of the functions $f(x)=4x+3$ and $g(x)=-5x^2+1$

Question: Answer:
\begin{align*}
(f \circ g)(x) & = f(g(x))\\
               & = 4(-5x^2+1)+3\\
               & = -20x^2+8+3\\
               & = -20x^2+11
\end{align*}
\begin{align*}
(g \circ f)(x) & = g(f(x))\\
               & = -5(4x+3)^2+1\\
               & = -5[(4x+3)(4x+3)]+1\\
               & = -5(16x^2+24x+9)+1\\
               & = -80x^2-19x-45+1\\
               & = -80x^2-19x-44
\end{align*}
Is my working out and answer correct?
Answer: You have the right idea, except your algebra is off. For the first one
$$4(-5x^2+1)+3=-20x^2+4+3$$
$$=-20x^2+7$$
For the second one:
$$-5(16x^2+24x+9)+1=-80x^2-120x-45+1$$
$$=-80x^2-120x-44$$


Need visualization advice for learning partial derivatives and calculus with more than one variable.

Question: Okay so I just recently started learning calculus with more than one variable and whilst I'm coming to grips with many of the ideas and stuff I'm finding it difficult to visualize certain things for example, what does a directional derivative look like in 3D and stuff like this.
Is there a good site or something where I can get a visualization to try and help cement my understanding?
Thank you.
Comment: Read Paul's notes here:
http://tutorial.math.lamar.edu/Classes/CalcIII/CalcIII.aspx

They really are the best for a beginner.
Comment: A directional derivative tells you how much the function changes in a particular direction. What more intuition do you want?
Comment: @Shaun Hello;  I have included a screenshot of Sagemath, and I could recommend a book; by  George F. Simmons,  (2nd Edition) "Calculus with Analytic Geometry" It have been invaluable for me at least; good luck!
Answer: The Math Insight website at http://mathinsight.org/ is replete with diagrams and visualizations of concepts from multivariable and vector calculus.
For the directional derivative, see: http://mathinsight.org/directional_derivative_gradient_introduction.
Answer: In 3D you have the graph of a function of two variables $(x,y,z)=(x,y,f(x,y))$. Fix a point $(x_0,y_0)$ in your domain. For the sake of concreteness, suppose $(x_0, y_0)=(2,3)$ and $f(x,y)=e^{xy}$. Imagine slicing the graph by the plane $x=2$, that is, all points of the form $(x,y,z)=(2,y,z)$, where $y,z$ range through all real numbers. This plane is parallel to the $yz$-plane. Now focus your attention on the part of the graph that is in this plane $(x,y,z)=(2,y,z)$. That is, consider the points $(x,y,z)=(2,y,f(2,y))=(2,y,e^{2y})$ for all real numbers $y$. This is a curve, call it $C_1$, in the plane $x=2$  that, in particular, contains the point $(2,3,e^{6})$.
Since $x$ is constant on $C_1$, we can temporally ignore this component. We are then looking at the graph of a function of one variable, say $z=g(y)=e^{2y}$. We know that its derivative $g'(y)=2e^{2y}$ and that, in particular, $g'(3)=2e^{6}.$ This value represents the slope of the tangent line to the curve $z=g(y)=e^{2y}$ at the point $(y,z)=(3,g(3))=(3,e^{6}).$ For $y$ close to $3$, $g(y)$ is close to $g(3)+g'(3)(y-3)=e^6+2e^6(y-3).$ In 3D, this value represents the slope of the tangent line to the curve $(x,y,z)=(2,y,f(2,y))=(2,y,e^{2y})$ at the point $(x,y,z)=(2,3,f(2,3))=(2,3,e^{6})$.
Let's go back to considering all of the graph of $z=f(x,y)=e^{xy}$. If we stand on the surface formed by the graph and move in just the y direction from the given point, $(2,3,e^6)$, we are remaining in the $x=2$ plane and following the curve $C_1$ discussed above. It follows that our altitude (the $z=f(x,y)$ value) changes almost in accordance with the rule
$$g(3)+g'(3)(y-3)=e^6+2e^6(y-3)=f(2,3)+2e^6(y-3)$$ when $y$ is close to $3$.
This is the meaning of the directional derivative when the direction is the direction of the positive $y$ axis. Of course, you know it as the partial derivative of $f$ with respect to $y$. However, there is nothing in our reasoning above that prevents us from doing the same for any other direction. Suppose, for example, that we want the directional derivative in the direction pointing away from the origin of the xy plane at an angle of $\theta$ radians from the positive $x$ axis. Now note that in polar coordinates a vector of length $|t|$ with direction specified by $\theta$ is given by
$$\begin{align}
(x,y)&=t (\cos\theta,\sin\theta)
=t\left(\cos\theta,\left(\frac{\cos\theta}{\cos\theta}\right)\sin\theta\right)=
t (\cos\theta,\cos\theta \tan\theta)\\
&=(t, t \tan\theta).
\end{align}
$$ Let's consider again the example $f(x,y)=e^{xy}$ with $(x_0,y_0)=(2,3)$, and $\theta=\pi/4$. The line in the xy plane with our specified direction and through the point $(2,3)$ is given by $(2,3)+(t, t \tan\pi/4)=(2+t, 3+t)$. This time we slice the graph of $f$ by the plane
$(x(t), y(t), z(t))=(2+t, 3+t, z)$. The part of the graph of $f$ that is in this plane is the curve $C_2$ given by $(x(t), y(t), z(t))=(2+t, 3+t, f(2+t,3+t))=(2+t, 3+t, e^{(2+t)(3+t)}).$ When $t=0$, we are at the point on the graph $(2,3, e^6)$. If we vary $t$ we trace the curve $C_2$. If $t$ is close to zero, then $f(2+t,3+t,e^{(2+t)(3+t)})=z(t)$ is close to $e^6+\frac{dz}{dt}t$, where $\frac{dz}{dt}$ is the directional derivative. It is the rate at which $f$ changes as we move from $(2,3)$ along the line $x+2=y+3$.
The basic idea is that, given a function of two variables and a point in its domain, we can turn it into a function of one variable by ignoring all but one of its directions through that point. It seems that people like to teach the directional derivative as a generalisation of partial derivatives. I prefer to think the other way: partial derivatives are just special cases of the directional derivative. If we know how to differentiate functions of one variable, we can apply the same procedures to take partial derivatives. This ease of calculation makes them seem more intuitive than the general directional derivative but in fact  one must understand the directional derivative in order to understand partial derivatives.