text:
Q: Passing a function to edit state from class component to function based component through props not working I have a react frontend and most of my components are Class Based components, but it just so happens that one of the Components inside these class components has to be a functional component, so I currently have a functional component with a class based component.
Inside the functional component, I have a button that triggers a fetch call. After this fetch call is complete, I want the state of the class based (parent) component to update.
My approach was to make a function in the class based component (called setSubscriptoin) that adjusts the state of the class based component, then pass that function down to the functional component through props and call the function with a .then promise after the fetch call.
However, It appears that when I pass down the function through props, the functional component is not even able to detect the function and I get this error:
Uncaught (in promise) TypeError: e.setSubscription is not a function.
Here is the important code:
The class based component:
class OuterComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {subscription: {}}
    }

    setSubscription(subscription) {
        this.setState({subscription: subscription})
    }

    render() {
        return(
            <Elements>
                <FunctionComponent setSubscription={this.setSubscription.bind(this)}></FunctionComponent>
            </Elements>
        )
    }
}

I wanted to include the elements part because I'm not sure if that could be effecting it. The FunctionComponent is wrapped inside a Stripe Elements provider. Not sure why that would do anything but I figured I should include it just in case.
The functional component:
const FunctionComponent = (props) => {
    const fetchSomething = () => {
        fetch('fetch is made here and is successful')
        .then(response => {
            if (some_condition) {
                props.setSubscription({value1: 1, value2: 2}))
            }
        }
    }
}

The problem is that the function component doesn't even recognize props.setSubscription as a function (as the error says).
I've tried console logging the props variable, and it does in fact have the function setSubscription in it so I have no clue what the issue could be. I've been trying to figure this out and am completely stumped. Does anyone know why this error is happening?

A: then should have a callback try this :
const FunctionComponent = (props) => {
    const fetchSomething = () => {
        fetch('fetch is made here and is successful')
        .then(()=>props.setSubscription({value1: 1, value2: 2}))
    }
}


text:
Q: homebrew: how to tell if a formula is binary How do I tell if a particular formula will be installed as binary of from source?
Is there a brew command for this?

A: You could use brew edit ${formula_name}. That will open an editor with the formula contents. If there is a reference to a "bottle", then installing it with default settings will use that.
However, if you add an option, then homebrew will compile the software for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to write all lines that match to a file I want to go over every file in a directory and if there is a match (specific IP in the file content), to write those matches into a new file in another directory. And do this for every file in the directory.
So far I have this, but it writes only one line in the new file. Could you guys help?
import os, re

wanted = ['10.10.10.10']
dir_list = os.listdir('D:\\path\\07')

for i in dir_list:
    n = open('D:\\path\\07\\'+i,'r')
    m=n.readlines()
    for line in m:
        if  any(wanted_word in line for wanted_word in wanted):
            with open('Z:\\PYTHON\\Filtered-'+i,'w') as filtered_log:
                filtered_log.write(line)

I have tried this one as well - nothing.. no error, even no result here.
import re, os

regex = "(.*)10.10.10.10(.*)"

dir_list = os.listdir('D:\\path\\07')

for i in dir_list:
    n = open('D:\\path\\07\\'+i,'r')
    for line in n:
        if re.match(regex, line):
            with open('Z:\\PYTHON\\Filtered_'+i,'w') as filtered_log:
                filtered_log.write(lines)

A: The . is a special character in regular expressions, so you need to make sure you escape it:
>>> import re
>>> e = r'10\.10\.10\.10'
>>> s = "There are some IP addresses like 127.0.0.1 and 192.168.1.1, but the one I want is 10.10.10.10 and nothing else"
>>> s2 = "I only contain 192.168.0.1"
>>> re.search(e, s)
<_sre.SRE_Match object at 0x7f501fb771d0>
>>> re.search(e, s2)

What is happening with your code is that everytime you match a line, you open the file again in write mode, which deletes the contents of your file; the effective result is only the last line in written.
You need to make sure you open the file only once for writing, and then close it when you have filtered all the files in your target directory:
import os
import re

e = r'10\.10\.10\.10'

base_directory = r'D:/path/07'
base_dir_out = r'Z:/Python/'

for f in os.listdir(base_directory):
    with open(os.path.join(base_directory, f), 'r') as in_file,
         open(os.path.join(base_dir_out, 'Filtered-{}'.format(f), 'w') as out:
          for line in in_file:
              if re.search(e, line):
                  out.write(line)

Note the following:

*

*You can use / even in Windows.

*You should always use os.path.join when combining file paths.

A: You're opening your file as w, which will truncate the previous file, that's why you only see one line in the new file.
wanted = ['10.10.10.10']
dir_list = os.listdir('D:\\path\\07')

for i in dir_list:
    n = open('D:\\path\\07\\'+i,'r')
    m=n.readlines()
    n.close()
    for line in m:
        if  any(wanted_word in line for wanted_word in wanted):
            tempFile = 'Z:\\PYTHON\\Filtered-' + i
            if exists(tempFile):
                with open('Z:\\PYTHON\\Filtered-'+i,'a') as filtered_log:
                    filtered_log.write(line)
            else:
                with open('Z:\\PYTHON\\Filtered-'+i,'w') as filtered_log:
                    filtered_log.write(line)


text:
Q: Find date when app was first installed / downloaded from the App Store I'd like to monetise currently free features of my app in future releases. Since I don't want to agitate existing users I want to make sure things stay free for them.
In order to find out whether they had used my app before the new release I'd like to find a way to acquire the date when they first installed the app or downloaded it from the App Store.
I've found this discussion: Detect first launch of iOS app
But it stores the first launch in the user defaults of the app, which to my knowledge, will be wiped once the app is deleted.
My app does not communicate with any online service/data base where I could store such information.
Is there a way to do what I'm looking for?
If there is another way please point me into the right direction.


text:
Q: Positively curved manifold with almost extreme diameter Suppose $M$ is a 1-connected closed manifold with sectional curvature $\ge 1$. So the diameter $D$ of $M$ satisfies
$$
D \le \pi
$$
When equality holds $M$ is isometric to round sphere. In fact this rigidity holds under the assumption of $Ric \ge n-1$. Hence it is natural to ask what happens to almost extreme case. i.e. when $$D \ge \pi -\epsilon $$Under the Ricci assumption only, the manifold is not necessary sphere by a counter example of M. Andersen. However with extra assumption: sectional curvature is bounded from below, Perelman proved it is homeomorphic to a twist sphere. (Is Perelman the first one prove this?)
By Grove-Shiohama's Diameter Sphere Thereom, under the assumption sectional curvature $\ge 1$ and $D\ge \pi-\epsilon$, $M$ is a twist sphere. (It also follows from Perelman's theorem above)
My question is: Is $M$ diffeomorphic to the standard sphere?
Either Perelman's proof or Grove-Shiohama's Diameter sphere theorem uses the 'soft' approach, i.e. It is not by convergence argument, nor a Lipschitz distance between $M$ and $S^n$ is derived.
Actually, I suspect that it is not Gromov-Hausdorff close to the round sphere, as one might round off two tips of $S^2/\mathbb Z_p$, where $\mathbb Z_p$ acts on $S^2$ by rotation along the $z$-axis.
What if one assume there is also an upper bound $K$ on sectional curvatures, i.e. $$1\le sec(M) \le K$$

A: I will answer the last question.
Namely, let me show that if $1\le \mathrm{sec}\,M \le K$ and $\mathrm{diam}\, M>\pi-\varepsilon$ for sufficiently small $\varepsilon>0$ then it has to be diffeomorphic to $\mathbb S^m$.
Asssume contrary, then there is a sequence of $m$-dimensional manifolds $M_n$ such that $1\le \mathrm{sec}\,M_n \le K$ and $\mathrm{diam}\, M_n\to\pi$ as $n\to \infty$.
Let's pass to a converging sequence $M_n\to A$.
Note that $A$ is $m$-dimensional and $1\le \mathrm{sec}\, A \le K$ in the sense of Alexandrov and $\mathrm{diam}\, A=\pi$.
It follows that $A$ is isometric to $\mathbb S^m$
Finally note that $M_n$ is diffeomorphic to $A$ for all large $n$;
the later was essentally proved by Cheeger in his thesis.


text:
Q: Trouble with external monitor under Windows 7 on MacBook Pro Boot Camp I'm running Windows 7 32-bit on a mid-2010 15" MacBook Pro Intel Core i5 under Boot Camp. I've had trouble getting it to work with my second display and searching Google for an appropriate answer has failed me.
I'm on the latest version of Boot Camp - 3.2 - and have updated the drivers for the NVIDIA GeForce GT 330M.
The monitor is connected via a VGA cable, and is a Dell ST2410.
The monitor is recognised by Windows, which knows it's a Dell and its resolution. The desktop should be extended onto the second monitor - however nothing is showing. It remains black, though it doesn't show a lack of signal coming through which I would have expected.
Any ideas what's wrong?


text:
Q: Process multiple columns with Pandas apply method when columns are not predefined I would like to create a general function to process all columns that start with something. The caveat being that I don't know how many columns will start with that thing beforehand.
For example, I would like to just process columns that start with "dog":
df = pd.DataFrame([[1, 2,5], [1, 3,4], [4, 6,1]], columns=['dog1', 'cat1','dog2'])

Returns
    dog1    cat1    dog2
0   1          2    5
1   1          3    4
2   4          6    1

I can create a list of those columns:
col_list = []
for col in df.columns:
    if col.startswith('dog'):
        col_list.append(col)
col_list

Returns
['dog1', 'dog2']

In this example I use apply to process the things in that list by specifying them individually. The answer I'm looking for would use the list. This is just to show how I am using apply now.
Also, I would like to apply more complex functions than summing so I'm looking to be able to apply general functions. Summing the two columns with a function is just for the purposes of the example.
def sum_dogs(d1,d2):
    return d1+d2

df['sum_dogs'] = df.apply(lambda x: sum_dogs(x['dog1'],x['dog2']),axis=1)

Returns
    dog1    cat1    dog2    sum_dogs
0      1    2          5    6
1      1    3          4    5
2      4    6          1    5

I would like to apply whatever the output of "col_list" may return for any DataFrame.

ANSWER from RafaelC below:
I just wanted to show how the answer is used to solve my (confusing) example :).
def sum_dogs(col_list):
    sum = 0
    for col in col_list:
        sum = sum+col
    return sum

df['sum_dogs'] = df.loc[:, df.columns.str.startswith('dog')].agg(sum_dogs, 1)

A: Taking a shot here, you can use .loc[:, cols] to slice only columns that matter, and .agg in axis 1 to perform your logic
df.loc[:, df.columns.str.startswith('dog')].agg(function, 1)

