text:
Q: USB/Ethernet to a (real) bell based on a signal I'm a total beginner in hardware, but I'd like to build a piece of material that would make a real bell ring for a specific duration, or eventually instead of a bell, a light that would switch on based on a specific duration.
The start and duration would be triggered remotely via USB or Ethernet, coded in a Java language (part I'm most experienced with).
I thought about using an Arduino, but since I don't know anything in the hardware area, I'm asking you for your advice on how and what do buy for making this the cheaper way.
Also, it would be great if this device would be sell alimented, I'm most thinking about using an USB then, am I right?
Thank you very much for your help :)

A: Personally I'd go about this using a small PIC microcontroller or similar.  The USB side of it can be quite a pain to program (on the PIC chip) for the beginner (I haven't fathomed it yet), so a USB to RS232 converter (either as a USB dongle or as a USB to RS232 chip) can make things an awful lot easier to handle.
The PIC16F88 is a good starting point if you don't want to program the USB yourself,  and is dirt cheap (you can get free samples from the manufacturer).  If you want USB then you should look at the PIC18F series of microcontrollers (I just got my first one working today - yippee).
If you don't want to go about building your own hardware and programming the PIC yourself there are many DIY kits that come with a pre-programmed PIC (such as the K8055 from Velleman) which often have the USB built into it already.

A: First thing first:
There is no way to cheaply do this in Java only. There are some chips that can execute Java, but I haven't heard of any which are accessible for beginners.
So it's either C or the Arduino's language if you go for that route.
Next, you're going to need a power source for the bell. This will depend on the bell and will make a major impact on the circuit you'll be making. You'll probably need a relay and protection circuit for it which will control the bell which will be powered from a separate power source (like for example mains power). You'll need to look up specifics for Arduino's (or whatever you want to use) pins and get a relay which can be triggered by such power source.
Next, you'll need Ethernet or USB connection. Matt already recommended USB to RS-232 chips and that is an easy way to solve the problem. The chip will appear as a serial port and all you'll need to do is make a Java program which will send data to the port to the microcontroller.
The other more complicated option would be to use Ethernet. For Arduino, there's an already existing Ethernet shield which is supported by its IDE. You could also pick up another Ethernet board like this one or this one. The positive side of Arduino shield is that you get to use existing library with it that could prove to be helpful. For a third-party solution, you'll have to write the code yourself.
Also a bit of comparison between Arduino, bare AVR chips or PIC.
First, today's PIC and AVR chips are more or less similar in price and capabilities. Some people will recommend PIC and some will recommend AVR. There are countless raging fanboys on each side, but my advice is to ignore them. If you're planning to seriously get into the microcontroller world, it would be good idea to get familiar with both families, because they are both very popular. The chips are generally programmed in C or assembly and there are many development tools (some of them free) available for both lines.
Next we have Arduino. First, it's not a chip. It's a development board line and that is an important difference. It uses AVR chips inside and a special bootloader to make them easier to program. With that you have packaged a nice IDE which uses a C++ like language for programming and may make some things easier for a beginner. Recently it has gained enormous popularity with beginners. Its main problem is that it hides some operational concepts of the chi[ from the user and at one point you may get the feeling that you're fighting the IDE and the language.
On the other hand, we have also the PICAXE which are basically PIC version of Arduino. They also have IDE and programming language (a BASIC derivative) and bootloader. As far as I can see PICAXE boards aren't as popular as Arduino for some reason, but I don't have any experience with them, so I can't elaborate why.
So to sum this up: If you want a single project, consider Arduino or PICAXE. This way, you won't have to pay for setup costs (like programmer, time needed for training and board design and so on) which working with single microcontroller brings.
If you plan to seriously work with microcontrollers in the future, consider doing this with an AVR of PIC chip. It'll be much more educational experience but it could get too complicated if you just doing a one-off project.

A: There are off the shelf solutions for USB controlled relays, usually with libraries for a variety of high level languages.
Later Edit:  It occurs to me that if the timing requirement isn't too tight, one could just use an off the shelf USB-serial converter and utilize one of the control signals.
It's likely that the controlling program can be written in Java, if the JVM will give you access to the port, or allow you to exec something like the stty tool on linux/unix or a windows equivalent.

A: I would recommend to use PIC18F24J50. It is a much better microcontroller and it is easy to program. You don't even need high voltage to program it. I managed to program it from scratch (firmware --> DLL --> VB and C++ aplications). What makes it more funny, I even made a simple programmer for it out of industrially preprogrammed MCP2200 microcontroller... It's simple because PIC18F24J50 doesn't need high voltage (like 9V or 12V) to program..


text:
Q: Trigger background image at each new link I'm not a pro in coding and I'm trying to trigger a different background image that takes the whole page in the background as the mouse hovers each link.
Here's the code :

        Crépuscule en Mineur

        Bel Abandonné

        Alicia's Dream

Here's the CSS
    .bloc-films {
font-size: 20px;
font-weight: 400;
font-style: italic;
text-align: center;
line-height: 200%;
position: fixed;
transform: translate(-50%, -50%);
top: 50%;
left: 50%; }

A: HTML Code

  Page 1
  Page 2

CSS Code
.links a:hover::before {
  content: '';
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: -1;
}

.page-1::before {
  background-image: url("./img/bg-1.jpg");
}
.page-2::before {
  background-image: url("./img/bg-2.jpg");
}

Change the background-image:url() to your image path.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I replace the commas in my string without affecting the commas in my CSV file? I have a data set which I'm loading with strings and it contains something like this:
"10, 14, 15, "20,152", 37, "42,167", 22"
How can I use Java to parse the data so that the commas inside the quotation marks are safely removed and the other commas are not affected?

A: Assuming you want to keep the quotation marks something like this would work. If not then you can edit it a little to also remove the quotation marks.
public String process(String input) {
    StringBuilder result = new StringBuilder();
    boolean insideDoubleQuotes = false;
    for (char currentCharacter : input.toCharArray()) {

      if (currentCharacter == '"') {
        insideDoubleQuotes = !insideDoubleQuotes;
      } else if (currentCharacter == ',' && insideDoubleQuotes) {
        continue;
      }

      result.append(currentCharacter);
    }

    return result.toString();
  }

A: Try this:
import java.util.ArrayList;

public class Main {

    public static void main(String args[]) {
        String input = "'10,11', '12,14', 15, '20,152', 37, '42,167', 22"; //
        String[] list = input.split("'"); // Split the string using "'" as delimeter(change it to quotation mark)
        ArrayList<String> elements = new ArrayList<>();
        for (int i = 0; i < list.length; i++) {
                        // condition to check if it is outside/outside the quotation mark
            if (i % 2 != 0) {  // if inside a quotation mark
                if (!list[i].trim().isEmpty()) { // so that spaces will not be included
                    elements.add(list[i].trim()); // add the element to the list
                }
            } else { //if outside the quotation marks
                String[] tmp = list[i].split(","); // split the regular comma separated values
                for (String s : tmp) { // iterate each splits
                    if (!s.trim().isEmpty()) { // check for spaces
                        elements.add(s.trim()); // add element to the list
                    }
                }
            }
        }

        for (String s : elements) {
            System.out.println(s);
        }
    }

}


text:
Q: Select with Inner Join operator and IN (long results) - Optimize Query I do a MySql query that looks for results in two different tables.
Tables
Contract
id, contract, creditor_id, client_id, event_id
Invoice
id, contract_id, invoice, due, value
The idea is to select the contracts using some parameters in the query, such as:
initial delay and final, initial value and final, events, creditor.
For this, I use the INNER JOIN, HAVING and IN.
Details:
After receiving the result, I take the values and loop to make an update on each query result, using the result ID.
I built an example in SQL Fiddle for better visualization.
The problem is, when I do this query with very long results or thousands of lines, the query is really slow.
So, I wanted to know if there is a better way to do the same query in an optimal way.
Query:
SELECT `c`.`id`,
       `c`.`contract`,
       `c`.`creditor_id`,
       `c`.`client_id`,
       `c`.`event_id`,
       `t`.`total_value`,
       `delay`
FROM `contract` `c`
INNER JOIN
  (SELECT contract_id,
          Sum(value) total_value,
          Datediff(Curdate(), due) AS delay
   FROM invoice t GROUP  BY contract_id
   HAVING delay <= 99999
   AND delay >= 1
   AND total_value >= 1
   AND total_value < 99999) t ON `t`.`contract_id` = `c`.`id`
WHERE `c`.`creditor_id` = 1
  AND `c`.`event_id` IN(4, 7, 5, 8, 13, 3, 6, 15, 2, 24, 1, 21, 20, 14, 17, 18, 16, 23, 25, 22, 9, 10, 26, 12, 19, 11)

A: *

*If "1..99999" means "any value", then remove the test from the query.  That is construct a different query when the user wants an open-ended test.

*Deal with the lack of due in the GROUP BY.

*Change Datediff(Curdate(), due) > 123 to due < CURDATE() - INTERVAL 123 DAY.  That will give us a chance to use due in an INDEX.

*Qualify due and value; we can't tell which table they are in.

*Please provide SHOW CREATE TABLE.

*c could use INDEX(creditor_id, event_id), but after the above issues are addressed, there may be an even better index.


text:
Q: Flutter - Wrap text on overflow, like insert ellipsis or fade I'm trying to create a line in which center text has a maximum size, and if the text content is too large, it fits in size.
I insert the TextOverflow.ellipsis property to shorten the text and inserting the triple points ... but it is not working.
main.dart
import 'package:flutter/material.dart';

void main() {
runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) => new Scaffold(
    appBar: new AppBar(
      backgroundColor: new Color(0xFF26C6DA),
    ),
    body: new ListView  (
      children: <Widget>[
        new Card(
          child: new Container(
            padding: new EdgeInsets.symmetric(horizontal: 16.0, vertical: 18.0),
            child: new Row(
              children: <Widget>[
                new Container(
                  padding: new EdgeInsets.only(right: 24.0),
                  child: new CircleAvatar(
                    backgroundColor: new Color(0xFFF5F5F5),
                    radius: 16.0,
                  )
                ),
                new Container(
                  padding: new EdgeInsets.only(right: 13.0),
                  child: new Text(
                    'Text lar...',
                    overflow: TextOverflow.ellipsis,
                    style: new TextStyle(
                      fontSize: 13.0,
                      fontFamily: 'Roboto',
                      color: new Color(0xFF212121),
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                new Container(
                  child: new Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: <Widget>[
                      new Row(
                        children: <Widget>[
                          new Text(
                            'Bill  ',
                            style: new TextStyle(
                              fontSize: 12.0,
                              fontFamily: 'Roboto',
                              color: new Color(0xFF9E9E9E)
                            ),
                          ),
                          new Text(
                            '\$ -999.999.999,95',
                            style: new TextStyle(
                              fontSize: 14.0,
                              fontFamily: 'Roboto',
                              color: new Color(0xFF212121)
                            ),
                          ),
                        ],
                      ),
                      new Row(
                        children: <Widget>[
                          new Text(
                            'Limit  ',
                            style: new TextStyle(
                              fontSize: 12.0,
                              fontFamily: 'Roboto',
                              color: new Color(0xFF9E9E9E)
                            ),
                          ),
                          new Text(
                            'R\$ 900.000.000,95',
                            style: new TextStyle(
                              fontSize: 14.0,
                              fontFamily: 'Roboto',
                              color: new Color(0xFF9E9E9E)
                            ),
                          ),
                        ],
                      ),
                    ]
                  )
                )
              ],
            ),
          )
        ),
      ]
    )
  );
}

result:

expected:

A: I went through such a problem several times using rows within columns. Here's a good way to fix it:
 return Column(
  children: [
    Row(
      children: const [
        Icon(Icons.close, color: Colors.red), // an example icon
        // use the flexible widget above the padding
        Flexible(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 10.0),
            child: Text(
              "Exemple of text",
              overflow: TextOverflow.ellipsis, // I used ellipsis, but it works with others (fade, clip, etc.)
              maxLines: 1,
            ),
          ),
        ),
      ],
    )
  ],
);

