text:
Q: Are there an infinity of consecutive primes that have no common digit? Examples: $2$ & $3$, $3$ & $5$, $5$ & $7$, $59$ & $61$, $99999989$ & $100000007$.
I was inspired by the fact that, in English, all consecutive numbers share a common letter, such as seven & eight that share 'e'. See Alex Bellos's Math Puzzle section of the Guardian newspaper dated February 20, 2023. Instead I consider consecutive primes and their base representation.
Except for $2$ & $3$, $3$ & $5$ and $5$ & $7$ all such base-$10$ consecutive primes are of the form: $a \times 10^n - b$ and $a \times 10^n + c$ with $1 \le a\le 8$. It is easy to show that $a$ cannot be $9$.
I found $701$ cases below $10^{500}$. A larger example (with probable primes) is $1 \times 10^{4001}-15141$ and $1 \times 10^{4001}+1011$.
I am pessimistic that the conjecture can be easily proved.
Landau's conjecture that there are infinitely many primes $p$ of the form $p=n^2+1$ remains open.
For other bases: in base $2$ there are no such consecutive primes.
In base $3$ it is easy to show that there are none, except $2$ & $3$.
Base $4$ is the first interesting base.
All cases must be of the form $4^n - b$ and $4^n + c$
(except for $2$ & $3$).
I found only $5$ cases with $n$ = $1$, $4$, $28$, $83$ and $1816$.
EDIT: Replaced "disjoint" with the more standard "have no common digits". See the result for squares in oeis.org/A156981

A: Heuristically, we expect the typical gap between primes of $n$ digits to be on the order of  $n$.   When this is much larger than $10^{10}$, it becomes unlikely that the
greatest prime $< a \times 10^{n}$ and the least prime $> a \times 10^{n}$ are disjoint. So I would suspect that there are only finitely many disjoint consecutive primes.  Of course this is not a proof.


text:
Q: How to detect the given model is a keras or scikit model using python? If I want to determine the type of model i.e. from which framework was it made programmatically, is there a way to do that?
I have a model in some serialized manner(Eg. a .h5 file). For simplicity purposes, assume that my model can be either tensorflow's or scikit learn's. How can I determine programmatically which one of these 2 is the one?

A: you can either use type(model) to see its type
you can also use help(model) to get the doc string from model.
you can also use dir(model) to see its member function or parameters.
you can also use import inspect inspect.getsource(model) to get source code of a object.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use a function in onclick that was declared inside window.onload? Here is my code:
<html>
    <head>
    <script type="text/javascript">
    window.onload = function(){
        function b(){c();}
    }
    function c(){alert('');}
    </script>
    </head>
    <body>
    <input type="button" onclick="b()">
    </body>
</html>

Q1 : I want to access function b() on click event of button in body tag.
Q2 : I want to access function c() from function b() within window.onload.

A: Q1 : I want to access function b() on click event of button in body tag.
That's fine, you just need to be able to access it. onclick="b()" is the same as onclick="window.b()" so that obviously won't work the way it is. You can either make window.b evaluate to the correct function or establish the event programatically from code.
Q2 : I want to access function c() from function b() within window.onload.
That's fine, and it already works that way.


text:
Q: error while trying vaadin jpacontainer example I'm getting
java.lang.NoClassDefFoundError: com/vaadin/data/util/converter/Converter$ConversionException
error. I have made Person class as entity, and my application class is like this:
public class SimplejpaApplication extends Application  {

    @Override
    public void init() {
        // TODO Auto-generated method stub
        VerticalLayout layout = new VerticalLayout();
        JPAContainer<Person> persons =
        JPAContainerFactory.make(Person.class, "book-examples");
        persons.addEntity(new Person("Marie-Louise Meilleur", 117));
        Table personTable = new Table("The Persistent People",persons);
        layout.addComponent(personTable);

        setMainWindow(new Window("simple",layout));
    }

I'm using vaadin-jpacontainer-agpl-3.0-3.0.0-alpha2.jar
Can someone tell why this error happening? thank you.

A: Converter class is from Vaadin 7 but you are using Vaadin 6. You need to use vaadin-jpacontainer-agpl-3.0-2.1.0 for Vaadin 6.
Or you can upgrade your project to Vaadin 7 and use vaadin-jpacontainer-agpl-3.0-3.0.0-alpha2.jar.
Both jar files can be downloaded from Vaadin add-on page https://vaadin.com/directory#addon/vaadin-jpacontainer.


text:
Q: Monitoring and reading new lines in a file? The program uses the AnyEvent event loop. The program should read new lines that sometimes (rarely) appear in a text file on the local file system. As I understood, AnyEvent::io can not be used. What can I advise to read new lines from a file?

A: One way is to "watch" the file with a tool that tracks and reports events on filesystem objects.
An example using Linux::Inotify2, based on the synopsis in module's documentation
use warnings;
use strict;
use feature 'say';

use AnyEvent;
use Linux::Inotify2;

my $file = shift @ARGV || 'growing.txt';
die "Usage: $0 file-to-watch\n" if not $file;

say '';
open my $fh, '<', $file  or die "Can't open $file: $!";
print while <$fh>;

my $inotify = Linux::Inotify2->new or die "Can't create inotify object: $!";

$inotify->watch( $file, IN_MODIFY, sub {
    my $e = shift;
    if ($e->IN_MODIFY) {
        print while <$fh>;
    }
});

my $inotify_w = AnyEvent->io (
    fh => $inotify->fileno, poll => 'r', cb => sub { $inotify->poll }
);

1 while $inotify->poll;

The monitor can be used with many major event handling tools. This example uses AnyEvent.
First create the file growing.txt, presumably with some content. Then start the program and put it in the background (watcher.pl &), when its lines are printed. Then add to the file
echo "new line\nanother" >> growing.txt

and the watcher prints

new line
another

Please see this post for a little more and some general comments, and study the module's docs and man inotify on your system.
To do this along with other things you can put it in a forked process and send changes to the parent as they come (via pipe, socketpair, or files). Any events that happen during the processing are still detected, and delivered as new events once the control returns.
The parent can deal with the question of when to read by doing its other work in a loop with a non-blocking IO::Select::can_read, or with a signal handler for a user signal (SIGUSR1) which the child sends after writing to its pipe end.
This is an outline of something that isn't quite simple.  There are also ready solutions. Some options from the AnyEvent ecosystem are AnyEvent::Fork and friends, AnyEvent::Subprocess with its "delegates" mechanism, AnyEvent::Handle to watch that pipe for when it can be read.
All these require an event loop as well, in which case all work is done in handlers (callbacks). Then the main work can be done in an "idle watcher," for instance, but this may turn out a bit convoluted and in this particular case the outlined manual approach for the child management may end up being clearer.
The most suitable management of the monitor depends on the details of your program.

If the file is changed in a way that changes the inode, the code above won't be able to detect that. This can happen with many common tools, like zip, rsync, etc. To secure against that, along with possible file disappearance, you can use other flags so to detect those events.
$inotify->watch( $file,
    IN_MODIFY |IN_ATTRIB | IN_MOVE_SELF | IN_DELETE_SELF,
    sub {
        my $e = shift;
        my $name = $e->fullname;
        if ($e->IN_MODIFY) {
            print while <$fh>;
        }
        if ($e->IN_ATTRIB)      { say "$name meatadata changed" }
        if ($e->IN_MOVE_SELF)   { say "$name was moved" }
        if ($e->IN_DELETE_SELF) { say "$name was deleted" }
});

For the inode change it is IN_ATTRIB that is fired.
Then you may need to re-open the file (and perhaps first find it). A separate directory monitor would be very helpful here. All this can also be done by using a directory monitor alone.


text:
Q: Issue with height in the paper-material polymer I have the following needed in my project, and I've really tested every combination of css that I have found on the internet, but I can't solve this problem, I have created two custom elements in a polymer application based on Polymer Starter Kit:
First element:
<dom-module id="my-register">
    <template>

        <paper-material elevation="1" animated="true" class="paper-material-presentation">

Risk-Free 30 Days Trial

                        <my-registerform></my-registerform>

                        <my-peoplecomment></my-peoplecomment>

        </paper-material>
    </template>

</dom-module>

Second Element:
<dom-module id="my-registerform">
    <template>

        <paper-material elevation="1" animated="true" class="paper-material-register-form">

Let's Get Started