For a simple sum, for example, this can be
df.loc[:, df.columns.str.startswith('dog')].agg(sum, 1) # or sum(1)

A: Do you have to use apply?
Showing a methods that provide a multitude of results.
Perhaps this is more what you are looking for.
import pandas as pd

df = pd.DataFrame([[1, 2,3], [2, 3,4], [3, 4,5]], columns=['dog1', 'cat1','dog2'])
lookfor = 'dog'
col_list = df.columns[df.columns.str.startswith(lookfor)]

def col_sum(col_list):
    return col_list.sum(axis=1)

def col_collective(col_list):
    return(col_list.values.tolist())

def sum_text(col_list):
    val = col_list.sum(axis=1)
    for i in range(len(val)):
        val[i] = f'{val[i]} {lookfor}s'
    return val

def allthelittleones(col_list):
    val = col_list.sum(axis=1)
    for i in range(len(val)):
        val[i] = str([1,]*val[i])
    return val

df['sum_'+lookfor] = col_sum(df[col_list])
df['collective_'+lookfor] = col_collective(df[col_list])
df['sumtext_'+lookfor] = sum_text(df[col_list])
df['alltheones_'+lookfor] = allthelittleones(df[col_list])

print(df)


text:
Q: What part of speech is i.e.? What part of speech is i.e. ?
If translated it means "that is", so a sentence like

I like citrus fruits, i.e., the juicy, edible fruits with leathery, aromatic rinds.

(from https://www.dictionary.com/e/ie-vs-eg/)
can be rewritten to

I like citrus fruits, that is, the juicy, edible fruits with leathery, aromatic rinds.

It sounds like a subordinating complementizer to me in this case, equivalent to

I like citrus fruits, which are juicy, edible fruits with leathery, aromatic rinds.

introducing the non-restrictive relative clause which are juicy, edible fruits with leathery, aromatic rinds.
Does that mean that in the original sentence:

I like citrus fruits, i.e., the juicy, edible fruits with leathery, aromatic rinds.

i.e. is a complementizer that introduces the non-restrictive relative clause i.e., the juicy, edible fruits with leathery, aromatic rinds? Is i.e. both the verb of the subclause and its C-head at the same time?
Or should i.e. be treated like a preposition in syntactic analysis? (I couldn't find a way to replace it with a preposition in the sentence).

A: Id est is a Latin phrase, and as it lacks the ability to take modifiers or dependents of any kind, it is difficult (and largely pointless) to categorize it as a part of speech - especially if we expect part of speech classifications to tell us about the form of the item in question, describing its internal structure and possible dependents.
The relevant question to ask is what function it has in this clause. Its function is that of indicator in a supplement with the anchor citrus fruits; the same function could also be performed by an adverb or a preposition phrase.

I like citrus fruits, [i.e., the juicy, edible fruits with
leathery, aromatic rinds].
I like citrus fruits, [namely, the juicy, edible fruits with
leathery, aromatic rinds].
I like citrus fruits, [in other words, the juicy, edible fruits
with leathery, aromatic rinds].

Indicators generally serve to clarify the nature of the supplement's semantic relation to the anchor.


text:
Q: Serializing/deserializing aliased primitives in Jackson without too much boilerplate I have a class I want to deserlialize into a Java into a class. One of the class attributes is itself a serializable class which has one primitive (String) parameter and really represents an aliased String, i.e., a String with some extra stuff around it to make sure it comes in the correct format. This is useful in a variety of applications (e.g., identifiers), in this case it's a Cron string that has to have specific representation. So I have
class ScheduleConfigurations {
    private Cron cron;
    private Set<Cron> overrides;
    // other attributes, getters/setters, constructor
}

class Cron {
    private String cronString;

    private void validate() { // validates string has correct representation }
    // getters, setters, constructor
}

Obviously the standard Jackson deserializer expects a JSON of the format
{
    "cron": {
        "cronString": "someCronString",
    "overrides": [
        { "cronString": "someCronString1" },
        { "cronString": "someCronString2" }
    ]
}

However, the Cron class is clearly just an aliased String. I'd want the above to be serialized/deserialized as
{
    "cron": "someCronString",
    "overrides": ["someCronString1", "someCronString2"]
}

I can make that happen with a custom serializer with a bunch of boilerplate, but I am looking for an elegant way to say to Jackson "hey, this class has one String attribute, just pass through it and treat its serialized representation as its only attribute".

A: Since you want the entire object to be (de)serialized as a string, it's very easy:
@JsonSerialize(using = ToStringSerializer.class)
class Cron {
    private String cronString;
    public Cron(String cronString) { // Called by Jackson when deserializing from JSON string
        this.cronString = cronString;
    }
    @Override
    public String toString() { // Called by Jackson when serializing to JSON
        return this.cronString;
    }
}

Since the class is just a wrapper around a string, you don't even need getter, setter, or other constructor, not even for other Java code, though you can of course still have them.
Test
ScheduleConfigurations configObj = new ScheduleConfigurations();
configObj.setCron(new Cron("someCronString"));
configObj.setOverrides(new LinkedHashSet<>(Arrays.asList(
        new Cron("someCronString1"), new Cron("someCronString2"))));
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
System.out.println(mapper.writeValueAsString(configObj));

String json = "{\r\n" +
              "  \"cron\" : \"someCronString\",\r\n" +
              "  \"overrides\" : [ \"someCronString1\", \"someCronString2\" ]\r\n" +
              "}";
ScheduleConfigurations configObj = new ObjectMapper().readValue(json, ScheduleConfigurations.class);
System.out.println("cron = " + configObj.getCron());
System.out.println("overrides = " + configObj.getOverrides());

Output
{
  "cron" : "someCronString",
  "overrides" : [ "someCronString1", "someCronString2" ]
}

cron = someCronString
overrides = [someCronString1, someCronString2]


text:
Q: How to convert date to general format in Alteryx? Can you please tell how I can convert date to General format (as we have in Excel) please?
Basically I am looking for Date-INT(Date) in Alteryx.

A: You can use the formula  - DateTimeAdd("1900-01-01",[Field Name],"days") in formula tool to extract the date.
 Also you should subtract the date in general format by '2' before processing as excel computes 1900 as leap year.
Alteryx Workflow


text:
Q: Web scrapping com python não traz a informação completa da pagina html Saudações pessoal, estou tentando utilizar python para poder pegar as informações da pagina http://www.nfce.se.gov.br/portal/painelMonitor.jsp , é uma pagina da sefaz onde tem o status de ping dos envios da NFC-e, porém ao usar o soup com python pra puxar as informações da pagina, ela nao me traz as informações que estão la em tempo real, ele não ta me trazendo todas as informações que eu consigo ver com o inspect F12 do browser, alguem teria alguma ideia do que pode ser ? Segue abaixo o código que estou utilizando:
#!/usr/bin/env python

# -*- coding: UTF-8 -*-

import requests
from bs4 import BeautifulSoup

page = requests.get('http://www.nfce.se.gov.br/portal/painelMonitor.jsp')
soup = BeautifulSoup(page.text, 'html.parser')

autorizador = soup.find(id='tabDados')

print(autorizador.prettify())

A: As informações da página são preenchidas por código em Javascript que é executado depois que a chave é carregada. Esse codigo faz as requisições em tempo real aos vários servidores, e etc...
Com tecnologias de web-scrapping normais não é possível obter esses dados. Quando é assim, você tem duas opções:
Tnetar olhar o código da página (como baixado pelo Python - com requests ou o framework de scrapping que estiver usando) ,  e fazer a engenharia reversa das URLs consultadas pelo Javascript e tentar fazer as mesmas consultas a partir do seu código em Python . Nesse caso, estaria até favorável fazer algo assim já que o Javascript que faz as operações não está obfuscado. Além de um pouco de código na própria página que você carrega, a maior parte do código em Javascript está na URL http://www.nfce.se.gov.br/portal/framework/js/nfce/nfc-e.js .
Essa opção, dependendo de quais dados você precisa e de quanto complexo é o código pode ser muito complicada (se for uma página com Javascript obfuscado nem tente começar por aí).
A outra opção é usar em vez do beautifulsoup, o Selenium - O selenium usa um browser "real" (embora, na configuração atual, sem uma janela visível), e roda todo o javascript da página como numa navegação normal, inclusive efetuando outros requests de HTTP. E ele expõe uma API que permite que você veja o HTML gerado pelo javascript executado.
Perceba que a grande diferença é que o Selenium realmente inclui um navegador completo, com um engine javascript (por padrão ele usa o firefox, mas isso é configurável) - e permite que seu programa em Python veja a página como ela ficou enquanto o Javascript está em execução.
Esta segunda opção definitivamente é mais apropriada para você seguir, uma vez que não vai estar sujeito a ficar horas analizando o código Javascript da página e tentando replicar o seu comportamento, apenas para em algumas semanas ou meses, os autores mudarem o código e você ter que refazer todo o trabalho. Com Selenium você pega o HTML já renderizado da página e pode proceder a isolar os dados que precisa com o Beautfulsoup normalmente.

A: O código abaixo usa lxml para parsear a página diretamente da URL:
import requests, lxml.html

resp = requests.get('http://www.nfce.se.gov.br/portal/ConStatusAuto?Origem=1')
doc = lxml.html.fromstring(resp.text)
for tr in doc.xpath('//tr'):
    nome = tr[0].text_content().strip()
    print(nome.ljust(25), '|'.join('{: >7}'.format(td.text_content().strip())
        for td in tr.xpath('.//td')[1:]))

Resultado:
SEFAZ Amazonas                   |  783ms|  900ms|  361ms|    0ms|  900ms|  661ms|    0ms|  806ms|   50ms|  783ms|  783ms|  196ms|    0ms|    0ms|    0ms
SEFAZ São Paulo                  |    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms
SEFAZ Paraná                     |  429ms|1s808ms|  559ms|  433ms|1s808ms|  620ms|  429ms|  799ms|  495ms|  512ms|  521ms|  518ms|    0ms|    0ms|    0ms
SEFAZ Goias                      |    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms
SEFAZ Mato Grosso                |    0ms|  896ms|  310ms|  609ms|  861ms|  301ms|    0ms|  896ms|  325ms|    0ms|  476ms|  159ms|    0ms|    0ms|    0ms
SEFAZ Rio Grande do Sul          |  852ms|1s886ms|  974ms|  852ms|1s166ms|  964ms|  871ms|1s886ms|  986ms|  867ms|  986ms|  940ms|    0ms|    0ms|    0ms
SEFAZ Virtual RS                 |  761ms|5s854ms| 1s11ms|  830ms|1s245ms|  964ms|  761ms|5s854ms| 1s65ms|  899ms|  969ms|  925ms|    0ms|    0ms|    0ms
SEFAZ Mato Grosso do Sul         |    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms
SEFAZ Ceará                      |    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms
SEFAZ Minas Gerais               |    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms
SEFAZ Pernambuco                 |    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms|    0ms


text:
Q: MariaDB AUTO_INCREMENT Jump to Max (unsigned) int EDIT: it was a bug in or application
What could cause the auto_increment value to jump up billions of values to strike max int?
Our core table uses an int unsigned auto_increment primary key column. Today it skipped every value all the way up to 4294967295.
I was able to resolve this by deleting the offensive row and running
ALTER TABLE [table] AUTO_INCREMENT = [new value];

but I cannot explain how or why it happened.
Our environment is MariaDB 10.2.27 under PHP/Apache.

A: Any INSERT can specify a high value, and this will implicitly advance the next auto-increment value. In other words, an auto-increment for a table will never be less than the largest value currently inserted in the table, and any client can override the auto-increment mechanism simply by specifying a value in an INSERT.
Demo:
mysql> create table mytable (id int unsigned auto_increment primary key);

mysql> insert into mytable (id) values (DEFAULT);
Query OK, 1 row affected (0.01 sec)

That should have inserted id value 1, so the next AI will be 2:
mysql> show create table mytable\G
*************************** 1. row ***************************
       Table: mytable
Create Table: CREATE TABLE `mytable` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4

Now I specify a large value, and the AI is updated accordingly:
mysql> insert into mytable (id) values(1000000000);
Query OK, 1 row affected (0.01 sec)

mysql> show create table mytable\G
*************************** 1. row ***************************
       Table: mytable
Create Table: CREATE TABLE `mytable` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1000000001 DEFAULT CHARSET=utf8mb4

Note a value greater than the max unsigned int value 232-1 will be truncated to that value.
mysql> insert into mytable (id) values(1000000000000);
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> show create table mytable\G
*************************** 1. row ***************************
       Table: mytable
Create Table: CREATE TABLE `mytable` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4294967295 DEFAULT CHARSET=utf8mb4

So someone must have inserted a large value. Any value larger than 4294967295 will be truncated to 4294967295, and then subsequent inserts that try to use the AI sequence will fail.


text:
Q: display: inline does not work with jquery animate () I am trying to animate a div that is hidden by default on mousing over the header of a site here is the jquery code that does not currently work:
    $("#header_title").mouseenter(function() {
        $('#header_links').animate({
            display: "inline",
            width: "600px"
            }, 1500 );
    });

    $("#header").mouseleave(function() {
        $('#header_links').css({
            display: "none",
            }, 1500 );
    });

It works fine when I change animate to css, however I dont want the menu to just appear, I want it to animate after being hidden. Any suggestions?

A: You forgot to animate it back to zero width, and you can't animate the display property, that's either visible or not, there's nothing to animate inbetween, as it's not a numerical property ?
$("#header_title").mouseenter(function() {
    $('#header_links').css('display','inline').animate({
        opacity: 1,
        width: 600
    }, 1500 );
});

$("#header").mouseleave(function() {
    $('#header_links').animate({
        opacity: 0,
        width: 0
    }, 1500, function() {
        $(this).css('display','none');
    });
});


text:
Q: positive harmonic function has a zero limit at a point on the boundary Let $u$ be a positive harmonic function in $\{ \Re{z} > 0\}$ such that
$\lim_{r \rightarrow 0^+} u(r) = 0 $.
Prove that then $\lim_{r \rightarrow 0^+} u(re^{i\theta}) = 0 $ for any $\theta \in (-\pi/2, \pi/2)$.
What I have tried is to consider the equivalent problem by transforming the domain to the unit disc using the Moebius map $z \rightarrow \frac{z-1}{z+1}$. Then we have
$\lim_{r \rightarrow -1^+} u(r) = 0 $ and we need to prove that this limit is zero when approaching along the arcs of other circles which intersect the unit circle perpendicularly at $-1$ or in other words the limit is the same when approaching from different non-tangential directions. Note also we have a simply connected domain and hence a holomorphic function, $f$ exists whose real part is $u$. Also since u was positive, hence $f$ maps the unit disc to itself which means it is bounded. This in turn means that $f$ has a finite limit a.e. on the boundary. Any ideas how to proceed or how to prove this otherwise?

A: The assumption that $u$ is positive should bring to mind Harnack's inequality. Let's state its special case for the disk: if $u$ is positive and harmonic in $\{z:|z-z_0|<R\}$, then
$$\frac{R-|z-z_0|}{R+|z-z_0|}u(z_0)\le u(z) \le \frac{R+|z-z_0|}{R-|z-z_0|}u(z_0)$$
for all $z$ in the disk.
The precise form of constants does  not matter; the fact that they depend only on $|z-z_0|/R$ is a consequence of the scale invariance of the Laplace equation.
Apply the above with $z=re^{i\theta}$ and  $z_0=R=r\sec\theta$. Observe that $|z-z_0|/R=|\sin\theta|<1$, independently of $r$. Thus,
$$u(re^{i\theta})\le \frac{1+|\sin\theta|}{1-|\sin\theta|}u(r\sec\theta)$$
from where the conclusion $u(re^{i\theta})\to 0$ follows.


text:
Q: Spring Boot 1.3.3 Application with Tiles 3 on JBoss 6.4 - Error JBWEB000065 - 404 Not Found I am strugging to deploy a Spring Boot War Application (with Tiles views) on JBoss EAP 6.4. This application runs smoothly on Tomcat 8 but when I deploy it on JBoss it doesn't answer. The startup logs are OK but when I call a controller from the browser I get error JBWEB000065. I happens both deploying from Eclipse STS and putting the war in standalone/deployments.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.codependent.gitprofiles</groupId>
    <artifactId>boot3</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>boot3</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <groupId>org.springframework.boot</groupId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

ServletInitializer:
public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Boot3Application.class);
    }

}

Boot3Application:
@SpringBootApplication
@RestController
public class Boot3Application {

    @RequestMapping("/home")
    public String home(){
        return "home";
    }

    public static void main(String[] args) {
        SpringApplication.run(Boot3Application.class, args);
    }
}

TilesConfiguration:
@Configuration
public class TilesConfiguration {

     @Bean
     public TilesConfigurer tilesConfigurer() {
         final TilesConfigurer configurer = new TilesConfigurer();
         configurer.setDefinitions(new String[] { "WEB-INF/**/tiles.xml" });
         configurer.setCheckRefresh(true);
         return configurer;
     }

     @Bean
     public TilesViewResolver tilesViewResolver() {
         final TilesViewResolver resolver = new TilesViewResolver();
         resolver.setViewClass(TilesView.class);
         return resolver;
     }

}

Startup Logs:
[org.jboss.web] (ServerService Thread Pool -- 80) JBAS018210: Registrar el contexto web: /boot3
[org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/boot3]] (ServerService Thread Pool -- 80) Spring WebApplicationInitializers detected on classpath: [org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration$JerseyWebApplicationInitializer@57c6298e, com.codependent.gitprofiles.ServletInitializer@16df6757]
[org.hibernate.validator.internal.util.Version] (background-preinit) HV000001: Hibernate Validator 4.3.2.Final-redhat-2
[stdout] (ServerService Thread Pool -- 80)
[stdout] (ServerService Thread Pool -- 80)   .   ____          _            __ _ _
[stdout] (ServerService Thread Pool -- 80)  /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
[stdout] (ServerService Thread Pool -- 80) ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
[stdout] (ServerService Thread Pool -- 80)  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
[stdout] (ServerService Thread Pool -- 80)   '  |____| .__|_| |_|_| |_\__, | / / / /
[stdout] (ServerService Thread Pool -- 80)  =========|_|==============|___/=/_/_/_/
[stdout] (ServerService Thread Pool -- 80)  :: Spring Boot ::        (v1.3.3.RELEASE)
[stdout] (ServerService Thread Pool -- 80)