Notice that I put the Flexible above the padding, because when the text grew, the padding also broke the screen. It would be useless to put it only in Text. Hope this helps.

A: You should wrap your Container in a Flexible to let your Row know that it's ok for the Container to be narrower than its intrinsic width. Expanded will also work.

Flexible(
  child: new Container(
    padding: new EdgeInsets.only(right: 13.0),
    child: new Text(
      'Text largeeeeeeeeeeeeeeeeeeeeeee',
      overflow: TextOverflow.ellipsis,
      style: new TextStyle(
        fontSize: 13.0,
        fontFamily: 'Roboto',
        color: new Color(0xFF212121),
        fontWeight: FontWeight.bold,
      ),
    ),
  ),
),

A: Wrapping whose child elements are in a row or column, please wrap your column or row is new Flexible();
https://github.com/flutter/flutter/issues/4128

A: Depending on your situation, I think this is the best approach below.
final maxWidth = MediaQuery.of(context).size.width * 0.4;
Container(
        textAlign: TextAlign.center,
        child: Text('This is long text',
        constraints: BoxConstraints(maxWidth: maxWidth),
),

A: If you simply place text as a child(ren) of a column, this is the easiest way to have text automatically wrap. Assuming you don't have anything more complicated going on.  In those cases, I would think you would create your container sized as you see fit and put another column inside and then your text.  This seems to work nicely.  Containers want to shrink to the size of its contents, and this seems to naturally conflict with wrapping, which requires more effort.
Column(
  mainAxisSize: MainAxisSize.min,
  children: <Widget>[
    Text('This long text will wrap very nicely if there isn\'t room beyond the column\'s total width and if you have enough vertical space available to wrap into.',
      style: TextStyle(fontSize: 16, color: primaryColor),
      textAlign: TextAlign.center,),
  ],
),

A: Use an ellipsis to indicate that the text has overflowed.
SizedBox(
              width: 120.0,
              child: Text(
                "Enter Long Text",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                softWrap: false,
                style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0),
              ),
            ),

A: First, wrap your Row or Column in Expanded widget
Then
Text(
    'your long text here',
    overflow: TextOverflow.fade,
    maxLines: 1,
    softWrap: false,
    style: Theme.of(context).textTheme.body1,
)

A:     SizedBox(
                        width: width-100,
                        child: Text(
                          "YOUR LONG TEXT HERE...",
                          maxLines: 3,
                          overflow: TextOverflow.clip,
                          softWrap: true,
                          style: TextStyle(
                            fontWeight:FontWeight.bold,
                          ),
                        ),
                      ),

A: 1. clip
Clip the overflowing text to fit its container.
SizedBox(
          width: 120.0,
          child: Text(
            "Enter Long Text",
            maxLines: 1,
            overflow: TextOverflow.clip,
            softWrap: false,
            style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0),
          ),
        ),

Output:

2.fade
Fade the overflowing text to transparent.
SizedBox(
          width: 120.0,
          child: Text(
            "Enter Long Text",
            maxLines: 1,
            overflow: TextOverflow.fade,
            softWrap: false,
            style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0),
          ),
        ),

Output:

3.ellipsis
Use an ellipsis to indicate that the text has overflowed.
SizedBox(
          width: 120.0,
          child: Text(
            "Enter Long Text",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            softWrap: false,
            style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0),
          ),
        ),

Output:

4.visible
Render overflowing text outside of its container.
SizedBox(
          width: 120.0,
          child: Text(
            "Enter Long Text",
            maxLines: 1,
            overflow: TextOverflow.visible,
            softWrap: false,
            style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0),
          ),
        ),

Output:

Please Blog: https://medium.com/flutterworld/flutter-text-wrapping-ellipsis-4fa70b19d316

A: You can use this code snipped to show text with ellipsis
Text(
    "Introduction to Very very very long text",
    maxLines: 1,
    overflow: TextOverflow.ellipsis,
    softWrap: false,
    style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
),

A: Wrap the Container with Expanded()
Expanded (child: Container(
                  padding: new EdgeInsets.only(right: 24.0),
                  child: new CircleAvatar(
                    backgroundColor: new Color(0xFFF5F5F5),
                    radius: 16.0,
                  )
                ),
                new Container(
                  padding: new EdgeInsets.only(right: 13.0),
                  child: new Text(
                    'Text lar...',
                    overflow: TextOverflow.ellipsis,
                    style: new TextStyle(
                      fontSize: 13.0,
                      fontFamily: 'Roboto',
                      color: new Color(0xFF212121),
                      fontWeight: FontWeight.bold,
                    ),
                  ),
),

A:
In Column We make text ellipsis by wraping column with flexibale widget,
 Container(
            height: SizeConfig.blockSizeVertical * 20,
            width: SizeConfig.blockSizeHorizontal * 88,
            child: Flexible(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  PicClipper(
                      height: 50,
                      width: 50,
                      circularRadius: 30,
                      circularImage: imageUrl[index]),
                  SizedBox(
                    width: SizeConfig.blockSizeHorizontal * 3,
                  ),
                  const Text(
                    fontSize: 12,
                    fontWeight: FontWeight.normal,
                    text:
                        'Lorem ipsum dolor sit amet,consectetur adipiscing elit.Lorem ipsum dolor sit amet,consectetur adipiscing elit.',
                    fontStyle: FontStyle.normal,
                    textColor: AppColors.blackTextColor,
                    overflow: TextOverflow.ellipsis,
                    fontFamily: "Poppins",
                    maxLine: 3,
                    textAlign: TextAlign.start,
                  ),
                ],
              ),
            ),
          ),

A: If you are facing the problem inside a Row a widget, try to wrap the Text widget with Expanded
Row(
  children: [
    Text('first'),
    Expanded(
      child: Text('a really long message...'),
    )
  ]
)

A: Text inside Row
1. Preference of text in  Column 1 > Column 2

Row(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: const [
    Text(
      "This is very very  long text in column 1 of Row",
      style: TextStyle(
          overflow: TextOverflow.ellipsis, backgroundColor: Colors.green),
    ),
    Flexible(
      child: Text("This is very very  long text in column 2 of Row",
          style: TextStyle(
              overflow: TextOverflow.ellipsis,
              backgroundColor: Colors.yellow)),
    )
  ],
)

2. Preference of text in  Column 2 > Column 1

   Row(
     crossAxisAlignment: CrossAxisAlignment.start,
     children: const [
        Flexible(
          child: Text(
             "This is very very  long text in column 1 of Row",
             style: TextStyle(overflow: TextOverflow.ellipsis,  backgroundColor: Colors.green),
          ),
        ),
       Text("This is very very  long text in column 2 of Row",
        style: TextStyle(overflow: TextOverflow.ellipsis, backgroundColor: Colors.yellow))
    ],
   )

3. Same Preference

Row(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: const [
    Flexible(
      child: Text(
        "This is very very  long text in column 1 of Row",
        style: TextStyle(
            overflow: TextOverflow.ellipsis, backgroundColor: Colors.green),
      ),
    ),
    Flexible(
      child: Text("This is very very  long text in column 2 of Row",
          style: TextStyle(
              overflow: TextOverflow.ellipsis,
              backgroundColor: Colors.yellow)),
    )
  ],
)

Text inside Column
define the maxLine attribute.

Column(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: const [
    Text(
      "This is very very very very very very very very very very very very very very very very very  long text in Row 1 of Column",
      maxLines: 2,
      style: TextStyle(
          backgroundColor: Colors.green, overflow: TextOverflow.ellipsis),
    ),
    Text("This is very very  long text in Row 2 of Column",
        style: TextStyle(
            overflow: TextOverflow.ellipsis,
            backgroundColor: Colors.yellow))
  ],
)

Note: If your requirement is to show the entrie content without overflow but not messing with the constraints, remove the overflow attribute but keep the Flexible as is:

Row(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: const [
    Flexible(
      child: Text(
        "This is very very  long text in column 1 of Row",
        style: TextStyle(backgroundColor: Colors.green),
      ),
    ),
    Flexible(
      child: Text("This is very very  long text in column 2 of Row",
          style: TextStyle(
              overflow: TextOverflow.ellipsis,
              backgroundColor: Colors.yellow)),
    )
  ],
)

A: Using Ellipsis
Text(
  "This is a long text",
  overflow: TextOverflow.ellipsis,
),

Using Fade
Text(
  "This is a long text",
  overflow: TextOverflow.fade,
  maxLines: 1,
  softWrap: false,
),

Using Clip
Text(
  "This is a long text",
  overflow: TextOverflow.clip,
  maxLines: 1,
  softWrap: false,
),

Note:
If you are using Text inside a Row, you can put above Text inside Expanded like:
Expanded(
  child: AboveText(),
)

A: You can do it like that
Expanded(
   child: Text(
   'Text',
   overflow: TextOverflow.ellipsis,
   maxLines: 1
   )
)

A: I think the parent Container needs to be given a maxWidth of the proper size.  It looks like the Text box will fill whatever space it is given above.

A: One way to fix an overflow of a Text Widget within a row if for example a chat message can be one really long line. You can create a Container and a BoxConstraint with a maxWidth in it.
            Container(
              constraints: BoxConstraints(maxWidth: 200),
                child: Text(
                  (chatName == null) ? " ": chatName,
                  style: TextStyle(
                      fontWeight: FontWeight.w400,
                      color: Colors.black87,
                      fontSize: 17.0),
                )
            ),

A: You can do that by First wrapping your Column inside Flexible or Expanded and then use Text as usual and it will get wrapped up automatically.
Container(
  child: Row(
    children: [
      Flexible(
        child: Column(
          children: [
            Text("This text is so long and long and long and long and long and that's why it is not wrapping to next line.")
          ]
        ),
      )
    ],
  ),
),

A: SizedBox(
    width: 200.0,
    child: Text('PRODUCERS CAVITY FIGHTER 50X140g',
                overflow: TextOverflow.ellipsis,
                style: Theme.of(context).textTheme.body2))

Just wrap in inside a widget that can take a specific width for it to work or it will assume the width of the parent container.

A:
In Row We make text ellipsis to go second line by wraping  firstly Text with Container and than wrap container with flexible widget
 Container(

            height: SizeConfig.blockSizeVertical * 10,
            width: SizeConfig.blockSizeHorizontal * 88,

            child: Row(
              crossAxisAlignment:
              CrossAxisAlignment.start,
              children: [
                PicClipper(height: 50, width:50, circularRadius: 30, circularImage:imageUrl[index]),
                SizedBox(
                  width:
                  SizeConfig.blockSizeHorizontal * 3,
                ),
                Flexible(
                  child: Container(
                    child: const
                    AppText
                      (
                      fontSize: 12,
                      fontWeight: FontWeight.normal,
                      text:
                      'Lorem ipsum dolor sit amet,consectetur adipiscing elit.Lorem ipsum dolor sit amet,consectetur adipiscing elit.',
                      fontStyle: FontStyle.normal,
                      textColor: AppColors.blackTextColor,
                      textOverflow: TextOverflow.ellipsis,
                      fontFamily: "Poppins",
                      maxLine: 3,
                      textAlign: TextAlign.start,
                    ),
                  ),
                ),

              ],
            ),
          ),