            <paper-input label="Enter your email" id="email" required value="{{email}}">
                <iron-icon icon="mail" prefix class="iron-icon-padding"></iron-icon>
                <paper-icon-button suffix onclick="clearInput()" icon="clear" alt="clear" title="clear" />
            </paper-input>
            <paper-button raised id="bt_register" class="paper-button-fullsize">
                Continue...
                <iron-icon icon="arrow-forward" suffix></iron-icon>
            </paper-button>
            Have an account already? Please Login
        </paper-material>
    </template>

My question is: How can I make the paper-material of the First Element to increment and fit the height of the components inside it. Because right now when I see the page in the mobile or tablet the paper material inside the Second Element expand outside the paper material container.
Note: The code of css is the original one I tested use `height=auto`, change `position=relative` but anything worked.

A: Thank you all for your comments, I found the solution, in the first element delete from the class: div-generalla referencia a: @apply(--layout-fit); and after that assign a height in pixels to the class: div-top. And that's all everything working...


text:
Q: Create EML file MethodInfo.Invoke giving Parameter count mismatch I am trying to create .eml file . I use below code. But whenever it reaches to method.Invoke it gives me error Parameter count mismatch..Below is my code to create eml file.
    try
        {
           MailMessage m = new MailMessage();
           m.Body = htmlbody;
           var htmlView = AlternateView.CreateAlternateViewFromString(m.Body, null, "text/html");

            MailAddress newFromAddress = new MailAddress("select.sender@sender.com", "(Please select sender)");
            m.Sender = null;
            m.From = newFromAddress;
            m.Headers.Add("X-Unsent", "1");  //Make the eml file open in compose mode
            m.AlternateViews.Add(htmlView);  //Add the html content to the email
            m.Subject = subject;
            m.IsBodyHtml = true;

            var assembly = typeof(SmtpClient).Assembly;
            var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
            using (MemoryStream stream = new MemoryStream())
            {
                //Construct the mail message file .eml
                ConstructorInfo mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
                object mailWriter = mailWriterContructor.Invoke(new object[] { stream });
                MethodInfo sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);
                ///**This is line where I get error**///  sendMethod.Invoke(m, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null);

                return stream.ToArray();
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.ToString());
        }

UPDATE :
I am using .Net Framework 2.0. Is this making issue?

A: Looking at the source it seems Send method only takes 2 arguments
 internal void Send(BaseWriter writer, bool sendEnvelope)

http://www.dotnetframework.org/default.aspx/DotNET/DotNET/8@0/untmp/whidbey/REDBITS/ndp/fx/src/Net/System/Net/Mail/MailMessage@cs/2/MailMessage@cs
You will need to pass these into the invoke call.
sendMethod.Invoke(m, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true}, null);


text:
Q: Visual Studio 2012 deploying workflow I uploaded the wsp file of a visual studio 2012 workflow to galleries->solutions in central admin. The feature appears in manage features on central admin but does not show up in site settings on sites to be activated. Also does not show up on list of workflows.

A: Have you checked this link. This is the users' sentiment about VS2012 deployment:
http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/3041773-bring-back-the-basic-setup-and-deployment-project-


text:
Q: Is CP-1251 an extension to ASCII? If I need Cyrillic characters in ASCII format that will imply that I will need an extended ASCII table, right? I want to know if cp-1251 is an extension of ASCII and if not what is it considered to be. I got a bit confused with searching google. In some places they say it is a codepage in other extension.
Also if I have cp-1251 character O with code 206 then the UTF-8 value of the same char will be 041E, right?

A: "Extended ASCII" is an ambiguous term.
US-ASCII supports 128 values (the 8th bit is reserved) and does not support any Cyrillic code points. The first half of Windows 1251 maps code points to the same range of values. The same is true of UTF-8. Therefore, any documents encoded as ASCII are legal Windows 1252, Windows 1251, UTF-8, ISO-8859-1, and a few other encodings.
U+004F ( LATIN CAPITAL LETTER O) encoded as ASCII, Windows-1251 or UTF-8 will have the same octet value (4F) when viewed using a hex editor.
For natural language data most non-Unicode encodings should be considered obsolete.

A: ASCII is a standard.  It is a 7 bit code.
It contains values in the range of 0 .. 127.
Everything else is not ASCII.
On a PC one can deal with Code Pages.   You may be able to select a code page which contain the characters you are interested in.
It may be of benefit to look into Unicode which can support ASCII and pretty much any other character that was ever invented.

A: Technically, ASCII is a 7-bit format that contains no Cyrillic characters.  Given this, one cannot truly have Cyrillic characters in genuine ASCII format.
CP-1251 is an 8-bit encoding that includes Cyrillic characters.  The first 128 characters of CP-1251 are the same as ASCII, so in that sense it is an extension of ASCII.  Ultimately, however, CP-1251 is just a character encoding, i.e. a mapping between characters and numeric values.
The Unicode family of encodings has the greatest momentum for modern internationalized applications at this time, with UTF-8 being the most popular due to its compact representation for basic ASCII characters.  Using Unicode fully requires being able to process multi-byte characters, including using more sophisticated algorithms for text-processing tasks like sorting, searching, and text comparison.
Unfortunately, character encoding is no longer as simple as it was when US-ASCII was king.  Of course, even then competitors like EBCDIC muddied the waters.
A few links that might help:
http://www.unicode.org/
http://msdn.microsoft.com/en-us/goglobal/cc305144
http://en.wikipedia.org/wiki/Windows-1251


text:
Q: How to get the class of a generic interface with wildcard I'm trying to achieve to get a class from his name.
In my case all classes I want to get implements the generic interface Prototype<T>.
But the delicate part of my problem is that I'm "Warningophobe".
I wrote:
// Warning: Usage of interface raw type
Class<? extends Prototype> prototypeClass;
try {
    Class<?> clazz = Class.forName("mova.game.monster.Goblin");
    prototypeClass = clazz.asSubclass(Prototype.class);
    System.out.println(prototypeClass);
} catch (ClassNotFoundException cnfe) {
    cnfe.printStackTrace();
}

This code work, but here, my IDE (IntellIJ) tell me that I'm using my "raw interface".
I know I can do that:
Class<? extends Prototype<?>> prototypeClass;
try {
    Class<?> clazz = Class.forName("mova.game.monster.Goblin");
    // Warning: unchecked cast
    prototypeClass = (Class<? extends Prototype<?>>) clazz.asSubclass(Prototype.class);
    System.out.println(prototypeClass);
} catch (ClassNotFoundException cnfe) {
    cnfe.printStackTrace();
}

But now, I have an uncheked cast.
So, is there a proper way to achieve this problem without warning?


text:
Q: This item isn't available in your country I had uploaded a new application on google play store, and everything done, but some users have a problem in downloading the application:
"This item isn't available in your country", I don't know what to do in this case, can anyone help me with this please.

A: Check your listing in the Developer control panel.
There is a listing for where the app is available (Pricing & Distribution section - Manage Countries).  The checkbox for whatever country needs to be checked on.  Otherwise, it's locked out.
For convenience, there is a box at the top that says "SELECT ALL COUNTRIES".
For what it's worth, if the country in question is not on the list, there is nothing you can do about that.  There are a number of rules and regulations about where Google Play can distribute stuff.  You have no control over that.

A: I moved to a new country and i was facing this issue whenever i tried to install some apps that are famous in this country so i had tried various ways to resolve this issue through online forums unfortunately nothing worked so i contacted the google play services support desk and they helped me in resolving this issue, the steps I followed are below:

*

*Go to https://payments.google.com/payments

*Click on settings at left side of screen

*Create a new payments profile in which you will be giving the country to which you have moved recently.

*After successfully completion of creating a payments profile, go to phone settings => all apps => Google play store => clear cache and data.

*Click back and open system apps => search for download manager => clear cache and data.

*Most probably it should work right now if not wait for an hour.


text:
Q: Explanation how it can be that $f'(x) = g(x)$ but wolfram alpha says $\int g(x) \neq f(x)$? I've just started learning about antiderivatives/primitive functions/indefinite integrals, and I have the functions
$f(x) = 3 \ln((\frac{x+2}{3})^2 + 1)$
$g(x) = \dfrac{2\frac{x+2}{3}}{(\frac{x+2}{3})^2 + 1}$
I came to the conclusion that $f'(x) = g(x)$ so that $\int g(x) = f(x)$ and I wanted to check with wolfram alpha, but wolfram says that $\int g(x) \neq f(x)$ even though it says $f'(x) = g(x)$.
It seems to me that this violates the definition of antiderivative?

A: The symbol $\int g(x) dx$ means the set of all antiderivatives of $g$. Since $f$ is an antiderivative of $g$ , we have
$\int g(x) dx=f(x)+C.$

A: The function $f(x)$ is one of the infinite number of antiderivatives of the function $g(x)$ which differ only by a constant. In the case of $f(x)$, that constant, typically denoted as $C$, is 0. When you integrate $g(x)$, you get a whole set of functions. Not just one function. That set is usually denoted $f(x)+C$ where $C\in\mathbb{R}$. Therefore, this means that there are going to be as many functions in that set as there as real numbers—that is, an infinite number. That's why, technically speaking, $\int g(x)\,dx\neq f(x)$. The result of the integration process is not a function, but a set of functions. Those are slightly different concepts.