[org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] (ServerService Thread Pool -- 80) Mapped "{[/home]}" onto public java.lang.String com.codependent.gitprofiles.Boot3Application.home()
...

Calling http://localhost:8080/boot3/home on the browser shows the following with nothing appearing on the JBoss logs;
JBWEB000065: HTTP Status 404 - /boot3/error
JBWEB000309: type JBWEB000067: Status report
JBWEB000068: message /boot3/error
JBWEB000069: description JBWEB000124: The requested resource is not available.
JBoss Web/7.5.7.Final-redhat-1

UPDATE: I found a solution on Stackoverflow but it useless in my case: using server.servlet-path=/* the application starts processing the requests, now the controller is invoked BUT it's unable to render the Tiles views:
Cannot forward to error page for request [/home] as the response has already been committed. As a result, the response may have the wrong status code. If your application is running on WebSphere Application Server you may be able to resolve this problem by setting com.ibm.ws.webcontainer.invokeFlushAfterService to false

I have checked on Tomcat that if I use server-servlet-path/* it doesn't work either (with the same error) but it does with /.
To sum up, in JBoss I cannot have both server.servlet-path=/* (to allow the invocation on controllers) and server.servlet-path=/ to allow the Tiles views rendering, so how can I workaround this problem?

A: I had the exact problem. After installing the Jboss patch jboss-eap-6.4.6-patch.zip the problem does not occur anymore.
After patching I did not need to use the setting server.servlet-path=/*


text:
Q: How to separate a column of a pandas dataframe that contains the geographic coordinates in two columns for latitudes and longitudes? I have the following pandas dataframe:
      import pandas as pd

      df = pd.DataFrame({'NAME': ['Paris', 'New York', 'Rio'],
                         'GEO': ['POINT (48.85 2.31647)',
                                 'POINT (40.731499671618 -73.993457389558)',
                                 'POINT (-22.9 -43.2)']})

      print(df)

       NAME            GEO
       Paris      POINT (48.85 2.31647)
       New York   POINT (40.731499671618 -73.993457389558)
       Rio        POINT (-22.9 -43.2)

I need to separate the GEO column into two columns. One column to store latitude and another column to store longitude.
So, based on this code: Adding Lat Lon coordinates to separate columns (python/dataframe) , I implemented the following:
       df['GEO'].str('POINT ()').str.strip(' ', expand=True).rename(columns={0:'LAT', 1:'LONG'})

However, it is giving the error: "TypeError: 'StringMethods' object is not callable"
I would like the output to be:
      NAME             GEO                                   LAT              LONG
       Paris      POINT (48.85 2.31647)                      48.85            2.31647
       New York   POINT (40.731499671618 -73.993457389558)   40.731499671618  -73.993457389558
       Rio        POINT (-22.9 -43.2)                        -22.9            -43.2

A: You could use a regex:
df2 = df.join(df['GEO'].str.extract(r'(?P<LAT>-?\d+\.\d+) (?P<LONG>-?\d+\.\d+)'))

output:
       NAME                                       GEO              LAT              LONG
0     Paris                     POINT (48.85 2.31647)            48.85           2.31647
1  New York  POINT (40.731499671618 -73.993457389558)  40.731499671618  -73.993457389558
2       Rio                       POINT (-22.9 -43.2)            -22.9             -43.2

or, to get float:
df2 = df.join(df['GEO'].str.extract(r'(?P<LAT>-?\d+\.\d+) (?P<LONG>-?\d+\.\d+)'))
              .astype(float))

output:
       NAME                                       GEO      LAT       LONG
0     Paris                     POINT (48.85 2.31647)  48.8500   2.316470
1  New York  POINT (40.731499671618 -73.993457389558)  40.7315 -73.993457
2       Rio                       POINT (-22.9 -43.2) -22.9000 -43.200000

A: You were very close. But the .str function is not callable. You can not invoke it as .str(). Modify your code to this and it works (but won't be quite as sleek as your one-liner)
df[['POINT', 'LAT', 'LONG']]  = df['GEO'].str.split(' ', expand=True).rename(columns=({0:'POINT', 1:'LAT', 2:'LONG'}))

df['LAT'] = df['LAT'].str.replace('(','')
df['LONG'] = df['LONG'].str.replace(')','')

You can then delete df['POINT']


text:
Q: Android Why this error ENOENT (No such file or directory) comes I want to know why this error comes when try to upload file with real device using Marshmallow. Can you please explain the solution for this.

12-28 10:39:32.606: E/3(17552): Excption : java.io.FileNotFoundException: /storage/emulated/0/WoodenstreetD.doc: open failed: ENOENT (No such file or directory)

I was stuck with this for last week and still getting same issue.
Thanks In Advance.

A: This error comes due to wrong path. The path your getting from onActivityResult is not correct. Use this to get path of selected file.
public static String getRealPathFromUri(Context ctx, Uri uri) {
    String[] filePathColumn = { MediaStore.Files.FileColumns.DATA };

    Cursor cursor = ctx.getContentResolver().query(uri, filePathColumn,
            null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        picturePath = cursor.getString(columnIndex);
        Log.e("", "picturePath : " + picturePath);
        cursor.close();
    }
    return picturePath;
}

picturePath gives you full path of image/file.
It'll work for me.

A: i worte this and it'll work for me.
 public static java.io.File convertUriTFile(Activity activity, Uri uri) {
        InputStream inputStream = null;
        java.io.File file = null;
        try {
            inputStream = activity.getContentResolver().openInputStream(uri);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            file = new java.io.File(activity.getCacheDir(), "temp");
            try (OutputStream output = new FileOutputStream(file)) {
                byte[] buffer = new byte[4 * 1024];
                int read;

                while ((read = inputStream.read(buffer)) != -1) {
                    output.write(buffer, 0, read);
                }

                output.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return file;

    }


text:
Q: Problem with StringFormat I'm trying to use the StringFormat in XAML to populate the Header text on a TabItem.  The code I am using is:
<TabControl.ItemContainerStyle>
    <Style TargetType="{x:Type TabItem}" BasedOn="{StaticResource TabItemStyle}">
        <Setter Property="Header" Value="{Binding MyValue, StringFormat='My Value is {0}'}" />
        <EventSetter Event="FrameworkElement.Loaded" Handler="OnTabItemLoaded" />
        <EventSetter Event="FrameworkElement.Unloaded" Handler="OnTabItemUnloaded" />
    </Style>
</TabControl.ItemContainerStyle>

The problem is my header is only showing the value of MyValue in the Header and not the formatted text.

A: Because the Header property is not a string property.
You need to use a headertemplate containing a TextBlock which you can bind the Text property using your stringformat
<TabControl.ItemContainerStyle>
    <Style TargetType="{x:Type TabItem}" BasedOn="{StaticResource TabItemStyle}">
        <Setter Property="HeaderTemplate">
          <Setter.Value>
            <DataTemplate>
              <TextBlock Text="{Binding MyValue, StringFormat='My Value is {0}'}" />
            </DataTemplate>
          </Setter.Value>
        </Setter>
        <EventSetter Event="FrameworkElement.Loaded" Handler="OnTabItemLoaded" />
        <EventSetter Event="FrameworkElement.Unloaded" Handler="OnTabItemUnloaded" />
    </Style>
</TabControl.ItemContainerStyle>

A: The simplest solution is to use the HeaderStringFormat property:
<Setter Property="Header" Value="{Binding MyValue}" />
<Setter Property="HeaderStringFormat" Value="My Value is {0}" />

WPF seems to follow this pattern whenever you can assign a string to a generic content property, another example would be ContentControl.ContentStringFormat.


text:
Q: Problem with JavaFX project after adding Maven support (Exception in Application start method) I created a JavaFX project using JDK 1.8. Works correctly. But if I try to add Maven support, compilation fails.
Firstly, I tried to do it in Java 11 with JavaFX 11 but effect was the same. I spent two days on finding why it doesn't work, glancing at stackoverflow a lot of hours. Finally, I decided to try it on Java 8 but it still haven't solved my problem.
There is no difference if 'sample.fxml' exists in the same folder as Main or in resources, compilation fails on both of them.
SDK is set correctly.
Console log:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException: Location is required.
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3207)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at sample.Main.start(Main.java:13)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
... 1 more
Exception running application sample.Main

Process finished with exit code 1

pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>pl.wojciech</groupId>
<artifactId>javafx11</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.6.0</version>
            <executions>
                <execution>
                    <goals>
                        <goal>java</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <mainClass>sample.Main</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>
</project>

There is Main method (generated by IntelliJ, changed multiple times):
public class Main extends Application {

@Override
public void start(Stage primaryStage) throws Exception{
    Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
    primaryStage.setTitle("Hello World");
    primaryStage.setScene(new Scene(root, 300, 275));
    primaryStage.show();
}

public static void main(String[] args) {
    launch(args);
}
}

And my project structure:
javafx8 [
    .idea {}
    src
        {
        main
            java
                sample
                     Controller
                     Main
                     sample.fxml
                resources
         }
    test {}
    target {}
    javafx8.iml
    pom.xml
]

A: You have your sample.fxml file in the wrong place. Maven (and Gradle) follow a standard directory layout by default. It expects source files to be under src/main/java and resources to be under src/main/resources. Any resource files under src/main/java do not end up on the classpath/modulepath at runtime.
You should either:

*

*Move sample.fxml to src/main/resources. Or,

*

*This requires changing your code to getResource("/sample.fxml").

*Move sample.fxml to src/main/resources/sample.

*

*With this option you can keep your code as is.

Note: You have a directory named src/main/java/resources. I'm assuming this is where you tried to put the FXML file and found it still didn't work. The reason is because Maven doesn't expect resources to be at that location (location indicates source files). Maven expects resources to be under src/main/resources.

But if I try to add Maven support, compilation fails.

The stack trace you posted, as fabian mentions, is not the result of a compilation error. It is a runtime error.


text:
Q: adjusted R2 for conditional constrained ordination After a model selection of a partial ordination, is it correct to apply the function RsquareAdj(mod.sel) to get the adjusted R2?
Or is it correct to use Ezekiel's formula in a straightforward manner?

A: It seems that vegan does not do it in straightforward way. The function is not exported, but use vegan:::RsquareAdj.rda to see how the partial models are handled. If everything else fails, you may also consider looking at the documentation which reads

The raw R-squared of partial 'rda' gives the proportion explained
       after removing the variation due to conditioning (partial) terms;
       Legendre et al. (2011) call this semi-partial R-squared. The
       adjusted R-squared is found as the difference of adjusted
       R-squared values of joint effect of partial and constraining terms
       and partial term alone, and it is the same as the adjusted
       R-squared of component '[a] = X1|X2' in two-component variation
       partition in 'varpart'.


text:
Q: Canonical Markov Process Let $X$ be a canonical, right-continuous Markov process with values in a Polish state space $E$, equipped with Borel-$\sigma$-algebra $\mathcal{E}$ and we assume that $t\rightarrow E_{X_{t}}f(X_{s})$ is right continuous everywhere for each bounded continuous function f.
For $x\in E$ define $\sigma_{x}=\inf\{t>0\mid X_{t}\neq x\}$.
I've come to the conclusion that $\sigma_{x}$ is an optional time. I would now like to use the Markov property of $X$ to show that for every $x\in E$ it holds that
$$P_{x}\{\sigma_{x}>t+s\}=P_{x}\{\sigma_{x}>t\}P_{x}\{\sigma_{x}>s\}$$
for all $s,t\geq 0$
I've tried using the indicator function $\mathbb{1}_{\sigma_{x}>t+s}$ but didnt come to the desired result. Could anyone help me prove this?

A: Indeed $\sigma_x$ is exponentially distributed under $P_x$. To see this, note that $[\sigma_x\gt s]\subseteq[X_s=x]$ hence
$$
P_x[\sigma_x\gt t+s\mid\sigma_x\gt s]=P_x[\sigma_x\gt t+s\mid X_s=x]=P_x[\sigma_x\gt t].
$$
This is specific to the starting distribution $P_x$. For other starting distributions, the distribution of $\sigma_x$ is the barycenter of the exponential distribution $P_x\circ\sigma_x^{-1}$ and of the Dirac mass at $0$ with respective weights $P[X_0=x]$ and $1-P[X_0=x]$.


text:
Q: EMStagePatches_$ORACLE_SID is using up space We have this directory:
$ORACLE_HOME/EMStagePatches_$ORACLE_SID

We are running out of space and this directory is using up a lot of space. Is it safe to delete it? I think it is something to do with the Enterprise Manager patches. How can I stop Enterprise Manager from downloading stuff into that directory?
We are using Oracle Database 11g Enterprise Edition Release 11.1.0.6 running on Red Hat Enterprise Linux Server release 5.2.

A: Just to make sure this is not used by your OEM
- rename the folder to $ORACLE_HOME/EMStagePatches2_$ORACLE_SID and restart your OEM if nothing bad happens i think is fine ti assume that is just a staging folder for the uploaded patches


text:
Q: Require 2 decimal places in text input with jQuery validation I'm building a payment form and using jQuery validate to perform my validation. How can I validate the "Payment Amount" field only if it has 2 decimal places? I want it to fail if the user leaves off the .00 on the amount.
Here's my Javascript:
$(document).ready(function () {

    $('#payment-form').validate({ // initialize the plugin
        rules: {
            order_id: {
                required: true
            },
            price: {
                required: true,
                number: true
            }
        },
        messages: {
            order_id: "Please enter your Invoice Number",
            price: "Please enter Payment Amount"
        },
        submitHandler: function (form) { // for demo
            alert('valid form submitted'); // for demo
            return false; // for demo
            //form.submit();
        }
    });

    $('#price').keypress(function(event) {
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }
        if(     ($(this).val().indexOf('.') != -1) &&   ($(this).val().substring($(this).val().indexOf('.'),$(this).val().indexOf('.').length).length>2 )         ){
            event.preventDefault();
        }
    });

});

And my HTML:
<form id="payment-form" class="user-forms" method="post">

    Invoice Number*
    <input class="text-input" name="order_id" type="text" id="order_id" value="">

    Payment Amount*
    <input class="text-input" name="price" type="text" id="price" value="">
    You must enter an amount to 2 decimal places (i.e. 19.00)

    <input type="hidden" name="cust_id" value="<?php echo $current_user->user_firstname . ' ' . $current_user->user_lastname; ?>">
    <input type="hidden" name="email" value="<?php echo $current_user->user_email; ?>">
    <input name="finalize_payment" type="submit" id="finalize_payment" class="submit button btn btn-blue" value="Finalize Payment">

</form>

Thanks in advance!

A: You must create a custom rule using the .addMethod() method.
jQuery.validator.addMethod("dollarsscents", function(value, element) {
    return this.optional(element) || /^\d{0,4}(\.\d{0,2})?$/i.test(value);
}, "You must include two decimal places");

DEMO:  http://jsfiddle.net/w62Fb/
$(document).ready(function () {

    jQuery.validator.addMethod("dollarsscents", function(value, element) {
        return this.optional(element) || /^\d{0,4}(\.\d{0,2})?$/i.test(value);
    }, "You must include two decimal places");

    $('#payment-form').validate({ // initialize the plugin
        rules: {
            order_id: {
                required: true
            },
            price: {
                required: true,
                number: true,
                dollarsscents: true
            }
        },
        // other options, etc.
    });

});

Otherwise, to validate "dollars and cents", you might want to use the currency method that's already part of the additional-methods.js file.  It validates two decimal places and you can toggle the symbol.
price: {
    required: true,
    currency: ['$', false] // false = dollar symbol not required
}

DEMO 2:  jsfiddle.net/jz5xLeu1/

A: May be It's too late to answer but this could help someone.
Please check this Jsfiddle

<input type="text" class="number"/>

 $('.number').keypress(function(event) {
  if ((event.which != 46 || $(this).val().indexOf('.') != -1) &&
    ((event.which < 48 || event.which > 57) &&
      (event.which != 0 && event.which != 8))) {
    event.preventDefault();
  }

  var text = $(this).val();

  if ((text.indexOf('.') != -1) &&
    (text.substring(text.indexOf('.')).length > 2) &&
    (event.which != 0 && event.which != 8) &&
    ($(this)[0].selectionStart >= text.length - 2)) {
    event.preventDefault();
  }
});

This solution is from JQuery allow only two numbers after decimal point


text:
Q: Using SQL Server temp tables in ColdFusion ColdFusion uses #'s to delineate variables. In SQL Server a table name with # or ## is temp table and a global temp table respectively. How does one use SQL Temp tables in ColdFusion?

A: ColdFusion treats shows ## as a single # in the output. Hence
<cfquery name="qryTempUser">
SELECT *
FROM   ##tempUsers
WHERE  Active_CODE = 1
</cfquery>

is pulling from a temp table called #tempUsers
<cfquery name="qryTempUser">
SELECT *
FROM   ###myTableName#
WHERE  Active_CODE = 1
</cfquery>

is pulling from a  temp table called that is specified in a ColdFusion variable called myTableName
<cfquery name="qryTempUser">
SELECT *
FROM   ####tempUsers
WHERE  Active_CODE = 1
</cfquery>

is pulling from a global temp table called ##tempUsers
<cfquery name="qryTempUser">
SELECT *
FROM   #####myTableName#
WHERE  Active_CODE = 1
</cfquery>

is pulling from a global temp table called that is specified in a ColdFusion variable called myTableName

A: Another alternative is to use stored procedures.  You have to write all that t-sql somewhere and a stored procedure might make it easier for you.


text:
Q: Fragmentation and action bar sherlock I am using sherlock action bar API  for action bar implementation,My problem is
I am using fragmentation in android.my main activity class is using more then 3
fragments to display things now I need to access that action bar in every fragment
but whenever I moved from main activity to any other fragments action bar is not
accessible there. when ever I call any action it gives my null pointer exception kindly need your help.

A: Be sure that other fragments are extending SherlockFragment
And then call this method:
this.getSherlockActivity().getSupportActionBar().setTitle(TheString);

A: if I understand the question, you need to reach the actionbar from the fragment inside an activity. So once you reach the activity from the fragment, from there you can get the  actionbar. say that you need to set the title:
from the fragment (it should be a SherlockFragment) do the following
getSherlockActivity().getSupportActionBar().setTitle(theTitle);


text:
Q: Why is perspective not applied to the children of the container? I'm making a 3D floorplan with 4 floors and want to apply the same perspective to all floors. That turns out to be a problem.
For unrelated reasons, I have to put wrappers around the divs that will contain the actual floor plan images. The structure looks like this:

The difference between getting perspective from a parent and from an individual's own stacking context is demonstrated on this codepen: https://codepen.io/HugoGiraudel/pen/JImvb
It seems that the wrappers (div.floor) in my example introduce new stacking contexts, creating perspective for each floor individually. This makes the .plan div inside each .floor div to get perspective with its own set of perspective lines. I need all .plan divs to get the same perspective and not just inherit the property from .map.
Here's the code with the issue: https://codepen.io/kslstn/pen/OzMQjO
The relevant SCSS lines are (I think):
.map{
  position: relative;
  z-index: 1;
  perspective: 90px;
}

.floor{
  position: relative;
  transition: padding ease-in 300ms;

  &.active{

    .plan{
      transform: translateX(120px) translateY(-100px) rotateX(45deg) rotateY(0deg) rotateZ(20deg);
    }
  }
  }
  .plan{
    transform: perspective(900px) translateX(120px) translateY(-100px) translateZ(0px) rotateX(60deg) rotateY(0deg) rotateZ(60deg);
    transition: all ease-in 300ms;
  }
}

.floor:nth-child(1) .plan{
    z-index: 40;
}
.floor:nth-child(2) .plan{
    z-index: 30;
}
.floor:nth-child(3) .plan{
    z-index: 10;
}
.floor:nth-child(4) .plan{
    z-index: 0;
}

As you can see, .floor has position: relative, but no own z-index. According to MDN that should not create a new stacking context.

A: The wrapper divs (.floor) need:

  transform-style: preserve-3d;

https://developer.mozilla.org/en-US/docs/Web/CSS/transform-style


text:
Q: Techniques for XSLT exception handling As of XSLT 2.0, as far as I know (correct me if I'm wrong), there's no native mechanism in the language for exception handling.
I have some stylesheets that attempt to do some processing on specified chunks of an input document, copying everything else unaltered. There are rare exceptional conditions that I can't easily detect before I start producing output for a given chunk. These are rare enough that when I encounter them, all I want to do is cancel processing on this chunk and emit it unaltered. Some sort of exception handling is in order, but XSLT doesn't help very much. I don't want to get Java or another language into the mix here.
I have a workable solution described below, but I'm wondering about other approaches. Do you all have a better way of doing something like this?
Here's an example of the sort of scenario I'm talking about. Here's an input document:
<doc>
    <block>some text, just copy.</block>

a	b	c

b	a	c

b	c	a

    <block>some more text, just copy.</block>

a	b	c

b	a	x

b	c	a

</doc>

I want to look through each table and replace all cell values 'a' with 'B'. However, if there's an 'x' somewhere in the table, I want to just copy the table unmodified. I know that in this case, I could just do a tr/td[.='x'] test on the table to discover this condition. In the real case, though, it's not so easy to test ahead of time for the condition.
Here's some XSLT that doesn't account for the exception:
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="table">
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:apply-templates mode="inner"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template mode="inner" match="td">
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:choose>
                <xsl:when test=". = 'a'">
                    <xsl:value-of select="'B'"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="."/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:copy>
    </xsl:template>

    <xsl:template mode="inner" match="@*|node()" priority="-10">
        <xsl:copy>
            <xsl:apply-templates mode="inner" select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="@*|node()" priority="-10">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

The output of that is:
<doc>
    <block>some text, just copy.</block>

B	b	c

b	B	c

b	c	B

    <block>some more text, just copy.</block>

B	b	c

b	B	x

b	c	B

</doc>

It did the substitutions in the second table, which I don't want.
My current solution is to do this:

*

*Emit each table into a variable instead of directly into the output

*If the exception occurs, emit an <EXCEPTION/> tag

*After each table is processed, look through the variable for the <EXCEPTION/> tag.

*If the exception happened, copy the original table, else copy the contents of the variable.

Here's the modified code:
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="table">
        <xsl:variable name="result">
            <xsl:copy>
                <xsl:copy-of select="@*"/>
                <xsl:apply-templates mode="inner"/>
            </xsl:copy>
        </xsl:variable>
        <xsl:choose>
            <xsl:when test="$result//EXCEPTION">
                <xsl:copy-of select="."/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy-of select="$result"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

    <xsl:template mode="inner" match="td">
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:choose>
                <xsl:when test=". = 'a'">
                    <xsl:value-of select="'B'"/>
                </xsl:when>
                <xsl:when test=". = 'x'">
                    <EXCEPTION/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="."/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:copy>
    </xsl:template>

    <xsl:template mode="inner" match="@*|node()" priority="-10">
        <xsl:copy>
            <xsl:apply-templates mode="inner" select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="@*|node()" priority="-10">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

And the correct output:
<doc>
    <block>some text, just copy.</block>

B	b	c

b	B	c

b	c	B

    <block>some more text, just copy.</block>

a	b	c

b	a	x

b	c	a

</doc>

A: If you can wait for XSLT 2.1 there will then be try/catch expressions

A: The example provided is very simple and doesn't need any exception-handling capabilities.
The mode attribute is your friend:
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:output omit-xml-declaration="yes"/>

 <xsl:template match="node()|@*" mode="#default copy">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*" mode="#current"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="table[tr/td[.='x']]">
  <xsl:apply-templates select="." mode="copy"/>
 </xsl:template>

 <xsl:template match="td/text()[.='a']">B</xsl:template>
</xsl:stylesheet>

when this transformation is applied on the provided XML document:
<doc>
    <block>some text, just copy.</block>

a	b	c

b	a	c

b	c	a

    <block>some more text, just copy.</block>

a	b	c

b	a	x

b	c	a

</doc>

the wanted, correct result is produced:
<doc>
    <block>some text, just copy.</block>

B	b	c

b	B	c

b	c	B

    <block>some more text, just copy.</block>

a	b	c

b	a	x

b	c	a

</doc>

In case exceptions are really needed (we need yet to see a good use-case), they will be standard in XSLT 3.0.


text:
Q: Hide div only when scroll is not available on page I'm trying to hide a div but only when the page is showing 100%, I'm trying to do this since I've added a ScrollToTop and ScrollToBottom button to the page, this page has a list of servers that you can toggle to only show Offline servers but not the online ones, in case the list is so small that the page is fully shown (so no scroll bar is present)
Is it possible to hide a div only when scroll isn't possible or not?

  ▲
  ▼

Should only be visible if the page is scroll-able (all i.e. 200 servers are shown), but if this button is pressed:

Toggle Deployments

only i.e. 3 servers are shown, so everything on the website fits on screen (no scroll bar)
The wrapper should be hidden too.
View all servers
View only offline

A: Do you mean something like this
if($(document).height() <= $(window).height()) {
    $('div').hide()
}


text:
Q: Programatically Pin\UnPin the folder from quick access menu in windows 10 I have a desktop application written in c#, and this application enables users to create the folder on their machine Hard drive . on windows 7 and 8, The App creates a shortcut for this folder under Favorit menu on the left side of windows Explorer window.
In windows 10 there is no Favorite menu, it was replaced by Quick access menu, and if you right click on the folder you can choose to Pin folder for quick access.
To do this  programmatically from inside c# code, I found a .exe that can execute the Pin action as if the user clicked on the menu item to pin the folder
I got it from here  http://www.maddogsw.com/cmdutils/
The problem is this exe does not contain an option for Unpin the folder from quick access so i will not be able to remove the shortcut from the quick access menu unless if I deleted it and I don't want to do that.
I tried to find the shortcut file and I found it in this path
%AppData%\Windows\Recent\AutomaticDestinations
but there is no mapping between this file shortcut and the file itself. and at the same time when I delete the files from this path, all the Pinned folders shortcut delete from the quick access not only my shortcut.
anyone can help in this ??
Do I need to know if there is any command that I can use it to Pin\Unpin folders to quick access from the command prompt?

A: I know it's a bit late, but I've found a way to do it and thought maybe someone could still use this.
So as was mentioned by Bradley Uffner, there is no API for this to avoid the constant abuse of such APIs. But there is still a (rather ugly) way to do it!
I'm no expert in PowerShell, but I found a way to do it using PowerShell:
# To add 'C:\path\to\folder' to quick access:
$qa = New-Object -ComObject shell.application
$qa.NameSpace('C:\path\to\folder').Self.InvokeVerb("pintohome")

# To remove 'C:\path\to\folder' from quick access:
($qa.Namespace("shell:::{679F85CB-0220-4080-B29B-5540CC05AAB6}").Items() | Where-Object { $_.Path -EQ 'C:\path\to\folder' }).InvokeVerb("unpinfromhome")

Which finally led me to the solution using C#:
using System.Management.Automation;
using System.Management.Automation.Runspaces

private static void AddFolderToQuickAccess(string pathToFolder)
{
    using (var runspace = RunspaceFactory.CreateRunspace())
    {
        runspace.Open();
        var ps = PowerShell.Create();
        var shellApplication =
            ps.AddCommand("New-Object").AddParameter("ComObject", "shell.application").Invoke();
        dynamic nameSpace = shellApplication.FirstOrDefault()?.Methods["NameSpace"].Invoke(pathToFolder);
        nameSpace?.Self.InvokeVerb("pintohome");
    }
}

private static void RemoveFolderFromQuickAccess(string pathToFolder)
{
    using (var runspace = RunspaceFactory.CreateRunspace())
    {
        runspace.Open();
        var ps = PowerShell.Create();
        var removeScript =
            $"((New-Object -ComObject shell.application).Namespace(\"shell:::{{679f85cb-0220-4080-b29b-5540cc05aab6}}\").Items() | Where-Object {{ $_.Path -EQ \"{pathToFolder}\" }}).InvokeVerb(\"unpinfromhome\")";

        ps.AddScript(removeScript);
        ps.Invoke();
    }
}

NOTE: For this to work, you need to add a reference to System.Management.Automation which can easily be obtained as a nuget.


text:
Q: Question about SVD proof from Trefethen and Bau In Trefethen and Bau's proof of the SVD (see image below), they start by defining the following:
$$
U_1^* A V_1 = \begin{bmatrix} \sigma_1 & w^* \\ 0 & B \end{bmatrix}
$$
I understand the setup until this point, and I think I understand (broadly) how the proof proceeds: show that $w^* = 0$, then by the induction hypothesis, show that $B$ has the same structure, and so on.
What I don't understand is  the block matrix above: why is the bottom-left element known to be zero, but the top right element isn't? Why don't we need to prove that the bottom left element is also 0?

A: We have constructed the bases so that $Av_1 = \sigma_1 u_1$.
It follows that the first column of $U_1^*AV_1$ is
$$
(U_1^*AV_1)e_1 = U_1^*A(V_1e_1) = U_1^*Av_1 = U_1^* (\sigma_1 u_1) = \sigma_1 e_1
$$
where I have used $e_1$ to denote the first standard basis vector, $e_1 = (1,0,\dots,0)^T$.


text:
Q: Query to find the percentage difference of each row in sql server I have a table with some columns in it. I would like to write a query that iterates through each row and find the total count of all rows that match a column in the selected row and also find the count of all rows that match 2 columns. With these 2 values, I would like to find the percentage difference and print them as column1, percentage(query1(column2)/query2(column2 and column3)).
Below is the query which I wrote
    SELECT DISTINCT (t2.column1)
    ,(
        SELECT count(DISTINCT column2)
        FROM table1 t1
        WHERE t1.column1 = t2.column1
        ORDER BY column2
        ) AS total_count
    ,(
        SELECT count(DISTINCT column2)
        FROM table1 t1
        WHERE t1.column1 = t2.column1
            AND column3 IN (
                10
                ,20
                )
        ORDER BY column1
            ,column2
            ,column3
        ) AS column3_count
FROM table1 t2;

The above query works but takes a lot of time to process.
I want it as
   SELECT DISTINCT (column1)
    ,percentage(query1 that matches ALL rows WITH column1 / query2 that match ALL rows WITH column1
        AND SOME other CONSTRAINT)
FROM TABLE t1

I would like to optimize the above query too. Please let me know
Thanks

A: I think you just want conditional aggregation.  For the counts:
select t1.column1,
       count(distinct column2) as num_column2,
       count(distinct case when column3 in (10, 20) then column2 end) as num_column2_column3
from table1 t1
group by t1.column1;

I don't understand the calculation for the percentage, but it would seem to be based on these numbers.

A: select t1.column1,
       count(distinct column2) as num_column2,
       count(distinct case when column3 in (10, 20) then column2 end) as num_column2_column3
from table1 t1
group by t1.column1;


text:
Q: Displaying records from database which are equal to logged on user I have created an MVC3 application which needs to show user specific data. The problem I am having is trying to display records which are equal to @user.Identity.Name.
The following Linq to SQL has been used to try to accomplish this:
        public ActionResult Index()
    {

        using (var db = new mydatEntities())
        {
            var details = from t in db.testadtas
                          where t.UserID ==  Viewbag.UsersRecord
             select t;

            return View();
        }

    }

(Update)
New to c# and Linq and finding it hard to write a query which will only display the logged on users records.
I have used the code below
 MembershipUser currentUser = Membership.GetUser  (User.Identity.Name, true /*   userIsOnline */);