A: There is a very simple class TextOneLine from package assorted_layout_widgets.
Just put your text in that class.
For example:
Row(
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      SvgPicture.asset(
        loadAsset(SVG_CALL_GREEN),
        width: 23,
        height: 23,
        fit: BoxFit.fill,
      ),
      SizedBox(width: 16),
      Expanded(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextOneLine(
              widget.firstText,
              style: findTextStyle(widget.firstTextStyle),
              textAlign: TextAlign.left,
            ),
            SizedBox(height: 4),
            TextOneLine(
              widget.secondText,
              style: findTextStyle(widget.secondTextStyle),
              textAlign: TextAlign.left,
            ),
          ],
        ),
      ),
      Icon(
        Icons.arrow_forward_ios,
        color: Styles.iOSArrowRight,
      )
    ],
  )

A: Try:
 Expanded(
  child: Container(
      child: Text('OVER FLOW TEST TEXTTTT',
          overflow: TextOverflow.fade)),
),

This will show OVER FLOW. If there is an overflow, it  will be handled.


text:
Q: Upper and lower bound of $L_2$ norm of $\lVert A x \rVert_{2}$, where $A \in M_{m,n}(\mathbb{C})$ and $x \in M_{n,1}(\mathbb{C})$ I am sorry for asking a (trivial)  question which might have been raised Before. But I could not find it with simple search. Perhaps, it is well-known (?)

Do we have an upper and lower (preferably tight) bound of an $L_2$ norm of a matrix-vector product $\lVert A x \rVert_{2}$, where $A \in M_{m,n}(\mathbb{C})$ and $x \in M_{n,1}(\mathbb{C})$?

partial attempt
\begin{align}
 \alpha \ \lVert x \rVert_{2} \leq \lVert A x \rVert_{2} \leq \underbrace{\beta}_{\lVert A\rVert_{F} \ ?} \ \lVert x \rVert_{2} \ .
\end{align}

*

*Is $\beta = \lVert A\rVert_{F}$  (Frobenius norm of $A$)? If yes, which theorem applies?

*What would be an appropriate $\alpha$?

A: As @logarithm points out in comments, the tight bounds come from the spectrum of $A^\star A$. Indeed, writing $\|Ax\|^2=\langle Ax|Ax\rangle=\langle A^\star A x| x\rangle$, we see that
$$
\begin{array}{cc}\displaystyle
   \sup_{x\ne 0} \frac{\|Ax\|^2}{\|x\|^2}=\max \sigma (A^\star A), & \displaystyle \inf_{x\ne 0} \frac{\|Ax\|^2}{\|x\|^2}=\min \sigma (A^\star A),
\end{array}
$$
where $\sigma(A^\star A)$ is the set of all eigenvalues of $A^\star A$. Note that such eigenvalues are nonnegative, because $A^\star A$ is semidefinite positive.
In practice, computing these eigenvalues can be difficult. The Frobenius norm is a much simpler object, and it provides an upper bound, which, however, is not sharp. To see this, note that
$$
\|Ax\|^2=\sum_i\left\lvert \sum_j a_{ij}x_j\right\rvert^2 \le \sum_i(\sum_j |a_{ij}|^2 \sum_j |x_j|^2)=\|A\|_F^2 \|x\|^2, $$
where we used the Cauchy-Schwarz inequality.


text:
Q: Nilpotent matrices linear combination Let be $\ A \in M_{nxn}$ be a nilpotent matrix. Prove that any $\ A^k \neq 0, k \in \mathbb N $ is not a linear combination of the matrices $\ A^{k-i}, i \in \{1,...,k-1\} $.

A: Hint: Let $m$ be minimal such that $A^m=0$. By assumption, $m>k$. Suppose
$$
  A^k=a_1A^1+\ldots+a_{k-1}A^{k-1}.
$$
Multiply by $A^{m-2}$ to conclude $a_1=0$. Similarly conclude $a_2=0$, etc. Derive a contradiction.


text:
Q: Prevent the button from showing the hash symbol and the id name in the browser URL in pure JavaScript I click on the p tag button call go-to-the-end and it takes me to a certain section of the page but it changes the url. For example before the click occurs the browser url looks like this www.example.com/test.html after I press the button it changes the browser url to www.example.com/test.html#end I
don't want my url to change by showing the hash symbol and the id name
so I basically want to press the button and the url does not change but it still takes me to a certain location on the page so how can I do this in pure JavaScript?
I found posts on this topic on this website but the ones I found are based on jQuery. I need an example in pure JavaScript.
Here is my code

document.querySelector('#go-to-the-end').addEventListener('click',goToTheEnd);

function goToTheEnd(){

document.location = '#end';

}
#go-to-the-end{
  color: white;
  font-weight: bold;
  background-color: red;
  padding: 5px;
  display: inline-block;
  border-radius: 8px;
  cursor: pointer;
}

#random-info{
  width: 100px;
}

Go to the end

  Three years after the second season of Batman: The Animated Series ended production, the show was moved from Fox to The WB network, which was airing and producing Superman: The Animated Series. These shows were merged as part of an hour-long segment called The New Batman/Superman Adventures. The WB wanted more episodes of Batman, so 24 new episodes were produced, which featured a different format and more focus on Batman's supporting cast.

In addition to the network's demands, the producers decided to make the show match the graphic style of Superman, so all the characters and objects were redesigned as more "animation friendly" with fewer lines, usually referred to by the fans and creative staff as the "revamp" (or alternately, the "new look"). A similar graphic style was used in the rest of the DCAU later on.

The entire series was released on DVD as Batman: The Animated Series Volume Four (From The New Batman Adventures), most likely to establish the connection with the original series.

A: You can call scrollIntoView() on the element you want to scroll to, which does not require a window.location change:

document.querySelector('#go-to-the-end').addEventListener('click',goToTheEnd);

function goToTheEnd(){
  document.querySelector('#end').scrollIntoView();
}
#go-to-the-end{
  color: white;
  font-weight: bold;
  background-color: red;
  padding: 5px;
  display: inline-block;
  border-radius: 8px;
  cursor: pointer;
}

#random-info{
  width: 100px;
}

Go to the end

  Three years after the second season of Batman: The Animated Series ended production, the show was moved from Fox to The WB network, which was airing and producing Superman: The Animated Series. These shows were merged as part of an hour-long segment called The New Batman/Superman Adventures. The WB wanted more episodes of Batman, so 24 new episodes were produced, which featured a different format and more focus on Batman's supporting cast.

In addition to the network's demands, the producers decided to make the show match the graphic style of Superman, so all the characters and objects were redesigned as more "animation friendly" with fewer lines, usually referred to by the fans and creative staff as the "revamp" (or alternately, the "new look"). A similar graphic style was used in the rest of the DCAU later on.

The entire series was released on DVD as Batman: The Animated Series Volume Four (From The New Batman Adventures), most likely to establish the connection with the original series.


text:
Q: Facebook comments in dreamweaver Please, I will really need your kind assistance here. This is what I am trying to achieve: on my news website, there is (for example) a URL - nigerianobservernews.com/15082013/news/news1.html. On this URL, the title and the content changes on a daily basis. I want to know how I can use facebook comment in such a way that the comment on yesterday's article on that same URL will be different on the comment on today's article even though the page/url is the same

A: You need to scrape your page to refresh Facebook's internal cache.
To scrap you can send a web request to the Facebook Object Debugger and pass your URL, or you can do like this:
curl "http://developers.facebook.com/tools/debug/og/object?q=$url"

Also:

When does Facebook scrape my page?
Facebook needs to scrape your page to know how to display it around
the site. Facebook scrapes your page every 24 hours to ensure the
properties are up to date. The page is also scraped when an admin for
the Open Graph page clicks the Like button and when the URL is entered
into the Facebook URL Debugger. Facebook observes cache headers on
your URLs - it will look at "Expires" and "Cache-Control" in order of
preference. However, even if you specify a longer time, Facebook will
scrape your page every 24 hours.


text:
Q: L^1 is a Banach space with integral of the absolute value norm I have to show that if $(X,\mathcal{M}, \mu)$ is a complete measure space (if $E\in \mathcal{M}$ has measure $0$, then every subset is measurable and has measure $0$, then $\mathcal{L}^1(\mu)$ with the norm $||f||_1=\int_X|f|d\mu$ is a Banach space.
So, first of all, I showed that the given norm, is indeed a norm, which is easy. But my problem begins with the completness. I know that I have to prove that the normed space is complete:
I was told by my  professor that I can use this proposition:
If $(V,||\cdot||)$ is a normed space such that for every sequence $(v_n)$ with the property: if $\sum ||v_n||<\infty$, then  $\sum v_n < \infty$; then the normed space is complete.
So let $\{f_n\}_{1}^{\infty}$ be a sequence in  $\mathcal{L}^1(\mu)$, with the given property. I started with $\sum ||f_n||_1 = \sum \int_X |f_n| d\mu$. The  first thing that comes to my mind is that I should define a function and prove that  my series converges to that.
Let $\varphi_n$ be the sequence given by: $\varphi_n = \sum_{i=1}^{n} |f_i|$ for every $n \in \mathbb{N}$. It's a monotone sequence and $\int \varphi_n = \sum \int |f_i| = \sum_{i=1}^{n} ||f||_1 < \sum_{i=1}^{\infty}||f_i||_1 $ for every n.
By the monotone convergence theorem, there exists $\varphi$ such that $lim_n \varphi_n(x) = \varphi(x)$ for almost every x,  so for almost all x the series $\sum |f_i(x)| = \varphi(x)$ converges.
Now, defining $f= \sum f_i$, it also converges, but for almost all x.
What should I do with that measure 0 set? I can define f to be any number, 0, for example, in that set? And are those the same element of $\mathcal{L}^1$?Also, I cannot figure out why or when I should use the complete measure space hypothesis. Maybe is to justify that indeed, those are the same element of $\mathcal{L}^1$.
Any help? Thanks in advance

A: $\sum \int_X |f_n|d\mu <\infty$ implies $ \int_X \sum |f_n|d\mu <\infty$ by Fubini/Tonelli and this implies $\sum |f_n| <\infty$ a.e.. So $f=\sum f_n$ is well defined (:define it ot be $0$ on then null set where $\sum |f_n|$ does not converge). Conclude that $\sum f_n =f$ in $L^{1}$ norm.


text:
Q: Websockets vs. iOS Push Notifications Take an iOS app like Instagram. Instagram is fundementally a real-time application that updates its UI whenever a user interacts with you. For example, if someone likes your post and you are using the app, the UI is updated to trigger dopamine release and inform you that something has hapened to one of your posts. Similarly, when someone sends you a direct message on instagram, while using the app, you see the message spring down from the top, all in real-time.
In terms of implementing such real time features it is obvious that a naive HTTPS polling approach is far too inefficient. Thus this leaves two strategies:
1.) APNS Push Notifications:
When a user likes a post, sends a direct message, comments (etc.), send an HTTP POST to a backend server that will then update the database and send a silent Apple push-notification to the device of the recipient. The recipient, which is using the app, will receive the pushed payload and will send an HTTP GET to the backend server to fetch the needed data (ie. the contents of the direct message sent). The UI is updated in quasi "real-time".
2.) Websockets:
Whenever any user opens the iOS app, connect the user to the server via a websocket. This means, that all users currently using the app are connected to the server via their own websocket. When a user likes a post, sends a direct message, comments (etc.), the app sends a message to the server through the socket indicating the action. The server, before updating the database, finds the socket associated with the recipient and forwards the message through the socket to the recipient. Upon reception of the message, the UI is updated in real-time
Which of these approaches is scalable and better suited for a production environment?