text:
Q: How to die Correctly on Soap::Lite in perl I have written a perl script that connects using Soap::Lite and collect data from a web-service and update a database. This works well, until the password gets locked out and I get a server 500 error which is where my question comes in. How do I let the Soap::Lite query die when it does not make a successful connection, so it does not continue with the rest of the script?
  .....
  my $host   = "hostname";
  my $user   = "user";
  my $pass   = "pass";
     $soap_proxy  = "https://" . $user . ":" . $pass . "@" . $host . ":8090/services/ApiService";
     $uri    = "http://api.config.common.com";

     $client                                    =  new SOAP::Lite
       uri                                           => $uri,
       proxy                                         => $soap_proxy,
       autotype                                      => 0;
  my $soap_respons = $client->getSomething();
  ....

I have tried the usual or die $! but that does not die like other queries do and still continues with the remaining script.
according to the SOAP::Lite examples on CPAN, you could use:
if ($@) {
   die $@;
 }

But I do not know where to put this. I tried directly under my $soap_respons but still it does not die.

A: SOAP::Lite queries will give a fault with a faultstring result if errors occur, something like this should work.
die $soap_respons->faultstring if ($soap_respons->fault);
print $soap_respons->result, "\n";

A: You could set the on_fault callback. This way you wouldn't have to check every response.
$client->on_fault(sub { die($_[1]) });


text:
Q: JTextArea Won't Update Unless I Resize JFrame Whenever I run my program my JTextArea does not follow the dimension that I have given it, but if I resize my JFrame it updates and sets its size to what I put.
What is the issue?
    public ControlPanel() {
    // create our list of players
    list = new JList(model);

    // create our scroll panes
    userspane = new JScrollPane(list);
    consolepane = new JScrollPane(console);

    // set sizes
    userspane.setSize(100, 500);
    jta.setSize(100, 500);
    list.setSize(100, 500);
    consolepane.setSize(100, 500);
    console.setSize(100, 500);

    // add to panel
    panel.add(userspane, BorderLayout.CENTER);
    panel.add(kick);
    panel.add(ban);
    panel.add(info);
    panel.add(consolepane, BorderLayout.CENTER);

    // set frame properties
    setTitle("RuneShadows CP");
    setSize(280, 400);
    //setResizable(false);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setContentPane(panel);
    setVisible(true);
}

A: Don't set the sizes to anything.

*

*For JTextArea you can use the constructor JTextArea(int rows, int charSpaces)

*Just pack() the JFrame and it will respect all the preferred sizes of the components inside.

*Also instead of setting the content pane to the panel, just add the panel. That will respect the preffered size of the panel when pack() is called

I'm not exactly sure what variable was what (or the sizes you wanted the), so I assumed text areas, and others as well. See this example where I just used the JTextArea constructor I mentioned and just packed.
EDITED with no sizes set
import java.awt.BorderLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class ControlPanel extends JFrame {

    JScrollPane userspane;
    JList list;
    DefaultListModel model = new DefaultListModel();
    JScrollPane consolepane;
    JTextArea console = new JTextArea(20, 50);
    JTextArea jta = new JTextArea(6, 50);
    JPanel panel = new JPanel();

    JButton kick = new JButton("Kick");
    JButton ban = new JButton("Ban");
    JButton info = new JButton("Info");

    public ControlPanel() {
        // create our list of players
        list = new JList(model);

        // create our scroll panes
        userspane = new JScrollPane(list);
        consolepane = new JScrollPane(console);

        // add to panel
        panel.add(userspane, BorderLayout.CENTER);
        panel.add(kick);
        panel.add(ban);
        panel.add(info);
        panel.add(consolepane, BorderLayout.CENTER);

        add(panel);
        pack();
        setTitle("RuneShadows CP");
        //setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                new ControlPanel();
            }
        });
    }
}

UPDATE - with positioning
Keep in mind also, with BorderLayout you need to specify a position for every component you add or else it will default to CENTER and each position an only have one component.  I noticed you trying to add two components to the CENTER
import java.awt.BorderLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class ControlPanel extends JFrame {

    JScrollPane userspane;
    JList list;
    DefaultListModel model = new DefaultListModel();
    JScrollPane consolepane;
    JTextArea console = new JTextArea(20, 50);
    JTextArea jta = new JTextArea(6, 50);
    JPanel panel = new JPanel(new BorderLayout());

    JButton kick = new JButton("Kick");
    JButton ban = new JButton("Ban");
    JButton info = new JButton("Info");

    public ControlPanel() {
        // create our list of players
        list = new JList(model);

        // create our scroll panes
        userspane = new JScrollPane(list);
        consolepane = new JScrollPane(console);

        // add to panel
        panel.add(userspane, BorderLayout.SOUTH);
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(kick);
        buttonPanel.add(ban);
        buttonPanel.add(info);
        panel.add(buttonPanel, BorderLayout.CENTER);
        panel.add(consolepane, BorderLayout.NORTH);

        add(panel);
        pack();
        setTitle("RuneShadows CP");
        //setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                new ControlPanel();
            }
        });
    }
}


text:
Q: Delphi - Show a multiline caption in the designer I am replacing in runtime the Caption of several components to get a multiline Caption.
MySpeedButton.Caption := 'Line 1' + #13 + #10 + 'Line 2';

Is there a way to persuade Delphi to show a wordwrap also in the designer?

A: You can force the caption of a TSpeedButton to be multiline by editing the caption in Text View of the form:
  object SpeedButton1: TSpeedButton
    Left = 8
    Top = 63
    Width = 113
    Height = 50
    Caption = 'Line 1Line 2'       // original caption
    Caption = 'Line 1'#10'Line 2'  // modified caption
  end

Note! You must add the two single quotes on both sides of the #10. Instead of #10 you can use #13 or both #13#10.
For an ordinary TButton you need to set the WordWrap property in addition to the above modification to the Text View of the form.

A: You can do that by using the CnPack
After installing it, make sure the String Caption Editor is enabled and add TSpeedButton.Caption to the Customize section.

In the Object Inspector you will see a button edit which will allow you to set a multi line caption.


text:
Q: How can one decipher the IANA port registration form? I have created a simple Twisted based TCP server and Android client. I have used my own protocol for this purpose. While I have tried to lay out my protocol in a way which seems logical, this is the first protocol that I have written, so I doubt it conforms to any standards for a TCP protocol, if such norms even exist. However, I did design it so that I could easily add features without breaking backwards compatibility with older versions of the protocol.
To avoid a potential port conflict, I would like to register a port with IANA. I found the registration form here. However, the questions seem to be highly technical, and I only have a basic knowledge of protocols. So, my question is this: Can anyone describe what these questions are asking? And, how one would answer them in general? If possible, please also include how the general answers would relate to my protocol. That way, anyone else who has a similar question can see both types of answers.
Thanks,
Sean W.

A: I don't wish to be unkind but unless you can answer those simple questions you really aren't ready to register a port number request with IANA. Are you sure you need to? Couldn't you get away with configuration of the server and client? or a naming service?


text:
Q: What does the skewness, when converted to the units of the data, represent? I have calculated the skewness of my data. I was wondering what the skewness, when converted to the units of the data, represents in non-mathematical (biological?) terms? For instance, I know that the variance, when "converted" to the standard deviation, represents how far, on average, a single datum deviates from the mean.
Any help would be greatly appreciated!
Alex

A: By "the skewness" I guess you mean the moment-based skewness calculated from third and second powers of deviations from the mean. But there are other ways of thinking about skewness that perhaps come closer to what you seek. You can measure skewness by a measure using mean, median and standard deviation (SD):
(mean $-$ median) / SD
Like any other similar measure, that ratio is a reduction that allows different shapes to be represented by the same value (and, notably, is necessarily zero when the mean and median are equal, regardless of whether the distribution is symmetric). So the distance between mean and median is pertinent to skewness and is made a measure of skewness (so unitless) by dividing by the SD. The measure is also interesting because it must fall in the interval $[-1, 1]$. This measure can be traced to Karl Pearson, although he did not do much with it.
Other measures start with
[(upper quartile $-$ median) $-$ (median $-$ lower quartile)] /
(upper quartile $-$ lower quartile)
which also falls in the same interval $[-1, 1]$. The same idea can be applied to any other symmetrically placed quantiles. As with the first measure, the numerator has the same units as the variable, and is made a measure of skewness by dividing by a reference distance. This measure has been attributed to Francis Galton, who did not propose it, although he did discuss measures in similar spirit; to Arthur Lyon Bowley, who did evidently invent it; and to George Udny Yule, who might have invented it independently but published after Bowley.
That's far from the end of what has been proposed or is possible, but I will stop there.


text:
Q: Is there any different JDBC driver to connect TERADATA instead of TERAJDBC.jar? I want to connect terada but can i find different jdbc driver instead of terajdbc driver.
I mean I can connect MSSQL with mssql jdbc driver and also jtds jdbc driver.
Thanks.