Viewbag.UsersRecord = currentUser.ProviderUserKey;

I have then input the Viewbag.UserRecord into a textbox which updates a database field with the UserID in a table I have created.
I now want to write a linq query to say if UserID = Viewbag.UserRecord then show record with the UserID only
Is this a correct method to use for showing logged on user records?
or is there any other way which I can implement this in MVC3?

A: Just use HttpContext.User.Identity.Name


text:
Q: Data validation on Realtime Database I'm trying to do a simple validation as a test but it's not working, I think I didn't get the syntax. the idea is to store an email on the db, so the first test that i'm trying is to set the length as shown here:
{
  "rules": {
    ".read": false,
    ".write": true,
      ".validate": "newData.val().length <= 50"
  }
}

With this rules i get permission denied everytime, my db id structured like this, db>infos>random key>email, so I tried this and get the same result:
{
  "rules": {
    "infos": {
      "email": {
        ".write":true,
            ".validate": "newData.val().length < 50"
      }
    }
  }
}

What is the right way to do something like that?(I'm a beginner on web development in general)
On standard rules, when I enter some data on the website it gives me that on the database

Validation test 1:
 Denied on website and playground
Validation test 2
 Denied on website and passes on the playground

A: The first reject is expected, as you're writing a JSON object to the root and that doesn't have a length property.
Remember newData is the data as it exists at the location where the rule is defined, so in that case newData is your entire database. You'll typically want to define your rules on the level of the data you're validating, like in your second example.
Since the second example works in the playground, please edit your question to include the (standalone) code that doesn't work.


text:
Q: Select "intelligently" from a drop down list Trying an advanced search on the datalist
I have created a datalist like so:
<datalist id=attractions>
     <option value="India Agra Taj Mahal">
     <option value="India Delhi Red Fort">
     <option value="India Agra Red Fort">
     <option value="India Jaipur Jal Mahal">
     <option value="India Mathura Sheesh Mahal ">
</datalist>
<input id =places type=text list=attractions>

So when I type India Agra in the textbox the option values which will start with India Agra ie only two (1st and 3rd)
but if I type India Mahal it will be unable to search for anything. I would want to be returned the answers: 1, 4 and 5. they contain all the two words in order (India and Mahal)
Is there some  way to enable such a search more contextually rather than by the exact terms.
What else can be thought of
If I search Indiaahal then also it should give those places which has "India" and "ahal" contained in order. So it should show the outputs like both "India Agra Taj Mahal", "India Jaipur Jal Mahal" and "India Mathura Sheesh Mahal"
I believe:

*

*The solution proposed in the links below do not seem to correctly do what I want. My question is not about "contains" but more than just contains. It is about contains fragments at different locations.

*The solution given by @yash Shukla is close to what I was looking for.

A: Suppose you have a datalist like below :
<datalist id="locations">
  <option value="India taj mahal">
  <option value="India Qutub Minar">
  <option value="China gate">
</datalist>

Now you can select all option values and put them in an array like below :
var options = document.getElementById('locations').options;
var values = [];
for(var i=0; i<options.length; i++)
{
  values.push(options[i].value);
}

Now let's suppose your search term is India Minar, so you can build a search logic something like below :
var searchTerm = "India Minar";

var searchSplit = searchTerm.split(" ");

var availableSearches = [];

for(var i=0; i<values.length; i++) {
  for(var j=0; j<searchSplit.length; j++) {
    if(values[i].indexOf(searchSplit[j]) >= 0 &&
      availableSearches.indexOf(values[i]) < 0){
      availableSearches.push(values[i]);
    }
  }
}

console.log(availableSearches);
//["India taj mahal", "India Qutub Minar"]

This logic will search text with both India and Minar in the collection. If this is not exactly you are looking for, you can easily tweak logic.


text:
Q: How are euclidean rings and norms related? How could I link norms with euclidean rings?
Why is the norm 1 for invertible elements?
Why are there arbitrarily constant in fields?
Why are local PIDs euclidean (a more intuitive approach, since my text book doesn't explain this very well)?
Thankyou

A: This is the definition of Euclidian rings I know: It is a commutative integral domain with unity($1$) that we will denote $E$, where there exists a function $\phi$$:$ $E$ $\rightarrow$ $\Bbb Z$ satisfying
(1) If $a,b$ $\in$ $E$, and $a,b$ are nonzero, $a$ $\mid$ $b$, then $\phi(a)$ $\leq$ $\phi(b)$
(2) For $a,b$ $\in$ $E$, $a\neq 0$, there are elements $q,r$ $\in$ $E$ such that $b = aq + r$ and $\phi(r)$ $\lt$ $\phi(a)$
Such a function $\phi$ is what is what I mean by a norm. $\phi(0)$ has to be less than any other norm, because for any $a \neq 0$,we have that $a = aq + r$ for some $r,q \in E$ with $\phi(r)$ $\lt$ $\phi(a)$ which means that $a - aq$ $=$ $a(1-q)$ $=$ $r$, which means that $a \mid r$, which in turn means that $\phi(a)$ $\leq$ $\phi(r)$; a contradiction, unless $r = 0$. We have, in summary, $\phi(r) = \phi(0) $ $\lt$ $\phi(a)$.
That the norm of an invertible element (unit) is the same as the norm of $1$ in an Euclidian ring (domain):
Call the Euclidian ring $E$. Let the norm be $\phi$, let $a$ be invertible in $E$. Then for every element $\qquad$ $\,$ $b$ $\neq$ $0$ $\in$ $E$, $\phi$$(a)$ $\leq$ $\phi$$(b)$, since  a unit divides every element in any ring with $1$. Especially, $\phi (a)$ $\leq$ $\phi(1)$. But $1$ is also a unit [$1\ast1$ $=$ $1$], so  $\phi(1)$ $\leq$ $\phi(a)$. Therefore, $\phi(a)$ = $\phi(1)$ , since two numbers can't both be greater than the other number.
Constant norm in a field:
In a field you could define the norm to be $1$ for each element except $0$, since every nonzero element in a field is a unit and therefore each one of them divides each other. By defining the norm of $0$ to be the number zero, you are assured of having a remainder with norm less than the norm of the element you "divide" with. Of course, you can let the norm of all the nonzero elements of the field be any constant $c$, as long as the norm of $0$ is less than this constant.
Local PIDs are euclidean
Before I go through a proof of this result, there are some things I will assume you know, and if you don't know these things, I expect you to look them up.
First of all, for a commutative ring $R$ with unity, every ideal in $R$ not equal to $R$ is contained in a maximal ideal. This is a consequence of Zorn's lemma. This in turn, means that every non-unit is contained in a maximal ideal, because the ideal generated by this non-unit is unequal to $R$; otherwise the non-unit would divide $1$. An element not contained in any maximal ideal must therefore be a unit.
I expect you to know what an $R$-module is, what it means for it to be finitely generated, and most importantly, this;
Nakayama's lemma: If $M$ is a finitely generated $R$-module, and $A$ is an ideal contained in the Jacobson-radical $\Bbb J$ of $R$, then $AM = M \implies M=0$. [The Jacobson-radical of $R$ is the intersection of all the maximal ideals in $R$].
Now for the good stuff:
A local PID is a PID with only one maximal ideal. Therefore, its Jacobson-radical is equal to this one ideal.
The fact that a field is a local PID I suspect you can deduce. $\{0\}$ is the maximal ideal and its generator is $0$.
I already provided a norm on fields. To show condition (2), let $a,b \in R$ ($R$ a field), $a \neq 0$. $b = a(a^{-1}b) + 0$. Now, $\phi(a) = 1, \phi(0) = 0$, so
$\phi(0) \lt \phi(a)$.
Let $R$ be a local PID. Let $pR$ be the only maximal ideal in $R$. For $a \neq 0$, define $\phi:R \to \Bbb N$ by $\phi(a) =n$ where $n$ is the first $n$ such that $a \notin p^nR$, and let $\phi(0) = 0$.
Are you missing something? No. We will have to prove that such an n exists for each nonzero element in $R$.
Let $M =\bigcap_{n=1}^{\infty}p^nR$. This is the intersection of all ideals $p^nR$, where $n \in \Bbb N$. Now, $pM \subseteq M$, because $M$ is an ideal, and $M \subseteq pM$, because $pM =\bigcap_{n=2}^{\infty}p^nR \supseteq \bigcap_{n=1}^{\infty}p^nR$.
In effect, $pM = M$, which means that $(pR)M = M$, since $RM = M$, since $1 \in R$. But $M$ is finitely generated, because every ideal in a PID is finitely generated (of the form $cR$). Because the ideal $M$ can be viewed as a module, and $pR$ is the Jacobson-radical, and therefore contained in itself, we have by Nakayama that $M = 0$.
What do we do with this? Well, $M = 0$ means that only $0$ is in every ideal of the form $p^nR$. So if $a \neq 0$, then $a$ can't be in $p^nR$ for all $n$. There must be a least such n by the well-ordering principle. We have confirmed that $\phi$ is well-defined.
Do we have an Euclidean norm though? Let $a$ be a unit. Then $a \notin pR$, so $\phi(a) = 1$, and for $b \neq 0$ we clearly have $\phi(b) \geq \phi(a)$.
Anyway, let $a \neq 0, b \neq 0$. Further, let $\phi(a) = m+1$, and let $\phi(b) = n+1$. Then $a = p^mr$ for $m \in \Bbb N$ (or $m = 0$)and $r \in R$. We have $b= p^ns$ for $n \in \Bbb N$ (or $n = 0$) and $s \in R$. Let $p^0$ mean $1$.
$a \mid b$ means $p^mr \mid p^ns$. Then $m \gt n$ gives us $p^{m-n}r \mid s$ $\implies$ $b = p^np^{m-n}rk$ for some $k \in R$, which is basically saying that $b = p^mrk$, but $b$ can't be in $p^mR$, because $p^mR \subseteq p^{n+1}R$. Therefore, $\phi(a) \leq \phi(b)$
Property (2): Let $a, b \in R, a \neq 0$. Let $\phi(a) = n$. We have $a = p^{n-1}u$, where $u$ is a unit. If $u$ wasn't, it would have to be in pR [in a local ring, every element outside the maximal ideal is a unit], say $u = pr$, and we get $a = p^{n-1}pr = p^nr$; a contradiction.
So now, if $\phi(b) \lt n$, consider $b = a\cdot0 + b$. This is in accordance with (2). If $\phi(b) \geq n$, then $b = p^mx$ for some $x$ in $R$ and $m \in \Bbb N \cup 0$, where $m \geq n-1$, which means that $b$ is also of the form $p^{n-1}y$. We see that $b = au^{-1}y + 0 = p^{n-1}u \cdot u^{-1}y = p^{n-1}y = b$.
Of course, $\phi(0) \lt \phi(a)$ when $a \neq 0$.
It seems to me that property (2) is the only thing that requires there to be only one maximal ideal. The maximal ideal in a field is the $0$-ideal, generated by $0$, that is, let $p=0$ and write $0 = 0 \cdot R$. Now, any nonzero elements are not in this ideal, so their norm would all be $1$.


text:
Q: SQL merging two cells into one (much like & in excel) Could you please help me how to merge two cells into one?
For example, table1 has column A and column B

And I want to extract data as below

Please help, thank you very much!

A: SELECT CONCAT(A, B) AS combined FROM table1


text:
Q: How to run a function each time I hit enter in the Python shell I sometimes write small functions at the interactive shell.
They very rarely are correct the first time, so I spend a lot of time running the versions of my function on the same testset to verify correctness.
>>> def test_foo():
        print( foo(4) == 5 )
        print( foo(8) == 9 )
>>> def foo(x): return x + 1
>>> test_foo()
True
True

But foo may be more complicated and I may need 5 or more rewritings to get it to pass my tests, as running the suite manually is boring, I need something like this:
>>> def test_foo():
        print( foo(4) == 5 )
        print( foo(8) == 9 )
>>> :SET_ON_EXECUTION test_foo

And now each time I rewrite my foo function and send it to definition the test will be run too.
Some research

*

*Searching Google gives no useful answer.

*In the shell python -h does not tell me how to do this.

*Neither does %quickref in  'ipython, `.

A: You could edit your code in an editor and run your tests in a terminal using a file watcher, resulting in your tests being run every time you save the code or test files.
For information on how to run a command whenever a file changes (file watcher), see the answers on this question: https://superuser.com/questions/181517/how-to-execute-a-command-whenever-a-file-changes

A: I would strongly recommend using Jupyter notebooks (previously known as IPython) for this. It allows you to create a 'cell' containing code which you can re-execute with Ctrl-Enter key combination.
For example in your case you could put the function definition and the execution in the same cell and then easily re-execute it as you edit.

In this way you can gradually build up your code, fixing and developing a single function at a time.
As you already have IPython installed you should be able to get up and running with:
$ pip install jupyter
$ jupyter notebook

It will launch in your browser. Create a new notebook by clicking 'New' in the upper-right and selecting one of the Python kernels under 'Notebooks'.

A: Since you're using ipython, you can just create a whatever.py file containing the code you want to run on startup, and then run ipython via ipython whatever.py.
You can also run Python code by modifying your ~/.ipython/ipy_user_conf.py:

There should be a simple template ipy_user_conf.py file in your ~/.ipython directory. It is a plain python module that is imported during IPython startup, so you can do pretty much what you want there - import modules, configure extensions, change options, define magic commands, put variables and functions in the IPython namespace, etc. You use the IPython extension api object, acquired by IPython.ipapi.get() and documented in the "IPython extension API" chapter, to interact with IPython.

You can also place a file called ipythonrc in your current working directory:

As we've already mentioned, IPython reads a configuration file which can be specified at the command line (-rcfile) or which by default is assumed to be called ipythonrc. Such a file is looked for in the current directory where IPython is started and then in your IPYTHONDIR, which allows you to have local configuration files for specific projects. In this section we will call these types of configuration files simply rcfiles (short for resource configuration file).
execute : give any single-line python code to be executed.
execfile : execute the python file given with an execfile(filename) command. Username expansion is performed on the given names. So if you need any amount of extra fancy customization that won't fit in any of the above 'canned' options, you can just put it in a separate python file and execute it.


text:
Q: obtaining a substring with \directlua when original string contains %-character I want to implement in LaTeX a sort of function with two parameters

*

*a String containing a percentage e.g. "3.20 %"

*an integer, e.g. 2000
The result should be the product of both numbers (in this case 3.20)

I tried to achieve this with a \directlua command, but I didn`t get the trick to handle a string containing the special character "%".
I tried something like:
\documentclass[11pt,a4paper]{article}

\begin{document}
% I produce the LaTeX document such that the arguments to the calculation get filled in
% directly into the xxx.tex file. Yes I could fill in the value without

Input arguments are
\begin{itemize}
   \item percentage: 3.20 \%
   \item factor: 2000
\end{itemize}

The result is: \directlua{
        s=string.sub('3.20 \%', 1, -3)
        tex.sprint( s / 100 * 2000)
    }.
\end{document}

A: You can use \@percentchar
\documentclass[fontsize=11pt, paper=a4]{article}

\makeatletter
\let\pc\@percentchar
\makeatother

\begin{document}
% I produce the LaTeX document such that the arguments to the calculation get filled in
% directly into the xxx.tex file. Yes I could fill in the value without

Input arguments are
\begin{itemize}
   \item percentage: 3.20 \%
   \item factor: 2000
\end{itemize}

The result is: \directlua{s=string.sub('3.20 \pc', 1, -3) tex.sprint( s / 100 * 2000)}.
\end{document}

A: Instead of using the primitive instruction \luadirect, you could use the macro \luaexec, which is provided by the luacode package, to get the job done. Put differently, once the luacode package is loaded, all you need to do is replace \directlua{s=string.sub('3.20 \%', 1, -3)... with \luaexec{s=string.sub('3.20 \%', 1, -3)....

\documentclass[11pt,a4paper]{article}
\usepackage{luacode} % for \luaexec macro

\begin{document}
Input arguments are
\begin{itemize}
   \item percentage: 3.20 \%
   \item factor: 2000
\end{itemize}

The result is:
\luaexec{%
   s=string.sub('3.20 \%', 1, -3)
   tex.sprint( s * 2000 / 100 )
}.
\end{document}

A: Expert users appear to prefer using \directlua. If you don't understand the concept of category codes in TeX well, I'd recommend using luacode* environment to avoid surprises.
%! TEX program = lualatex

\documentclass{article}

\usepackage{luacode}

\begin{document}
% I produce the LaTeX document such that the arguments to the calculation get filled in
% directly into the xxx.tex file. Yes I could fill in the value without

Input arguments are
\begin{itemize}
   \item percentage: 3.20 \%
   \item factor: 2000
\end{itemize}

The result is:
\begin{luacode*}
s=string.sub('3.20 \\%', 1, -3)
tex.sprint( s / 100 * 2000)
\end{luacode*}
.
\end{document}

An alternative is
The result is: \luaexec{ s=string.sub('3.20 \\\%', 1, -3) tex.sprint( s / 100 * 2000) }.

Refer to the documentation of luacode package for details.
Another alternative is (not recommend because of surprises)
The result is: \directlua{ s=string.sub([[3.20 \%]], 1, -3) tex.sprint( s / 100 * 2000) }.

This will pass literally [[3.20 \%]] to Lua, which is valid Lua code because \ inside [[ ... ]] are not processed.

A: The subject of your question is:
"obtaining a substring with \directlua when original string contains %-character"
\directlua on the TeX-side processes a piece of ⟨general text⟩, i.e., a set of TeX-tokens.
\directlua is as if the tokens belonging to the ⟨general text⟩ are expanded by TeX and the set of tokens resulting from expansion are written to an external text file by TeX according to TeX's rules for writing tokens to external text files. Then that external text file is fed as input-file to a Lua interpreter. The Lua interpreter probably creates output and probably passes that output to TeX. The Lua interpreter can pass its output to TeX via routines like tex.sprint which insert characters into TeX's mouth. The Lua interpreter can also pass its output to TeX via routines like token.put_next(token.create(...)...) which append TeX-tokens to TeX's token stream which in turn begins in TeX's gullet.
Where is your focus when referring to "original string"? On the .tex-input-file? On the TeX-side? On the Lua-side?
To me it seems you are struggling with bringing percent-characters into the argument of the \directlua-directive while the only purpose of bringing them in is giving string.sub the opportunity of removing them.
Why not just \directlua{tex.sprint( 3.20 / 100 * 2000)}?  (The number 3.20 could as well be provided as a macro argument.)
In case you wish to know about methods for having the TeX-side pass characters which are special on the side of TeX as ordinary characters to the Lua-side, the following approach might be of interest to you:
Expl3 comes along with a fully expandable routine \cs_to_str:N which delivers the name of a control-sequence-token without leading escape character (usually backslash) by triggering two expansion-steps to \cs_to_str:N.
You can use this for obtaining a character token from the corresponding control symbol token. (With the following example \cs_new_eq:NN is used for giving the control word token \GetCsName the same meaning as  the control word token \cs_to_str:N.)
This way you can obtain special characters other than % as well as long as the corresponding control symbol token is not \outer.
This way ensuring that TeX supplies a sequence of characters that are properly understood by Lua and conform to Lua's syntax , e.g., escaping characters that in Lua need to be escaped, is still up to you.
You might be interested in combining usage of \GetCsName/\cs_to_str:N with \luaescapestring (=\luatexluaescapestring with less recent LaTeX releases) or \luastring/\luastringN/\luastringO from the package luacode.
\documentclass[11pt, a4paper]{article}

\ExplSyntaxOn \cs_new_eq:NN \GetCsName \cs_to_str:N \ExplSyntaxOff

\begin{document}

Let's use the Lua-backend for printing TeX's special characters:

\directlua{
  tex.sprint(
     '\\verb*|%
                \GetCsName\}%
                \GetCsName\ %
                \GetCsName\$%
                \GetCsName\&%
                \GetCsName\#%
                \GetCsName\^%
                \GetCsName\_%
                \GetCsName\%%
                \GetCsName\~%
                \GetCsName\{%
                \GetCsName\\\GetCsName\"% Double quote must be escaped in Lua-string
                \GetCsName\\\GetCsName\'% Single quote must be escaped in Lua-string
                \GetCsName\\\GetCsName\\% backslash must be escaped in Lua-string
             |'
  )
}

\end{document}

Alternatively you can use expl3's \char_generate:nn for creating explicit character tokens of category 12(other):
\documentclass[11pt, a4paper]{article}

\ExplSyntaxOn \cs_new:Npn \CreateOtherChar #1 { \char_generate:nn {`#1} {12} } \ExplSyntaxOff

\begin{document}

Let's use the Lua-backend for printing TeX's special characters:

\directlua{
  tex.sprint(
     '\\verb*|%
                \CreateOtherChar\}%
                \CreateOtherChar\ %
                \CreateOtherChar\$%
                \CreateOtherChar\&%
                \CreateOtherChar\#%
                \CreateOtherChar\^%
                \CreateOtherChar\_%
                \CreateOtherChar\%%
                \CreateOtherChar\~%
                \CreateOtherChar\{%
                \CreateOtherChar\\\CreateOtherChar\"% Double quote must be escaped in Lua-string
                \CreateOtherChar\\\CreateOtherChar\'% Single quote must be escaped in Lua-string
                \CreateOtherChar\\\CreateOtherChar\\% backslash must be escaped in Lua-string
             |'
  )
}

\end{document}

A: It's possible to use \directlua: \luastring does the magic.
Perhaps someone out there has a nice explanation why this works.
Every comment why this is working and if there are pros or cons for this approach are welcome.
\documentclass[11pt,a4paper]{article}

\usepackage{luacode} % for the use of \luastring

\begin{document}

Input arguments are
\begin{itemize}
    \item percentage: 3.20 \%
    \item factor: 2000
\end{itemize}

The result is: \directlua{
    s=\luastring{3.20 \%}
    s = string.sub(s, 1, -3)
    tex.sprint( s / 100 * 2000)}.
\end{document}


text:
Q: How would I access the Windows Login (Authentication) API from a C++ Service Application? Let us imagine for a moment that I have a piece of hardware that can act as an authentication for a user on a given system. I want to write an application in C++ to run as a service, look for this device and if found log the appropriate user in. I believe I have found the API's I would need to use to perform the hardware and service portions of the application but am having a hard time nailing down a way to create a "real" user login. Is this possible? If so where would I look to find resources on accomplishing this? I think of it as being an analog to fingerprint scanner login type devices.

A: I think you are probably looking for the GINA ("Graphical Identification aNd Authentication) APIs. There is a good tutorial here.

A: If you are looking for an API to validate the credentials, here is one way..
Public Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String],
ByVal lpszDomain As [String], ByVal lpszPassword As [String], _
ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
ByRef phToken As IntPtr) As Boolean

Here is the full code ->  http://codingforpassion.blogspot.com/2011/07/windows-logon-api-for-net.html
Thanks,
Srikanth.V


text:
Q: I can't use django in coderunner 2 I have been trying to import and use django in python, and it cant import any modules I installed via pip.
When I downloaded django on the command line it said in anaconda which was outside my user. So I tried to put it in my user d=and see if that would help but it didn't.


text:
Q: Reset Combo-box C# WP 8.1 my problem is that i don't know how to reset a combo-box to it's default value choose an item, after clicking a button.
I only found the following code, but it erases all the items of tha combo-box which is not what i want!

myCombo1.Items.Clear();

Also, is it possible to create an instance of MainPage and use it in navigation function?

Frame.Navigate(typeof(MainPage));

A: This should do the trick:
myCombo1.SelectedIndex = -1;

A: Use simplly clear() method :
ComboBoxName.Clear();.


text:
Q: How to store image preview of PDF page to disk on non-UI thread? I'm trying to create a thumb preview of a PDF's pages and store them on disk as PNGs. This is supposed to run in a separate thread and not on the UI thread.
To achieve this I'm using CGContextRef to draw the PDF page, then get a CGImage from it, convert that to a UIImage, get a PNG from it (which will be NSData) and save that NSData to disk. All clear so far.
However CGImage and UIImage are a UI elements and should not be used on another thread - but I don't want to bring that image on screen ever. Is it okay to use them on another thread in that case? Or is there another way to render a PDF page preview directly to disk?

A: UIKit is generally not thread safe (some calls are but it's very badly documented). OTOH CoreGraphics is thread safe. So avoiding UIImage and using only CGImage is the safest way to do image processing in a background thread.
See Saving CGImageRef to a png file? to save an CGImageRef as a PNG file.