A: TL;DR You'll love websockets + Combine framework, event driven to update your UI smoothly. APNS can be somewhat unreliable in terms of deliverability and resource/database costs, and to me is more of an information center.
Reasons to like websockets:

*

*Decreases DB costs (e.g. finding device to send to)

*You know when the user is not using the app, decreasing outbound data costs

*Latency and faster practically speaking (more in depth in the websocket paragraph)

To answer the question: websockets are scalable based on your user count obviously. APNS is not server side testable in the CI, not cross platform, and not exactly feasible in terms of resource consumption.

I have a bias with websockets. But to present why I like it more, think about the efficiency given by your Instagram example.
To me, websockets == Event Driven, APNS is a simple information center.
APNS:
You sign up with APNS and you save the device in your backend. Great, every time an action is performed, like someone liking your post, query your backend, find the device that is linked to the OP, then send it outbound (which costs money if you think cloud computing costs). And you have to do that every single time someone likes your post (obviously you can aggregate, but why bother when you have websockets?). So database costs is one thing to think about. Additionally, a user could be muting their notifications. I don't have Instagram, but something efficiency wise they could have done (if not by sockets) is updating their UI based on incoming notifications for likes/hearts rather than a websocket connection. That's slow in terms of latency, costly, and unreliable if marked as spam. However, APNS has the benefit of not needing authorization unlike websockets, but...
Websockets:
When we approach websockets, you only authorize once (at least for mobile applications). You're removing outbound data costs (in terms of $$ and latency) by removing stuff like headers. You want to send small chunks of data, and sockets are just sending text/binary (I like to create commands out of them using JSON. A notable example is GitHub). When your user is done with the app, you close the connection and you don't need to send anymore data via APNS. Your server itself can be communicating with a single websocket via something like Redis PubSub in order to update your UI when someone uses a POST request to heart a post without needing to send some push notification. That's a win for the liker (who doesn't need to wait for that push notification to be sent) or the other way if you offload it to a background task (the OP doesn't need to wait). Websockets == Event Driven:

*

*Small data chunks that are constantly delivered (as in a lot) is much better than having APNS in which it can be slow to actually deliver, especially if you're flooding Apple/your user with notifications, marking you as spam. Although, disclaimer, that's just my personal belief and speculation depending on your use case.

*You're removing those unnecessary database costs.

*A downside would be keeping the connection alive.

Personally, I've used websockets with the combine framework recently for a chat application, but it can be used in so many different circumstances. Updating a Facebook feed/comment section, live notifications via the websocket instead of APNS, even posting content.

A: APNS is not guaranteed to be delivered, especially if you have a lot of notifications - I don't remember where I read that, but after some threshold per min it'll stop working. Also, you'll have to send them to all your users, not just online ones. It's possible to send silent notifications, but it's still not optimal.
That's why websocket is a preferred way. Also you can use something like https://github.com/centrifugal/centrifugo, which is a helper for your server, that'll hold all the connections, and is very stable.

A: It is not one out of two, even the web-socket isn't failsafe, but all of above should be considered for an effective communication, when the app is in foreground use a web-socket to listen for any updates from the server, expect a confirmation from client when something is delivered by socket, if the web-socket connection is not active or the there is no confirmation response deliver the update through APNS/FCM, as APNS/FCM it is not guaranteed to deliver, deliver the updates when next Socket connection is successful.


text:
Q: ?? operator didn't trigger System.DBNull type in DataTable DataRow This is a follow-up question to .Net C# String.Join how to output "null" instead of empty string if element value is null? where the answer suggested to use the ?? operator to define a custom null value, but the replacement never got triggered.
DataSet myDataSet = new DataSet();
mySqlDataAdapter.Fill(myDataSet);
DataTable rotationData = myDataSet.Tables["Table"];

rotationValues = string.Join(", ",
    from r in rotationData.Rows.OfType<DataRow>()
    select r[5] ?? "null");

When I change the code to:
rotationValues = string.Join(", ",
    from r in rotationData.Rows.OfType<DataRow>()
    select r[5].GetType());

I can observe that the data type for elements that have valid data in them is System.Double whereas the data type for elements which are NULL is System.DBNull.  Does ?? not operate on System.DBNull?

A: No DBNull and null is not the same thing.
But you can write this instead:
select r[5] == DBNull.Value ? "null" : r[5]);

Another possibility is to use Field extension method, it will give you strongly-typed access to each of the column values in the specified row, and the ?? operator will work.
select r.Field<string>(5) ?? "null";

A: ?? operates on the programming language null, not on the database DBNull.
From MSDN:

Do not confuse the notion of null in an object-oriented programming language with a DBNull object. In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column.


text:
Q: How to treat object with **ALMOST ZERO** probability Eight random lines are constructed in the plane.
Compute the expected number of intersections.
I was thinking $28$, because that's the number of intersections of $8$ lines such that no three lines intersect at a single point and no two lines have the same slope.
And I know the answer is no less, because the probability of three lines intersecting is almost zero and the probability of two lines with the same slope is almost zero.
But is almost zero allowed to be treated as zero?

A: The probability that three lines are concurrent, or that two lines are parallel, is not almost zero: it is actually zero. When we are dealing with continuous distributions, zero probability does not mean impossibility. Events with zero probability can, and do, happen.


text:
Q: Swapping elements in a Common Lisp list Is there a Common Lisp function that will swap two elements in a list given their indices and return the modified list?

A: I would avoid indexing into the list twice by using nthcdr to get the cdr of the cons cell containing the first element that you want to swap and then use elt to get the remaining element out of the sublist. This means that you only have to actually index starting from the head of the list once.
 (let ((list-tail (nthcdr i list)))
    (rotatef (car list-tail)
             (elt list-tail (- j i)))
    list)

At least from my perspective, this is sufficiently tedious to justify a function.

A: You can use rotatef:
(rotatef (nth i lst) (nth j lst))

Of course, list indexing can be expensive (costing O(size of list)), so if you do this with any regularity, you'd rather want to use an array:
(rotatef (aref arr i) (aref arr j))


