text:
Q: How to avoid 502 Bad Gateway with Nginx + Rails + Unicorn? I have same 502 errors everyday, but can't find reason of that.
2014/12/22 16:33:03 [error] 1697#0: *331 upstream prematurely closed connection while reading response header from upstream, client: 105.121.243.92, server: server01.domain.com, request: "GET /doco/in_documents HTTP/1.0", upstream: "http://unix:/tmp/unicorn.docs.sock:/doco/in_documents", host: "go.domain.com:443"
2014/12/22 16:33:05 [error] 1697#0: *331 connect() failed (111: Connection refused) while connecting to upstream, client: 105.121.243.92, server: server01.domain.com, request: "GET /doco/in_documents HTTP/1.0", upstream: "http://10.213.0.46:80/doco/in_documents", host: "go.domain.com:443"
2014/12/22 16:33:09 [error] 1697#0: *334 upstream prematurely closed connection while reading response header from upstream, client: 10.212.255.3, server: server01.domain.com, request: "GET /doco/in_documents HTTP/1.1", upstream: "http://unix:/tmp/unicorn.docs.sock:/doco/in_documents", host: "server01.domain.com"
2014/12/22 16:33:09 [error] 1697#0: *334 connect() failed (111: Connection refused) while connecting to upstream, client: 10.212.255.3, server: server01.domain.com, request: "GET /doco/in_documents HTTP/1.1", upstream: "http://10.213.0.46:80/doco/in_documents", host: "server01.domain.com"
2014/12/22 16:33:15 [info] 1697#0: *333 client closed connection while waiting for request, client: 10.212.255.3, server: 0.0.0.0:80
2014/12/22 16:33:15 [info] 1697#0: *335 client closed connection while waiting for request, client: 10.212.255.3, server: 0.0.0.0:80
2014/12/22 16:33:15 [info] 1697#0: *336 client closed connection while waiting for request, client: 10.212.255.3, server: 0.0.0.0:80
2014/12/22 16:33:15 [info] 1697#0: *338 client closed connection while waiting for request, client: 10.212.255.3, server: 0.0.0.0:80
2014/12/22 16:33:15 [info] 1697#0: *337 client closed connection while waiting for request, client: 10.212.255.3, server: 0.0.0.0:80
2014/12/22 16:33:17 [info] 1697#0: *334 epoll_wait() reported that client prematurely closed connection, so upstream connection is closed too while sending request to upstream, client: 10.212.255.3, server: server01.domain.com, request: "GET /doco/in_documents HTTP/1.1", upstream: "http://unix:/tmp/unicorn.docs.sock:/doco/in_documents", host: "server01.domain.com"
2014/12/22 16:33:19 [info] 1698#0: *343 epoll_wait() reported that client prematurely closed connection, so upstream connection is closed too while sending request to upstream, client: 105.121.243.92, server: server01.domain.com, request: "GET /doco/in_documents HTTP/1.0", upstream: "http://unix:/tmp/unicorn.docs.sock:/doco/in_documents", host: "go.domain.com:443"
2014/12/22 16:33:35 [info] 1698#0: *347 client closed connection while waiting for request, client: 10.212.255.3, server: 0.0.0.0:80
2014/12/22 16:33:35 [info] 1698#0: *346 client closed connection while waiting for request, client: 10.212.255.3, server: 0.0.0.0:80

Any ideas how to avoid this? I tried different ways from another questions but it has no effect.

A: According to your error log and the returned status(502), one thing is sure that your upstream server didn't give back a response. I suggest you check your upstream configuration, the address, the port, or something else.


text:
Q: Dúvida sobre Expressão Regular Boa noite a todos.
Gostaria de saber de uma expressão regular para obter as seguintes informações:
Numeração e título de um capítulo.
Exemplo:

*

*INTRODUÇÃO

número = 1.
título = INTRODUÇÃO
1.1. OBJETIVO GERAL
número = 1.1.
título = OBJETIVO GERAL
1.2. OBJETIVO ESPECÍFICO
número = 1.2.
título = OBJETIVO ESPECÍFICO
Preciso disso para gerar um sumário no seguinte formato:

*

*|  INTRODUÇÃO         | PÁGINA

1.1. | OBJETIVO GERAL      | PÁGINA
1.2. | OBJETIVO ESPECÍFICO | PÁGINA
Ou seja, a expressão regular deverá ser capaz de reconhecer números seguido de pontos, no seguinte formato genérico:
Título Primário => x.
Título Secundário => x.x.
Título Terciário => x.x.x.
Título Quaternário => x.x.x.x.
E assim por diante.
Desde já agradeço a atenção. Abraço a todos.

A: Essa expressão regular aqui resolve:
"^\s*?(?P<numero>(\d\.)+)\s*(?P<titulo>.*)$"

Você não disse que ferramenta vai usar para aplicar a expressão regular - esta pode ter alguma coisa específica das expressões regulares de Python - onde testei a mesma. A documentação está em: https://docs.python.org/3/library/re.html
Num prompt interativo de Python 3.5:
In [47]: import re

In [48]: a = """
    ...: 1.INTRODUÇÃO
    ...: número = 1.
    ...:
    ...: título = INTRODUÇÃO
    ...:
    ...: 1.1. OBJETIVO GERAL
    ...:
    ...: número = 1.1.
    ...: título = OBJETIVO GERAL
    ...:
    ...: 1.2. OBJETIVO ESPECÍFICO
    ...:
    ...: 1.2.1. Detalhamento
    ...: 2. Outro Capítulo
    ...: """

In [49]: [(m.group('numero'), m.group('titulo')) for m in re.finditer(r"^\s*?(?P<numero>(\d\.)+)\s*(?P<titulo>.*)$", a, re.MULTILINE) ]
Out[49]:
[('1.', 'INTRODUÇÃO'),
 ('1.1.', 'OBJETIVO GERAL'),
 ('1.2.', 'OBJETIVO ESPECÍFICO'),
 ('1.2.1.', 'Detalhamento'),
 ('2.', 'Outro Capítulo')]

(A função re.finditer devolve um iterador de "match objects" - esses por sua vez tem um método group que pode ser chamado com o nome do grupo desejado. O nome dos grupos, por sua vez, é dado dentro da própria expressão regular, usando a construção (?P<nome>...) )
Essa parte dos nomes dos grupos deve ser a única coisa que muda caso a ferramenta de regexp que você for usar seja diferente das regexps de Python.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: maven sources plugin includes configuration I have a maven project with a non standard configuration:
$> tree
.
├── pom.xml
├── symbolic-link-to-sources -> ../src
└── target
    ├── maven-archiver
    │   └── pom.properties
    ├── project-1.0-SNAPSHOT-sources.jar
    ├── project-1.0-SNAPSHOT.jar
    └── surefire

I am trying to generate the sources jar of this maven module, whose sources are in ../src. I created a symbolic link to ../src in the case the plugin does not accept parent folders in paths. To do so I use the maven source plugin configured like this:
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-source-plugin</artifactId>
  <version>2.2.1</version>
  <configuration>
    <includePom>true</includePom>
    <includes>
      <include>symbolic-link-to-sources/**</include>
    </includes>
  </configuration>
</plugin>

I run this plugin with mvn source:jar. Unfortunately I get only pom.xml in my sources jar. If I set includePom to false the plugin does not create the source archive.
I tried a lot of things as <include>: ../src, ../src/**, ../**, symbolic-link-to-sources, symbolic-link-to-sources/**, ../**/*.java none of them get me my sources into my sources jar. Although the documentation about it say its a relative fileset pattern.
Any idea how to get the content the java files of the ../src folder into my sources jar?
(Yes my symbolic link is not broken, no there is no way to rearrange my modules to have a standard folder hierarchy, this is a wrapper project around an ant based project).

A: You would use the <includes property to specify files/patterns to include within the source folder.
Have you set <sourceDirectory> to the correct location of the source (symbolic link and so on)?   If so, can you omit the entire plugin configuration above and just run mvn source:jar on the pom?  It should generate the sources correctly.

A: Stuck with the same problem and after googling and trying finally came to this:
<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>build-helper-maven-plugin</artifactId>
  <executions>
    <execution>
      <phase>package</phase>
      <goals>
        <goal>add-source</goal>
      </goals>
      <configuration>
        <sources>
          <source>../common/src/main/java</source>
        </sources>
      </configuration>
    </execution>
  </executions>
</plugin>
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-source-plugin</artifactId>
  <executions>
    <execution>
      <id>attach-sources</id>
      <goals>
        <goal>jar</goal>
      </goals>
    </execution>
  </executions>
</plugin>

Where "../common/src/main/java" is a path to sources that are linked as symbolic link in the current project.
Please note that build-helper-maven-plugin has package phase. With phase generate-sources I was getting "duplicate class" since the same sources were added from the symbolic link dir and from the dir configured in build-helper-maven-plugin.


text:
Q: Displaying UTF-8 characters in a PlainTextEdit I'm trying to display Chinese characters encoded in UTF-8 in a PlainTextEdit control, but it doesn't render them properly.
My data comes from a database and I know that the string I get in Qt is correct (the bytes are the same as in the database). Once I have the Chinese character in a QString, I tried various things to display it but always results in either question marks or random ASCII characters:
QString chineseChar = query.value(fieldNo).toString(); // get the character

ui->plainTextEdit->appendPlainText(chineseChar); // doesn't work
ui->plainTextEdit->appendPlainText(chineseChar.toUtf8()); // doesn't work
ui->plainTextEdit->appendPlainText(QString::fromUtf8(chineseChar.toAscii()); // doesn't work

Any suggestion on how to handle that?

A: "My data comes from a database and I know that the string I get in Qt is correct (the bytes are the same as in the database)."
How did you check that? Try with chineseChar.toUtf8().toHex().
Once your string data is in a QString, all UI elements accepting a QString will handle it correctly. Usually the error happens when converting from plain text data(const char*/QByteArray) to the QString.
The conversions here:
ui->plainTextEdit->appendPlainText(chineseChar.toUtf8()); // doesn't work
ui->plainTextEdit->appendPlainText(QString::fromUtf8(chineseChar.toAscii()); // doesn't work

convert the unicode string to a bytearray, and then implicitely back to a QString, as those methods expect a QString.
I suggest you define QT_NO_CAST_FROM_ASCII and QT_NO_CAST_TO_ASCII to avoid any unwanted QByteArray<->QString conversions.
If the string is wrong, the error usually happened before, when converting from QByteArray/const char* to QString, i.e. in query.value(fieldNo).toString(). Try with:
 QString chineseChar = QString::fromUtf8( query.value(fieldNo).toByteArray() );

If that doesn't help, the problem is somewhere in QtSQL assuming the wrong encoding for the data it receives from the database.


text:
Q: proof of equivalent definitions of recurrent states for Markov chains I am wondering if anyone could prove the following equivalent definition of recurrent/persistent state for Markov chains:
1) $P(X_n=i,n\ge1|X_0=i)=1$
2) Let $T_{ij}=min\{n: X_n=j|X_0=i\}$, a state $i$ is recurrent if for $\forall j$ such that $P(T_{ij}<\infty)>0$, one has $P(T_{ij}<\infty)=1$