A: Not aware of one offhand. If you are having specific problems have you considered opening an incident with the Teradata Global Support Center to obtain insight from their engineering staff?
What version of Teradata are you using? Have you tried using a newer version of the JDBC driver? For example Teradata 14's driver with Teradata 13.10 which is certified as backward compatible with Teradata 13.10 (sans Teradata 14 specific features).


text:
Q: java.net.SocketException: Permission denied: connect Starting Tomcat 7 I'm migrating a backend project from JBoss 5.1 to Tomcat 7 and I'm having serious problems trying to run the new configuration. Tomcat 7 it's giving to me the next exception trace:
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Error de E/S: The Network Adapter could not establish the connection)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1549)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1388)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider.getConnection(InjectedDataSourceConnectionProvider.java:46)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:111)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2101)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1325)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:132)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:268)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:530)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:496)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:657)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:630)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:156)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:339)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1325)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1325)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:270)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:125)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1325)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5110)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5633)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1694)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1684)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.sql.SQLRecoverableException: Error de E/S: The Network Adapter could not establish the connection
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:458)
    at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:546)
    at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:236)
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:521)
    at org.apache.tomcat.dbcp.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
    at org.apache.tomcat.dbcp.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:582)
    at org.apache.tomcat.dbcp.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:1556)
    at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1545)
    ... 74 more
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
    at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:392)
    at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:434)
    at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:687)
    at oracle.net.ns.NSProtocol.connect(NSProtocol.java:247)
    at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1102)
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:320)
    ... 82 more
Caused by: java.net.SocketException: Permission denied: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:579)
    at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:150)
    at oracle.net.nt.ConnOption.connect(ConnOption.java:133)
    at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:370)
    ... 87 more

As you can see, the problem is java.net.SocketException: Permission denied: connect, it's having problems connecting to the database. I have the next database access configuration:
On Tomcat 7 context.xml:
<Resource auth="Container"
          driverClassName="oracle.jdbc.OracleDriver"
          maxActive="20"
          maxIdle="5"
          maxWait="5"
          name="jdbc/myname"
          password="mypassword"
          type="javax.sql.DataSource"
          url="jdbc:oracle:thin:@myurl:myport:myssid"
          username="myuser"/>
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>

The web.xml important configuration it's the next one:
<resource-ref>
 <description>DATABASE</description>
 <res-ref-name>jdbc/myname</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
</resource-ref>

And, by Spring (we use Spring 3), I create the connection like this (Spring context starts by a XML file):
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" >
      <property name="jndiName" value="jdbc/myname"/>
      <property name="resourceRef" value="true" />
</bean>

<bean id="entityManagerFactory" scope="singleton"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="jpaProperties">
      <props>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
            <prop key="hibernate.bytecode.use_reflection_optimizer">true</prop>
            <prop key="hibernate.transaction.factory_class"> org.hibernate.transaction.JDBCTransactionFactory</prop>
            <prop key="hibernate.current_session_context_class">thread</prop>
            <prop key="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
      </props>
    </property>

    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

I tried all I could mine in Google: windows firewall problems, catalina.policy permissions, and another configurations; but anything works. I can assure that it's not a database side problem, cause other people on my team can connect problemless to that database (with previous JBoss configuration, obviously), even I can connect to the database with other software, so It has to be a Tomcat 7 configuration problem, or maybe a Spring  configuration problem with the datasource and I can't see what It is, could you give me some help, please?
Thank you all!

A: You'll need to run Tomcat as root for it to be able to bind to port 80. All ports below 1024 require superuser permissions for binding.
Just run your command with SUDO


text:
Q: Advanced multiple search replace Problem:
I want to batch replace patterns in a file in an advanced way, so I cannot use any standard search and replace tools:
Let's assume there is file 1:
B
B
A
  B
B
B
A
  B
B
A
  B

And I want to replace B by something else. But only each B, which comes after a A.
Here is File 2, which holds the "rules", how to search and replace:
A;B;C1
A;B;C2
A;B;C3

The ";" should be the divider. Can be anything else.
Script should search for and A. Then continue to search for B. And replace that B by C1.
Afterwards continue to the next occurence of A. Search for the next B and replace this B by C2. And so on.
When the script has replaced B by C3, it should stop, because there is no further rule.
Final file should look like:
B
B
A
  C1
B
B
A
  C2
B
A
  C3

I want to use python for it, but it is not mandatory, if there is an easier way.

A: You could implement something similar using regular expressions. re.finditer returns starting/ending position of match and re.sub accepts parameter how many substitutions should be made. You can start from this:
import re

data = '''B
B
A
  B
B
B
A
  B
B
A
  B'''

rules = [
    (r'A.*?(B)', r'C1'),
    (r'A.*?(B)', r'C2'),
    (r'A.*?(B)', r'C3'),
]

startpos = 0
while rules:
    rule = rules.pop(0)
    for g in re.finditer(rule[0], data[startpos:], flags=re.DOTALL):
        data = data[:startpos + g.start(1)] + re.sub(g.group(1), rule[1], data[startpos + g.start(1):], count=1)
        startpos += g.start(1)
        break

print(data)

Prints:
B
B
A
  C1
B
B
A
  C2
B
A
  C3

A: I started writing a regex based solution, but @Andrej got there first! So I present you a more "naive" approach that does not use regex.
#!/usr/bin/env python3
import sys

def read_rules(fpath="/tmp/test.rules", sep=";"):
    rules = []
    with open(fpath) as f:
        for line in f:
            rules.append(line.strip().split(sep))

    return rules

def parse_data(rules, fpath="/tmp/test.data"):
    cur_rule = rules[0]
    rule_idx = 0
    data = []
    state = None

    with open(fpath) as f:
        for line in f:
            line = line.strip('\n')
            if not cur_rule:
                data.append(line)
                continue

            # We match start
            if cur_rule[0] in line and not state:
                # End matches in the same line and start < end
                # This case is not in your data
                if (
                    cur_rule[1] in line
                    and line.index(cur_rule[0]) < line.index(cur_rule[1])
                ):
                    new_line = line.replace(cur_rule[1], cur_rule[2], 1)
                    data.append(new_line)
                    rule_idx += 1

                    # We reached the end of rules
                    if len(rules) == rule_idx:
                        cur_rule = None
                    else:
                        cur_rule = rules[rule_idx]
                else:
                    # Set state to looking for end
                    state = 1
                    data.append(line)

                continue

            # Now, if here we are looking for end...
            if state == 1:
                # Nope... not found... move on
                if cur_rule[1] not in line:
                    data.append(line)
                    continue

                # replace
                data.append(
                    line.replace(cur_rule[1], cur_rule[2], 1)
                )

                # Reset state
                state = None

                rule_idx += 1

                # We reached the end of rules
                if len(rules) == rule_idx:
                    cur_rule = None
                else:
                    cur_rule = rules[rule_idx]
                continue

            # Here, no line matched
            data.append(line)

    return data

def main():
    rules = read_rules()
    print(rules)
    data = parse_data(rules)
    print("\n".join(data))

if __name__ == "__main__":
    sys.exit(main())

Explanation:

*

*This is a line-by-line algorithm which makes it efficient for large datasets

*It is "state" based: We either look for "start" (first character) or "end" (second character to match)

*If start is found:

*

*If we have end in the same line, perform replacement and advance to the next rule

*If we do not have end in the same line, change state and move to the next line

*If we are in state=1 (looking for "end") and we find it in the current line, perform replacement and move to the next rule

*At any point we advance rule, if we reached the end of rules, set cur_rule to None. All lines past that point are just copied from the input to the output without any processing

Pros:

*

*This should be faster for huge input. Output can also be optimized to be "on-the-fly" and not stored in memory

*Easier to follow I think

Cons:

*

*It does not handle all cases, that's why I called it "naive". One example is if you have 2 matches in the same line, or if you match "end" and "start" in the same line (in this order - end first). It can be adjusted for such cases if necessary but it might get complex and a regex solution becomes more attractive

Output (note I added one extra match to check that it stops when rules finish):
B
B
A
  C1
B
B
A
  C2
B
A
  C3
A
  B


text:
Q: Is motion conserved? In physics it is said that there is a law of 'conservation of energy'. Also there is a law of 'conservation of momentum'.
I am interested in the term or concept of 'MOTION'. I think motion is related to 'velocity' (v) (similar to speed), or 'momentum' (mass multiplied by velocity) (p=mv).

I think it is arguable that fundamental forces (or fundamental interactions) such as 'electromagnetism' and 'gravity', by definition, 'can put more matter into motion over more time' (or put infinite mass into motion over infinite time), and thus motion doesn't have to be conserved over time.
Another argument against conservation of motion may be that human has the ability to move from intelligence or free will. Using intelligence or free will, a human can create a motion (with magnitude and direction) that was not going to exist. But a criticism may be that humans cannot move more than the energy they get for example from food.