text:
Q: Can a sequence of functions converge to different functions pointwise and on average? Is it possible for a sequence of functions in $\mathcal{C}\left[0,1\right]$
  to converge to one function pointwise (not necessarily to a continuous function) and to a different function in average (i.e with respect to $\Vert f\Vert=\left(\int\limits _{0}^{1}\left|f\left(x\right)\right|^{2}dx\right)^{\frac{1}{2}}$ ?
I know neither convergence mandates the other but I'm wondering whether it's possible for both convergences to occur but to different functions.
Thanks in advance!
Following some of the replies let's take as an example the sequence of functions defined by $f_{n}\left(x\right)=x^{n}$
 , pointwise it has a limit which is $$f\left(x\right)=\begin{cases}
0 & x\in\left[0,1\right)\\
1 & x=1
\end{cases}$$
  but on average I can see that it converges to the zero function as $$\Vert f_{n}\left(x\right)-0\Vert\overset{n\to\infty}{\longrightarrow}0$$
 Obviously $f\left(x\right)$
  and $0$
  are a.e equivalent so $f_{n}$
  also converges to $f$
  on average. However, while the zero function is in $\mathcal{C}\left[0,1\right]$
  the pointwise limit $f$
  is not. So unless I'm missing something here, the limit only has to be same up to a.e equivalence even if it's a sequence of continuous functions. I assume that if the pointwise limit was also continuous then it would have to be equivalent everywhere?

A: Convergence in average to a function $f$ implies the existence of a subsequence that converges pointwise a.e. to the same function $f$ (See Rudin's Real & Complex Analysis theorem 3.12). Thus, if the sequence also converges pointwise to a function, it must be the same function a.e.
The other issue you raise is continuity of the limit. Not all modes of convergence preserve limits. Pointwise convergence doesn't as your example illustrates. Convergence in the supremum norm does, however, and it is equivalent to uniform convergence.
The $L^2$ norm (or average as you call it) doesn't preserve continuity. In fact, one can prove that a class of continuous functions called continuous with compact support is dense in the space of integrable functions $L^p$. This means that for every integrable function in the $L^p$ sense (not necessarily continuous), one can find a sequence of continuous functions with compact support that converges to it in $L^p$. This is an important result in functional analysis.


text:
Q: F# Custom Comparison operators for type I want to create custom comparison operators for my type (<, >, <=, >=, etc). I have tried:
type MyType() =
    static member (>) (left: MyType, right: int) = true

let foo = new MyType();
let bar = foo > 12;

and receive the error:
The type 'MyType' does not support the 'comparison' constraint. For example, it does not support the 'System.IComparable' interface

(Why would a language feature like operator overloading depend on an interface IComparable that comes from a framework? shouldn't the language and the frameworks it use be independent?) So I try:
type MyType() =
    interface IComparable
        member self.CompareTo yobj = true
    interface IComparable<int>
        member self.CompareTo yobj = true
    static member (>) (left: MyType, right: int) = true

and I get:
This expression was expected to have type 'MyType' but here has type 'int'

How can I get the expected behavior?

A: The Reason Why You Get Such An Error
I don't know why F# doesn't allow me to write such codes like C#.
public class MyType
{
    public int Value {get;set;}

    public static bool operator >(MyType left, int right)
    {
        return left.Value > right;
    }

    public static bool operator <(MyType left, int right)
    {
        return left.Value < right;
    }
}

Even if this type doesn't implement the IComparable interface, I could compare it with an int as below:
t > 2
t < 6

It seems that F# treat the (>) as a T' -> T' -> bool:
val ( > ):
   x: 'T (requires comparison )->
   y: 'T (requires comparison )
   -> bool

This indicates :

*

*The left and right parameters are the same Type.

*The T' requires comparison (IComparable)

If I understand it correctly, this is the reason why you get an error like:

This expression was expected to have type 'MyType' but here has type 'int'

Even if you has implemented the IComparable interface, the standard (>) requires that the left and the right parameters belong to the same Type.
A Walkaround
One walk around is to create a custom function (>) that accepts a left MyType and a right int parameters directly:

type MyType(info)  =
    member x.Info : int = info

let inline (>) (left: MyType) (right: int) =
    left.Info > right

let inline (<) (left: MyType) (right: int) =
    left.Info < right

// see https://stackoverflow.com/questions/19682432/global-operator-overloading-in-f
let inline (>) (left) (right) =
    match (box left, box right) with
    | (:? MyType as l, :? int as r ) ->
        l.Info > int right
    | (:? IComparable as left', :? IComparable  )->
        let r = left'.CompareTo right
        r > 0
    | _ -> failwith "not support type "

let inline (<) (left) (right) =
    match (box left, box right) with
    | (:? MyType as l, :? int as r ) ->
        l.Info < int right
    | (:? IComparable as left', :? IComparable  )->
        let r = left'.CompareTo right
        r < 0
    | _ -> failwith "not support type "

A: Note that there is also a warning emitted at the declaration of >:

The name '(>)' should not be used as a member name. To define comparison semantics for a type, implement the 'System.IComparable' interface. If defining a static member for use from other CLI languages then use the name 'op_GreaterThan' instead.

As itminus' answer shows, this is because > is defined on two 'Ts that satisfy the comparable constraint.
There is no operator overloading in F# like you can do in C#. This is because operators are functions, and functions cannot be overloaded.
So your choices are either to (a) implement System.IComparable as the warning suggests, or (b) apply a workaround with inline functions as itminus proposes.


text:
Q: Cython+NumPy - compiler not using numpy.pyd I have a code that uses numpy and I want to compile it using Cython. I added the cimport directive:
import numpy as np
cimport numpy as np

I am on Windows 7, compiling using distutils with gcc (MinGW) as the compiler. It yields an error when I try to compile it. This is the error:
ssepMC.c:346:31: fatal error: numpy/arrayobject.h: No such file or directory
 #include "numpy/arrayobject.h"
                               ^
compilation terminated.
error: command 'gcc' failed with exit status 1

I believe this error occurs because the compiler is trying to compile the numpy package. But this is an unnecessary step because a compiled version of numpy exists in Cython under
C:\Python27\Lib\site-packages\Cython\Includes\numpy\numpy.pxd

So the question is: How do I make the compiler use the compiled version of numpy?
Thanks in advance.

A: As mentioned elsewhere, you need to point gcc to numpy/arrayobject.h which you can do by setting include_dirs to [np.get_include()].
Note - this is not 'recompiling' numpy, this is using the directives in the numpy arrayheader file to instruct gcc how to compile your code.
from Cython.Build import cythonize
import numpy as np

ext_modules = [Extension("hello", ["hello.pyx"], include_dirs=[np.get_include()])]

setup(
  ext_modules = cythonize(extensions)
)


text:
Q: Android Location Listener call very often I am using Network Location provider.
I need to call onLocationChanged method from my LocationListener only once per 1 hour.
Here is my code:
MyLocationListener locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3600000, 0,locationListener);

But it doesn't work. My onLocationChanged calling  very often.
What parameters must I use?

A: From the LocationManager#requestLocationUpdates() documentation:

Prior to Jellybean, the minTime parameter was only a hint, and some location provider implementations ignored it. From Jellybean and onwards it is mandatory for Android compatible devices to observe both the minTime and minDistance parameters.

However you can use requestSingleUpdate() with a Looper and Handler to run the updates once an hour.

Addition
To start you can read more about Loopers and Handlers here.
You are using API 8 which is a good choice, but this limits which LocationManager methods we can call since most were introduced in API 9. API 8 only have these three methods:
requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener, Looper looper)
requestLocationUpdates(String provider, long minTime, float minDistance, PendingIntent intent)

Let's use the first method, it is the simplest.
First, create your LocationManager and LocationListener as you normally would, but in onLocationChanged() stop requesting more updates:
@Override
public void onLocationChanged(Location location) {
    mLocationManager.removeUpdates(mLocationListener);
    // Use this one location however you please
}

Second, create a couple new class variables:
private Handler mHandler = new Handler();
private Runnable onRequestLocation = new Runnable() {
    @Override
    public void run() {
        // Ask for a location
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
        // Run this again in an hour
        mHandler.postDelayed(onRequestLocation, DateUtils.HOUR_IN_MILLIS);
    }
};

Of course, you ought to disable all of your callbacks in onPause() and enable them again in onResume() to prevent the LocationManager from wasting resources by acquiring unused updates in the background.

A more technical point:
If you are concerned about blocking the UI thread with the LocationManager, then you can use the second requestLocationUpdates() method to supply a specific Looper from a new Thread (say a HandlerThread).


text:
Q: Detect reconnection after DBMS was down or unreachable I am trying to pause JMS listeners when DBMS is unreachable and resume them right after the connection is back alive (so message delivery is not being retried and messages won't end up in DLQ). Datasource and connection is handled by Atomikos in Spring boot project.
The problem is how to detect connection to DB is back alive so I can resume my JMS listeners.
I have tried using Spring AOP and even full aspectj support without a success. With Spring AOP I am able to detect (the first) exception when there is a query to database, but not a test query (SELECT 1) and not a successful reconnect.
@AfterThrowing(pointcut = "execution(* com.atomikos.jdbc.AbstractDataSourceBean.getConnection())", throwing = "ex")
public void afterConnectionError(Exception ex) {
    // connection is broken, pausing JMS listeners
}

@AfterReturning(pointcut = "execution(* com.atomikos.jdbc.AbstractDataSourceBean.getConnection())")
public void afterConnectionSuccess() {
    // connection is ok, if JMS listeners are paused -> resume
}

Is it possible to use Spring AOP to catch atomikos datasource test query or what other approaches would you suggest for detecting a successful reconnect?
One idea I have is to do a test query manually and repeatedly and act on its success/exception. This approach feels like reinventing the logic which is already there.


text:
Q: Laurent series of $\log(z)\sin(1/(z-1))$ I would like to calculate the Laurent series of $$\log(z)\sin \left(\frac{1}{z-1} \right)$$ I have developed  separately $\log z$ et the sinus and tried to multiplied them terms by terms but it is complicated. Is there another simplier way?

A: Assuming we expand about $\zeta=z-1$, then
$$\log{(1+\zeta)} = \sum_{k=1}^{\infty} \frac{(-1)^k \zeta^k}{k} $$
$$\sin{\frac1{\zeta}} =  \sum_{n=0}^{\infty} \frac{(-1)^n}{(2 n+1)!\,\zeta^{2 n+1}} $$
There really is no substitute for multiplying the series out.  The best you can do is write
$$\log{(1+\zeta)} \sin{\frac1{\zeta}} = \sum_{m=-\infty}^{\infty} a_m \zeta^m $$
and compute the coefficients $a_m$ as needed.  As an example, let's compute the residue, or the coefficient of $\zeta^{-1}$.  By multiplying the terms out, you can show that the residue is
$$a_{-1} = 2 \sum_{k=1}^{\infty} \frac1{(4 k)!}  =  \left (\cosh{1} + \cos{1} \right ) - 2 = 2 \left (\sinh^2{\frac12} - \sin^2{\frac12} \right )$$

A: Hints and a bit of example
Use the substitution
$$z - 1 = u$$
so that
$$\sin\left(\frac{1}{z-1}\right) = \sin\left(\frac{1}{u}\right) = \frac{1}{u} - \frac{1}{3!u^3} + \cdot$$
and
$$\log(z) = \log(u+1) = u - \frac{u^2}{2} + \frac{u^3}{3} - \cdot $$
In this way you get simply
$$\left(\frac{1}{u} - \frac{1}{3!u^3}\right)\cdot \left(u - \frac{u^2}{2} + \frac{u^3}{3}\right) = -\frac{1}{6u^2} + \frac{1}{12u} + \frac{17}{18} - \frac{u}{2} + \frac{u^2}{3}$$


text:
Q: ActionController::ParameterMissing (param is missing or the value is empty: bid) When I try to customize my bid_params to add a parameter to the database, my strong parameters are not working for some reason. I need to be able to have the current_user passed into the database on the creation of a bid. This object is nested in a has_many belongs_to relationship with Auctions. Here is my controller:
class BidsController < ApplicationController
  def index
    @auction = Auction.find(params[:auction_id])
    @bids = @auction.bids
  end

  def new
    @auction = Auction.find(params[:auction_id])
    @bid = @auction.bids.build
  end

  def create
    @auction = Auction.find(params[:auction_id])
    @bid = @auction.bids.create(bid_params)
    if @bid.save
      flash[:success] = "Bid has been successfully placed."
      redirect_to @auction
    else
      flash[:error] = @bid.errors.full_messages.join('. ')
      render 'new'
    end
  end

  def destroy
     @auction = Auction.find(params[:auction_id])
     @bid = @auction.bids.find
    @bid.destroy
    flash[:notice] = "Successfully destroyed Bid."
    redirect_to auction_url(@bid.article_id)
  end

  private

  def bid_params
    params.require(:bid).permit(:auction_id).merge(bidder: current_user)
  end

end

and Stack Trace:
Started POST "/auctions/2/bids" for 127.0.0.1 at 2014-12-06 08:54:35 -0600
Processing by BidsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"6x4hV8y323a10kaJN5Rubj1z3uhUrSDQrD6aoaWCUhk=", "commit"=>"Create Bid", "auction_id"=>"2"}
  Auction Load (0.1ms)  SELECT  "auctions".* FROM "auctions"  WHERE "auctions"."id" = ? LIMIT 1  [["id", 2]]
Completed 400 Bad Request in 2ms

ActionController::ParameterMissing (param is missing or the value is empty: bid)

New Form:

Create a New Bid

<%= form_for ([@auction, @bid]) do |f|%>

<%= f.submit %>

<%end%>

Thanks!

A: Look at parameters that controller received:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"6x4hV8y323a10kaJN5Rubj1z3uhUrSDQrD6aoaWCUhk=", "commit"=>"Create Bid", "auction_id"=>"2"}

And then you try to permit these params:
def bid_params
  params.require(:bid).permit(:auction_id).merge(bidder: current_user)
end

And error was thrown in this operation: params.require(:bid) as this method suppose your params looks like:
{ ..., "bid" => { "auction_id" => "2" } }

Hence you may change your view/js that sends params or change def bid_params implementation to:
def bid_params
  params.permit(:auction_id).merge(bidder: current_user)
end


text:
Q: Gathering multiple mapper's result sorted at Reducer in Hadoop I have multiple very large files(nearly 500MB) as input to my MR program. I divide(split) these files into equal size partitions. Each Mapper gets
single partition of a file
Mapper : Key=(filename, partition_number) and Value= (character stream of partition)
I am applying some computation on value(character stream) in mapper.
I want to gather result corresponding to a input file(for all of its partitons) in one reducer. So I thought of reducer i/p key as 'filename'. But those output from mapper must be gathered sequentially in reducer.( like [partition1 o/p + partition2  +...+partitionN o/p] )
Can you plz suggest me the logic.
Thanks.

A: You need a secondary sort. For an example see https://vangjee.wordpress.com/2012/03/20/secondary-sorting-aka-sorting-values-in-hadoops-mapreduce-programming-paradigm/
In this case"

*

*Primary Comparator compares on [filename, partition_number]

*Group Comparator on filename only

*Partitioner on filename only


text:
Q: Probability of a piece of stick being a certain size? Suppose Alex has a one meter long wooden stick that Alex breaks randomly in two places such that the location of the breaks are independently distributed uniformly along the length of the wooden stick.
(a) Calculate the probability that one of the pieces will be more than 75 cm.

Is this just $\frac{75}{100}$?

(b) Calculate the probability that the three resulting pieces of the stick can be arranged to form a triangle.

I know the stick cannot form a triangle unless all three pieces are no longer than the sum. But I don't know how to make this into a probability? If $\alpha$ is the first break and $\beta$ is the second break and L is the length of the stick, then $\alpha < \frac{L}{2}$ and $\beta < \frac{L}{2}$. How would I turn this into a probability?

A: Let the first point be located at a distance of $X$ and the second point be located at a distance of $Y$ from the start of the stick. We know that $X \sim U(0,1)$ and $Y \sim U(0,1)$.
Part (a)
For one of the line segments to be more than $0.75$ cm, then the following are the conditions where this is satisfied
$$
X > 0.75 \text{ and } Y > 0.75 \Rightarrow P(X > 0.75, Y > 0.75)=1/16 \\
Y < 0.25 \text{ and } X < 0.25, \Rightarrow P(Y < 0.25, X < 0.25)=1/16 \\
Y - X > 0.75 \text{ if } Y > X\\
X - Y > 0.75 \text{ if } X > Y
$$
To calculate the probability for the latter two conditions, let us visualize this graphically.

The area of the two triangles together is
$$2 * \frac{1}{2} * \frac{1}{4} * \frac{1}{4} = \frac{1}{16}$$
Hence the probability that one line segment is longer than $75$ cm is
$$3 * \frac{1}{16} = \frac{3}{16}$$
Part (b)
For these three line segments to form a triangle, the following conditions must be satisfied
$$
    X + Y - X > 1 - Y   \Rightarrow Y > 1/2 \\
    Y -X + 1 - Y > X \Rightarrow X < 1/2 \\
    X + 1 - Y > Y - X \Rightarrow Y < X + 1/2
$$
This is for the case assuming $Y > X$. We can write another set of 3 equivalent equations for the case $X >Y$. Visualizing these two feasible regions on a graph, we get

The total area of the shaded figure, and hence the probability that the three line segments form a triangle is
$$2 * \frac{1}{2} * \frac{1}{2} * \frac{1}{2} = \frac{1}{4}$$

A: Let $X_1$, $X_2$ be the two uniform variables where the breaks happen.
HINTS:
(a) No it's far from $75/100$. One case where the biggest stick is 75 cm long is when both $X_1$ and $X_2$ occur before the 25% mark. The probability this happens is $\mathbb{P}(X_1<0.25 \cap X_2<0.25)=\mathbb{P}(X_1<1/4)\mathbb{P}(X_2<1/4)= 1/16$. What are the other possibilities of values for $X_1$ and $X_2$ that would give a piece of more than 75cm, and what are their probabilities?
(b) Your remarks are correct. Maybe it might be better to wonder in which case the stick cannot form a triangle. In any case, having solved the question (a) will help you greatly.


text:
Q: How to make specified area of an image transparent with Imagick? I want to make a part of an image transparent, I tried the code below, even tried many constants as COMPOSITE_DSTOUT, but all didn't work, does anyone know how to?
$fooImage->newImage(256, 256, new ImagickPixel('transparent'));
$Image->compositeImage($fooImage, Imagick::COMPOSITE_DSTOUT, $offsetX, offsetY);

I tested the code below, just got yellow with black, not transparent:
$width = 256;
$height = 256;

$image = new Imagick();
$image->newImage($width, $height, new ImagickPixel('yellow'));

$x = 50;
$y = 100;
$fooWidth = 100;
$fooHeight = 60;

//Create a new transparent image of the same size
$mask = new Imagick();
$mask->newImage($width, $height, new ImagickPixel('none'));
$mask->setImageFormat('png');

//Draw onto the new image the areas you want to be transparent in the original
$draw = new ImagickDraw();
$draw->setFillColor('black');
$draw->rectangle($x, $y, $x + $fooWidth, $y + $fooHeight);
$mask->drawImage($draw);

//Composite the images
$image->compositeImage($mask, Imagick::COMPOSITE_DSTOUT, 0, 0,
    Imagick::CHANNEL_ALPHA);

$image->setImageFormat('png');
$image->writeImage($path);

Got black inside yellow, not transparent in yellow

A: You need to make a black and white mask image the size of your input (white where you want it to be opaque and black where you want it to be transparent). Then use the equivalent of -compose copyopacity -composite to put the mask into the alpha channel of the image. Sorry, I do not code Imagick.
Here is an example using ImageMagick command line syntax:
Input:

convert logo.jpg \( -size 640x480 xc:white -size 200x200 xc:black -geometry +200+100 -compose over -composite \) +geometry -alpha off -compose copy_opacity -composite result.png

You can see it is transparent by compositing it over another image (in this case a checkerboard).
convert ( -size 640x480 pattern:checkerboard ) result.png -compose over -composite result2.jpg

A: Do you try \Imagick::COMPOSITE_COPYOPACITY ?
Because that's probably the right one.


text:
Q: Calculate average over column after group separation I've got DataFrame with columns a and b, where b contains the values Y or N corresponding for True and False.
I'd like to group by a and then, for each group, get the average of b's (meaning, the number ofTrue`s in the group divided by the number of lines in that group).
What I've got so far is
data['b'] = data['b'].map({'Y': True, 'N': False})
data.groupby('a', as_index=False)['b'].mean()

But I guess that's not the direction..

Example of data:
a   b
1   Y
1   Y
1   N
2   Y
2   Y
2   N
2   N

And the output should be
a   avg
1   2/3
2   1/2

A: I'd do this with groupby and value_counts(normalize=True):
df.groupby('a')['b'].value_counts(normalize=True).unstack(1)['Y']

a
1    0.666667
2    0.500000
Name: Y, dtype: float64

No conversion/replacement/map needed.

A: Using crosstab
pd.crosstab(df.a,df.b,normalize='index').Y
Out[336]:
a
1    0.666667
2    0.500000
Name: Y, dtype: float64

A: You can do it this way also:
df.assign(avg=df.b=='Y').groupby('a')['avg'].mean()

Output:
a
1    0.666667
2    0.500000
Name: avg, dtype: float64

Add reset_index:
   a       avg
0  1  0.666667
1  2  0.500000

A: numpy.bincount
i, a = data['a'].factorize()
b = (data['b'].values == 'Y')

pd.DataFrame(dict(a=a, avg=np.bincount(i, b) / np.bincount(i)))

   a       avg
0  1  0.666667
1  2  0.500000


text:
Q: Can slow VM be due to CPU, even if its utilisation percentage is low? I run 2 VMs. Those two VMs are not doing any CPU intensive tasks, and the host machine has a Sandy Bridge Celeron CPU, 8GB of DDR3 RAM and conventional HDDs. When I checked the CPU usage, it is not high, like 20~30%. Also the RAM is enough, I think.
But the VMs are really slow. Is it possible that even if the CPU utilisation percentage (measured in the host) is low, VMs run slow due to the CPU being a low-end (Celeron)? I have the money to buy a higher-end CPU like an i5, the only reason I chose a Celeron because I thought it would not read much power.

A: What kind of VMs, are you running? In case you have HDDs, you should check HDD queue length first. You can check it in resource monitor of host machine (you can run it typing resmon in command prompt). If you see there 3 or more than you should consider separating each VMs' disks files on different disks.

A: The answer to your question is most probably not.
VMs normally require RAM rather than CPU, however that depends on what you are doing and how you set them up in the first place.
Please answer my comment questions and I'll expand my answer?

A: I suggest you also to watch the CPU Ready Time parameter of your VMs. Normal values are about tens or hundreds of miliseconds. Celeron is not very appropriate processor for virtualization and may be a reason of those lags. Although I agree with Deesbek, that slow HDD is the reason of your troubles.


text:
Q: 'NoneType' object has no attribute 'text', beautifulsoup python When i try to run the code and export it to csv. the error "'NoneType' object has no attribute 'text'" appears and I hace tried every way to fix it but nothing seems to be working.The ProductName Prints out but the Price is the one causing the error
    from bs4 import BeautifulSoup
    import requests
    import csv

    csv_file = open('CultBeauty.csv', 'w', encoding='utf-8')
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow(['Product Name','Price'])

    for i in range(10):
        url = requests.get('https://www.cultbeauty.com/skin-care.list?pageNumber={}&facetFilters=en_beauty_skincareSkinType_content:Dry'.format(i+1)).text
        soup = BeautifulSoup(url, 'lxml')
        lists = soup.find_all('div', class_= "productBlock")
        for list in lists:
            ProductName = list.find('h3', class_="productBlock_productName")
            ProductName= ProductName.text.strip()
            print(ProductName)
            Price = list.find('span', {'class' : "productBlock_priceValue"})
            Price = Price.text.strip()
            print(Price)
            csv_writer.writerow([ProductName,Price])
    csv_file.close()

output:
Paula's Choice Skin Perfecting 2% BHA Liquid Exfoliant (118ml)
36.00€
Paula's Choice Skin Perfecting 25% AHA and 2% BHA Exfoliant Peel 30ml
44.00€
Sunday Riley GOOD GENES Glycolic Acid Treatment 1.7 fl. oz.
140.00€
BYOMA Hydrating Serum 30ml
14.60€
Elemis Pro-Collagen Cleansing Balm 100g
51.90€
BYOMA Moisturising Gel Cream 50ml
13.50€
Paula's Choice Skin Perfecting 2% BHA Liquid Exfoliant - Trial Size (30ml)
12.00€
etc

but it doesn't save to csv file and brings out the error

A: Some list of items may not have price value.So you might  use try except and also need to add user-agent . It always be better practice  not using list as variable as list is a python keyword. Now it's working smoothly.
from bs4 import BeautifulSoup
import requests
import csv

csv_file = open('CultBeauty.csv', 'w', encoding='utf-8')
csv_writer = csv.writer(csv_file)
csv_writer.writerow(['Product Name', 'Price'])
headers={"User-Agent":"mozilla/5.0"}
for i in range(10):
    url = requests.get('https://www.cultbeauty.com/skin-care.list?pageNumber={}&facetFilters=en_beauty_skincareSkinType_content:Dry'.format(i+1),headers=headers).text
    soup = BeautifulSoup(url, 'lxml')
    lists = soup.find_all('div', class_="productBlock")
    for lis in lists:
        ProductName = lis.find('h3', class_="productBlock_productName")
        ProductName = ProductName.text.strip()
        print(ProductName)
        try:
            Price = lis.find('span', {'class': "productBlock_priceValue"})
            Price = Price.text.strip()
            print(Price)
        except:
            pass
        csv_writer.writerow([ProductName, Price])
csv_file.close()


text:
Q: Can't get basic pjax example to work EDIT: (non) working example here:
http://www.jogos-mmorpg.com/pjax.html
I'm trying to reproduce a very basic PJAX example like explained in the readme (https://github.com/defunkt/jquery-pjax)
This is the index.html:
<!DOCTYPE html>

My Site

        Go to next page.

And this is the next.html

next page

When i click on the "next page" link, i simply go to next.html and the only thing i see on the screen is the "next page" paragraph, just like i would with pjax completely disabled.
What am i missing?

A: Have you read the entire example page? Because I will consider that you didn't, as you have not mentioned it in the OP.
It, more specifically, says the following:

Magic! Almost. You still need to configure your server to look for pjax requests and send back pjax-specific content.
The pjax ajax request sends an X-PJAX header so in this example (and in most cases) we want to return just the content of the page without any layout for any requests with that header.

To me it seems that pjax is not that easy to use. You need to handle the sending of the X-PJAX header.
UPDATE: I have tested the following code on your site (with Firefox console), and it is working:
$(document).ready(function() {
    $("#pjax-container a").pjax(
        {
            container: "#pjax-container",
            timeout: 5000
        }
    );
});

Do note the following things:

*

*I have restructured the code to be more jQuery-compliant, not sure if that was the issue. What is does now is the following:

*

*

*On the selector $("#pjax-container a"), it uses the pjax() function.

*

*

*It targets container #pjax-container as the target for replacement.

*Also I have added timeout: 5000, because I have read that pjax initially has a very low timeout setting, so it would not work on slow webservers.

Another side note: I noticed that pjax also updates the window.location.href to the new url, decide for yourself if you want this behaviour or not.

A: syntax error in your code:


text:
Q: PHP MYSQLI Prepared statements struggling with update I've been trying various ways of doing this but just can't seem to get my update statement to work.
Below is my code I have included the select statement which works fine, errors do work when I do something wrong so it would suggest the syntax is correct, but for some reason it returns 0 rows affected. This I think would point to my command but there isn't anyway to my knowledge of debugging this more than I have.
I've tried the command in phpmyadmin and it seems to work fine.
If anyone can help I've been scratching my head for nearly a day :)
Working select statement:
$user_id = 101;
$stmt = $conn -> prepare('SELECT id, sign_on_signature, user_id FROM a_entry_form WHERE user_id = ?');

if (
    $stmt &&
    $stmt -> bind_param('s', $user_id) &&
    $stmt -> execute() &&
    $stmt -> store_result() &&
    $stmt -> bind_result($record_id, $signature, $user)
) {

    while ($stmt -> fetch()) {
        echo "$record_id - $signature: $user <br>";
    }

} else {
    echo 'Prepared Statement Error';
}

Failing update statement:
$stmt = $conn -> prepare('UPDATE a_entry_form SET sign_on_signature = ? WHERE user_id = ? ');

$name = 'Joe';
$id = 101;

if (
    $stmt &&
    $stmt -> bind_param('si', $name, $id) &&
    $stmt -> execute() &&
    $stmt -> affected_rows === 1
) {
    echo 'Updated';
} else {
    echo 'Not updated';
  echo $conn -> error;
}

The above should execute the following which works fine:
UPDATE a_entry_form SET sign_on_signature = 'bob' WHERE user_id = 101

A: Thank you all, it was a combination of two things:
$stmt -> affected_rows === 1
As it affected 2 rows it was always going to return false as it would have been 0 or 2 therefore I have changed this to:
$stmt -> affected_rows > 0
Or perhaps as mentioned, I just don't need it when the form is submitted unless I need to tell the user upon submission they haven't changed anything?
The other was as @RiggsFolly said if nothing has changed the result will be 0, I was still expecting it to return rows a human error on my part, I did not change the values between tests.


text:
Q: Is there a way to make the git Bash connect to the heroku server using my University proxy address? Could you help me be able to connect to the heroku so that I can be able to login credentials into my Heroku account?
I want to be able to also commit and git download my files using the University proxy:
proxy.uonbi.ac.ke

That proxy has a password of the form xxx@students.
How can this be done?

A: If you need to contact an heroku remote repo, this article "Heroku Behind a Proxy", from Kit Monisit mentions that:

*

*even exporting http_proxy statements in your bash_profile isn't enough

*a tool like procychains is needed: see its howto page

A tool that forces any TCP connection made by any given application to follow through proxy like TOR or any other SOCKS4, SOCKS5 or HTTP(S) proxy.
When you want two (or more) different proxies in chain:
like:

your_host <--> proxy 1 (TOR) <--> proxy 2 (HTTP or SOCKS4/5) <--> target_host

You may need it when the only way out from your LAN is through proxy server.
Or to get out from behind restrictive firewall that filters some ports in outgoing traffic.
And you want to do that with some app like telnet.

In your case:

Part of the problem is that the Heroku client uses HTTPS to log in remotely.
To work around this, you can use ProxyChains to tunnel HTTPS connections through your restrictive proxy server.
Its role is to provide proxy authentication services for software that otherwise cannot work with proxies.

The article explains the build and installation.
The setup is something along the lines of:

Copy the proxychains.conf file to your home directory.

$ cd ~
$ mkdir .proxychains
$ cd ~/dev/build/proxychains
$ cp etc/proxychains.conf ~/.proxychains

Configure the proxy server address.

$ cd ~/.proxychains
$ vim proxychains.conf

Comment out the following line so that it looks like

#proxy_dns

Towards the end of the file, below the header [ProxyList], add your proxy server in the following format:

type host port [user pass]

For example

http 12.34.56.78 8080 user_me pa55w0rd

In your .bash_profile or .bashrc, delete or comment out any export statements that set the proxy server for the terminal session. For example

# export http_proxy="http://user:pass@host.com:8080"

Note: if you have a special character in your password (like an "at sign"), you need to have those characters percent-encoded:
] [ ? / < ~ # ` ! @ $ % ^ & * ( ) + = } | : " ; ' , > { space

Your "@" in a password would be %40: xxx%40students.

Test your setup with Heroku

$ cd
$ proxychains heroku login


text:
Q: $9999\ldots9\cdot9999\ldots9$ will always contain exactly one $8$? Will a number consisting of only the digit $9$, multiplied with another number consisting of only the digit $9$, always result in a number that contains exactly one $8$ digit, and how can one know that this will always be true?

A: Such a number is of the form $(10^m-1)(10^n-1)=10^{(m+n)}-(10^m+10^n)+1, \text{such that}\ m,n>0.$
It is clear that only the $max{(m,n)}^{th}$ digit from right will be 8.

A: Well, the multiplication can be written as $$(10^x-1)(10^y-1)=10^{(x+y)}-(10^x+10^y)+1$$ so the result will be $$ 1000\ldots000-(1000\ldots00+1000\ldots000)+1=1000\ldots000-100\ldots001000\ldots000+1=9999\ldots999899\ldots99999\ldots0000+1=9999\ldots999899\ldots99999\ldots0001$$


text:
Q: How to show the visual representation of parse tree generated by Antlr in vscode we are using parser,lexer etc which is generated by our backend team for typescript we are using them in our angular applications to generate a parse. we are able to generate the parse tree and print that tree to console but we struggling in printing its visual representation of the parse tree.
below is the sample code used to generate the parse tree
let code: string = `
        begin rule "My rule"
        doc := input.document_id
        ref := input.refrence
        countryuppper := upper(doc.country)
        country := doc.country
        end rule
    `;
this.inputStream = new ANTLRInputStream(code);
this.lexer = new Lexer(this.inputStream);
this.tokenStream = new CommonTokenStream(this.lexer);
this.parser = new Parser(this.tokenStream);
this.tree = this.parser.program();
console.log(this.tree)

visual representation I mean is like in the below image

Could anyone please tell us how can we print the visual representation of the parse tree in vscode.


text:
Q: Sybase ASE - INSERT INTO statment i stored procedure, problems in formating string I have following problem formatting the @p_f_field variable correct, I get the error:
Could not execute statement.
Incorrect syntax near '+'
Sybase error code=102, SQLState="42000"
Severity Level=15, State=181, Transaction State=1
Line 7

My stored procedure:
create proc dbo.sp_m_efi_dw_full_dsa_table_load_im ( -- parameter examples:
@p_skm_name varchar(4096),
@p_usr_name varchar(4096),
@p_t_name_dsa varchar(4096),
@p_t_name_bas varchar(4096),
@p_f_name varchar(4096),
@p_f_field varchar(4096)
)
as begin
declare @sql varchar(4096)
if @p_skm_name is not null
begin
if @p_usr_name is not null
begin
set @sql='TRUNCATE TABLE '+@p_skm_name+'.'+@p_usr_name+'.'+@p_t_name_dsa
exec (@sql)
end
end
set @sql='INSERT INTO '+@p_skm_name+'.'+@p_usr_name+'.'+@p_t_name_dsa+' '+@p_f_name+
' VALUES '+@p_f_field
exec (@sql)
end

My call to the stored procedure:
execute BAS_efi.dbo.sp_m_efi_dw_full_dsa_table_load_im
@p_skm_name         = 'B_ef',
@p_usr_name         = 'dbo',
@p_t_name_dsa       = 'a_log',
@p_t_name_bas       = 'a_log',
@p_f_name           = '(NEWFIELD1)',
@p_f_field          = '('+char(39)+'daf9af01-6bc2-11e-b23182b0623e'+char(39)+')'

Any suggestions on how to format the variable @p_f_field correct, or any others suggestions on how to execute this simple INSERT INTO procedure?


text:
Q: mysql - search pattern and replace I have MySQL table wp422_posts and I need to manipulate one type of values in post_name column. Actually, I need to manipulate long value beginning with 4 digits (unique ID) and than text, I need to get the 4 digits and left them there. Could anybody help me, please? I'm new to MySQL. Other values - which do not start with 4 digits and dash has to stay same.
one example of value of post_name

*

*old:
"2147-sprava-uzivatelskych-uctu-databaze-oracle-v-prostredi-autocad-map-3d"
desired

*new one: "2147"

How to select correct values in column:
SELECT * FROM `wp422_posts` WHERE `post_name` LIKE "[0-9][0-9][0-9][0-9]%"

it returns empty result, but why?
How to get rid of not needed part?
Thanks relly much for your help.

A: If you are sure that starting part is always 4 digit number and that is only  needed, then you can use this:-
SELECT LEFT(COL_NAME, 4)
FROM `wp422_posts`

Then you can use update statement to update the table. Somthing like:-
UPDATE `wp422_posts`
SET COL_NAME = LEFT(COL_NAME, 4)

Hope this helps!!


text:
Q: Using train_test_split to generate test and train data causes changes in underlying data I am using trai_test_split from sklearn.cross_validation to split the source CSV data file into training and test data using simple Python code like this:
from sklearn.cross_validation import train_test_split
import pandas as pd

dataset = pd.read_csv(fPath + 'source.csv')

train, test = train_test_split(dataset, test_size = 0.2)
train.to_csv(fPath + "train.csv", index=False, index_label=False, header=False)
test.to_csv(fPath + "test.csv", index=False, index_label=False, header=False)

The data is split correctly in terms of proportions and randomization, but I noticed that the resulting underlying data in the newly generated TEST and TRAIN files is slightly different from the original source data, when re-combined and compared side-by-side. Not for every single row and cell, but for some, here and there, there are small, but significant differences.
The below input and output is hard to read, but it's an example of the original data (18 lines), and the combined TEST and TRAIN output data. I sorted all data by first column and then the differences are shown below. These are % numbers, so as you can see, the differences are small and random, but not insignificant. Is this expected?
-0.00095    -0.00048    -0.14%  -0.00109    -0.00011    -0.00015    0.00016
-0.00055    0.00021 0.06%   0.0006  0.00075 0.00086 0.00076
-0.00044    -0.00034    -0.10%  -0.00112    -0.00123    -0.00127    -0.00124
-0.00027    -0.00023    -0.02%  -0.00187    -0.0028 -0.00286    -0.00182
-0.00021    -0.00024    0.07%   0.0016  0.00166 0.00022 0.00044
-6.00E-05   -6.00E-05   0.01%   1.00E-05    -4.00E-05   0.00013 0.00099
-5.00E-05   0.00016 0.01%   -0.00019    5.00E-05    0.00039 4.00E-05
-2.00E-05   -1.00E-05   0.04%   0.0004  0.00053 0.0009  0.00114
2.00E-05    4.00E-05    -0.05%  -0.00205    -0.00285    -0.00151    -0.00206
8.00E-05    -0.00048    0.00%   0.00038 0.00114 0.00111 0.00112
8.00E-05    0.00147 0.04%   0.00037 0.00033 0.00029 0.00021
8.00E-05    4.00E-05    -0.02%  -0.00027    -0.00018    -0.00015    -0.00014
8.00E-05    -1.00E-05   -0.02%  0   -3.00E-05   -0.00078    -0.00125
0.00015 -0.0001 -0.07%  -0.0004 -0.00114    -0.00099    -0.00071
0.00017 0.00043 0.11%   0.00044 0.00027 -6.00E-05   -4.00E-05
0.00029 0.00019 0.08%   0.00112 0.00167 -0.0019 -0.0014
0.00054 0.00063 0.08%   0.00088 0.00095 0.00097 0.00046
0.00086 -6.00E-05   -0.05%  -0.00028    0.00012 -0.0007 -0.00215
0.00115 0.00221 0.03%   -0.00033    0.00011 -0.00078    -0.00076

-0.00095    -0.00048    -0.14%  -0.00109    -0.00011    -0.00015    0.00016
-0.00055    0.00021 0.06%   0.0006  0.00075 0.00086 0.00076
-0.00044    -0.00034    -0.10%  -0.00112    -0.00123    -0.00127    -0.00124
-0.00021    -0.00024    0.07%   0.0016  0.00166 0.00022 0.00044
-6.00E-05   -6.00E-05   0.01%   1.00E-05    -4.00E-05   0.00013 0.00099
-5.00E-05   0.00016 0.01%   -0.00019    5.00E-05    0.00039 4.00E-05
-2.00E-05   -1.00E-05   0.04%   0.0004  0.00053 0.0009  0.00114
2.00E-05    4.00E-05    -0.05%  -0.00205    -0.00285    -0.00151    -0.00206
8.00E-05    -0.00048    0.00%   0.00038 0.00114 0.00111 0.00112
8.00E-05    4.00E-05    -0.02%  -0.00027    -0.00018    -0.00015    -0.00014
8.00E-05    0.00147 0.04%   0.00037 0.00033 0.00029 0.00021
8.00E-05    -1.00E-05   -0.02%  0   -3.00E-05   -0.00078    -0.00125
0.00015 -0.0001 -0.07%  -0.0004 -0.00114    -0.00099    -0.00071
0.00017 0.00043 0.11%   0.00044 0.00027 -6.00E-05   -4.00E-05
0.00029 0.00019 0.08%   0.00112 0.00167 -0.0019 -0.0014
0.00054 0.00063 0.08%   0.00088 0.00095 0.00097 0.00046
0.00086 -6.00E-05   -0.05%  -0.00028    0.00012 -0.0007 -0.00215
0.00115 0.00221 0.03%   -0.00033    0.00011 -0.00078    -0.00076

0.00%   0.00%   0.00%   0.00%   0.00%   0.00%   0.00%
0.00%   0.00%   0.00%   0.00%   0.00%   0.00%   0.00%
0.00%   0.00%   0.00%   0.00%   0.00%   0.00%   0.00%
-0.01%  0.00%   -0.08%  -0.35%  -0.45%  -0.31%  -0.23%
-0.02%  -0.02%  0.06%   0.16%   0.17%   0.01%   -0.06%
0.00%   -0.02%  0.00%   0.02%   -0.01%  -0.03%  0.10%
0.00%   0.02%   -0.03%  -0.06%  -0.05%  -0.05%  -0.11%
0.00%   -0.01%  0.09%   0.25%   0.34%   0.24%   0.32%
-0.01%  0.05%   -0.05%  -0.24%  -0.40%  -0.26%  -0.32%
0.00%   -0.05%  0.02%   0.07%   0.13%   0.13%   0.13%
0.00%   0.00%   0.00%   0.00%   0.00%   0.00%   0.00%
0.00%   0.01%   0.00%   -0.03%  -0.02%  0.06%   0.11%
-0.01%  0.01%   0.05%   0.04%   0.11%   0.02%   -0.05%
0.00%   -0.05%  -0.18%  -0.08%  -0.14%  -0.09%  -0.07%
-0.01%  0.02%   0.03%   -0.07%  -0.14%  0.18%   0.14%
-0.03%  -0.04%  -0.01%  0.02%   0.07%   -0.29%  -0.19%
-0.03%  0.07%   0.13%   0.12%   0.08%   0.17%   0.26%
-0.03%  -0.23%  -0.07%  0.01%   0.00%   0.01%   -0.14%


text:
Q: Confusion with Avg() and Joining 2 tables I've got myself into a bit of a tiss over averaging and joining tables.
Essentially I want to display the average heights of different plant species using Highcharts, pulling the data from a MySQL database. Unfortunately the height data and the species names were setup to be added in different tables.
I've got it working, however when I download the data and find the averages in Excel the figures are different to those being displayed - so I'm obviously not doing it right. I've double checked I'm doing it right in Excel so almost certain it's my MySQL query that's stuffing up.
There's loads of entries in the actual tables, so I've just put an example below.
The query I have at the moment is:
<?php
$result = mysql_query("
SELECT DISTINCT(plant_records.plant_id), ROUND(AVG(plant_records.height),2) as plant_average, plant_list.id, plant_list.plant_species
FROM plant_records
INNER JOIN plant_list
ON plant_records.plant_id=plant_list.id
GROUP BY plant_list.plant_species
")  or die(mysql_error());

while ($row = mysql_fetch_array($result)) {
$xAxisValues[] = "'" . $row['plant_species'] . "'";
$AseriesValues[] = $row['plant_average'];
}
?>

Am I doing it right? I found some nice tutorials explaining joins, like this one, but I'm still confused. I'm wondering if I'm averaging before I've joined them, or something??
"plant_id" in the Records table corresponds with "id" in the List table
plant_records:
id  plant_id    date_recorded   height
1   3           01/01/2013      0.2523123
2   1           02/01/2013      0.123
3   3           03/02/2013      0.446
4   3           04/03/2013      0.52
5   1           05/03/2013      0.3
6   2           06/03/2013      0.111
7   2           07/05/2013      0.30
8   4           08/05/2013      0.22564
9   1           09/05/2013      1.27
10  3           10/05/2013      1.8

plant_list:
id  registration_date   contact_name    plant_species   plant_parent
1   01/01/2013          Dave            ilex_prinos     London_Holly
2   02/01/2013          Bill            acer_saccharum  Brighton_Maple
3   01/01/2013          Bob             ilex_prinos     London_Holly
4   04/01/2013          Bruno           junip_communis  Park_Juniper

EDIT:
I've tried every possible way of finding the data using Excel (e.g. deliberately not filtering unique IDs, different average types, selecting multiple species, etc) to find the calculation my query is using, but I can't get the same results.

A: If we are assuming that plant_id is not the unique identifier - meaning that a single plant_id is only for one single plant of any given species and you want to know what the average height of a single species is you can do this:
SELECT PL.plant_species, ROUND(AVG(PR.height),2) as plant_average
FROM plant_records AS PR
JOIN plant_list AS PL
     ON PR.plant_id=PL.id
GROUP BY PL.plant_species

This will return something like:
plant_species   plant_average
acer_saccharum  0.2100000
ilex_prinos     0.6700000
junip_communis  0.2300000

A: I notice two issues with your query at the moment.

*

*Selecting plant_list.id while having a GROUP BY plant_list.plant_species will not yield anything of interest, due to the fact that MySQL will return an arbitrary id from any of the plants that match each species.

*You state that you are only interested in the most recent recording, but nothing in your query reflects that fact.
Given that information, try this query:
SELECT ROUND(AVG(pr.height),2) as plant_average, plant_list.plant_species
FROM plant_records pr
INNER JOIN plant_list
ON pr.plant_id=plant_list.id
WHERE pr.date_recorded = (
    SELECT MAX(pri.date_recorded) FROM plant_records pri
    WHERE pri.plant_id = pr.plant_id
)
GROUP BY plant_list.plant_species

Alternately, if you want just the average heights for a specific date, simply pass that directly into the query, instead of using the subquery.


text:
Q: TARGETDIR gets corrupted on uninstall I have a WiX install package. I use the TARGETDIR property to do some stuff in my uninstall custom actions. The TARGETDIR used to work fine, but then I made a change (I don't remember which one), and now I always have TARGETDIR = "C:\" , while other folder path properties have correct values on uninstall. I don't set it anywhere in the code or in the WiX install file, so I think it got corrupt because I've added some new files or directories to the installation package. Note that on install the TARGETDIR property contains a correct value. Any ideas why the TARGETDIR property could get corrupt?

A: TARGETDIR will usually be set to the same a ROOTDRIVE (The Drive with the most amount of free space, be it a local, network or USB drive). For this reason you can't really rely on it to be the same during installation and removal, especially if you plug in a USB disk with more space free than your "C:\", and you can't hardcode it to C:\ as computers may differ in their local disk configuration - some may not even have a C:\

A: If the TARGETDIR directory has no files inside of it in the install package, then the property is evaluated incorrectly. It took an hour for me to figure it out. Creating install packages is very painful.


text:
Q: Data return with undefined fetches Hi I am creating my own CRUD, using fetch requests, when I am returning the data I am painting them by console but I get the following error

SyntaxError: "undefined" is not valid JSON
at JSON.parse ()
at envio_datos_registro_usuarios.js:19:33

. I tried with ajax and everything works fine, but I want to learn how to handle fetch. Thank you very much for reading and helping me!
<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<link rel="stylesheet" href="css/estilos.css">
<title>Creacion de Usuario</title>

Creación de Usuario

            <form id="formulario-nuevo-usuario">

                    Nombre:
                    <input type="text" name="nombre" title="Solo se aceptan letras" pattern="^[A-Za-zÑñÁÉÍÓÚáéíúóÜ\s]+$" required>

                    Apellido:
                    <input type="text" name="apellido" title="Solo se aceptan letras" pattern="^[A-Za-zÑñÁÉÍÓÚáéíúóÜ\s]+$" required>

                    Correo:
                    <input type="email" name="email" pattern="^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$" title="Email incorrecto" required>

                    Usuario:
                    <input type="text" name="user" title="El usuario es requerido" required>

                    Contraseña:
                    <input type="password" name="password"  required>

La contraseña debe cumplir con los siguientes requisitos:

Al menos una letra mayúscula

Al menos un número

Sin espacios en blanco

Tener 6 caracteres

                    Confirmar Contraseña:
                    <input type="password" name="password2" required>

                    <button type="submit" id="boton-registrar" name="boton-registrar" value="Registrar">Crear</button>

            </form>

Mi JS
const d=document;
d.addEventListener('DOMContentLoaded', e=>{
sendDatosForm();
})
function sendDatosForm () {
let $btnRegistro=d.getElementById('boton-registrar');
$btnRegistro.addEventListener('click', e=>{
        e.preventDefault();
    const datos=new FormData(d.getElementById('formulario-nuevo-usuario'));

    fetch('./modelo/registrar_usuarios.php', {
        method: 'POST',
        body: datos,
        headers:{
            'Content-Type': 'application/json'
        }
    })
    .then(res=>{return res.ok ?(res.json(), console.log(res)) :Promise.reject(res);})
    .then(data=>{console.log(JSON.parse(data))})
    .catch(err=>{
    console.log(err);
})
.finally(()=>{
    console.log('Esto se ejecutará independientemente del resultado de la Promesa Fetch')
})

})

}
PHP
<?php
$respuesta= array('respuesta' =>'Hello there' , );

echo json_encode($respuesta);
?>