A: See this page.
Edit: Since incorrect statements continue to pop up on this page, let me explain once again the situation.
First, two notations (standard in the field): for every state $i$, $P_i$ denotes the distribution of the Markov chain $(X_n)_{n\ge0}$ conditionally on the event $[X_0=i]$ and $T_i=\inf\{n\ge1;X_n=i\}$ denotes the first hitting time of $i$. Next, a tautology: the events $[\exists n\ge1,X_n=i]$ and $[T_i<+\infty]$ are equal.
Second, a statement of the question the OP is interested in. One considers two properties which may or may not be satisfied by a given Markov chain $(X_n)_{n\ge0}$ and a given state $i$:
(1) $P_i(\exists n\ge1,X_n=i)=1$.
(2) For every state $j$, either $P_i(T_j<+\infty)=0$ or $P_i(T_j<+\infty)=1$.
Property (1) is often taken as a definition of the fact that $i$ is a recurrent state of the Markov chain $(X_n)_{n\ge0}$. Property (2) is more unusual.
Now, an answer to the question.
Property (1) implies property (2). Proof: see Byron's post. Note that if (1) holds, both $P_i(T_j<+\infty)=0$ and $P_i(T_j<+\infty)=1$ can occur for different states $i$ and $j$ of the same Markov chain. Example: state space $\{0,1,2\}$, transitions $0\to1$, $0\to2$, $1\to1$, $1\to2$, $2\to1$ and $2\to2$ all with positive probabilities, the other transitions with probability zero. Then $P_i(T_0<+\infty)=0$ and $P_i(T_j<+\infty)=1$ for every $i$ and every $j\ne0$.
Property (2) does not imply property (1). Proof by an example: state space $\mathbb{Z}$, transitions $i\to i+1$ with probability $1$. Then $P_i(T_j<+\infty)=0$ if $j\le i$, $P_i(T_j<+\infty)=1$ if $j\ge i+1$, but $P_i(\exists n\ge1,X_n=i)=0$ for every $i$.
Finally (and once again), a congenial reference for this is the first chapter of the book Markov chains by James Norris, which is freely available here.

A: A recurrent state will satisfy property (2), but not the other way around. Take a two state Markov chain that jumps from $i$ to $j$ with probability one, then stays there forever. Then $i$ is transient, but $P(T_{ij}<\infty)=1$.
Edit:
 Here's a sketch of (1) implies (2) in terms of "taboo probabilities".
We assume that $i$ is recurrent, and all of the probabilities below are conditioned on $X_0=i$.
Define $T_i=\inf(n\geq 1 : X_n=i)$ and $T_j=\inf(n\geq 1 : X_n=j)$.
We want to show that $P(T_j<\infty)>0$ implies $P(T_j<\infty)=1$. It suffices to assume $i\not= j$, since $P(T_i<\infty)=1$.
Since $i$ is recurrent, we have $P(T_i < \infty)=1$ so that
$P(T_j < T_i)+P(T_i < T_j)=1,$ since $T_i=T_j$ implies $T_i=\infty$.
Also, if $P(T_j < \infty)>0$ we must have $P(T_j < T_i)>0$,
by considering the shortest possible path from $i$ to $j$ with non-zero probability.
Finally, letting $n$ represent the number of times we return to $i$ without
hitting $j$, the strong Markov property gives
$$P(T_j < \infty)=\sum_{n=0}^\infty P(T_i < T_j)^n P(T_j < T_i)
  =\sum_{n=0}^\infty P(T_i < T_j)^n [1-P(T_i < T_j)]=1.$$

A: I think the first property is wrong. That would be a strictly periodic state. Perhaps you missed something?


text:
Q: Lucene does not index some terms in documents I have been trying to use Lucene to index our code database. Unfortunately, some terms get omitted from the index. E.g. in the below string, I can search on anything other than "version-number":
version-number "cAELimpts.spl SCOPE-PAY:10.1.10 25nov2013kw101730 Setup EMployee field if missing"

I have tried implementing it with both Lucene.NET 3.1 and pylucene 6.2.0, with the same result.
Here are some details of my implementation in Lucene.NET:
using (var writer = new IndexWriter(FSDirectory.Open(INDEX_DIR), new CustomAnalyzer(), true, IndexWriter.MaxFieldLength.UNLIMITED))
{
  Console.Out.WriteLine("Indexing to directory '" + INDEX_DIR + "'...");
  IndexDirectory(writer, docDir);
  Console.Out.WriteLine("Optimizing...");
  writer.Optimize();
  writer.Commit();
}

The CustomAnalyzer class:
public sealed class CustomAnalyzer : Analyzer
{
    public override TokenStream TokenStream(System.String fieldName, System.IO.TextReader reader)
    {
        return new LowerCaseFilter(new CustomTokenizer(reader));
    }
}

Finally, the CustomTokenizer class:
public class CustomTokenizer : CharTokenizer
{
    public CustomTokenizer(TextReader input) : base(input)
    {
    }

    public CustomTokenizer(AttributeFactory factory, TextReader input) : base(factory, input)
    {
    }

    public CustomTokenizer(AttributeSource source, TextReader input) : base(source, input)
    {
    }

    protected override bool IsTokenChar(char c)
    {
        return System.Char.IsLetterOrDigit(c) || c == '_' || c == '-' ;
    }
}

It looks like "version-number" and some other terms are not getting indexed because they are present in 99% of the documents. Can it be the cause of the problem?
EDIT: As requested, the FileDocument class:
public static class FileDocument
{
    public static Document Document(FileInfo f)
    {

        // make a new, empty document
        Document doc = new Document();

        doc.Add(new Field("path", f.FullName, Field.Store.YES, Field.Index.NOT_ANALYZED));
        doc.Add(new Field("modified", DateTools.TimeToString(f.LastWriteTime.Millisecond, DateTools.Resolution.MINUTE), Field.Store.YES, Field.Index.NOT_ANALYZED));
        doc.Add(new Field("contents", new StreamReader(f.FullName, System.Text.Encoding.Default)));

        // return the document
        return doc;
    }
}

A: I think I was being an idiot. I was limiting the number of hits to 500 and then applying filters on the found hits. The items were expected to be retrieved in the order they had been indexed. So when I was looking for something at the end of the index, it would tell me that nothing was found. In fact, it would retrieve the expected 500 items but they would all have been filtered out.


text:
Q: Joomla problem with MVC component I have problem with Joomla layouts in my component..There must be something bad with file/class name convention..
I was trying to ask on Joomla developer forum, but noone answered..
So I am getting this error..  500 - View not found [name, type, prefix]: PostToBank,,postToBankView
The view is in views/postTobank/view.php and name is postToBankViewPostToBank
In my controllers/controller.php file I have class named PaymentController which contains this part of code.
$view = $this->getView('PostToBank','','postToBankView');
        $this->getModel("Payment")->savePaymentData($data);
        foreach ($data as $key => $value) {
            $view->assignRef($key, $value);
        }
        $view->setLayout('postTobank');
        $view->display();

my view.php file looks like this
class postToBankViewPostToBank extends JView{
function display($tpl=null){

    //display set template

    parent::display($tpl);
}

}
on attached image is full folder structure of my component..
Please whats wrong with this?Thanks

A: Joomla uses a naming conventions and you are not following them. Refer to http://docs.joomla.org/File_Structure_and_Naming_Conventions
Also, your views should be view.html.php and then you do not need to call setView.
FYI: this is where the error is coming from. Refer to this: http://docs.joomla.org/API16:JController/getView, even though it is 1.6 doc it is same in 1.5
Look though this tutorial and adopt regular conventions: http://docs.joomla.org/Developing_a_Model-View-Controller_Component_-_Part_1


text:
Q: Is there any post-game content in Rune Factory 4? I'm wondering what there is to do in RF4 after beating the story.  I'm currently level 59 so it will be difficult to start Arc 2, but is there any sort of activity that I can busy myself with in the meantime?

A: What you can do is busy yourself with preparing for Arcs 2 and 3. Level your crafting skills and work on unlocking all the crops. A little investment in these fields can go a long way in Arcs 2 and 3. Don't forget to explore, there are a few secret areas that you may or may not have found yet.
One of these secret areas is the Demon's Den. It is only accessible in the first week of each season. Beating the boss here will drop a Dungeon Seed, which allows you to grow your own dungeons. Delving into these Plant Dungeons may earn you a Sword or Shield Seed, which you can use to grow Plant Swords and Plant Shields respectively. The stats on these items are completely randomized so you may end up with a Plant Sword with post-post-game stats far earlier than is otherwise accessible.

A: What I liked to do was set a routine for myself.  Wake up, check crops, plant as many crops possible (ones that fit well with your current season).   Farm all boss monsters to get the drops, put in stash.  Go to farming spots and gather materials (color grass, lumber, stone) to get upgrades in both skills and your home.
Besides that, as Yuuki mentioned, you can wait for Act II or Act III.  Past Act III there is the level 200 dungeon, similar to the Dungeon seeds you can plant and venture into, but can only be unlocked via PP you get.
If farming isn't something you like, try building up a relationship with everyone else while you wait for the next arc to trigger.  So, talk to everyone you meet at least once a day, try adventuring with them, anything to build up points and unlock additional minievents to trigger other events (relationships, etc).  If you want, you can also look into setting festivals for your town and participating in those.


text: Q: Shebang line in Python I typed a simple program of if-else loop in PyCharm without the Shebang line, but I got the output. I came across about the Shebang line a few minutes back. Hence, I would like to know when to use the Shebang line and for what kind of programs should we use Shebang line?


text:
Q: Visual Studio Code: settings.json family of C_Cpp.xxx configurations vs c_cpp_properties.json? I'm pretty new to using the C/C++ Extension for VSCode. I'm confused what the precise roles and relationships are between configurations defined in the .vscode/c_cpp_properties.json file and the C_Cpp.xxx family of settings allowed in the settings.json file.
Do these two mechanisms allow the configuration of the same settings just under different precedence rules or something?

A: So there is a precedence relationship apparently: the C_Cpp.xxx family of settings serve as global defaults that can serve as a user level default (~/Library/Application Support/Code/User/settings.json) or a folder level default if so configured.
The relationship is covered in this documentation: (Customizing default settings)

You can override the default values for properties set in c_cpp_properties.json

Would probably have been better understood if written as:

You can override the default values for properties defined in settings.json with those set in c_cpp_properties.json.

The understanding here being that there's a name correspondence and matching between the two contexts. The language in the documentation seems to denote stuff in settings.json with the terminology of "VS Code settings".
This makes more sense when you actually manage to create a c_cpp_properties.json in a workspace by invoking one of the commands:

Then you'll find the newly generated file in your .vscode folder

The default config when editing via JSON renders on my mac as...
{
    "configurations": [
        {
            "name": "Mac",
            "defines": [],
            "macFrameworkPath": [
                "/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/System/Library/Frameworks"
            ],
            "compilerPath": "/usr/bin/clang",
            "intelliSenseMode": "clang-x64"
        }
    ],
    "version": 4
}

Just for reference all the itemized Cpp configurations are laid out here (c_cpp_properties.json reference), the mapping going as:
// settings.json
{
    C_cpp.default.<configName> : <configValue>
}

==>
// c_cpp_properties.json
{
    "configurations": [
    {
        "name": "MyLocalConfig",
        <configName>:<configValue>,
    }
}


text:
Q: Has the use of sudo changed in Debian 7? I will try to explain my situation first. I am currently running 6 virtualized Debian servers on a ESXi host machine. The virtual servers where installed with a Debian Linux 6 (Lenny).
Recently I updated the servers to debian Wheezy
root@ares> lsb_release -a                                                                                /home/vincent
No LSB modules are available.
Distributor ID: Debian
Description:    Debian GNU/Linux 7.1 (wheezy)
Release:        7.1
Codename:       wheezy

it has come to my attention that since this upgrade the 'sudo' command is displaying weird behaviour. Actually, it seems to have no effect at all. I checked the /etc/visudo file and everything seems ok. Sudo also asks for my password but then does not seem to run things as root.
An example is the 'ifconfig' command:
user@ares> ifconfig
zsh: command not found: ifconfig
[127] user@ares> sudo ifconfig
sudo: ifconfig: command not found
[1] user@ares> sudo su
root@ares>ifconfig
output shows

anyone who can help me out here?

A: Your PATH probably differs between your normal user and the root user, likely missing directories such as /sbin and/or /usr/sbin where administrative utilities like ifconfig normally live.

A: Michael's answer is correct, but I wanted to add a comment:
It is not mandatory to add administrative commands' path (/sbin, /usr/sbin, /usr/local/sbin) to an unprivileged user, as long as the secure_path directive is configured in /etc/sudoers on in your LDAP server, if you use an LDAP backend:
$ ip a s
-rbash: ip: command not found

$ sudo ip a s
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UNKNOWN qlen 1000
    link/ether 00:0c:29:57:80:d9 brd ff:ff:ff:ff:ff:ff
    inet 172.22.197.38/24 brd 172.22.197.255 scope global eth0

$ echo $PATH
/home/dawud/bin:/usr/lib64/qt-3.3/bin:/usr/local/bin:/bin:/usr/bin

$ sudo -l | awk '$0~/secure_path/ {print $1}'
secure_path=/bin\:/usr/bin\:/sbin\:/usr/sbin\:/usr/local/bin\:/usr/local/sbin

Check man 5 sudoers for further reference on secure_path (also of interest are exempt_group and env_reset).
 secure_path   Path used for every command run from sudo.  If you don't trust the people running sudo to have a sane PATH environment variable you may want to use this.  Another use is if you want to
               have the "root path" be separate from the "user path".  Users in the group specified by the exempt_group option are not affected by secure_path.  This option is not set by default.


text:
Q: Is there a way to skip an orchestration step based on a query parameter? I have a default user journey for signing up a user and I am trying to make an RP policy that will skip the first orchestration step so the user can go directly to signing up instead of logging in.
I am running into trouble with accomplishing this. From my research, I understand that we cannot pass a query parameter in and use it for a non-REST technical profile.
I have tried the following:

* Adding input claim and settings the default value of the RP

* Having the RP policy "IncludeClaimsFromTechnicalProfile" which sets the default value

* Attempted to overwrite the OrchestrationStep and replace the step type to "noop" which causes it to error out

What I am trying to do is to avoid having to write a new user journey because if the default journey changes, then it will duplicate work.

A: Problem is you can resolve the query param in the first step but at that point you're too late if step 1 is the sign in page. So you can either call a rest api in step 1 to echo this param or just copy the UserJourney into a new one without step 1 present. Then call the new journey id in your app instead of passing a query param.


text:
Q: iTunes updated on my iPhone 5c to 9.0.2 but now iTunes on my laptop won't connect to my phone I have updated the latest iOS software onto my iPhone. When trying to connect to my iTunes library on my laptop, I get an error message (the iPhone cannot be used because it requires a newer version of iTunes). Both my phone and iTunes on my laptop state that I have the latest version... help!

A: I just got the same error message.  Do you have a Windows system?  Is it Vista Home Premium?  I believe the problem is that iOS 9.0.2 needs iTunes 12.3, but Apple stopped supporting Vista with iTunes 12.3.  When I check for iTunes updates on my computer with Vista it tells me it's the current version.  It is 12.1, which IS the most current version for Windows Vista but the problem is iOS 9.0.2 needs iTunes 12.3.  They could have warned me before updating the iphone that it wouldn't work on the iTunes program that I was using to update the iphone.  Now what?  I have to upgrade Windows just to use itunes with my phone?
UPDATE:  Bingo!  I went to Apple's website and found a page with "older" versions of iTunes.  It's crazy but there was a newer version of iTunes for Vista, even though the iTunes update check tells you 12.1 is the latest. More specifically, I had 12.1.2.7.  I downloaded 12.1.3.6 which still works with Vista and I can connect to my iphone again!  I hope it works for you too!
So to recap, iTunes 12.1.3.6 will work with Vista AND iOS 9.0.2.  Here's the link for the download. Make sure you choose the right one for your version of Windows and video card (32 bit, 64 bit, or 64 bit for older video cards)
https://discussions.apple.com/docs/DOC-6562#versions


text:
Q: How can i connect my phone to expo when using WSL2 to run it Whenever i try to run expo start or npm start the IP for it is not my LAN IP but my WSL2 eth0 IP and this will cause my phone not connecting to the expo .
i have already tried to set REACT_NATIVE_PACKAGER_HOSTNAME with export command and it will change the ip in the browser related to expo as well but i think it will not run at that ip because my phone again will not connect (i also have turned firewall off too)
the expected thing for me is to be able to run my expo code on my phone without using the tunnel option which will use internet for it.

A: To add to Simons answer, here is what I had to do to get it running.
Forward the requests coming to Windows to the WSL2 instance.
In your WSL2, run ip addr (Ubuntu). This will give you your IP address. Look for eth0, probably something like "inet 172.22.182.52". (note that if you are running multiple Expos on your machine then you may need to do this for more ports)
Then, in a Windows terminal (as administrator), run:
netsh interface portproxy add v4tov4 listenport=19000 connectport=19000 connectaddress=172.22.185.52
netsh interface portproxy add v4tov4 listenport=19001 connectport=19001 connectaddress=172.22.185.52
netsh interface portproxy add v4tov4 listenport=19002 connectport=19002 connectaddress=172.22.185.52

Allow requests through Windows firewall
Windows firewall blocks stuff. Good. Now open up the ports expo needs. (note that if you are running multiple Expos on your machine then you may need to do this for more ports)
Inside Windows terminal (as administrator):
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort 19000 -Action Allow -Protocol TCP";
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort 19001 -Action Allow -Protocol TCP";
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort 19002 -Action Allow -Protocol TCP";
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort 19000 -Action Allow -Protocol TCP";
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort 19001 -Action Allow -Protocol TCP";
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort 19002 -Action Allow -Protocol TCP";

WSL2 IP changes on restart
I haven't tried these yet, but here are some scripts that automatically update the above stuff for you on restart.

*

*https://gist.github.com/xmeng1/aae4b223e9ccc089911ee764928f5486

*https://www.brianketelsen.com/blog/ssh-to-wsl2/
(Bonus) Update QR code that comes from Expo
You need to have a custom environment variable that specifies a different host for the QR code URL. Easiest is to prepend the variable to the command that you run. Preferably your project would have a file set up where you can put these variables.
In a terminal in Windows, run:
ipconfig /all.
Somewhere there you will have the IP address to your Windows machine. Probably under Wireless adapter or Ethernet adapter.
In your project (from WSL2):
REACT_NATIVE_PACKAGER_HOSTNAME=<IP address to your Windows machine> yarn expo:start (or whatever your command is).

A: Here's the full steps I found worked for LAN development between my mobile and expo running in WSL2 (Ubuntu 20 on Windows 10 20H2):
1. One time at the start: open Expo ports inbound in Windows Firewall
Windows firewall should be on, and it should block inbound attempts by default.
The following will open the Expo ports 19000–19006, inbound, but only on a network that you have configured as "private" (that's the -Profile Private part):
(powershell as Admin)
New-NetFireWallRule -Profile Private -DisplayName 'Expo ports for LAN development' `
    -Direction Inbound -LocalPort 19000-19006 -Action Allow -Protocol TCP

(You can check it after with Get-NetFirewallRule |Where-Object {$_.DisplayName -Match "Expo.*"})
2. Point portproxy to WSL; Re-run "Each time WSL has a new IP address"
(I'm not sure yet how often the WSL IP address changes, but I suspect only a reboot would)
I saw stuff on the web, including other answers here, saying portproxy to connectaddress=127.0.0.1 but it did not work for me (WSL2, Windows 10 20H2).
I can't say why others found it worked, I can only say that repeated testing confirmed for me that 127.0.0.1 did not work, but the WSL IP address did work.
So here's a reusable command to auto set the connectaddress to the right WSL address:
(powershell — just for the easy inline Trim() — as Admin)
netsh interface portproxy add v4tov4 listenport=19000 listenaddress=0.0.0.0 `
    connectport=19000 connectaddress=$($(wsl hostname -I).Trim());

netsh interface portproxy add v4tov4 listenport=19001 listenaddress=0.0.0.0 `
    connectport=19001 connectaddress=$($(wsl hostname -I).Trim());

3. Point Metro to your dev machine LAN IP Address; Re-run inside WSL "Each time dev host has a new IP address"
This is the one that probably changes most often. Your laptop local network IP certainly changes when you change networks (e.g. home/office) — and can change at other times too.
Fortunately it's also pastable / aliasable:
WSL2 shell
export REACT_NATIVE_PACKAGER_HOSTNAME=$(netsh.exe interface ip show address "Wi-Fi" | grep 'IP Address' | sed -r 's/^.*IP Address:\W*//')

echo Meteor will use dev machine IP address: $REACT_NATIVE_PACKAGER_HOSTNAME

(If your dev box doesn't change LAN often, you might get away with setting REACT_NATIVE_PACKAGER_HOSTNAME in your .bashrc / .zshrc)

I "wish I didn't have to re-run things and it could all be automated",
but that same laziness makes me happy to at least have commands 2 and 3 able to simple "rerun" and consistently get Expo LAN mode working for my WSL2-hosted Expo dev mode.

A: I was having this issue and this is the main thread about the topic so I thought I'd add a solution that worked for me.
To reiterate, this is running Expo SDK 36 and WSL2 (Ubuntu 18.04 LTS, Win 10 build 19559.1000).
expo start would run (in WSL2), and the QR code would pop up. Scanning the code with my phone would result in an error.
The solution I found was to go to the Metro Bundler window that opens up. Under "Connection", three options are available: Tunnel, LAN, and Local. expo start defaults to LAN. This is where the error is seeming to occur.
The solution was to switch from LAN to Tunnel. This produces a new QR code which allows the Expo phone app to correctly identify and connect to the Expo project.
expo start --tunnel

I understand that the original post didn't want to use the tunneling option, but for those who can, this works.
Hope this helps!

A: If you have IPV6 enabled on your windows machine, you can forward IPV4 requests on Exo's ports to locahost IPV6, like this:
netsh interface portproxy add v4tov6 listenport=19002 connectport=19002 connectaddress=::1 listenaddress=0.0.0.0
netsh interface portproxy add v4tov6 listenport=19001 connectport=19001 connectaddress=::1 listenaddress=0.0.0.0
netsh interface portproxy add v4tov6 listenport=19000 connectport=19000 connectaddress=::1 listenaddress=0.0.0.0

This is a permanent solution, since it keep working even when your WSL2 IP changes.
On your phone, you need to use exp://YOUR_WINDOWS_IP:19000
I found this when searching for a similar problem running Dokcer inside WSL2:
https://github.com/microsoft/WSL/issues/4983

A: Maybe as bit of a summary here's what I ended up doing.
1. Saved this as expo_wsl2_port_forwarding.ps1 and run once after my PC booted and WSL was opened:
$local_ip = "0.0.0.0";
$wsl_ip = iex "wsl hostname -I"

$ports = @(19000, 19001, 19002);
$ports_list = $ports -join ",";

# Firewall rules
iex "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock'";
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $ports_list -Action Allow -Protocol TCP";
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $ports_list -Action Allow -Protocol TCP";

# Port-forwarding
for($i = 0; $i -lt $ports.length; $i++){
    $port = $ports[$i];
    iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$local_ip";
    iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$local_ip connectport=$port connectaddress=$wsl_ip";
}

You need to run this in an elevated prompt ("Run as administrator").
You may see an error you run it the first time as there won't be an existing firewall rule to delete.
2. Then in WSL2 I run the following:
REACT_NATIVE_PACKAGER_HOSTNAME=`dig host.docker.internal +short` expo start --lan

Here's it's important to note that the hostname host.docker.internal will only be available if you're running Docker on the host (Windows). If you don't do that you'll have to figure out your host IP using another technique (see other answers).

A: Tunneling will redirect your traffic through the internet and is slower than a direct connection.
I solved the issue by forwarding the ports 19000 and 19001 to WSL
netsh interface portproxy add v4tov4 listenport=19000 listenaddress=0.0.0.0 connectport=19000 connectaddress=127.0.0.1
netsh interface portproxy add v4tov4 listenport=19001 listenaddress=0.0.0.0 connectport=19001 connectaddress=127.0.0.1

(based on this excellent blog post)
A few other things to verify:

*

*You might need to configure your Linux Firewall to allow connections on ports 19000 and 19001 (I didn't need to do this)

*You might need to set up a Windows Firewall rule for ports 19000, 19001 (I didn't need to do this)

*Make sure that both your PC and your mobile device are on the same WiFi network

A: An update, two years later, in case it's helpful - I no longer need to do the netsh commands shown in the Accepted answer to get this to work on WSL2 (and in fact, doing so breaks other things!) but I DID still need to do the firewall commands. Then all works well.

A: You can check if ports are correctly opened and set with sudo lsof -i -P -n | grep LISTEN
I also had to add export EXPO_DEVTOOLS_LISTEN_ADDRESS=0.0.0.0 in my zshrc config

A: You can use this script that i made!

https://github.com/jonhoffmam/wsl2_host

It automates the entire process that Simon Farshid and Skurpi commented, such as:

*

*Open ports 19000,19001,19002,19003,19004,19005 on the Windows firewall;

*Insert the REACT_NATIVE_PACKAGER_HOSTNAME environment variable into the .bashrc and .zshrc files (if there's);

*The environment variable REACT_NATIVE_PACKAGER_HOSTNAME automatically receives the IP address of the local machine (Windows);

*Defines a Windows registry key to facilitate the execution of the script through Run (Windows + "R") with the command wsl2host;

*Creates a schedule task on Windows to run the script at logon

Download this repository or if you have Git installed:

$ git clone https://github.com/jonhoffmam/wsl2_host.git

Run the start.bat file on the first run of the script
After is possible run script with command wsl2host on Run


text:
Q: Splitting out a large file I would like to process a 200 GB file with lines like the following:
...
{"captureTime": "1534303617.738","ua": "..."}
...

The objective is to split this file into multiple files grouped by hours.
Here is my basic script:
#!/bin/sh

echo "Splitting files"

echo "Total lines"
sed -n '$=' $1

echo "First Date"
head -n1 $1 | jq '.captureTime' | xargs -i date -d '@{}' '+%Y%m%d%H'

echo "Last Date"
tail -n1 $1 | jq '.captureTime' | xargs -i date -d '@{}' '+%Y%m%d%H'

while read p; do
  date=$(echo "$p" | sed 's/{"captureTime": "//' | sed 's/","ua":.*//' | xargs -i date -d '@{}' '+%Y%m%d%H')
  echo $p >> split.$date
done <$1

Some facts:

*

*80 000 000 lines to process

*jq doesn't work well since some JSON lines are invalid.

Could you help me to optimize this bash script?
Thank you

A: This awk solution might come to your rescue:
awk -F'"' '{file=strftime("%Y%m%d%H",$4); print >> file; close(file) }' $1

It essentially replaces your while-loop.
Furthermore, you can replace the complete script with:
# Start AWK file
BEGIN{ FS='"' }
(NR==1){tmin=tmax=$4}
($4 > tmax) { tmax = $4 }
($4 < tmin) { tmin = $4 }
{ file="split."strftime("%Y%m%d%H",$4); print >> file; close(file) }
END {
  print "Total lines processed: ", NR
  print "First date: "strftime("%Y%m%d%H",tmin)
  print "Last date:  "strftime("%Y%m%d%H",tmax)
}

Which you then can run as:
awk -f <awk_file.awk> <jq-file>

Note: the usage of strftime indicates that you need to use GNU awk.

A: you can start optimizing by changing this
sed 's/{"captureTime": "//' | sed 's/","ua":.*//'
with this
sed -nE 's/(\{"captureTime": ")([0-9\.]+)(.*)/\2/p'

-n suppress automatic printing of pattern space
-E use extended regular expressions in the script


text:
Q: Android swapping between to activities Can any one please tell me how can i swap between two activities horizontally. Once user swap screen to left the next activity will load. As i am beginner so please tell me the easiest way to achieve it.

A: You seem to be looking for the ViewPager component. This will allow you to swipe between screens. Please note you will have to implement the different screens as Fragments though.
There is a guide on this in the docs: http://developer.android.com/training/animation/screen-slide.html

A: I believe it would be better having only one Activity and using Fragment in conjunction with a ViewPager to achieve the desired effect.
The official training page on the subject explains this better than I could.
If you are not familiar with the concept of Fragment, there is also a training section on that here.
Finally, since you are a beginner, I would recommend you go through most of the official training or any other complete training support such as Mark Murphy's Busy Coder's Guide to Android Development or Reto Meier's Professional Android 4 Application Development.


text:
Q: How do I return a unique list based on JSON results in PHP? I'm attempting to use the values from one JSON link to populate values in other JSON links resulting in a unique list of values from the combined JSON.  I've gotten as far as creating the complete list of values, but I'm having a difficult time finding the syntax in the final loop to display only the unique values.  Any help would be appreciated.
$collection_string = file_get_contents("http://some_json_url.com/json");
$collection_list = json_decode($collection_string, true);

foreach ($collection_list as $col_lists => $col_list) {
     $object_string = file_get_contents('http://another_json_url.com/'.$col_list['key'].'/json');
     $object_list = json_decode($object_string, true);
     $object_array = array();

     foreach ($object_list as $objects => $object) {
          $object_array [] = array_unique($object); //Returns "Warning: array_unique() expects parameter 1 to be array, string given in..."
          echo '
'.$object_array.'
'; //Returns "Array"
          echo '
'.$object.'
'; //Returns complete list
     }

}

Working code:
$collection_string = file_get_contents("http://some_json_url.com/json");
$collection_list = json_decode($collection_string, true);

$object_array = array();

foreach ($collection_list as $col_lists => $col_list) {
     $object_string = file_get_contents('http://another_json_url.com/'.$col_list['key'].'/json');
     $object_list = json_decode($object_string, true);

     foreach ($object_list as $key => $value) {
          array_push($object_array, $value);
     }
}

$object_unique = array_unique($object_array);
natcasesort($object_unique);

foreach ($object_unique as $key => $value) {
     echo '
'.$value.'
';
}

A: Simply change this
$object_array [] = array_unique($object);

to that
$object_array [] = $object; // edited !
array_unique($object_array);

Maybe you can also do this with one line of code, but I dont know how to write it. But the way the way I wrote it it's a little bit unoptimized, it would be better to simply do the array_unique() only one time, right after the final loop.
Btw your problem is/was that you tried to make $object unique, which is not an array. it's a string/object.


text:
Q: WPF Commands, How to declare Application level commands? I'm interested in creating commands that are available from anywhere in my WPF application.
I'd like them to work in the same way as Cut, Copy, Paste and the other Application level commands, ie:
<Button Command="Paste" />

I assumed I could setup CommandBindings for the Application instance, but that property isn't available.
How is this done?
The best I have managed so far is to create a suite of commands on the top level window and then access them like this...:
<Button Command="{x:Static namespace::MainWindow.CommandName}" />

Which works, but is of course tightly coupled, and so extremely brittle.

A: I did not like the complexity of the other solutions, but after a few hours of research I found out it is really simple.
First setup your command as you usually do, but add a static property for WPF so that it can obtain an instance of your command.
class MyCommand : ICommand
{
    // Singleton for the simple cases, may be replaced with your own factory
    public static ICommand Instance { get; } = new MyCommand();

    public bool CanExecute(object parameter)
    {
        return true; // TODO: Implement
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        // TODO: Implement
    }
}

Add a reference to the namespace of your command in your XAML (last line), like this:
<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:commands="clr-namespace:MyProject.Commands">

Then just reference your static property in your XAML like this:
<Button Content="Button" Command="commands:MyCommand.Instance" />

A: StackOverflow members helped me so many time that I decide now to contribute and share ;-)
Based on Shou Takenaka's answer,  here is my implementation.
My interest was to produce only one reusable file.

First, create a command(s) container class
namespace Helpers
{
    public class SpecificHelper
    {
        private static RoutedUICommand _myCommand = new RoutedUICommand("myCmd","myCmd", typeof(SpecificHelper));
        public static RoutedUICommand MyCommand { get { return _myCommand; } }

        static SpecificHelper()
        {
            // Register CommandBinding for all windows.
            CommandManager.RegisterClassCommandBinding(typeof(Window), new CommandBinding(MyCommand, MyCommand_Executed, MyCommand_CanExecute));
        }

        // TODO: replace UIElement type by type of parameter's binded object
        #region MyCommand
        internal static void MyCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (!verifType<UIElement>(e.Parameter)) return;

            e.Handled = true;
            // TODO : complete the execution code ...
        }

        internal static void SelectAll_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (!verifType<UIElement>(e.Parameter)) return;

            e.CanExecute = true;
            var item = (e.Parameter as UIElement);
            // TODO : complete the execution code ...
        }
        #endregion

        private static bool verifType<T>(object o)
        {
            if (o == null) return false;
            if (!o.GetType().Equals(typeof(T))) return false;
            return true;
        }
    }
}

Next, declare a resource in App.xaml:
<Application x:Class="Helper.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:h="clr-namespace:Helpers"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             StartupUri="MainWindow.xaml" >
    <Application.Resources>
        <h:SpecificHelper x:Key="sh" />
    </Application.Resources>
</Application>

Finally, bind any command property to the property of your application resource:
<Button Content="Click to execute my command"
        Command="{Binding Source={StaticResource sh}, Path=MyCommand}"
        CommandParameter="{Binding ElementName=myElement}" />

that's all folks :-)

A: You can setup CommandBindings for "All Windows" of your WPF application and implement command handlers in Application class.
First of all, create a static command container class. For example,
namespace WpfApplication1
{
    public static class MyCommands
    {
        private static readonly RoutedUICommand doSomethingCommand = new RoutedUICommand("description", "DoSomethingCommand", typeof(MyCommands));

        public static RoutedUICommand DoSomethingCommand
        {
            get
            {
                return doSomethingCommand;
            }
        }
    }
}

Next, set your custom command to Button.Command like this.
<Window x:Class="WpfApplication1.MainWindow"
        ...
        xmlns:local="clr-namespace:WpfApplication1">
    <Grid>
        ...
        <Button Command="local:MyCommands.DoSomethingCommand">Execute</Button>
    </Grid>
</Window>

Finally, implement the command handler of your custom command in Application class.
namespace WpfApplication1
{

    public partial class App : Application
    {
        public App()
        {
            var binding = new CommandBinding(MyCommands.DoSomethingCommand, DoSomething, CanDoSomething);

            // Register CommandBinding for all windows.
            CommandManager.RegisterClassCommandBinding(typeof(Window), binding);
        }

        private void DoSomething(object sender, ExecutedRoutedEventArgs e)
        {
            ...
        }

        private void CanDoSomething(object sender, CanExecuteRoutedEventArgs e)
        {
            ...
            e.CanExecute = true;
        }
    }
}

A: If you try to define CommandBindings or InputBindings as resources in your App.xaml, you will find that you cannot use them, because XAML doesn't allow you to use either:
<Window ... CommandBindings="{StaticResource commandBindings}">

or to set command bindings with a style setter:
<Setter Property="CommandBindings" Value="{StaticResource commandBindings}">

because neither of these properties have a "set" accessor.  Using the idea in this post, I came up with a clean way of using resources from App.xaml or any other resource dictionary.
First you define your command bindings and input bindings indirectly, like you would any other resource:
    <InputBindingCollection x:Key="inputBindings">
        <KeyBinding Command="Help" Key="H" Modifiers="Ctrl"/>
    </InputBindingCollection>
    <CommandBindingCollection x:Key="commandBindings">
        <CommandBinding Command="Help" Executed="CommandBinding_Executed"/>
    </CommandBindingCollection>

and then you refer to them from the XAML of another class:
<Window ...>
    <i:Interaction.Behaviors>
        <local:CollectionSetterBehavior Property="InputBindings" Value="{StaticResource inputBindings}"/>
        <local:CollectionSetterBehavior Property="CommandBindings" Value="{StaticResource commandBindings}"/>
    </i:Interaction.Behaviors>
    ...
</Window>

The CollectionSetterBehavior is a reusable behavior that doesn't "set" the property to it's value, but instead clears the collection, and re-populates it.  So the collection doesn't change, only it's contents.
Here's the source for the behavior:
public class CollectionSetterBehavior : Behavior<FrameworkElement>
{
    public string Property
    {
        get { return (string)GetValue(PropertyProperty); }
        set { SetValue(PropertyProperty, value); }
    }

    public static readonly DependencyProperty PropertyProperty =
        DependencyProperty.Register("Property", typeof(string), typeof(CollectionSetterBehavior), new UIPropertyMetadata(null));

    public IList Value
    {
        get { return (IList)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }

    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(IList), typeof(CollectionSetterBehavior), new UIPropertyMetadata(null));

    protected override void OnAttached()
    {
        var propertyInfo = AssociatedObject.GetType().GetProperty(Property);
        var property = propertyInfo.GetGetMethod().Invoke(AssociatedObject, null) as IList;
        property.Clear();
        foreach (var item in Value) property.Add(item);
    }
}

If you are not familiar with behaviors, first add this namespace:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

and add the corresponding reference to your project.

A: Declare the CommandBinding at Application level from where it can be re-used everywhere.
<Application.Resources>
    <CommandBinding x:Key="PasteCommandKey" Command="ApplicationCommands.Paste" CanExecute="CommandBinding_CanExecute_1"/>
</Application.Resources>

In your App.xaml.cs file, define corresponding handlers :
  private void CommandBinding_CanExecute_11(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
    {
      e.CanExecute = false;
    }

Usage
In any xaml file, use it like below :
 <RichTextBox x:Name="Rtb1" ContextMenuOpening="Rtb1_ContextMenuOpening_1" FontSize="15" Margin="10,10,10,-73">
        <RichTextBox.CommandBindings>
            <StaticResourceExtension ResourceKey="PasteCommandKey"/>
        </RichTextBox.CommandBindings>


text:
Q: jQuery/Javascript Cookies and variable returning with value [object Object] I am attempting to set a cookie to a site using jQuery, ONLY if the user came from a specific site. In this case, lets use -http://referrersite.com- as the site they must come from for the cookie to be created as an example. The cookie value is being stored in a variable and everything up to this point is working fine.
There is a conditional statement checking whether the user came from the referred site, if the cookie exists already and if the cookie doesn't exist and the user did not come from the referred site. If the user came from the referred site the cookie is created and stored in a variable. If the cookie already exists, it is then stored in a variable. If the cookie does not exist and the user did not come from the referred site I am assigning the variable a static string of characters - this is where the issue lies.
When the variable is alerted from the non referred site and no existing cookie, it returns: [object Object], not the static string of characters.
The code I am using is below:
$(document).ready(function() {

    var referrer = document.referrer;

    if(referrer == "http://referrersite.com") {

        $.cookie("code","123456", { expires: 90, path: '/' });
        cookieContainer = $.cookie("code");
        alert(cookieContainer);

    } else if($.cookie("code")) {

        cookieContainer = $.cookie("code");
        alert(cookieContainer);

    } else if($.cookie("code") == null && referrer != "http://referrersite.com") {

        cookieContainer = "67890";
        alert(cookieContainer);

    }

});

In conclusion, my goal is to set cookieContainer with the string "67890" if the user did not come from the referred site, and $.cookie("code") does not exist. For some reason it is containing an object instead.
Please let me know if there is something I am missing as the code to me looks like it should work.
Thanks!

A: [Object Object] In short means the data in the cookie isn't a string, well not exactly. Chances are the data in the cookie more so resembles that of a JSON string/object. And to alert it out, print it on screen, or whatever it is your trying to do in the long run your going to have to either do a loop over the object and have it print it all out.. or if you know which property you want specifically you will have to call it specifically.
eg:
if(cookieContainer.property_name_whatever)
{
    alert(cookieContainer.property_name_whatever);
}

To find out the individual properties I would say your easiest bet with javascript is using Firefox, install the Firebug http://getfirebug.com/, and in your code instead of alert(cookieContainer) do console.log(cookieContainer) . After enabling the console with firebug, this will read the object as a whole and display the data on a per property => value basis.
The reason something exists when its not the cookie your looking for is its likely the person on the site came from another site or search engine. In using document.referrer any url landing to your page even internals can and likely will be treated as a referrer, its ultimately dependant upon the browser itself though, as all the major ones support it, they all treat it differently in various degrees. Im not going to lay claim completely understanding that particular object as I dont use it often myself. But to quote W3

Definition and Usage
The referrer property returns the URL of the document that loaded the
  current document.

The URL in mention could even be you on the same site jumping back and forth between pages via links on your page (Not sure if that applies on reloads/refreshes, but it could I suppose)


text:
Q: UART- Tx/Rx Line cut detection There are 2 systems,A and B. Communication between them is via Uart.
As part of periodic health check for CAN Bus, its possible to do a loopback and check the status of the CAN transceiver and the bus(in addition to those taken care of the CAN spec itself like error counters).
Similarly, if my choice is UART for communication, is there any method i can ensure that the Tx and Rx lines are functioning properly without System A having to send a msg to System B and asking System B to retransmit back the same data received by it? I want to make the Health test by each system independent of the other.

A: If "functioning properly" means proving that Tx and Rx lines are not open circuit then "no". To check this requires "something" at the far end however, even with something at the far end you cannot simply know that a line open fault is due to Tx, Rx or both.
You could develop a form of TDR (time domain reflectometry) but this seems overkill.
If you are looking for shorts between wires or to ground then it can be done at one end of the link.

A: Usually the transmit line is held high by the driver. You could add a weak pull-down on your receive line and measure the voltage there. If it's high, you know the transmitter on the other side is connected.


text:
Q: A general question about precession Does precession (of a top for example) occur only whenever the angular velocity vector is not parallel to a principal axis? I have yet found any clear definition of precession and when it is defined to occur.
If so, why does that imply that whenever the angular velocity vector is parallel to the angular momentum vector, there will not be any precession?

A: From the point of view of the physics taking place:
When the spin axis and the torque axis coincide then any work that the torque is doing will go into changing the rate of spin, instead of inducing precession.
In order to be in a position to induce precession the axis of the torque must be non-aligned with the spin axis.

Whatever definition is used, it must be compatible with the above.


text:
Q: How to adjust a sub view based of the screen orientation in Swift? I am trying a very basic app where there is a customised Menu Bar. The menu Bar is supposed to occupy 1/4th of the screen. And since this has to be calculated again when orientation changes, I am setting the menubar again everytime the orientation changes. But the problem is, when i initially open the app in portrait mode, the menubar is set right and even after the changing to landscape, it still is fine but when i swift from landsacpe to portarit, it for some reason does not do it right and the height of the menu bar is increased. Am I missing something ?
Below is my UIViewController
class HomeViewController: UIViewController{

var metrics : [String : CGFloat] = [:]
let table = OptionsTable()
let menuBar = MenuBar()
var views : [UIView] = []

override func viewDidLoad() {
    super.viewDidLoad()

    navigationController?.navigationBar.barTintColor = UIColor.getColorFromHex(hexCode: "1B9AF7")
    navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]

    setUpMenuBar()

}
private func setUpMenuBar(){
    views += [menuBar]
    view.addSubview(menuBar)
    let bottomPaddingForMenuBar = view.frame.height - (view.frame.height/4)
    print("Padding \(bottomPaddingForMenuBar)")
    metrics.updateValue(bottomPaddingForMenuBar, forKey: "bottomPaddingFormenuBar")
    view.addConstraintWithFormat("H:|[v0]|", views: views, metrics: metrics)
    view.addConstraintWithFormat("V:|-0@750-[v0]-bottomPaddingFormenuBar@750-|", views: views, metrics: metrics)

}

override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
     setUpMenuBar()
    if fromInterfaceOrientation == .portrait || fromInterfaceOrientation == .portraitUpsideDown {
        print("Landscape")
    }else{
        print("Portrait")
    }
}

Below is my addConstarintWithFormat() method
extension UIView{
func addConstraintWithFormat(_ format : String, views : [UIView], metrics : [String : CGFloat]) {

    var viewsDictionary = [String : UIView]()

    for(index, view) in views.enumerated(){
        let key = "v\(index)"
        view.translatesAutoresizingMaskIntoConstraints = false
        viewsDictionary[key] = view
    }
    print("duuh\(viewsDictionary["v0"]!)")
    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutConstraint.FormatOptions(), metrics: metrics, views: viewsDictionary))

}

Thanks in Advance!


text:
Q: Question mark in MYSQL console screen means? I'm using MYSQL 5.6.17. For the status column, given in the image, I use BIT datatype and values I use are 1 and 0. These values are displayed accurately in the GUI but on the console screen, they are displayed as question mark. Why is this so? Is there any problem?

A: As per comment - there's no problem involved, everything is fine :)
What you're seeing is unicode representation for the null character (all zeroes). Since you are dealing with a bit field, and its value is apparently zero, that's how it gets rendered in the terminal when unicode table is applied to that value.


text:
Q: Are digital filters example of dynamic programing? A digital filter can be represented using a discrete difference equation, for example:
Y[n]= k1* Y[n-1]+k2*X[n]

where Y[n] is the output of the filter and X[n] is the input to the filter, k1 and k2 are some constant. It's a simple first order filter. As I read about dynamic programing, it's described as a powerful technique. I am wondering if the above filter is an example of a dynamic program. Is representing a problem using recursion, the crux of dynamic programing?

A: strictly speaking, this is not an example of dynamic programming
for DP, u should make some decisions at each point, eg. maximum or minimum.
in your question, there is no decision making. so it is a recurrence, but not DP


text:
Q: Which Flutter plugin or feature can utilize an external iOS/Android display showing separate content from the main display I am building a cross-platform app which needs to show a different view on an external display (usually connected via an HDMI adapter cable connected to a LCD projector.)  Does Flutter have the ability to display a different screen on an external display either built-in or with an existing Flutter plugin? I would not want to write a bridge or plugin myself, as it would require native Swift (UIScreen) and Kotlin (Presentation class) code.
As I am exploring different cross-platform frameworks for iOS and Android I only found React Native with a usable package: React Native External Display - A React Native view renderer in External Display.
Is there anything similar available for Flutter or what would be the best way to approach this in Flutter?

A: You can try the presentation_displays. It supports running the app in 2 displays with independent images, not mirroring.

A: Flutter plugin supports to run on two screens. It's basically a tablet connected to another screen via an HDMI or Wireless
Plugin: link
Idea: We create a Widget by using Flutter code and pass it to Native code side then convert it to FlutterEngine and save it to FlutterEngineCache for later use.
Next, we define the Display by using displayId and we will define the UI flutter that needs to display by grabbing FlutterEngine in FlutterEngineCache and transferring it to Dialog Presentation as a View.
We provide methods to get a list of connected devices and the information of each device then transfer data from the main display to the secondary display.
Simple steps:
Create Widgets that need to display and define them as a permanent router when you configure the router in the Flutter code.
Get the Displays list by calling displayManager.getDisplays ()
Define which Display needs to display For instance: displays 1 .displayId Display the index 2.
Display it on Display with your routerName as presentation displayManager.showSecondaryDisplay (displayId: displays [1] .displayId, routerName: "presentation")
Transmit the data from the main display to the secondary display by displayManager.transferDataToPresentation (" test transfer data ")
The secondary screen receives data
@override
Widget build (BuildContext context) {
    return SecondaryDisplay (
        callback: (argument) {
        setState (() {
        value = argument;
        });
    }
    );
}

Note: Extracted from Github page.


text:
Q: .net core - MVC - Using an IEnumerable on a Viewmodel returns empty model Im populating a collapsable accordion from bootstrap, and there is a table in each and one of the collapsable blocks. In the GET request I get all viewmodels related to the customer and then I group them by month which makes the List an IEnumerable> that I send to the view and loop so that each accordion block is "Januari" and its table with data, and so on..
So, to summarize the view: I loop the groups in Model, add The date for each group in the accordion "Keys" to make the accordion blocks unique and then i add a table in the accordion block with all the rows in the group. Every row in the table have only one input, its a checkbox.
Problem: When I submit I get nothing. Empty list... This is the GET/POST and the View.
Actions..
        [HttpGet]
    public IActionResult CheckOffPriceListsAdjustments(int projectId)
    {
        //Get all the  priceListsAdjustments that are unchecked
        var priceListsAdjustments = _priceListsAdjustmentsHandler.GetPriceListsAdjustmentsByProjectId(projectId)
            .Where(x => x.Checked.Equals(false)).ToList();

        if (priceListsAdjustments.Any())
        {
            // Transform them to checkOffViewModels.
            var checkOffViewModels = _customerHandler.GetPriceListsAdjustmentsForCheckOff(priceListsAdjustments);
            var proj = _projectService.GetProjectById(projectId).ProjectName;

            ViewBag.ProjectName = proj.Contains(";") ? proj.Substring(proj.IndexOf(';') + 1) : proj;

            var grouped = checkOffViewModels.GroupBy(x => x.Date).Select(grp => grp.ToList());

            return View(grouped);
        }

        return View();
    }

    [HttpPost]
    public IActionResult CheckOffPriceListsAdjustments(IEnumerable<List<CheckOffViewModel>> grouped)
    {
        // TODO : Update rows in DB, save changes.
        return View();
    }

View:

@model IEnumerable<List<Blabla.Models.ViewModels.CheckOffViewModel>>
@using Blabla.Extensions

@ViewBag.ProjectName

blalblalblalblala....

    <form asp-controller="Customers" asp-action="CheckOffPriceListsAdjustments" method="post">
        @foreach (var group in Model)
        {

 x.Date).FirstOrDefault())" style="background-color: #337ab7">

                         x.Date).FirstOrDefault())" aria-expanded="true" aria-controls="collapseOne">
                            @group.Select(x => x.Date).FirstOrDefault()

 x.Date).FirstOrDefault())" class="collapse show" aria-labelledby="heading@(group.Select(x => x.Date).FirstOrDefault())">

                                    Bockad
                                    Månad
                                    Kund
                                    Projektnr
                                    Projektnamn
                                    Uppgift
                                    Avdelning
                                    Name
                                    Antal tim
                                    Pris

                                @foreach (var row in group.OrderBy(x => x.CustomerName))
                                {

                                        <input asp-for="@row.Checked" type="checkbox" />
                                        @row.Date
                                        @row.CustomerName
                                        @row.ProjNr
                                        @row.ProjName.TruncateString()
                                        @row.Description
                                        @row.SecCost
                                        @row.Employee
                                        @row.Hours
                                        @row.Price
                                        <input type="hidden" asp-for="@row.Checked" />
                                        <input type="hidden" asp-for="@row.PriceListsAdjustmentsId" />

                                }

        }

            <input id="checkOffPricelists-form-btn" type="submit" value="save blabla.." class="btn btn-success" style="width:25%" disabled />

    </form>

A: As discussed, you need to iterate through model collections with a for loop and reference the items via an index. You will also need to use a control such as TextboxFor for the binding to work.
You can see the difference in the html generated in the source between the two.
Thanks


text:
Q: How to use Eval() dynamically in Asp.net I want to use like this
for (int i = 1; i <= x; i++)
{
    string z = Request.Cookies[i.ToString()].Value;
    %>
        <%# Eval(z).ToString()%>
    <%
}

but its not taking variable "z". is any way to use like this.
Not found on search thats why posting.
thanks

A: z.ToString() maybe?
Can you confirm that the cookies actually exist?

A: I would suggest you investigate the ASP.Net Dynnamic Data Entities project type. Even if you only create a sample project and use what you learn from that.


text:
Q: Double sorting Array My array has sorting values from 1-6.
Array: 2 5 6 2 5 1 1

and then I can get the two's first before anything else for example.
So it would be like 2 2 5 6 5 1 1. But, then I need to sort by the other sorting values and dates.
Example: 2 2 1 1 5 5 6 and those also have dates attached to them and needs to be sorted in descending order.
Final example:
2 - 2012-06-02
2 - 2012-06-01
1 - 2012-03-05
1 - 2012-03-01
5 - 2012-08-09
5 - 2012-01-01
6 - 2012-11-29

My function looks like this at the moment and is used by the usort function.
ObjektTyp is the sorting value, different numbers depending on what type of house it is. All these values comes from a XML-source.
function sort_by_type(&$array, $sort = NULL)
{
    usort($array, function($a, $b) use ($sort)
    {
        if ($a["ObjektTyp"] == $sort) {
            return -1;
        } else {
            return 1;
        }
    });
}

I would love to get some help with this, been pulling my hair all day.
Thank you very much!

A: First sort by numbers, then by the dates.  This can be done by checking if the numbers are the same, and then sorting by dates.
Something like this:
function sort_by_type(&$array, $sort = NULL){
    usort($array, function($a, $b) use ($sort){
        if($a["ObjektTyp"] == $b["ObjektTyp"]){
            // already sorted by number, sort by date
            return strtotime($b['date']) - strtotime($a['date']); // sort descending
        }
        else{
            // sort by number
            if ($a["ObjektTyp"] == $sort) {
                return -1;  // 2s to the top
            }
            elseif($b["ObjektTyp"] == $sort){
               return 1;  // 2s to the top
            }
            else {
                return $a["ObjektTyp"] - $b["ObjektTyp"];
            }
        }
    });
}

DEMO: http://codepad.viper-7.com/3PMtmA


text:
Q: Find the EMM productPolicy within the Android device I'm updating an Android app which performs Android EMM along with our web app. From within our Android app, is there a way for me to get the Android device's productPolicy?
What's a productPolicy? Google shut down the old mechanism for distributing apps via EMM, and now to distribute apps, an EMM service (i.e. our web application) needs to make an api call to Devices: update with a device object in the request body. The device object has a member policy.productPolicy which is an array of objects corresponding to apps which the EMM service wants to install/update/configure on the targeted Android device. The information I want our Android app to obtain is the productId for each app specified in the productPolicy.
I don't know for certain that this information is on the Android device, but I suspect that after our web application sends this information to Google's api, Google passes some of it forward to the Android device because I observe that the apps which I specify in my productPolicy auto-install successfully after making this api request to Google.


text:
Q: How do I decode events of a transaction from the transaction receipt? On Etherscan it shows Swap, Remove Liq, Transfer, migrate etc... How do I decode this information from a TransactionReceipt using web3 API?
Currently, I see patterns on Liq removal such as a Null Address in the logs. Is this the way etherscan does it or is there a way to extract method type?

A: What you are looking for is called event signature in Solidity terminology. The event log first 4 bytes match the hash of an event ABI descriptor.
To decode, you need to have the ABI files of the events you are decoding. With the ABI file, you can decode the rest of the event data and convert it to human-readable info.
More here.


text:
Q: Erro ao conectar com o banco de dados firebird Estou tentando criar uma aplicação web e quero utilizar java e html.
Bom depois de tudo configurado e pronto para um pequeno teste de conexao o seguinte erro ocorre:
Fev 09, 2016 1:28:02 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [jsp] in context with path [/TesteTemplateImport] threw exception [java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at org.apache.jsp.main_jsp._jspService(main_jsp.java:190)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

Sou iniciante e nunca criei uma aplicação web, segue abaixo meu algoritmo para conexao com o banco:
package teste;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Conexao {

static final String JDBC_DRIVER = "org.firebirdsql.jdbc.FBDriver";
static final String DB_URL = "jdbc:firebirdsql:192.168.1.225/3050:D:/Dados/Suporte/Sisplan/Base/Belfast.GDB?sql_dialect=3";

static final String USER = "SYSDBA";
static final String PASS = "masterkey";

public static Connection getConexao() throws SQLException {

    try {
        Class.forName(JDBC_DRIVER);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    return DriverManager.getConnection(DB_URL, USER, PASS);

   }

}

Tem um pequeno detalhe que acredito que devo mencionar, esse erro ocorre não no momento em que eu faço o start do servidor. Ele inicia a aplicação rodando no eclipse, vou até o navegador web digito o endereço do servidor, ele abre a pagina porem quando executo um select ai sim o log do erro aparece.
Este é meu código dentro da pagina html:
<%@ page import="teste.Conexao" %>
<%@ page import="teste.UsuarioDao" %>
<%@ page import="teste.Usuario" %>

<%

UsuarioDao udao = new UsuarioDao();

Usuario usuario = (Usuario) udao.buscar("12345678");

out.print(usuario.getNome());
%>

Aqui esta meu select:
public Usuario buscar(String rg) {
    conectar();

    String sql = "SELECT nome FROM ENTIDADE_001 WHERE CODCLI = " + rg;

    try {
        ResultSet rs = st.executeQuery(sql);

        while (rs.next()) {
            String rG = rs.getString("rg");
            String nome = rs.getString("nome");

            pessoa = new Usuario(rG, nome);
        }

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        desconectar();
    }

    return pessoa;
}

E sim. Já adicionei o .jar correto com a mesma versão do meu jdk e minha variavel de ambiente HAVA_HOME nao tem espaços em branco e esta apontando corretamente para pasta da minha jdk.

A: Veja se esse material lhe ajuda a encontrar o "caminho das pedras".
Neste exemplo é criado um esquema de autenticação bem elaborado. Você não precisa se prender aos pormenores que o autor trata, basta focar no que você está de fato precisando.
Creio que a análise das listagens 10 e 13 lhe serão de grande ajuda no entendimento da interação entre a página JSP e o back-end da aplicação.


text:
Q: SQL Entry's Duped I messed up when trying to create a test Database and accidently duplicated everything inside of a certain table. Basically there is now 2 of every entry there was once before. Is there a simple way to fix this? (Using InnoDB tables)

A: Yet another good reason to use auto incrementing primary keys.  That way, the rows wouldn't be total duplicates.
Probably the fastest way is to copy the data into another table, truncate the first table, and re-insert it:
create temporary table tmp as
   select distinct *
   from test;

truncate table test;

insert into test
    select *
    from tmp;

As a little note:  in almost all cases, I recommend using the complete column list on an insert statement.  This is the one case where it is optional.  After all, you are putting all the columns in another table and just putting them back a statement later.


text:
Q: Bootstrap DateTimePicker Moment.js Estou tentando implementar o Bootstrap DateTimePicker no meu projeto que está com a versão 4.3.1 do Bootstrap.
O problema é que eu não sei como se faz isso.
Eu baixei deste site:
https://www.jqueryscript.net/time-clock/Date-Time-Picker-Bootstrap-4.html
e ele me trouxe esta estrutura de arquivos:

Eu tentei incluí-los no meu projeto assim:

<link rel="stylesheet" href="~/lib/bootstrap/css/bootstrap.min.css" />

Porém, eu nao posso utilizar ele atraves deste link. Como eu baixo ele manualmente para adicionar o caminho ao meu projeto?
EDIT1: Como eu mudo a linguagem para português?

Reapre que os dias e os meses então em inglês. Como eu os mudo para português?

Tradução pelo browser ^

A: Seu problema é que faltou vc indexar o moment.js antes do JS datapicker
Vc pode baixa-lo aqui: https://www.jqueryscript.net/demo/Date-Time-Picker-Bootstrap-4/build/js/bootstrap-datetimepicker.min.js (basta dar um ctrl+C no script e colocar em um arquivo .js no seu ambiente de trabalho e indexar no seu documento)
Veja um exemplo funcionando no Bootstrap 4 abaixo, repare na ordem e nos arquivos que foram indexados no documento

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="https://www.jqueryscript.net/css/jquerysctipttop.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="https://www.jqueryscript.net/demo/Date-Time-Picker-Bootstrap-4/build/css/bootstrap-datetimepicker.min.css" />

Date/Time Picker Component For Bootstrap 4 Demo

                  <input type='text' class="form-control" id='datetimepicker1' />


text:
Q: Im mysql, not getting id in our chat application, the following is the case, there is person 'A' who have chat with person 'B' in two cases,1) one-to-one chat and 2) group chat. so in the database records are as follows,
Table : core
  id   name
   1    A
   2    B
   3    C

Table : Master
  id    core_id
  1       1
  2       2

Table : recepient
 id    core_id    master_id
  1       1        1
  2       2        1
  3       1        2
  4       2        2
  5       3        2

so in the recepient table, we have 2 entries for Person 'A'. Now the problem is, i want the master_id = 1 form recepient table, in which person 'A' and 'B' are communicated. But there are two entries in recepient table for this. so how to get that id?

A: It's unclear what you are asking and your table names do not assist in making this any clearer. However, I suspect you are selecting records from the recipient table based only on the master_id and need to join with the other tables so that you can also include the name in the query.
So with this in mind, try the following (caveat: I haven't tested this, and I work with Oracle not mysql) but:
select *
from core c, master m, recipient r
where c.id = m.core_id
and   c.id = r.core_id
and   m.id = r.master_id
and   c.name = 'A'

And before anyone complains that this sql does not follow the latest ANSI standard, it's the way I do it and it works for me!


text:
Q: How to rename RavenDB database using ClientAPI? Is there a way of renaming a RavenDB database from code by using ClientAPI and operations?

A: A database cannot be renamed from code.
You need to 'soft' delete the database and then recreate it on the same path with a new name.
See full explanation in: RavenDB Book - Renaming a database


text:
Q: Max interval intersection point I am trying to implement the logic in python. Given a set of intervals, find the interval which has the maximum number of intersections. If input (1,6) (2,3) (4,11), then (1,6) should be returned. This has been answered in below but I have been unable to implement it in python.
given-a-set-of-intervals-find-the-interval-which-has-the-maximum-number-of-inte.
So far I am using the below logic. Any help will be greatly appreciated.
def interval_intersection(intervals):
    if len(intervals) ==1:
        return intervals
    intervals.sort(key=lambda x: x[0])

    res =[intervals[0]]
    for i in range(1,len(intervals)):
        if intervals[i][0] > res[-1][1]:
            res.append(intervals[i])
        else:
            res[-1] = [min(res[-1][0],intervals[i][0]),max(res[-1][1],intervals[i][1])]
    return res

Examples:

*

*[[1,5],[5,10],[5,5]]
ans should be [5,5]
In case of tie [5,5] the interval with least number of elements . Here [5,5] has only 1 element in the range ie 5 hence the ans

*[[1,2],[3,5]]
no intersection return -1

A: This is a fairly straightforward implementation of David Eisenstat's algorithm. The only subtleties are:

*

*I assume that all intervals are closed on both ends, which means that sorting events should put starts before ends if they're simultaneous. If you want intervals that are fully open, or open on the right side, this order needs to be reversed.

*The returned interval has the most intersections, with ties broken first by smallest length, then by earliest start.

def interval_solve(intervals: Sequence[Sequence[int]]) -> Union[Sequence[int], int]:
    start_type = -1  # Assumes all intervals are closed
    end_type = 1

    events = [(s, start_type, i) for i, (s, e) in enumerate(intervals)]
    events.extend((e, end_type, i) for i, (s, e) in enumerate(intervals))
    events.sort()

    inter_count: Dict[int, int] = {}

    start_count = 0
    stop_count = 0

    for event_time, event_type, event_id in events:
        if event_type == start_type:
            start_count += 1
            inter_count[event_id] = -(stop_count + 1)
        else:
            stop_count += 1
            inter_count[event_id] += start_count

    # Find max by most intersections, then by shortest interval, then by earliest start
    answer = max(range(len(intervals)),
                 key=lambda j: (inter_count[j], intervals[j][0] - intervals[j][1]))
    if inter_count[answer] == 0:
        return -1
    return intervals[answer]

A: The actual idea is pretty simple, we sort the intervals and store some of them with an index and a boolean key for indicating the start or end events.
Then, we just traverse it while counting the end events before an index and the start events. For any index i, interval overlap count is simply, number of start events before - number of end events before (-1).
Finally, we can just check which one has the minimum length in case of multiple solutions.
# https://stackoverflow.com/questions/69426852/max-interval-intersection-point

def max_interval_count(intervals):
    interval_sorted = []
    for idx, interval in enumerate(intervals):
        s, e = interval
        interval_sorted.append([s, idx, 0]) # 0 for start
        interval_sorted.append([e, idx, 1]) # 1 for end
    interval_sorted.sort(key = lambda x: x[0])

    print(interval_sorted)

    number_of_starts = 0
    number_of_ends = 0

    overlap_count = {}
    for event in interval_sorted:
        _, idx, start_end = event
        if start_end == 0: # start event
            # subtract all the ending before it
            overlap_count[idx] = - (number_of_ends)
            number_of_starts += 1
        else: # end event
            overlap_count[idx] += (number_of_starts - 1) # -1 as we should not include the start from the same interval
            number_of_ends += 1
    print(overlap_count)
    ans_idx = -1
    max_over_count = 0
    min_len_interval = 99999999999
    for idx, overl_cnt in overlap_count.items():
        if overl_cnt > max_over_count:
            ans_idx = idx
            max_over_count = overl_cnt
        elif overl_cnt == max_over_count and overl_cnt > 0 and (intervals[idx][1] - intervals[idx][0] + 1) < min_len_interval:
            min_len_interval = (intervals[idx][1] - intervals[idx][0] + 1)
            ans_idx = idx
    if ans_idx == -1:
        return ans_idx
    return intervals[ans_idx]

if __name__ == "__main__":
    test_1 = [[1,5],[5,10],[5,5]]
    test_2 = [[1,2],[3,5]]
    test_3 = [(1,6), (2,3), (4,11)]
    ans = max_interval_count(test_1)
    print(ans)
    print("---------")
    ans = max_interval_count(test_2)
    print(ans)
    print("---------")
    ans = max_interval_count(test_3)
    print(ans)
    print("---------")

[[1, 0, 0], [5, 0, 1], [5, 1, 0], [5, 2, 0], [5, 2, 1], [10, 1, 1]]
{0: 0, 1: 1, 2: 1}
[5, 5]
---------
[[1, 0, 0], [2, 0, 1], [3, 1, 0], [5, 1, 1]]
{0: 0, 1: 0}
-1
---------
[[1, 0, 0], [2, 1, 0], [3, 1, 1], [4, 2, 0], [6, 0, 1], [11, 2, 1]]
{0: 2, 1: 1, 2: 1}
(1, 6)
---------


text:
Q: How to ignore FIND errors in bash script? I'm using a script to cleanup logfiles from a tomcat webserver.
Problem:
find $file_pattern will return an error if a filepattern did not match any results.
The following is run by crontab:
arch_logs() {
    for file_pattern; do
        i=1
        for log_file in $(find $file_pattern | sort -r); do
            test $i -eq 1 && ((i=i+1)) && continue;
            sudo gzip "$log_file"
            sudo mv *.gz ./archive/
        done
    done
}

arch_logs 'catalina.2*' 'host-manager.*' 'localhost.*' 'localhost_access_log.*' 'manager.*'

https://yottabrain.org/tomcat/tomcat-log-backup/
Result: find: 'catalina.2*': No such file or directory
Question: how can I prevent those errors from find inside the function?


text:
Q: Adding multiple nested nodes in GeoExt? I have following codes, but i want to add severel parent>child>chill>child>child (4 level inside) nodes with all check box options (for user choice) in the tree panel, in fact sum of all these (parent + child) will be of around 800 entry (like tree panel of http://map.rostmuseum.ru/)
 again i want to load childs to be loaded as a part of the grand parent of all subsequent parent and childs (i think i will do it by including cql parameter included url from my geoserevr , is not it will be the best way) as overlay.
    var mapPanel;
    Ext.onReady(function() {
    // create a map panel with some layers that we will show in our layer tree
    // below.
    mapPanel = new GeoExt.MapPanel({
    border: true,
    region: "center",
    // we do not want all overlays, to try the OverlayLayerContainer
    map: new OpenLayers.Map({allOverlays: false}),
    center: [90.04142, 23.77647],
    zoom: 7,
    layers: [
    new OpenLayers.Layer.WMS("Bangladesh",
    "http://localhost:8080/geoserver/cite/wms", {
    layers: "thana"
    }, {
    buffer: 0,
    visibility: false
    }
    ),
    /* new OpenLayers.Layer.WMS("Tasmania State Boundaries",
    "http://demo.opengeo.org/geoserver/wms", {
    layers: "topp:tasmania_state_boundaries"
    }, {
    buffer: 0
    }
    ),*/
    /* new OpenLayers.Layer.WMS("Water",
    "http://demo.opengeo.org/geoserver/wms", {
    layers: "topp:tasmania_water_bodies",
    transparent: true,
    format: "image/gif"
    }, {
    isBaseLayer: false,
    buffer: 0
    }
    ),*/
    new OpenLayers.Layer.WMS("Rivers",
    "http://localhost:8080/geoserver/cite/wms", {
    layers: "cite:river",
    transparent: true,
    format: "image/gif"
    }, {
    isBaseLayer:true,
    buffer: 0
    }
    ),
    new OpenLayers.Layer.WMS("Roads",
    "http://localhost:8080/geoserver/cite/wms", {
    layers: "cite:roadnetwork",
    transparent: true,
    format: "image/gif"
    }, {
    isBaseLayer: false,
    buffer: 0
    }
    ),
    // create a group layer (with several layers in the "layers" param)
    // to show how the LayerParamLoader works
    new OpenLayers.Layer.WMS("Bangladesh (Boundaries)",
    "http://localhost:8080/geoserver/it.geosolutions/wms", {
    layers: [
    "internationalboundary",
    "divisionalboundary",
    "districtbounday",
    "thanaboundary"
    ],
    transparent: true,
    format: "image/gif"
    }, {
    isBaseLayer: false,
    buffer: 0,
    // exclude this layer from layer container nodes
    displayInLayerSwitcher: false,
    visibility: false
    }
    )
    ]
    });

    // create our own layer node UI class, using the RadioButtonMixin
    var LayerNodeUI = Ext.extend(
    GeoExt.tree.LayerNodeUI, new GeoExt.tree.RadioButtonMixin()
    );

    // using OpenLayers.Format.JSON to create a nice formatted string of the
    // configuration for editing it in the UI
    var treeConfig = new OpenLayers.Format.JSON().write([{
    nodeType: "gx_baselayercontainer"
    }, {
    nodeType: "gx_overlaylayercontainer",
    expanded: true,
    // render the nodes inside this container with a radio button,
    // and assign them the group "foo".
    loader: {
    baseAttrs: {
    radioGroup: "foo",
    uiProvider: "use_radio"
    }
    }
    }, {
    nodeType: "gx_layer",
    layer: "Bangladesh (Boundaries)",
    isLeaf: false,
    // create subnodes for the layers in the LAYERS param. If we assign
    // a loader to a LayerNode and do not provide a loader class, a
    // LayerParamLoader will be assumed.
    loader: {
    param: "LAYERS"
    }
    }], true);

    // create the tree with the configuration from above
    var tree = new Ext.tree.TreePanel({
    border: true,
    region: "west",
    title: "Layers",
    width: 200,
    split: true,
    collapsible: true,
    collapseMode: "mini",
    autoScroll: true,
    loader: new Ext.tree.TreeLoader({
    // applyLoader has to be set to false to not interfer with loaders
    // of nodes further down the tree hierarchy
    applyLoader: false,
    uiProviders: {
    "use_radio": LayerNodeUI
    }
    }),
    root: {
    nodeType: "async",
    // the children property of an Ext.tree.AsyncTreeNode is used to
    // provide an initial set of layer nodes. We use the treeConfig
    // from above, that we created with OpenLayers.Format.JSON.write.

    //work
    children: Ext.decode(treeConfig)

    },
    listeners: {
    "radiochange": function(node){
    alert(node.layer.name + " is now the the active layer.");
    }
    },
    rootVisible: false,
    lines: false,
    bbar: [{
    text: "Show/Edit Tree Config",
    handler: function() {
    treeConfigWin.show();
    Ext.getCmp("treeconfig").setValue(treeConfig);
    }
    }]
    });

    // dialog for editing the tree configuration
    var treeConfigWin = new Ext.Window({
    layout: "fit",
    hideBorders: true,
    closeAction: "hide",
    width: 300,
    height: 400,
    title: "Tree Configuration",
    items: [{
    xtype: "form",
    layout: "fit",
    items: [{
    id: "treeconfig",
    xtype: "textarea"
    }],
    buttons: [{
    text: "Save",
    handler: function() {
    var value = Ext.getCmp("treeconfig").getValue()
    try {
    var root = tree.getRootNode();
    root.attributes.children = Ext.decode(value);
    tree.getLoader().load(root);
    } catch(e) {
    alert("Invalid JSON");
    return;
    }
    treeConfig = value;
    treeConfigWin.hide();
    }
    }, {
    text: "Cancel",
    handler: function() {
    treeConfigWin.hide();
    }
    }]
    }]
    });

    new Ext.Viewport({
    layout: "fit",
    hideBorders: true,
    items: {
    layout: "border",
    deferredRender: false,
    items: [mapPanel, tree, {
    contentEl: "desc",
    region: "east",
    bodyStyle: {"padding": "5px"},
    collapsible: true,
    collapseMode: "mini",
    split: true,
    width: 200,
    title: "Catalog"
    }]
    }
    });
    });

Can you guide me?


text:
Q: How can design using pure css?
This is the image I want to design using pure css without background image, can use background color. Any suggestion me to do design for above mentioned image.

A: I don't have many reputations to comment on, i.e. I'm replying to you in the answer. I'm a newbie.

You have to research more on this content, you should search "Pure Css Posters" on youtube for reference.
For now, I would suggest you some ideas.
1. You can use 2 sections to create those white blocks, and For Shape Just use the "clip-path" Property and for the card container, put a gradient on the background using linear-gradient.
2. In those white sections, use before or after selectors to mark that greyish part.
3. Make sure you're using Flex properties to keep it aligned.


text:
Q: Abstract types puzzler Given class A is:
class A {
  type R
}

Why does the following code compile (and run too)?
val a = new A
println(a)

Isn't A supposed to be abstract?

A: A isn't abstract.  If it were abstract then it would look like:
abstract class A {
  type R
}

or
trait A {
  type R
}

Now, I can't find it in the spec (haven't had much luck with finding stuff in there lately) but I've seen this before.  If the type isn't used, then it appears as though it's not evaluated, which means the lack of its completeness is not an issue.
If you really want A to be abstract, make it so using one of the above definitions instead.

A: Just to elaborate on @alex22's comment:
scala> trait T { type R; def foo(r: R) = r }
defined trait T

scala> new T{}.foo("")
<console>:12: error: type mismatch;
 found   : java.lang.String("")
 required: _6.R where val _6: java.lang.Object with T
              new T{}.foo("")
                          ^

scala> new T{ type R = String }.foo("")
res37: java.lang.String = ""

A: Abstract type seems to have default value Nothing.