Is motion conserved?

A: Yes, according to Newton's first law of motion an object at rest tends to remain at rest until acted upon by another force. And an object in motion will remain in motion at a constant velocity until acted upon by another force. So this could be termed "conservation of motion" although inertial motion and momentum are generally assumed to have the same meaning.

A: In special relativity there is a kind of conservation of motion, the conservation of 4-velocity. It is defined as $$\mathbf{u}=\frac{\partial\mathbf{x}}{\partial \tau}$$ where $\mathbf{x}$ is the coordinates (in four dimensions) of the particle moving, and $\tau$ is the proper time experienced by it. If you have a object moving with 3-velocity $\mathbf{v}$ then the 4-velocity is $\mathbf{u}=\gamma[c, \mathbf{v}]$ where $\gamma=1/\sqrt{1-(||\mathbf{v}||/c)^2}$. The funny thing is that for every matter particle (this does not apply to light or superluminal particles) the length of this 4-dimensional vector is $$||\mathbf{u}||=c.$$
So in special relativity there is conservation of motion. In a sense everything is moving forward in space and time, and we just change our direction, trading "time velocity" for "space velocity".
Now, in Newtonian mechanics there are no such conservation laws. Particles can gain arbitrarily high velocities e.g. by close gravitational encounters.
One can appeal to Noether's theorem to see that the translation invariance of Newtonian mechanics leads to momentum conservation, time translation invariance to energy conservation, and rotation invariance to angular momentum conservation. There is no other continuous symmetries in flat 3-space to use (since I think screw displacements don't count? I have at least never seen anybody describe a conserved quantity for the symmetry).

A: If it counts as motion, then specifically during purely elastic collisions we have, apart from momentum conservation, also, shall we call it "speed difference" conservation:
$$v_{1A}-v_{1B}=-(v_{2A}-v_{2B})$$
This is a result of the kinetic energies being conserved by definition in purely elastic collisions, combined with the general momentum conservation law.


text:
Q: A list of the highest x's for each group a_list = [
'img_229_152_webp_1x',
'img_229_152_webp_2x',
'img_229_152_webp_3x',
'img_229_152_webp_4x',
'img_229_152_webp_5x',
'img_246_164_webp_1x',
'img_246_164_webp_2x',
'img_246_164_webp_3x',
'img_246_164_webp_4x']

Here we have two groups of images: img_229_152_webp_5x', and 'img_246_164_webp_4x'.
The list is sorted. And as for the last part (\d+x), each group of images is an   arithmetic progression, no missing element is possible. Example of impossible case: 1x, 2x, 4x.
Could you help me get a list of the highest x's for each group. In this case: [img_229_152_webp_5x', 'img_246_164_webp_4x'].

A: Using groupby you can group according to the prefix, and then get the max from each group:
import itertools

for k, g in itertools.groupby(a_list, key=lambda s: s.rsplit('_', 1)[0]):
    print(max(g, key=lambda s: s.rsplit('_', 1)[-1]))

Gives:
img_229_152_webp_5x
img_246_164_webp_4x


text:
Q: c3 timeseries graph - how to have X values with no initial Y values I have a C3 timeseries chart where I wish to display a bunch if times every 15 minutes for a day, so that the day takes up the whole X axis and then just display data as the day progresses and the data comes in.
I have the following setup..
var now = new Date().toISOString();

  this.lineChart = generate({
    bindto: '#line',
    transition: {
      duration: 1000
    },
    data: {
      x: 'x',
      xFormat: '%Y-%m-%dT%H:%M:%S.%LZ',
       columns: [
      ['x', now],
      ['data1', 0]
    ]
    },
    axis: {
      x: {
        type: 'timeseries',
        localtime: true,
        tick: {
          format: '%H:%M %p',
          culling : true,
          rotate : 60
        }
      }
    }
  });

An d I then load the dates as follows..
let shiftStart = new Date(startDateTime);
  let endTime = new Date(endDateTime);
  let nextDate = shiftStart;
  let dates = new Array<string>();
  dates.push(nextDate.toISOString());
  let data = [];
  while (nextDate <= endTime) {
    nextDate = moment(nextDate).add(30, 'm').toDate();
    dates.push(nextDate.toISOString());
    data.push(0); // to make them show up!
  }

  this.lineChart.load({
    columns: [
      ['x', ...dates],
      ['myData', ...data]
    ]
  })

It seems I have to add the data above to have the ticks show up for the times.
I would like to have ..
while (nextDate <= endTime) {
    nextDate = moment(nextDate).add(30, 'm').toDate();
    dates.push(nextDate.toISOString());
  }

  this.lineChart.load({
    columns: [
      ['x', ...dates],
    ]
  })

and for this to show just the X axis of times, and no values for the Y axis (yet)
Is this possible?
Any help greatly appreciated!

A: As it turns out, you can just use NaN for the value to get what I was after...

Now just to work out those uneven ticks, and truncated last tick value...


text:
Q: what variable name to use In my header file I have:
IBOutlet UITextField * _userNameOrEmail;
IBOutlet UITextField * _password;

@property (retain) IBOutlet UITextField * userNameOrEmail;
@property (retain) IBOutlet UITextField * password;

In my implementation I have:
@synthesize userNameOrEmail=_userNameOrEmail, password=_password;

When I go into my nib file, I can drag the UITextField and it gives me options for both _userNameOrEmail and userNameOrEmail
which one should I use?

A: With this line
@synthesize userNameOrEmail=_userNameOrEmail

you are declaring a property userNameOrEmail with the backing iVar _userNameOrEmail. You do NOT need to do another declaration like this:
IBOutlet UITextField * _userNameOrEmail;
IBOutlet UITextField * _password;

You can now acces the backing iVar via _userNameOrEmail = or the property via self.userNameOrEmail =. I would recommend that you use the property because you can access the variable via other classes if needed, it will manage memory for you, you can use the dot notation....

A: Current suggested Objective-C 2.0 practice is to use the same name for the ivar as the property. You can optionally assign a different ivar in the @property declaration, but the fact that by default, synthesized accessors for a property will access the ivar with the same name as the property indicates that's the pattern they expect you to follow.
The naming convention for the instance variable prefixed by _ is now clearly stated by Apple in the "Coding Guidelines for Cocoa", after the revision of 2012-02-16, with its reason.

Make sure the name of the instance variable concisely describes the attribute stored. Usually, you should not access instance variables directly, instead you should use accessor methods (you do access instance variables directly in init and dealloc methods). To help to signal this, prefix instance variable names with an underscore (_) ex -


text:
Q: ShellExecuteEx code 31 error any time I try to launch an EXE, how to find problematic driver? I don't know if this is the right forum for this question, so please direct me elsewhere if needed.
I am having a new issue launching .exe files. I keep receiving the following error:
ShellExecuteEx failed; code 31.
A device attached to the system is not functioning.

Specifically, I have recently tried to launch the following EXE and get that error:
uninstall_flash_player.exe
R-3.6.3-win.exe
Rtools35.exe
These are all downloaded from legit sources (Flash remover from Adobe website; R packages from R-CRAN).
I've restarted my computer a million times and I don't have any external hard drives plugged in. When I right-click and Run as Administrator, it still says gives the error box, "A device attached to the system is not functioning."
Based on this link, it looks like it is a driver issue, but I am not sure how to find out what driver is the culprit.
Windows 10, ASUS TUF, laptop is about 2 yrs old, issue just started a couple weeks ago (noticed it when I tried to uninstall Flash and just ignored it... now it's an issue I can't ignore)
Update
I restarted in safe mode, dropped the User Account Control (UAC) settings down to the lowest level, and this resolves the issues. I can run the EXE files and I can run Command Prompt as Administrator in non-safe mode.
I am not sure why this fixes things, as my account already is sent to Administrator. In the past, there would just be a pop-up window that said, "hey, you're about to make admin changes, is that ok?" So, I don't know what has changed.
I then changed the UAC settings back to the default. Following @BenN's question in the comments, I ran reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer in a non-elevated command prompt window, and this is the result, but I don't know what it means.


text:
Q: Bijection between $n$-partitions and "flattened" canonical $n+1$-partitions The set of $n$-partitions (partitions of the set $\{1, 2, \ldots, n\}$) and the set of "flattened" canonical $(n+1)$-partitions (those permutations obtained by removing the bars from an $(n+1)$ partition written in canonical form) are both counted by the Bell number $B(n)$. Can you give an intuitive bijection between these two sets?

A: In one of our recent article (see link below Section 4):
https://www.researchgate.net/publication/344683169_Run_Distribution_Over_Flattened_Partitions
we gave a bijection between set partitions of $[n]$ and flattened partitions of length $[n+1]$.
For example: Let us consider a partition $P = 12|3|45$ of $[5]$. Then re-ordering the entries of $P$ such that in each block, the smallest entry appears at the end, then we would have a new partition $P' = 21|3|54$. Increasing by 1, each of the entries in $P'$ gives $P* = 32|4|65$. The corresponding flattened partition is obtained by appending a "1" before $P*$ and ignoring the vertical marks "|" separating the blocks, i.e., $1P* = 132465$, which is a flattened partition of length 6.
Moreover, using now the flattened partition $1P* = 132465$, we can get back $P$ by inserting the vertical mark "|" immediately after each right to left minimum gives $1|32|4|65|$. Deleting 1 and re-ordering the remaining
gives the partition $P = 12|3|45$.
For technicalities and details of the bijection, please refer to the above link.


text:
Q: S3 connections timing out quickly in Python 2.7 I am writing a service that will retrieve data from S3 after receiving a request.  The data is stored in .gz files.  This service will not be constantly flooded with data, meaning it could go many seconds before receiving a second request.  I'm having trouble keeping my S3 connection from resetting after a fairly small amount of time.  The issue seems to be that boto3.client() resets the connection much more quickly than I would like it to.
To test, I used this bit of code:
import boto3
import logging
import datetime
import time
import gzipinputstream

logging.basicConfig(level='DEBUG')
logging.getLogger('botocore').setLevel('INFO')

s3_client = boto3.client('s3')
bucket = 'foo'
key = 'bar'

count = 0
while True:
  count += 1
  start = datetime.datetime.now()
  x = s3_client.get_object(Bucket=bucket, Key=key)
  y = x['Body']
  z = gzipinputstream.GzipInputStream(y)
  final_obj = z.read()
  end = datetime.datetime.now()
  print "Test #%d: started at %s, ended at %s, duration = %s" % (count,start,end,end-start)

When I run the above code, I see the following.  The initial request takes a bit longer than the rest, but each request from #2 onward is much faster:
INFO:botocore.vendored.requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): session4c.s3.amazonaws.com
Test #1: started at 2017-01-25 14:50:26.295239, ended at 2017-01-25 14:50:30.412478, duration = 0:00:04.117239
Test #2: started at 2017-01-25 14:50:30.412581, ended at 2017-01-25 14:50:30.447595, duration = 0:00:00.035014
Test #3: started at 2017-01-25 14:50:30.447655, ended at 2017-01-25 14:50:30.474377, duration = 0:00:00.026722
Test #4: started at 2017-01-25 14:50:30.474443, ended at 2017-01-25 14:50:30.499979, duration = 0:00:00.025536
Test #5: started at 2017-01-25 14:50:30.500040, ended at 2017-01-25 14:50:30.595240, duration = 0:00:00.095200

When I take that same code and add time.sleep(10) to the bottom of the loop to simulate a gap between requests, I see the following.  Each request takes roughly as long as the first due to each request reconnecting:
INFO:botocore.vendored.requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): session4c.s3.amazonaws.com
Test #1: started at 2017-01-25 14:50:44.916388, ended at 2017-01-25 14:50:49.315392, duration = 0:00:04.399004
INFO:botocore.vendored.requests.packages.urllib3.connectionpool:Resetting dropped connection: session4c.s3.amazonaws.com
Test #2: started at 2017-01-25 14:50:59.325521, ended at 2017-01-25 14:51:03.726388, duration = 0:00:04.400867
INFO:botocore.vendored.requests.packages.urllib3.connectionpool:Resetting dropped connection: session4c.s3.amazonaws.com
Test #3: started at 2017-01-25 14:51:13.736561, ended at 2017-01-25 14:51:17.273182, duration = 0:00:03.536621
INFO:botocore.vendored.requests.packages.urllib3.connectionpool:Resetting dropped connection: session4c.s3.amazonaws.com
Test #4: started at 2017-01-25 14:51:27.282636, ended at 2017-01-25 14:51:31.682258, duration = 0:00:04.399622
INFO:botocore.vendored.requests.packages.urllib3.connectionpool:Resetting dropped connection: session4c.s3.amazonaws.com
Test #5: started at 2017-01-25 14:51:41.692450, ended at 2017-01-25 14:51:45.225243, duration = 0:00:03.532793

I have searched high and low for ways to increase the timeout within the boto3.client() and its underlying requests and urllib3 libraries but have come up empty.  I see nothing in the boto3 docs either.  Adding use_ssl=False to the boto3.client() call does help somewhat by reducing network chatter.  The reconnects occur after 20-30 seconds instead of in <10 seconds.
Is there a way to increase the amount of time an S3 connection can stay open?  Any help would be greatly appreciated!

A: No, there isn't.
S3 itself drops any idle Keep-Alive connections after a few seconds... as any web server will do... the "connections" to S3 are just HTTP/S connections to the S3 API endpoint.  They aren't meant to stay usable for very long.
The real question may be why the connection takes 4 seconds to establish.  That seems excessive.


text:
Q: How to use KSoap 2 in android I've just came across to ksoap2 for using my own asp .net webservices in android apps.
I've found few great resources over internet and I've implemented my webservice in android app.
Following is the webservice's response I consumed:
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <CheckAuthenticationResponse xmlns="http://tempuri.org/">
      <CheckAuthenticationResult>boolean</CheckAuthenticationResult>
    </CheckAuthenticationResponse>
  </soap:Body>
</soap:Envelope>

For consuming the above service I implemented the following code:
public static Boolean isAuthenticated(String UserName, String Password)
{
    String NAMESPACE = "http://tempuri.org/";
    String METHOD_NAME = "CheckAuthentication";
    String SOAP_ACTION = "http://tempuri.org/CheckAuthentication";
    String URL = "http://primehangout.com/primehangoutweb.asmx";

    SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
    PropertyInfo pi = new PropertyInfo();
    pi.setName("UserId");
    pi.setValue(UserName);
    pi.setType(String.class);
    Request.addProperty(pi);

    PropertyInfo pi2 = new PropertyInfo();
    pi2.setName("Password");
    pi2.setValue(Password);
    pi2.setType(String.class);
    Request.addProperty(pi2);

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(Request);
    try
    {
    AndroidHttpTransport transp = new AndroidHttpTransport(URL);
    transp.call(SOAP_ACTION, envelope);
    SoapPrimitive result = (SoapPrimitive)envelope.getResponse();

    return Boolean.parseBoolean(result.toString());
    }
    catch(Exception e)
    {

    }

    return false;
}

It's working fine..
But now I'm going to consume a service.
The required service's request format is as follow:
POST /primehangoutweb.asmx HTTP/1.1
Host: primehangout.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/GetComment"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <AuthSoapHd xmlns="http://tempuri.org/">
      <strUserName>string</strUserName>
      <strPassword>string</strPassword>
    </AuthSoapHd>
  </soap:Header>
  <soap:Body>
    <GetComment xmlns="http://tempuri.org/">
      <UId>string</UId>
      <refID>int</refID>
    </GetComment>
  </soap:Body>
</soap:Envelope>

And response of desired service is following:
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

    <?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
      <soap:Body>
        <GetCommentResponse xmlns="http://tempuri.org/">
          <GetCommentResult>
            <xsd:schema>schema</xsd:schema>xml</GetCommentResult>
        </GetCommentResponse>
      </soap:Body>
    </soap:Envelope>

I've consumed the same services in my previous iPhone application using XMLReader classes but as I'm a newbie in android, I need your help guys.
:)
Thanks to all for reading my post!

A: For Integrating KSoap 2 You have to add dependency to your build.gradle file.
repositories {
    maven { url 'https://oss.sonatype.org/content/repositories/ksoap2-android-releases/' }
}

dependencies {
    compile 'com.google.code.ksoap2-android:ksoap2-android:3.6.2'
 }

Modify AndroidManifest.xml
In order to make soap calls on a web service exposed on the internet, additional permissions need to be added.
<uses-permission android:name="android.permission.INTERNET" />

Then dive into code
Thread thread = new Thread() {
            @Override
            public void run() {
                String SOAP_ACTION = "https://www.w3schools.com/xml/FahrenheitToCelsius";
                String METHOD_NAME = "FahrenheitToCelsius";
                String NAMESPACE = "https://www.w3schools.com/xml/";
                String URL = "https://www.w3schools.com/xml/tempconvert.asmx";

                //Initialize soap request
                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
                //Use this to add parameters
                request.addProperty("Fahrenheit", "10");

                //Declare the version of the SOAP request
                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet = true;
                envelope.setOutputSoapObject(request);

                try {
                    //Needed to make the internet call
                    HttpTransportSE transport = new HttpTransportSE(URL);
                    List<HeaderProperty> headerList = new ArrayList<HeaderProperty>();
                    headerList.add(new HeaderProperty("Authorization", "Basic " + Base64.encode((username + ":" + password).getBytes())));

                    transport.call(SOAP_ACTION, envelope, headerList);
                    //Get the Response from the envelope body.
                    SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
                } catch (Exception e) {
                    Log.e("TESTS", "KSOAP2", e);
                }
            }
        };

        thread.start();


text:
Q: Netbeans C/C++ JavaDoc code-completion I am developing C++ in NetBeans 6.7.1. When I press CTRL + space for autocomplete there is shown only method's signature. I am using JavaDoc for commenting my code but NetBeans doesn't show it. I have installed Doxygen plugin but it is only for generating complete documentation.
Is there any way how to force the IDE to show signature and JavaDoc for C++ please?
I think that it should not be a problem because this functionality is currently implemented for Java.
Thanks a lot.

A: So I asked on NetBeans forum this question ( using friend's account because I don't have my own ) and there is the conclusion: It is impossible and it is in requests.


text:
Q: Tensorflow placeholder instance with dynamic dimension I'm working with Tensorflow for classifying MNIST, and I'm trying to implement two function
data = model.x # placeholder of data. shape is (None, 782)
label = model.y #placeholder of label. shape is (None,)
logit = model.logit # placeholder of logit. shape is (None, 10)

These three are placeholder variables that I'm working inside customized class.
What I want to do is to get the logits corresponding label only like
want = logit[tf.range(n), label]
However I cannot get n from variable since it is declared as dynamic dimension.
Also when I give n as random value, such as 100, then I got error message
TypeError: Only integers, slices (`:`), ellipsis (`...`), tf.newaxis (`None`) and scalar tf.int32/tf.int64 tensors are valid indices, got <tf.Tensor 'range_14:0' shape=(100,) dtype=int32>

What should I do now? How can I access and fetch value with label?


text:
Q: how to transfer string from autoCompleteTextView in one activity to others using set and get methods [HELP]
please help me, what i want to do is, get String data from autoCompleteTextView and set it , then get String data in other activity
This is my AutoCompleteTextView code :
//autocomplete
    //Creating the instance of ArrayAdapter containing list of language names
    final ArrayAdapter<String> adapter = new ArrayAdapter<String>
            (this,android.R.layout.select_dialog_item,dapilAuto);
    //Getting the instance of AutoCompleteTextView
    final AutoCompleteTextView actv= (AutoCompleteTextView)findViewById(R.id.nama_dapil);
    actv.setThreshold(1);//will start working from first character
    actv.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
    actv.setTextColor(Color.BLACK);
    //ketika di pilih autocompletenya
    actv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String selection = (String)parent.getItemAtPosition(position);
            //String selection = actv.getText().toString();
            Dapil dapil = new Dapil(selection);
            dapil.setName_dapil(selection);

        }
    });

This is my get and set class :
 String name_dapil;

    public Dapil(){

    }

    public Dapil(String name_dapil){
        this.name_dapil = name_dapil;

    }

    public String getName_dapil() {
        return name_dapil;
    }
    public void setName_dapil(String name_dapil) {
        this.name_dapil = name_dapil;
    }

and This is how i get String data and implement it into cloud firestore to get document ID :
     Dapil dapil = new Dapil();
     String mDapil = dapil.getName_dapil();

     loadJumlahKursi(mDapil);

 private void loadJumlahKursi(String mDapil){

        DocumentReference kursiRef = firestoreDB.collection("perhitungansuara").document(mDapil);
        kursiRef.get()
                .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                        if(task.isSuccessful()){
                            DocumentSnapshot doc = task.getResult();
                            StringBuilder fields = new StringBuilder("");
                            fields.append("Jumlah Kursi: ").append(doc.get("jumlah_kursi"));
                            mJumlahKursi.setText(fields.toString());
                        } else {
                            Log.d(TAG, "Gagal mendapatkan data:  ", task.getException());
                        }

                    }
                });
    }

and this is the issues
02-06 18:18:27.700 5902-5902/com.example.erlangga.suaraku E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.example.erlangga.suaraku, PID: 5902
                                                                            java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.erlangga.suaraku/com.example.erlangga.suaraku.HasilActivity}: java.lang.NullPointerException: Provided document path must not be null.
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2219)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:136)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5045)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                                                                                at dalvik.system.NativeStart.main(Native Method)
                                                                             Caused by: java.lang.NullPointerException: Provided document path must not be null.
                                                                                at com.google.android.gms.common.internal.zzbq.checkNotNull(Unknown Source)
                                                                                at com.google.firebase.firestore.CollectionReference.document(Unknown Source)
                                                                                at com.example.erlangga.suaraku.HasilActivity.loadJumlahKursi(HasilActivity.java:157)
                                                                                at com.example.erlangga.suaraku.HasilActivity.onCreate(HasilActivity.java:81)
                                                                                at android.app.Activity.performCreate(Activity.java:5231)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2163)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:136)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5045)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                                                                                at dalvik.system.NativeStart.main(Native Method)

A: You are getting the following Exception:
java.lang.NullPointerException: Provided document path must not be null

because you are passing to the document() method the mDapil object which has the value of null. The reason is that the following line of code:
dapil.getName_dapil()

returns null.
If you want to pass mDapil between activities use an Intent. Here is how can be done.


text:
Q: MySQL Optimization I have a server with a LOT of CPU power.
My CPU idle is ~95% and io wait 0.2%.  How can I utilize more CPU to get a faster overall DB?  Should I switch a handful of my MyISAM tables into InnoDB?

A: I suspect you're hitting table locks, since your CPU and your iowait is so low.
InnoDB may help, but ultimately you're best served by fixing the application running on top.
You should get stats on how many locks have been requested, how many were immediately granted, etc- that should confirm if this is indeed the issue.
Another way to check is to regularly pull the processlist from mysql. You'll quickly see a pattern (eg., all queries waiting, use the "foo" table). The active query blocking the others is a good place to start optimising the software; that table is a good one to consider converting to InnoDB.

A: If your database is small enough then increase the size of your caches so the entire database can be stored in memory. Assuming that your queries are all optimized and you have indexes in the right place, you can't make your database much faster than that.
Disk access isn't really a CPU intensive task. The CPU says Go and waits for the answer. The I/O controller and the disk do all the work. Don't expect disk access to red line your CPU.

A: you can try mysql tuner from racker hacker.
http://blog.mysqltuner.com/download/


text:
Q: If $f$ is monotone increasing and $f$ is differentiable at $x_{0}$, then $f'(x_{0}) \geq 0$. Let $X$ be a subset of $\textbf{R}$, let $x_{0}\in X$ be a limit point of $X$, and let $f:X\rightarrow\textbf{R}$ be a function. If $f$ is monotone increasing and $f$ is differentiable at $x_{0}$, then $f'(x_{0}) \geq 0$. If $f$ is monotone decreasing and $f$ is differentiable at $x_{0}$, then $f'(x_{0})\leq 0$.
MY ATTEMPT
Lemma
Let $X\subseteq\textbf{R}$, $f:X\rightarrow\textbf{R}$, $g:X\rightarrow\textbf{R}$, $x_{0}\in X$ is an adherent point, $f(x) \leq g(x)$ for every $x\in X$ and $\displaystyle\lim_{x\rightarrow x_{0}}f(x) = L$ and $\displaystyle\lim_{x\rightarrow x_{0}}g(x) = M$. Then we have that $L \leq M$.
Proof
According to the definition of limit, for every $\varepsilon > 0$, there are $\delta_{1} > 0$ and $\delta_{2} > 0$ such that
\begin{align*}
\begin{cases}
0 < |x - x_{0}| < \delta_{1}\\\\
0 < |x - x_{0}| < \delta_{2}
\end{cases} \Longrightarrow
\begin{cases}
|f(x) - L| < \varepsilon\\\\
|g(x) - M| < \varepsilon
\end{cases} \Longrightarrow L - \varepsilon < f(x) \leq g(x) < M + \varepsilon
\end{align*}
Let us assume that $L > M$. In this case, we can choose $\displaystyle\varepsilon = \frac{L - M}{3}$, whence we get that
\begin{align*}
M - L + 2\varepsilon > M - L + \frac{2(L - M)}{3} = \frac{M - L}{3} > 0 \Longrightarrow M > L
\end{align*}
which leads to a contradiction. Therefore the original claim is true and $L \leq M$.
Solution
Assuming that $f$ is monotone increasing at $x_{0}$, we have that
\begin{align*}
\frac{f(x) - f(x_{0})}{x - x_{0}} \geq 0
\end{align*}
Taking the limit from both sides to $x_{0}$ we conclude that
\begin{align*}
\lim_{x\rightarrow x_{0}}\frac{f(x) - f(x_{0})}{x - x_{0}} = f'(x_{0}) \geq 0 = \lim_{x\rightarrow x_{0}}0
\end{align*}
simliar reasoning applies to the monotone decreasing case, and we are done.
Could someone please verify if I am arguing correctly? Any other solution is welcome.

A: Why did you even write the lemme? It looks like your solution is self-contained and correct.
Perhabs this helps you : $$(D_{x_0}f)(x):=\frac{f(x)-f(x_0)}{x-x_0}$$ is continuous everywhere, by the definition of the $f$. Then by your argument, ($D_{x_0}f\geq 0$ everywhere) $$\lim_{x\rightarrow x_0}(D_{x_0}f)(x)\geq 0.$$


text:
Q: Как заменить словосочетание в строке на 1 символ В строке 'в чем смысл вопросительный знак' нужно заменить словосочетание 'вопросительный знак' на соответствующий символ. Для этого я написал этот код:
cmd = "в чем смысл вопросительный знак"

if ("вопросительный знак" in cmd):
for x in "вопросительный знак":
    cmd = cmd.replace(x, "").strip()

print(cmd + '?')

В общем нужно чтобы программа удаляла только 'вопросительный знак' не трогая остальное и вместо этого добавлялся '?'. Но для выполнения этой цели моих знаний явно не хватает, так что искренне прошу помочь. И еще, пожалуйста, не кидайтесь в меня помидорами из-за непонятного кода, сначала он хоть как-то работал, но потом я напортачил и немного его поломал.
Заранее спасибо!

A: Позвольте внесу свои 5 копеек. Надеюсь, что еще актуально.
1) То что цикл for у Вас без отступа, это наверно случайно вышло, а если нет, то не забудьте, что отступ нужен, иначе инструкция if выполнятся не будет и вызовется ошибка.
2) В скрипте Вы "говорите" чтобы цикл для переменной x принимал как значение, каждый символ из строки "вопросительный знак" и в теле цикла для cmd, которая имеет значение "в чем смысл вопросительный знак" применяете метод replace.
Тем самым при первой итерации x = "в" из cmd "удалятся" (а вернее заменятся на "") все символы "в" и так далее с каждым символом.
3) метод strip() сам по себе ничего удалять не будет, нужно что-то указывать, а точнее символ из начала или конца строки, например:
str = "***привет удачи в питоне!**"
str = str.strip('*')
print(str)

Результат:
>>>'привет удачи в питоне!'

А так Вам уже ответили, как лучше всего (или можно) делать замену.
Еще можно загнать замену на вопросительный знак в функцию, если вдруг нужно будет часто такое делать и плодить лишние строки кода. Например так:
    cmd = "в чем смысл вопросительный знак"

    def replace_quest_mark(str):
        repl = "вопросительный знак"
        if repl in str:
            str = str.replace(repl, "?") #как вариант еще можно с убиранием пробела в конце
            #str = str.replace(repl, "").strip(" ") + "?"
        return str

    cmd = replace_quest_mark(cmd)
    print(cmd)

Придумывать можно много. Удачи!


text:
Q: How is Laravel 8 CSRF token actually safe? The most voted answer in this question (https://security.stackexchange.com/questions/19128/csrf-cookie-vs-session-based-tokens) states

If you put your token in a cookie, it will be send to the server automatically, just as session cookie, so you don't get any additional protection from that.

And Laravel seems to behave exactly as stated above. Here's the screenshot I have tested.

I am not sure whether I am doing some settings wrong or misunderstood about CSRF, but storing an extra CSRF cookie in addition to the session cookie really does not seem to be able to give any extra protection.
Any help would be appreciated.

A: Not always.
cookie with SameSite value of None will be always sent.
XSRF-TOKEN cookie has SameSite=Lax so it will be only sent at the same website.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#none

SameSite=None Cookies will be sent in all contexts, i.e. in responses to both
first-party and cross-site requests. If SameSite=None is set, the
cookie Secure attribute must also be set (or the cookie will be
blocked).

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#lax

SameSite=Lax Cookies are not sent on normal cross-site subrequests (for example to
load images or frames into a third party site), but are sent when a
user is navigating to the origin site (i.e., when following a link).


text:
Q: Sort dataGridView columns in C# ? (Windows Form) I have a datagridview that i bind from an sql table, in that dv i have those attributes: Id, Name and Price. When i set the SortMode of the Name Columns to Automatic and i click on the header of this column i can sort this dv based on the first letter of the Name, this way i can order products based on their first letters ( Acumulator, Boat, CocaCola, Engine etc).
Is there a way this thing to happen without clicking the header of the column Name. I am looking some code that will do this job when the form will load.

A: You can control the data returned from SQL database by ordering the data returned:
orderby [Name]

If you execute the SQL query from your application, order the data returned. For example, make a function that calls the procedure or executes the SQL and give it a parameter that gets the orderby criteria. Because if you ordered the data returned from database it will consume time but order it since it's executed as you say that you want it to be ordered not from the UI you want it to be ordered in the run time so order it when executing the SQL query.

A: This one is simplier :)
dataview dataview1;
this.dataview1= dataset.tables[0].defaultview;
this.dataview1.sort = "[ColumnName] ASC, [ColumnName] DESC";
this.datagridview.datasource = dataview1;

A: The best way to do this is to sort the list before binding data source.
cars = cars.OrderBy(o => o.year).ThenBy(o => o.color).ToList();
adgCars.DataSource = cars;

Sorry for my bad english.

A: dataGridView1.Sort(dataGridView1.Columns[0],ListSortDirection.Ascending);

A: There's a method on the DataGridView called "Sort":
this.dataGridView1.Sort(this.dataGridView1.Columns["Name"], ListSortDirection.Ascending);

This will programmatically sort your datagridview.

A: Use Datatable.Default.Sort property and then bind it to the datagridview.

A: I know 2 solutions to this problem.
1. Sort (DataGridViewColumn column, ListSortDirection direction) function
This function can be used to sort a column alphabetically or numerically or by date in descending or ascending order.
example:
dataGridView.Sort(dataGridView1.Columns[5],ListSortDirection.Ascending);

2. Sort (IComparer comparer) function
This function can be use for all other situations as
Sorting a column with specific order that is different than numeric order (example: sorting an amount that can be negative or positive using only absolute values)
Sorting a column with specific order that is different than alphabetic order (example: sorting a text using case insensitive sort)
Sorting multiples columns as sorting a table using AMOUNT column as first column and DATE column as second column.
VB.Net example:
Private Sub pbSort_Click(sender As Object, e As EventArgs) _
    Handles pbSort.Click

    grid.Sort(New AmountDateComparer(Me))
End Sub

Private Class AmountDateComparer : Implements IComparer

    Private frm As FrmSearch

    Public Sub New(frm As FrmSearch)
        Me.frm = frm
    End Sub

    Public Function Compare(x1 As Object, x2 As Object) As Integer _
        Implements IComparer.Compare

        Dim row1 As DataGridViewRow = x1
        Dim row2 As DataGridViewRow = x2

        ' compare AMOUNT values of columns

        Dim nAmount1 = Convert.ToDecimal(row1.Cells(frm.Col_AMOUNT.Index).Value)
        Dim nAmount2 = Convert.ToDecimal(row2.Cells(frm.Col_AMOUNT.Index).Value)

        Dim iCompareResult As Integer
            = System.Decimal.Compare(nAmount1, nAmount2)

        If iCompareResult = 0 Then
            'compare DATE values of columns
            Dim d1 = Convert.ToDateTime(row1.Cells(frm.Col_DATE.Index).Value)
            Dim d2 = Convert.ToDateTime(row2.Cells(frm.Col_DATE.Index).Value)

            iCompareResult = System.DateTime.Compare(d1, d2)
        End If

        Return iCompareResult
    End Function
End Class


text:
Q: admin page code igniter doesn't work because laravel valet? i have php project with ci framework. then i install laravel valet. I access my admin page using this domain myprojectname.dev/admin.  but the admin page return is 404Page Not found. can somebody help me to fix this ?

A: If You using codeigniters routing, then You should write like: myprojectname.dev/index.php/admin, if You hav not `.htaccess file in Your root folder


text:
Q: Center an object tag in a div How can I center object content within a div?
.parent{
background-color:yellow;
}

.ob{
margin: 0 auto;
}
</style>

<div class="parent">
<object width="400" height="400" class="ob" data="helloworld.swf">
</object>
</div>

Thanks in advance!

A: An object element has inline style by default, and margin: auto applies to block-level elements only.
Add this style:
.ob {
  display: block;
}

Fiddle

A: Or this since the object is an inline element.
.parent{
text-align: center;
}

If you want to get modern.
.parent{
    background-color:yellow;
    display: flex;
    justify-content:center
}


text:
Q: How to Perform logout in my application in android? I have an application through which user gets logged in during the first time,then he remains logged in.... Since my application contains chat in it,so the user needs to be logged in while in application... but i want to perform logout when application is in background...SO how to do this?

A: override onPause() method if you want to logout user each time chat activity goes to background.