text:
Q: Inconsistent response time of Lambda function under a VPC Recently, we have started exploring AWS lambda technologies with huge hope that we should be able to make all of our micro services to be server-less. These services are running in EC2 instances at this moment in production. So we picked one of them and tried to make it as lambda. There I am stuck by seeing the performance. I believe I am doing something seriously wrong and need your assistance to come out of the problem.
We have a java application that runs on Tomcat in a EC2 instance and it fetches data from another instance under same VPC and same region. Please note that there are couple of back and forth calls between these servers. The time taken for single request to the Tomcat service is between 4 to 5 secs and that is pretty consistent. Now when we run the same service under Lambda infrastructure, the response becomes very inconsistent (5 to 25 secs).
I did not associate our VPC with the lambda in the first phase. And I thought that could be the reason for inconsistent response time, since there are couple of http requests over internet between Lambda function and one of our EC2 instances. So I associated our VPC with the Lambda but sadly seeing same response time. Below are the vpc configuration I did.
1. We have only one VPC that contains all of our EC2 instances. I associated that with the Lambda function configuration through AWS console.
2. We have 2 subnets in the VPC. Both the subnets are given in the vpc-config.
3. I have added the security group ID that is assigned to my 2nd EC2 instances where I am making the calls.
My understanding is, if I associate a VPC with a Lambda function, the function will run on a machine that is under same VPC. So we should get GBPS speed as LAN between Lambda function and associated EC2 instances. But that is not happening perhaps. Our Tomcat service gives predictable response time since they are on same VPC LAN.
Please note I am measuring my functions response time directly by invoking it from client, no API gateway in between so far.
Below are the times (in milliseconds) taken by my Lambda after it's deployed for 10 subsequent calls:
16797,
17965,
10026,
5846,
7689,
5118,
4349,
9297,
4378,
11692
Where the Tomcat service (which runs the same code inside on the same data set) takes below times for 10 subsequent calls.
3597,
3568,
4009,
3808,
3585,
3859,
3576,
3657,
3444,
3440,
Please observe that the service calls to Tomcat service does not take more than 4 seconds.
Does "associating a Lambda with a VPC" mean that the Lambda program runs on the same LAN as other EC2 instances lying on same VPC? Or it's a secure connection over internet?
Edit1:
Below are the notes for all the points you have raised.

*

*Cold Start Time: I understood the fact. And I don't have any problem with it. If Lambda is idle for 5 minutes, the next call will take more time to Cold start. But the calls I made subsequently with a interval of 2 seconds. If I discount the first call for longer cold start time, then subsequent calls are also did not take much lesser time. In fact the 2nd call took more time than first call. If I compare server based response with lambda response, it's just one third in this case. Any explanation?

*Specified Lambda memory: I have configured the lambda to take the max memory available (i.e 1.5 GB). So this can not cause the issue.

*ENI: This is completely new thing to me and I do not have much knowledge on it. The EC2 instance that gets call from Lambda is c3.large. And from AWS doc I see Maximum Network Interfaces given for this kind of instance is 3. Is there any way we can tune it for the performance? If we go for bigger instance then can I expect better performance?

*Region: Both VPC and Lambda are in same region.

*Code Initialization: There is no data base connect from Lambda. We call http endpoint from Lambda to an EC2 box that hosting few services.
Edit2:
Further observations. I have created 2 test lambdas which connect to same EC2 endpoint lying in our VPC and fetch some data.

*

*Lambda1: Without VPC association. Calls to EC2 endpoint once through public IP.

*Lambda2: With VPC enabled, has access to the security group of EC2 instance. Calls to EC2 endpoint once through private (subnet) IP.
Both takes similar amount of time. Only 1st run of Lambda2 (VPC enabled) takes larger time for the Cold Start. I expected the response time will go down in Lambda2 since we are bringing the client and service under a same VPC (which should be equivalent of a LAN). But that's not happening.
The same java code I ran in another EC2 instance under same vpc (as a simple java application) and that takes consistently 1/3rd time than Lambda1 or Lambda2.
Is there any way I can get the same response time from a Lambda? Please help.

Edit3:
Here is the code I run from Lambda or Simple Java Application.
public class Lambda implements RequestStreamHandler {
@Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
try {
JSONObject payload = (JSONObject) new JSONParser().parse(new InputStreamReader(inputStream, "UTF-8"));
System.out.println("payload = " + payload);
outputStream.write(Request.Get("http://" + (String)payload.get("ip") + "/api/xxx").
execute().returnContent().toString()).getBytes());
} catch (ParseException e) {
e.printStackTrace();
}
}
}

ip in the payload is sent as Public IP for Lambda1 (With out VPC) and private or local ip for Lambda2 (VPC enabled) from caller.

A: What you're experiencing are known as cold starts. This is when the underlying AWS infrastructure must be provisioned and your function brought into memory. In a VPC the issue typically is worse due to the time it takes to provision an Elastic Network Interface (ENI). Some of your subsequent calls are faster because Lambda will keep containers available and warm for a period of time. You can find more info in the AWS docs. The below link is also relevant -
https://forums.aws.amazon.com/thread.jspa?threadID=181348
Additionally, there are several projects to keep your Lambdas warm. Some good ones are found here -
https://lambdacult.com/spark
https://serverless.com/blog/keep-your-lambdas-warm/

A: Lambda with a VPC means that the Lambda runs on the same set of subnets as other EC2 instances lying on same VPC.
There are several factors responsible for variable performance of Lambda.

*

*Cold start:This happens when Lambda function runs for the first time or haven't been triggered around last 5 minutes. To keep Lambda Hot, you should be able to create a scheduled Lambda to trigger it around 5 mins intervals with fast exit routine in Lambda code e.g 'ping' which will call the callback immediately.

*Specified Lambda memory: If you provision 128Mb memory for a Lambda, Amazon will provision these in low end hardware which will slowdown the endpint network performance and CPU performance.

*Elastic Network Interface (ENI): The time it takes to provision an Elastic Network Interface (ENI) can also impact the API.

*If you are acessing resources in a VPC using Lambda, having Lambda in the same region and availability zone will improve performance.

*Also keep initialization code such as database connection & etc outside handler, which will be reused for subsequent call.


text:
Q: How to customize the field name of the generated Java object using JAXB custom bindings? I'm trying to generate JAXB generated objects for the below sample xsd.
<xs:complexType name="AddressType">
      <xs:sequence>
        <xs:element name="USA" type="xs:string"/>
      </xs:sequence>
   </xs:complexType>

and the class that gets generated without any custom bindings is
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AddressType", propOrder = {
    "usa"
})
public class AddressType {

    @XmlElement(name = "USA", required = true)
    protected String usa;

    /**
     * Gets the value of the usa property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getUSA() {
        return usa;
    }

    /**
     * Sets the value of the usa property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setUSA(String value) {
        this.usa = value;
    }
}

as you see the field name is "usa" and setters/getters are getUSA/setUSA.
Is there any custom setting/binding to have the field name also be generated as "USA" instead of "usa", that way the field and property are all "USA".
I referred How to customize property name in JAXB?
but that is to customize the property, instead of field.. any help
By the way, I'm using maven-jaxb2-plugin

A: Example xjb file as in your case : binding.xjb
example :
<jaxb:bindings
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
version="2.1">

<jaxb:bindings schemaLocation="schema.xsd">
    <jaxb:bindings node="//xs:element[@name='USA']">
        <jaxb:property name="usa" />
    </jaxb:bindings>
</jaxb:bindings>

</jaxb:bindings>

Add -b binding.xjb with your xjc command or configure the binding file location in your maven xjc plugin.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I batch rename filenames in sequential order using the `rename` utility? Let's say I have a.jpg, b.jpg and c.jpg and I want to rename them like this: 001.jpg, 002.jpg and 003.jpg. How should I do this using rename?
EDIT: rename 's/.*/expr/' *.jpg | I need to change expr with something that will add 001, 002, 003 for each file.

A: How about bash for loop over the jpg files.
for i in *.jpg ;do mv $i $((++c)).jpg ;done

A: A for loop generating also the leading zeros:
for i in *.jpg ; do name=00$((++c)); mv $i ${name: -3}.jpg ; done


text:
Q: jQuery - get child element of elements in array I have a following HTML:

Then I have some business logic in JavaScript do decide what div elements to put in array:
var arr = [];
for(i = 1; i <= 4; i++) {
  if(someExpression) arr.push($("#div" + i));
}

The question: Is it possible to get all spans with class "text" from elements in arr (without using $(arr).each or for loop)?
I tried a simple things below, but they don't work..
$(arr).find(".text");
$(".text", $(arr));
$(".text", arr);

Thanks

A: You can use a disguised loop :
var texts = arr.map(function(div){ return div.find('.text') });

Starting from your existing arr array, there's not really a way to avoid a kind of loop.
But note that it would simpler to do
var texts = $('#div1,#div2,#div3,#div4').find('.text');

or if you don't have other divs whose id starts with div :
var texts = $('[id^=div] .text');

A: You have an array of jQuery objects, that's why you can't create a jQuery object from the array.
Put the elements in the array instead:
var arr = [];
for(i = 1; i <= 4; i++) {
  if(someExpression) arr.push($("#div" + i)[0]);
}

Then you can create a jQuery object from the array, and using find works fine to find the elements:
var texts = $(arr).find(".text");

Demo: http://jsfiddle.net/Guffa/Wu92L/

A: why don't you just select all div.text?

var arr = $(".text");


text:
Q: Spring JPA - org.hibernate.LazyInitializationException: could not initialize proxy - no Session I'm using Spring JPA to query a list of JPA objects (say B) which has a relation to another Object (say A) with lazy fetch. JPQL to filter based on the lazy-loaded object throws an exception
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy  - no Session exception. How to solve this?
I tried using JOIN, FETCH, LEFT JOIN and @EntityGraph attributes. I couldn't get the expected result.
@Entity
public class B {
    ...
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "A_Id", referencedColumnName="id", nullable = false)
    private Parent parent;
    ...
}

public interface BRepository extends PagingAndSortingRepository<B, Integer> {

    ...
    @Query("SELECT b FROM B b join fetch b.parent p where p.id = :parentId")
    List<B> findBsByParent(@Param("parentId") int parentId);
    ...
}

@Service
public class MyService {
   @Autowired
   private BRepository bRepository;

   public void workFunc(int parentId) {
      List<B> bList = bRepository.findBsByParent(parentId);
      ...
      // do certain ops with bList and other stuff too
      ...
   }
}

I expect findBsByParent method should return all B's that has given parentId. Unfortunately, I wouldn't be able to use native query here.

A: Add following property in your application.properties file:
hibernate.enable_lazy_load_no_trans = true


text:
Q: Vertically Center Sub and Super Script in HTML Is there a way to vertically center a sub and super script at the same time?  I would like the "e" vertically centered with the "r".
erTeam 1

A: Well, there is but you pretty much have to strip away all the default stylings that are inherent to these tags. So you might as well use spans.
You'll also need a wrapper so that you can arrange them how you want...I've used flexbox but I'm sure there are other methods.

body {
  font-size: 36px;
  text-align: center;
}
span.column {
  flex-direction: column;
  display: inline-flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  vertical-align: text-top;
}
sup,
sub {
  top: 0;
  bottom: 0;
  line-height: 1;
  font-size: .5em;
}

  er
Team 1

A: If you don't mind a monospace font for the [sub][super]scripts, you could do the following:

span {
  font: 20px verdana;
}

sup, sub {
  font-family: monospace;       /* make letters same width so the transform aligns them properly */
}

sup + sub {
  display: inline-block;        /* transform doesn't work on inline elements */
  transform: translateX(-100%); /* move backwards */
}
erTeam 1

A: Just one more solution. Note this will work only when you have 1 letter in your sub or superscript.

span {
  font-size: 30px;
  position: relative;
  padding-left: 0.5em
}
sup,
sub {
  position: absolute;
  left: 0;
  line-height: 0.8;
  font-size: .6em;
}
sup {
  top: 0;
}
sub {
  bottom: 0;
}
erTeam 1


text:
Q: Geting MAC address by using VB.NET 2010 I have tried to get the MAC address of each network interface card on a machine by using the below function in VB.NET, but I just realized that this function doesn't work in Windows XP:
  Function getMacAddress()
        Dim nics() As NetworkInterface = NetworkInterface.GetAllNetworkInterfaces()
        Return nics(1).GetPhysicalAddress.ToString
    End Function

How can I make this code to run on Windows XP? What other alternatives exist to get the list of MAC addresses on Windows XP?

A: I did some digging when connecting to different VPNs.  So far the below seems pretty reliable.  Relying on 0 or 1 for the actual physical adapter as suggested above does not work in many cases.  In some cases my actual Ethernet adapter was the 3rd adapter.  Excluding the loopbacks, tunnels, and ppp adapters should narrow it down.  I found that many of my non physical adapters have the string "00000000000000E0" as the mac address.
Private Function getMacAddress() As String
    Try
        Dim adapters As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()
        Dim adapter As NetworkInterface
        Dim myMac As String = String.Empty

        For Each adapter In adapters
            Select Case adapter.NetworkInterfaceType
                'Exclude Tunnels, Loopbacks and PPP
                Case NetworkInterfaceType.Tunnel, NetworkInterfaceType.Loopback, NetworkInterfaceType.Ppp
                Case Else
                    If Not adapter.GetPhysicalAddress.ToString = String.Empty And Not adapter.GetPhysicalAddress.ToString = "00000000000000E0" Then
                        myMac = adapter.GetPhysicalAddress.ToString
                        Exit For ' Got a mac so exit for
                    End If

            End Select
        Next adapter

        Return myMac
    Catch ex As Exception
        Return String.Empty
    End Try
End Function

A: Works for me on XP, except I've got a few interfaces and my first (0th) is my "real" MAC address, and it corresponds to the MAC address reported by a non-.NET program.


text:
Q: How to get dates by days which have intervals of 7 days each hello guyz am new to flutter and am practicing on dates then i encounter a difficulty on how can i acheive the result same below using a loop or something in order to get this result.
so far i tried is
final now = DateTime.now();

for(var d = 1 ; d <= 5 ; d++){
  // Don't know whats next to do here to get the same result below
}

i want result like this
Apr 19, 2022
Apr 26, 2022
May  3, 2022
May 10, 2022
May 17, 2022

can some help me and explain.

A: Dart's DateTime class has an add function, where you can specify a duration which will be added the current Date.
Therefore, what you can do is:
DateTime now = DateTime.now();

for(var d = 1; d <= 5; d++) {
  ...
  now = now.add(Duration(days: 7)); // here you can specify your interval. Also possible: hours, minutes, seconds, milliseconds and microseconds
}

I'll recommend reading the Docs, e.g. DateTime Docs and Duration Docs


text:
Q: Resizing a UITextField programmatically automatically reverts back to old size After a certain user action I wish to resize a UITextField and move it to the right: e.g.
CGRect oldFrame = self.sampleTextField.frame;
CGRect newFrame = CGRectMake(oldFrame.origin.x + 100,
                             oldFrame.origin.y,
                             oldFrame.size.width - 100,
                             oldFrame.size.height);
[self.sampleTextField setFrame:newFrame];

This works for about half a second and then the UITextField snaps back into it's original, unedited frame.
The UITextField is put in place in a storyboard but I have removed all auto-layout constraints from it.
Is it auto-layout that is returning the UITextField to it's original frame?
Is there a way of achieving this with my current setup or will I have to take the UITextField out of the storyboard and programmatically add it to the View?

A: If you build and run without adding any constraints to an element, you'll find that Interface Builder fixes the element's width and height, and pins its position relative to the top left corner of the superview.
To make your interface react correctly to changes in size or orientation, you need to start adding constraints. You can also remove the automatically added constraints programmatically before you set the frame and set translatesAutoresizingMaskIntoConstraints to NO.

A: The easiest way to accomplish what you want is to add the proper constraints in IB (left edge, top or bottom edge, and width), and make IBOutlets to the left constraint and the width constraint (I'll call them leftCon and widthCon). In code, you then adjust the constant value of those constraints,
self.leftCon.constant += 100;
self.widthCon.constant -= 100;

If you want to animate that, then put them in (or just above, it works either way) an animation block,
- (void)adjustTextField {
    self.leftCon.constant += 100;
    self.widthCon.constant -= 100;
    [UIView animateWithDuration:1 animations:^{
        [self.view layoutIfNeeded];
    }];
}


text:
Q: mPDF v8.0.4 - setProtection function it is not working as expected I´m trying to use the functionality of the function setProtection().

*

*I have the feeling that the generated file it´s not protected because I can copy and I can print the file content.

According with the documentation, every action of copy, print and etc should be denied for whom tries to manipulate the file after downloaded. Example #1
// Encrypt the file and grant no permissions to the user to copy, print etc.
// The user will be able to open the file as no password is specified
// Owner cannot access full rights because no owner_password was set

$mpdf->SetProtection(array());

*

*Am I using the function in the correct place in the file?

*Is there some bug to fix in this method?

*Is there an alternative solution outside the box that can someone use to protect the file that will be generated?
An API ou something else?

*As a PDF reader Tool I´m Evince V.2.32.0.145
This is the code: Thank you so much.
// Security method
$mpdf->SetProtection(array());

//$mpdf->SetProtection(array('print-highres'), '', 'test123456&&987%654', 128);

$mpdf->SetTitle("Quorum sine causa fieri nihil");
$mpdf->SetAuthor('Quorum sine causa fieri nihil');
$mpdf->SetCreator('Quorum sine causa fieri nihil');
$mpdf->SetSubject('Quorum sine causa fieri nihil');
$mpdf->SetKeywords('Quorum sine causa fieri nihil');

$css = file_get_contents(__DIR__. '/assets/css/mpdf.css');

$mpdf->WriteHTML($css,1,\Mpdf\HTMLParserMode::HEADER_CSS); // Load the CSS

$mpdf->WriteHTML($html,\Mpdf\HTMLParserMode::HTML_BODY);// Load the html

// INVOICE name generated.
$fileName = 'Invoicename'.'_'.date('D-d-m-Y-H-i-s').'_'.$order_id.'.pdf';

$mpdf->Output($fileName,"D");

$mpdf->cleanup();

A: Looks like you need to set the permission, user and password with the SetProtection function.
// Encrypt the file and grant no permissions to the user
// The user will need to use "UserPassword" to open the file
// Owner has full rights using the password "MyPassword"
$mpdf->SetProtection(array(), 'UserPassword', 'MyPassword');

Documentation here:
https://mpdf.github.io/reference/mpdf-functions/setprotection.html


text:
Q: Adobe Search&Promote non-standard  tag A website I am working on uses Adobe Search&Promote (SP) as it's internal website indexing and searching tool.
I need to exclude common parts of each web page from being indexed by SP (such as the header, nav, footer) because they are the same on every single page.
SP's documentation states the following:

"To prevent parts of individual web pages from being searched, you can exclude portions of a page from indexing. Surround the text with <noindex> and </noindex> tags. This method is useful if you want to exclude navigation text from searches."

Of course, <noindex>, is not a standard HTML tag/element.
Is there javascript or something I should be doing to register/create this fake tag in browsers so I don't have to worry about any strange behavior as a result of having a non-standard HTML tag just hanging out in my code? Or should I just not care because browsers will ignore this non-existent element?
Note: There is absolutely no styling that needs to be done on this <noindex> element. It simply needs to wrap around content in the HTML.

A: There is nothing you need to do. Browsers are expected to ignore unknown tags, and they do, so they see <noindex>foo</noindex> just as foo. Well, not quite. Technically, modern browsers construct an element node (of type HTMLUnknownElement) in the DOM. But the element has no associated default styling and no associated action, so it's really a dummy element and represents its content only.
It would be possible to remove such elements nodes using client-side JavaScript, but that would be quite unnecessary.
The only real risk is that some day some specification or some browser or some web-wide indexing robot might start treating noindex as a real element with some defined meaning, possibly with default rendering and default functionality. Then you would be in trouble if these differ from what you expected. But it's a rather small risk, and it seems that you don't have a choice.

A: Although it's not in the documentation, our team consulted an Adobe consultant regarding this. He told us that we can use a 'noindex' class instead of the <noindex> element. He was even recommending us to use the class instead of the tag.
A warning though, the 'noindex' class is only working with
 elements but not on other elements such as
, , or .
So a usage will be something like this:

This should not be indexed.


text:
Q: How to make a QML toggle button that tracks/controls any boolean property My QML/QtQuick exercise for today is to make a little ToggleButton widget that I can instantiate to monitor the state of a specified boolean QML property, and that also toggles that property's state when I click on the ToggleButton.
So far I have this for my ToggleButton component:
// Contents of ToggleButton.qml
import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Controls.Styles 1.4

Button {
    property bool isActive: false

    onClicked: {
        isActive = !isActive;
    }

    style: ButtonStyle {
        background: Rectangle {
            border.width: control.activeFocus ? 2 : 1
            border.color: "black"
            radius: 4
            color:  isActive ? "red" : "gray";
        }
    }
}

.... and here is my little test harness that I use to see whether it works the way I want it to, or not:
// Contents of main.qml
import QtQuick 2.6
import QtQuick.Window 2.2

Window {
   visible: true
   width: 360
   height: 360

   Rectangle {
      property bool lighten: false;

      id:blueRect
      x: 32; y:32; width:64; height:64
      color: lighten ? "lightBlue" : "blue";

      MouseArea {
         anchors.fill: parent
         onClicked:    parent.lighten = !parent.lighten;
      }
   }

   Rectangle {
      property bool lighten: false;

      id:greenRect
      x:192; y:32; width:64; height:64
      color: lighten ? "lightGreen" : "green";

      MouseArea {
         anchors.fill: parent
         onClicked:    parent.lighten = !parent.lighten;
      }
   }

   ToggleButton {
      x:32; y:128
      text: "Bright Blue Rect"
      isActive: blueRect.lighten
   }

   ToggleButton {
      x:192; y:128
      text: "Bright Green Rect"
      isActive: greenRect.lighten
   }
}

You can run this by saving the code to ToggleButton.qml and main.qml (respectively) and then running "qmlscene main.qml".
Note that if you click on the blue or green rectangles, it works as expected; the boolean "lighten" property of the Rectangle object is toggled on and off, causing the Rectangle to change color, and the associated ToggleButton also reacts appropriately (by turning itself red when the "lighten" property is true, and gray when the "lighten" property is false).
So far, so good, but if you then click on the ToggleButton itself, the binding is broken:  that is, clicking on the ToggleButton causes the ToggleButton to turn red/gray as expected, but the rectangle's color doesn't follow suit, and after doing that, clicking on the rectangle no longer causes the ToggleButton's state to change, either.
My question is, what is the trick to doing this properly, so that I always have a bidirectional correspondence between the ToggleButton and the property it is tracking?  (Note that the ideal solution would add as little code as possible to main.qml, since I'd like this functionality to be encapsulated inside ToggleButton.qml, to minimize the amount of complexity exposed to the rest of my QML app)

A: The reason this does not work is that you are overwriting the binding with a fixed value. By manually assigning a value in you onClicked you overwrite the binding with a value.
The problem is: QML does not support 2way bindings right now. There are, however, some tricks to create one. See http://imaginativethinking.ca/bi-directional-data-binding-qt-quick/
Note: Instead of using the isActive property like this, why not use the checked state of the button? (From the documentation) This way the binding won't break, even if you click the button:
// Contents of ToggleButton.qml
import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Controls.Styles 1.4

Button {
    //use the "checked" property instead of your own "isActive"

    checkable: true

    style: ButtonStyle {
        background: Rectangle {
            border.width: control.activeFocus ? 2 : 1
            border.color: "black"
            radius: 4
            color:  checked? "red" : "gray";
        }
    }
}

A: It looks like one way to solve this problem is to have the ToggleButton declare its state using an alias-property, rather than a regular property.  That way there is only the one external property (since the ToggleButton's internal property is really just an alias to the external one), and therefore no bidirectional binding is necessary.  Here's an updated version of the QML code that works as expected:
ToggleButton.qml:
// Contents of ToggleButton.qml
import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Controls.Styles 1.4

Button {
    onClicked: {
        isActive = !isActive;
    }

    style: ButtonStyle {
        background: Rectangle {
            border.width: control.activeFocus ? 2 : 1
            border.color: "black"
            radius: 4
            color:  isActive ? "red" : "gray";
        }
    }
}

main.qml:
// Contents of main.qml
import QtQuick 2.6
import QtQuick.Window 2.2

Window {
   visible: true
   width: 360
   height: 360

   Rectangle {
      property bool lighten: false;

      id:blueRect
      x: 32; y:32; width:64; height:64
      color: lighten ? "lightBlue" : "blue";

      MouseArea {
         anchors.fill: parent
         onClicked:    parent.lighten = !parent.lighten;
      }
   }

   Rectangle {
      property bool lighten: false;

      id:greenRect
      x:192; y:32; width:64; height:64
      color: lighten ? "lightGreen" : "green";

      MouseArea {
         anchors.fill: parent
         onClicked:    parent.lighten = !parent.lighten;
      }
   }

   ToggleButton {
      x:32; y:128
      text: "Bright Blue Rect"
      property alias isActive: blueRect.lighten
   }

   ToggleButton {
      x:192; y:128
      text: "Bright Green Rect"
      property alias isActive: greenRect.lighten
   }
}


text:
Q: Choosing Open Sets in Applying the Seifert-Van Kampen Theorem to Topological space I am studying some algebraic topology and have come across a question that asks to find the fundamental group of a space given below.  Naturally, my inclination is to use the Seifert-Van Kampen Theorem, but I am not quite sure what to choose as my sets.  Can anyone point me in the right direction or explain what would be reasonable choices of sets?

A topological space X consists of four triangles with a common side $PQ$. Their sides $AP$, $PB$, $CP$, and $PD$ are glued together (note the directions!) and their sides $CP$, $PQ$ and $QC$ are also glued together. Compute the fundamental group of $X$ in terms of generators.

A: First I wanted to write this as a comment .... but it was too long :)
I would do it as follows: Before starting the gluing construction remove the triangle $PQC$ "from the picture". Of course the side $PQ$ is still in the picture of the remaining three triangles $PQA$, $PQB$ and $PQD$.
The "first" gluing construction (the "simple arrows") is only inside your picture with the three traingles.
The "second" gluing construction (the "double arrows") is only inside your pictucre with the single triangle $PQC$.
The last gluing (in the box it is actually the first sentence) is putting your two pictures together along the edge $PQ$.
I hope you see what I am trying to say ;)


text:
Q: Security Patch SUPEE 8788 problem Even I follow the procedure as mentioned in magento.

Apply SUPEE-8788
To apply patch SUPEE-8788:

*

*Open /app/etc/applied.patches.list in a text editor.

*Verify SUPEE-8788 is not applied. If it is, and it's version 1, see Replace SUPEE-8788 version 1 with version 2.

*Verify whether or not patch SUPEE-1533 is applied. If it is, and your Magento version is earlier than EE 1.14.1.0 or CE 1.9.1.0, revert
SUPEE-1533.

*If your Magento version is earlier than EE 1.14.1.0 or CE 1.9.1.0, and SUPEE-3941 is not applied, apply SUPEE-3941.

*Get version 2 of SUPEE-8788.

*Apply version 2 of SUPEE-8788.

I followed same procedure to my project. I am using magento 1.7.0.2.
When installing Security Patch SUPEE 8788, I am getting the following issues
checking file app/code/core/Mage/Adminhtml/controllers/IndexController.php
Hunk #1 succeeded at 373 (offset -19 lines).

checking file app/code/core/Mage/Wishlist/controllers/IndexController.php
Hunk #1 FAILED at 48 (different line endings).
Hunk #2 FAILED at 152 (different line endings).
Hunk #3 FAILED at 162 (different line endings).
Hunk #4 FAILED at 192 (different line endings).
Hunk #5 FAILED at 212 (different line endings).
Hunk #6 FAILED at 337 (different line endings).
Hunk #7 FAILED at 393 (different line endings).
Hunk #8 FAILED at 412 (different line endings).
Hunk #9 FAILED at 428 (different line endings).
Hunk #10 FAILED at 447 (different line endings).
Hunk #11 FAILED at 536 (different line endings).
Hunk #12 FAILED at 632 (different line endings).
Hunk #13 FAILED at 641 (different line endings).
Hunk #14 FAILED at 663 (different line endings).
Hunk #15 FAILED at 719 (different line endings).
15 out of 15 hunks FAILED

checking file app/design/frontend/base/default/template/catalog/product/view.phtml
Hunk #1 FAILED at 40 (different line endings).
1 out of 1 hunk FAILED

checking file app/design/frontend/base/default/template/persistent/customer/form/login.phtml
Hunk #1 FAILED at 38 (different line endings).
1 out of 1 hunk FAILED

checking file app/design/frontend/base/default/template/wishlist/view.phtml
Hunk #1 FAILED at 52 (different line endings).
1 out of 1 hunk FAILED

checking file js/mage/adminhtml/uploader/instance.js
can't find file to patch at input line 7570
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git lib/Unserialize/Parser.php lib/Unserialize/Parser.php
|index 423902a..2c01684 100644
|--- lib/Unserialize/Parser.php
|+++ lib/Unserialize/Parser.php
--------------------------
File to patch:
Skip this patch? [y]
Skipping patch.
1 out of 1 hunk ignored
can't find file to patch at input line 7582
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git lib/Unserialize/Reader/Arr.php lib/Unserialize/Reader/Arr.php
|index caa979e..cd37804 100644
|--- lib/Unserialize/Reader/Arr.php
|+++ lib/Unserialize/Reader/Arr.php
--------------------------
File to patch:
Skip this patch? [y]
Skipping patch.
1 out of 1 hunk ignored
can't find file to patch at input line 7598
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git lib/Unserialize/Reader/ArrValue.php lib/Unserialize/Reader/ArrValue.php
|index d2a4937..c6c0221 100644
|--- lib/Unserialize/Reader/ArrValue.php
|+++ lib/Unserialize/Reader/ArrValue.php
--------------------------
File to patch:
Skip this patch? [y]
Skipping patch.
1 out of 1 hunk ignored
checking file lib/Unserialize/Reader/Null.php
checking file skin/adminhtml/default/default/boxes.css
checking file skin/adminhtml/default/default/media/flex.swf
checking file skin/adminhtml/default/default/media/uploader.swf
checking file skin/adminhtml/default/default/media/uploaderSingle.swf

A: I'm using Magento 1.7.0.2:
I have resolved HUNK FAILED at 372 by applying SUPEE-3941
sh PATCH_SUPEE-3941_EE_1.14.0.1_v1-2015-02-10-08-32-02.sh
^^^ try applying it.
Battling right now: Hunk #1 FAILED at 40.

My current procedure is:
1) sh PATCH_SUPEE-1533_EE_1.12.x_v1-2015-02-10-08-19-16.sh -R

2) clear

3) sh PATCH_SUPEE-3941_EE_1.14.0.1_v1-2015-02-10-08-32-02.sh

4) clear

IF HUNK 1 at 40

5) Download vanilla 1.7.0.2 app/design/frontend/base/default/template/catalog/product/view.phtml and copy it to your /app/design/frontend/base/default/template/catalog/product/ folder

5) zip up PATCH_SUPEE-8788_CE_1.7.0.2_v2-2016-10-14-09-32-17.sh

6) upload

7) unzip

8) sh PATCH_SUPEE-8788_CE_1.7.0.2_v2-2016-10-14-09-32-17.sh

There is something else I'm missing with HUNK 1.
UPDATE:
I downloaded vanilla 1.7.0.2:
app/design/frontend/base/default/template/catalog/product/view.phtml
and applied it to my base folder.
Looks I messed with base folder when I was developing the theme.
After this the patch was applied successfully.
UPDATE:
I got a response from Magento Community Manager:
------------- RESPONSE -----------------
Community Manager sherrie
Community Manager
sherrie
Posts: 746
Registered: 03-04-2015
Re: SUPEE-8788 (V2) -- SUPEE-3941 is it safe to apply to 1.7.0.2?
Options
54m ago
Hi all, I talked to our product team and SUPEE-3941 should be fine to apply to lower versions. It exists only to address issues with Connect.
Community Manager, Magento
Problem solved? Click Accept as Solution!
Still stuck? Check out our documentation: http://magento.com/help/documentation
------------- RESPONSE -----------------

A: The "different line endings" messages hint at a problem with Windows line breaks versus Unix line breaks. Your existing Magento files are probably saved in Windows format (CRLF) and you should convert them to Unix format (LF). You can use your IDE or text editor if it offers you a "convert line endings" feature, or a command line tools like dos2unix.


text:
Q: Realm query for latest record for each user How would I accomplish a similar query in realm java like that one asked in this question:
how do I query sql for a latest record date for each user
Cause it seems realm lacks a group by method when fetching queries
Here's my RealmObject:
public class Memo extends RealmObject {
    @Ignore
    public static final int SENT = 1;
    @Ignore
    public static final int UNREAD = 2;
    @Ignore
    public static final int READ = 3;
    @Ignore
    public static final int PENDING = 4;
    private static final String TAG = Memo.class.getName();
    @PrimaryKey
    public String id = "";
    @Index
    public String connection = "";
    public String subject = "";
    public String body = "";
    public int status = 0;
    public Date date;
    public Boolean sentByMe = false;
    public String remoteId = "";
    public Boolean isFile = false;
    public String filepath = "";
}

This represents the user:
public String connection

A: RealmResults<Memo> latestMemos = realm.where(Memo.class)
                                      .findAllSorted("date", Sort.DESCENDING)
                                      .distinct("connection");


text:
Q: If $T$ normal invertible operator, then $\sigma(ST)=\sigma(TS).$ Let $\mathcal{B}(F)$ the algebra of all bounded linear operators on a complex Hilbert space $F$.
It is well known that if $T,S\in\mathcal{B}(F)$, then
$$\{0\}\cup\sigma(ST)=\{0\}\cup\sigma(TS).$$

If $T$ is normal and invertible, why
  $$\sigma(ST)=\sigma(TS).$$

I see in a lecture note the following proof:
Since $T$ is normal and invertible, then
$$\sigma(TS) = \sigma(T^{-1} TS T) = \sigma(ST).$$
I don't understand, why
$$\sigma(TS) = \sigma(T^{-1} TS T).$$
holds.

A: Actually, if $T$ is invertible, then we have
$$
\sigma(ST)=\sigma(TS).
$$ Since we already know that
$
\sigma(ST)\setminus\{0\}=\sigma(TS)\setminus\{0\},
$ it suffices to show that $$
0\in \sigma(ST) \ \ \ \Longleftrightarrow \ \ \ 0\in \sigma(TS).
$$ To show this, let us prove that $ ST$ is invertible if and only if $TS$ is invertible. ($\Longrightarrow$) Suppose that $ST$ is invertible and let $R=(ST)^{-1}$ so that $STR=RST = I$. Since $T$ is assumed to be invertible, we also find that $RST=TRS = I$. From this, we know that $STR=TRS$, i.e. $S^{-1} = TR$. This implies $TS$ is invertible with $(TS)^{-1}=S^{-1}T^{-1}$.
($\Longleftarrow$) To prove converse, assume $TS$ is invertible with $R=(TS)^{-1}$. Then it holds $TSR=RTS=I$ and $TSR=SRT=I$. Hence $S^{-1} =RT$ and $(ST)^{-1} = T^{-1}S^{-1}$.
As a result, we find that $\sigma(ST) = \sigma(TS)$ as wanted.

A: In fact, for any  invertible $A \in \mathcal B(H)$ and any $B \in \mathcal B(H)$, we have $\sigma(B) = \sigma(A^{-1}BA)$. This is because of the following : $$A^{-1}(B - \lambda I)A = A^{-1}BA - \lambda I$$
Using the above, it is easy to see that for any $\lambda \in \mathbb C$ ,we have  $(A^{-1}BA - \lambda I)$ is invertible if and only if $(B - \lambda I)$ is. For example, if $C = (B-\lambda I)^{-1}$ then (one side)$C(B-\lambda I) = I$ so we have :
$$
(A^{-1}CA)(A^{-1}BA - \lambda I) = (A^{-1})C(B - \lambda I)A = A^{-1}A = I
$$
Similarly if $(B-\lambda I)C = I$, and similarly if $A^{-1}BA - \lambda I$ is invertible, use $(B-\lambda I) = A(A^{-1}BA - \lambda I)A^{-1}$ to get that $(B-\lambda I)$ is invertible.
Hence, the spectra  of $B$ and $A^{-1}BA$ coincide.
So, in fact one does not need to normality of $A$ over here at all.


text:
Q: log4j2 doesnt write log in files following XML configuration is my log4j config, I see the log messages in console but the log file is empty, whats wrong in it ?
I am using log4j-api-2.1

<Properties>
    <Property name="log-path">logs</Property>
</Properties>

<Appenders>

    <RollingFile name="file-log" fileName="${log-path}/logtile.log/"
        filePattern="${log-path}/logtile-%d{yyyy-MM-dd}.log">

        <PatternLayout>
            <pattern>%d{HH:mm:ss.SSS} [%t] %-5level - %msg%n</pattern>
        </PatternLayout>
        <Policies>
            <TimeBasedTriggeringPolicy interval="1"
                modulate="true" />
            <SizeBasedTriggeringPolicy size="500" />
        </Policies>
        <DefaultRolloverStrategy max="20" />
    </RollingFile>

    <Console name="Console" target="SYSTEM_OUT">
        <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level - %msg%n" />
    </Console>

</Appenders>

<Loggers>
    <Logger name="mylogger" level="info" additivity="false">
        <appender-ref ref="file-log" level="info" />
        <appender-ref ref="Console" level="info" />
    </Logger>

    <Root level="info">
        <appender-ref ref="Console" />
    </Root>
</Loggers>

A: How does your code obtain Logger instances? Assuming your code looks something like this:
Logger log = LogManager.getLogger(com.mycompany.MyClass.class);
log.info("Where is my message?");

Note that the fully qualified name of your logger is "com.mycompany.MyClass".
This logger will send messages to the root logger, and all named loggers whose name matches "com.mycompany.MyClass". The following configuration names would match this fully qualified class:

*

*<Logger name="com.mycompany.MyClass" ...>

*<Logger name="com.mycompany" ...>

*<Logger name="com" ...>
However, the named logger in your configuration only matches "mylogger", so this logger will not receive the "Where is my message?" log event. The root logger will get the event and send it to its appender, the console.


text:
Q: Number of rules in my fuzzy logic I have 6 variables with 4 membership functions such as "tiny,small,large,huge".
I tried to write the rules and came up with 200 rules but the combinations are killing me and it is still incomplete.
Can anyone tell me what is the exact number of rules that would cover every combination possible ?
For example one rule would be -
IF var1 IS huge AND var2 IS large AND var3 IS tiny AND var4 IS small AND var5 IS huge AND var6 IS huge THEN output IS small

A: If there are $6$ variables, and each can be assigned one of $4$ adjectives, then the number of possible rules is $4 \times 4 \times 4 \times 4 \times 4 \times 4 = 4^6 = 4096$. (Assuming each rule is in the form of IF a IS (adj) AND b IS (adj) ... THEN)


text:
Q: Clear Application's badge Number I have made local notification in iphone app. And set icon badge number.
All works good. But if i have two notification in tray and user clicks on clear button than notification deletes from tray.
But the badge number of icon remains same.
I want to set the badge number to zero.
Thanks.

A: For Swift3, you can clear badge number in your application didFinishLaunchingWithOptions with this line :
UIApplication.shared.applicationIconBadgeNumber = 0

You can used this line in anywhere in code if you want too.

A: What you want to achieve is only possible using the Server Notifications. You can not set badge number locally without opening the application. As you won't have any control when user clears the tray. There's no way you can set the badge count at that moment.

A: use this in application didfinshlaunchingwithoptions
        application.applicationIconBadgeNumber = 0;


text:
Q: Parsing a textfile in java I have a txt file that has ~900 questions that look like this:
On to the questions:
-----------------------------------------------------------------------------
  #0001 Which disease devastated livestock across the UK during 2001?
-----------------------------------------------------------------------------
 *Hand-and-foot
 *Foot-in-mouth
 *Hand-to-mouth
 *Foot-and-mouth

Answer: Foot-and-mouth

-----------------------------------------------------------------------------
  #0002 Which of these kills its victims by constriction?
-----------------------------------------------------------------------------
 *Andalucia
 *Anaconda
 *Andypandy
 *Annerobinson

Answer: Anaconda

I have an object that stores the question, and objects that store the answer
IE:
Question.java
public class Question {
    private String questionText;
    private Answer a, b, c, d;

    public Question(String questionText, Answer a, Answer b, Answer c, Answer d) {
        this.questionText = questionText;
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
    }

    public String getQuestionText() {
        return questionText;
    }

    public void setQuestionText(String questionText) {
        this.questionText = questionText;
    }

    public Answer getA() {
        return a;
    }

    public void setA(Answer a) {
        this.a = a;
    }

    public Answer getB() {
        return b;
    }

    public void setB(Answer b) {
        this.b = b;
    }

    public Answer getC() {
        return c;
    }

    public void setC(Answer c) {
        this.c = c;
    }

    public Answer getD() {
        return d;
    }

    public void setD(Answer d) {
        this.d = d;
    }

    public String toString() {
        return  questionText +
                "\nA) " + a +
                "\nB) " + b +
                "\nC) " + c +
                "\nD) " + d;
    }
}

Answers.Java
public class Answer {
    private String answerText;
    private boolean correct;

    //constructor to set correct answer
    public Answer(String answerText, boolean correct) {
        this.answerText = answerText;
        this.correct = correct;
    }

    public Answer(String answerText) {
        this.answerText = answerText;
        this.correct = false;
    }

    public String getAnswerText() {
        return answerText;
    }

    public void setAnswerText(String answerText) {
        this.answerText = answerText;
    }

    public boolean isCorrect() {
        return correct;
    }

    public void setCorrect(boolean correct) {
        this.correct = correct;
    }

    public String toString() {
        return answerText;
    }
}

I would like to make an array list that stores all the question objects parsed from the text file. I'm new to Java and programmed primarily in python before, and am a bit confused on how to do text file parsing in java as it seems a lot more complex. I know how to parse like line by line or a list of words for example. I don't know how to do it with the extra text in the file.
Any help would be appreciated.
Sample of two line question:
-----------------------------------------------------------------------------
  #0016 Which word follows 'North' and 'South' to give the names of two
        continents?
-----------------------------------------------------------------------------
 *Africa
 *America
 *Asia
 *Australia

Answer: America

A: Implement a simple FSM and parse it line by line. Read until you find a line that starts with #dddd, then read until you find a line that starts with -. Those lines make up a question. Read until you find a line that starts with a *, then read until you hit a blank line. Those are your choices. Next read until you find a line that starts with Answer, that's your answer. Repeat.

A: Hi there here is something that might do the trick ;)
    String file = "text.txt";
    BufferedReader br = null;
    int nbAnswer = 4;
    try {
        br = new BufferedReader(new FileReader(file));
        String line;
        while((line = br.readLine()) != null) {
            if( line.contains("-----------"))
            {
                line = br.readLine();
                String question = line.split("#[0-9]{4} ")[1];
                while(!(line = br.readLine()).contains("-----------"))
                    question += " " + line.trim();

                String[] answers = new String[4];

                for( int i = 0; i < nbAnswer; i++)
                    answers[i] = br.readLine().substring(2);

                br.readLine();
                String sol = br.readLine().split("Answer: ")[1];
                System.out.println(question + "\nanswer: " + answers[0] + " " + answers[1] + " " + answers[2] + " " + answers[3] + "\nsol " + sol);
            }
        }
    }
    catch(IOException ex) {
        System.err.println(ex);
    }

line.split("#[0-9]{4} ")[1]; is a regex that will allow you to split the string after a # followed by 4 numbers and a space.
At least it's a good beginning ;)
PS: There are many wrong thing about doing a beautiful .txt containing the questions etc.

*

*It's harder to parse

*It's bigger in size

You could for example change *Foot-and-mouth to (*)Foot-and-mouth to indicate that this is the answer instead of having 2 more lines for it ;)

A: If each your question takes exactly 10 lines in a file, it's much simply to parse it line-by-line, getting mean of each record from its position, not content:
public class Parse {
    public static final int OPTION_PREFIX_LENGTH = "*".length();
    public static final int ANSWER_PREFIX_LENGTH = "Answer: ".length();
    public static final String QUESTION_SEPARATOR = "-----------------------------------------------------------------------------";

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("/Users/Marboni/tmp/test.txt"));

        try {
            while (br.ready()) {
                br.readLine();                                     // Skip separator (----).

                StringBuilder questionBuilder = new StringBuilder();
                String questionLine;
                while (!QUESTION_SEPARATOR.equals(questionLine = br.readLine())) {  // Reading lines and add them to question until separator.
                    questionBuilder.append(questionLine.trim()).append(' ');
                }
                String questionText = questionBuilder.toString().trim();
                String a = parseQuestion(br.readLine());           // Option a).
                String b = parseQuestion(br.readLine());           // Option b).
                String c = parseQuestion(br.readLine());           // Option c).
                String d = parseQuestion(br.readLine());           // Option d).
                br.readLine();                                     // Skip blank line.
                String answer = parseAnswer(br.readLine());        // Answer.

                if (br.ready()) {
                    br.readLine();                         // Skip blank line between questions, if exists.
                }

                Question question = new Question(questionText,
                        new Question.Answer(a, answer.equals(a)),
                        new Question.Answer(b, answer.equals(b)),
                        new Question.Answer(c, answer.equals(c)),
                        new Question.Answer(d, answer.equals(d))
                        );

                // Do something with it.
            }
        } finally {
            br.close();
        }
    }

    private static String parseQuestion(String record) {
        return record.trim().substring(OPTION_PREFIX_LENGTH);
    }

    private static String parseAnswer(String record) {
        return record.trim().substring(ANSWER_PREFIX_LENGTH);
    }
}


text:
Q: Where does Woocommerce store the product information or how can I see what was last changed? I am developing a site and the client ended up editing some of the products. Where can I see what they changed? My thought is to look at the database or files. I just don't know where the plugin stores the informaion for each product (I'm still don't completely know how wordpress works). I've tried looking at products page and sort by date, but my team has found some were changed but the date doesn't show the accurate date.

A: Like most WP plugins, WooCommerce treats the products as a specific type of post, so you'll find them in the posts table as either product or product_variation types. WP also stores additional information regarding posts in the postmeta table.
However, without anything to compare it to, you will probably struggle to work out exactly what has changed; the posts have a timestamp that will tell you when it was last modified, but you don't really have much way of telling what the user changed. While WP does support post revisions they only apply to posts and pages by default.


text:
Q: R: Erasing Lines on ggplot2 - drawing half rectangles I am working with the R programming language.
I generated some random data and plotted the following graph:
library(ggplot2)

var_1 = rnorm(1000,20,20)
var_2 = rnorm(1000,20,20)

my_data = data.frame(var_1, var_2)

ggplot(data=my_data, aes(x=var_1, y=var_2)) + geom_point()

I now want to make the following pattern on this graph:

I tried to do this with the following code, but this is the closest I could get:
a1 = ggplot(data=my_data, aes(x=var_1, y=var_2)) +
  geom_point()+
  geom_hline(yintercept=0, color = "red") +
  geom_vline(xintercept=0, color = "red")

a2 = a1 + geom_point() +
  geom_hline(yintercept=50, color = "red") +
  geom_vline(xintercept=50, color = "red")

My Question: Could someone please show me a "direct" way to make this pattern on this graph? Is there some way to "erase" these extra lines?
Suppose I had a data frame ("my_points") that looked like this:
my_points = data.frame(var_1_point_1 = 0, var_1_point_2 = 50, var_2_point_1 = 0, var_2_point_2 = 50)

Could the graph be made using "my_data", and the lines be made by "referencing" the points in "my_points"? For example, something like this:
a1 = ggplot(data=my_data, aes(x=var_1, y=var_2)) +
      geom_point()+
      geom_hline(yintercept my_points[1,2], color = "red") +
      geom_vline(xintercept=my_points[1,1], color = "red")

Thanks!

A: You'll need to use geom_segment instead of geom_hline or geom_vline since you'll need to specify xend and yend for each segment.
library(tidyverse)

var_1 = rnorm(1000,20,20)
var_2 = rnorm(1000,20,20)

my_data = data.frame(var_1, var_2)

ggplot(data=my_data, aes(x=var_1, y=var_2)) +
  geom_point() +
  geom_segment(aes(x = -50, xend = 0, y = 0, yend = 0), color = "red") +
  geom_segment(aes(x = 0, xend = 0, y = 0, yend = -50), color = "red") +
  geom_segment(aes(x = -50, xend = 50, y = 50, yend = 50), color = "red") +
  geom_segment(aes(x = 50, xend = 50, y = 50, yend = -50), color = "red")

Created on 2022-03-21 by the reprex package (v2.0.1)
Update
Since OP wish to use an extra dataframe, here is the updated code:
library(ggplot2)

var_1 = rnorm(1000,20,20)
var_2 = rnorm(1000,20,20)

my_data = data.frame(var_1, var_2)

mypoint <- data.frame(var_1_point_1 = c(-50, 0),
                      var_1_point_2 = c(0, -50),
                      var_2_point_1 = c(-50, 50),
                      var_2_point_2 = c(50, -50))

ggplot(data=my_data, aes(x=var_1, y=var_2)) +
  geom_point() +
  geom_step(data = mypoint, aes(var_1_point_1, var_1_point_2), color = "red") +
  geom_step(data = mypoint, aes(var_2_point_1, var_2_point_2), color = "red")

Created on 2022-03-22 by the reprex package (v2.0.1)

A: People tend to forget about geom_linerange - in vanilla ggplot sadly only available for vertical lines. But there is also ggstance::geom_linerangeh. Those would allow you to pass a data frame with your x/y coordinates and you will "only" need two geom layers for vertical and for horizontal lines (if your lines always start at the edge of the plot). You could apply the same idea with geom_segment of course, then without need of another package.
library(ggplot2)
library(ggstance)

## changed data frame my points:
x <- y <- c(0, 50)
my_points <- data.frame(x, y)

ggplot() +
  geom_point(aes(x = var_1, y = var_2), data = my_data) +
  geom_linerange(aes(x = x, ymin = -Inf, ymax = y), data = my_points, color = "red", size = 2) +
  geom_linerangeh(aes(xmin = -Inf, xmax = x, y = y), data = my_points, color = "red", size = 2)

A: Another option would be to make your own stat and use this with geom_segment:
library(ggplot2)

var_1 <- rnorm(1000, 20, 20)
var_2 <- rnorm(1000, 20, 20)

my_data <- data.frame(var_1, var_2)

## changed data frame my points:
x <- y <- c(0, 50)
my_points <- data.frame(x, y)

StatEdge <- ggproto("StatEdge", Stat, compute_group = function(data, scales) {
  x <- c(rep(-Inf, nrow(data)), data$x)
  y <- c(data$y, rep(-Inf, nrow(data)))
  xend <- rep(data$x, nrow(data))
  yend <- rep(data$y, nrow(data))
  data.frame(x, xend, y, yend)
})

## now you can use the new stat for your geom
ggplot() +
  geom_point(aes(x = var_1, y = var_2), data = my_data) +
  geom_segment(data = my_points, aes(x, y), stat = "edge", size = 2, color = "red")

Created on 2022-03-21 by the reprex package (v2.0.1)


text:
Q: ElasticSearch 1.1.2 not starting properly I'm in the process of upgrading ElasticSearch for my company. To start this, I need the old version (1.1.2) running on my machine, which is running OSX Sierra (10.12.6). I have elasticsearch@1.1.2 downloaded from my company's repository, but it's not starting properly. I'm getting this:
$ brew services list
Name                Status  User        Plist
elasticsearch@1.1.2 started pjscopeland /Users/pjscopeland/Library/LaunchAgents/homebrew.mxcl.elasticsearch@1.1.2.plist

... but Homebrew's status "started" is yellow, where the rest of them are green, and if I run it manually, I get this:
$ elasticsearch
Java HotSpot(TM) 64-Bit Server VM warning: Option UseParNewGC was deprecated in version 9.0 and will likely be removed in a future release.
Java HotSpot(TM) 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will likely be removed in a future release.
Exception in thread "main" java.lang.ExceptionInInitializerError
    at org.elasticsearch.bootstrap.Bootstrap.main(Bootstrap.java:190)
    at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:32)
Caused by: java.lang.UnsupportedOperationException: Boot class path mechanism is not supported
    at java.management/sun.management.RuntimeImpl.getBootClassPath(RuntimeImpl.java:99)
    at org.elasticsearch.monitor.jvm.JvmInfo.<clinit>(JvmInfo.java:77)
    ... 2 more

NB. Please bear in mind, my Java skills are at a level where I might just be able to read it, but probably not work out anything I might need to change.

A: Looks like you have Java 9 installed:

Java HotSpot(TM) 64-Bit Server VM warning: Option UseParNewGC was deprecated in version 9.0 and will likely be removed in a future release.

although ElasticSearch does not support it.
According to this matrix, Java 9 is not supported by any ES version from 2.3 to 5.6; ES 1.x is not listed most likely because it is no longer supported.
There is also an issue related to logstash (a component of ElasticSearch) with similar stack trace.
The exception that you posted

Caused by: java.lang.UnsupportedOperationException: Boot class path mechanism is not supported

suggests that there is something wrong with your JVM. The exception occurs in RuntimeImpl class.
I suggest that you check out which version of Java is installed on your production machines and install it on yours. Tips on how to manage different versions of Java on your Mac you may look up in this SO question.


text:
Q: unable to call REST API from browser My REST API with basic authentication works fine using Rest client (Google Chrome extn).
The same also working fine with below Curl command:
curl --header "Accept:application/json" -i --user user1:user1Pass http://localhost:8080/authenticate
But when testing the same in browser I'm getting 404 not found error. The browser URL: http://user1.user1Pass@localhost:8080/authenticate
Can anyone please help me on this?

A: You're using a period instead of a colon.

A: The format of the url should be http://user1: user1Pass@localhost:8080/authenticate
The main point is you need to separate username and password by colon.


text:
Q: Converstion of seconds in minutes I have to change seconds into minutes, hours.
I am already using this code:
   int minutes = floor(seconds/60);
   int sec = trunc(seconds - minutes * 60);
   int hours1 = floor(seconds / (60 * 60));

It works fine, but when "60 minutes" completed it gives 01:61:01 I want timer in this format 01:01:01.
i.e. my minutes does not convert after 60 minutes.
Please suggest me or help me. I am searching lots of code but still not find exact solution.

A: you can calculate minutes from seconds with bellow formula...
int minutes = (secondsLeft % 3600) / 60;

see the whole code for hours,minutes and seconds bellow...
int hours, minutes, seconds;
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
NSLog(@"\nTime is => %02d:%02d:%02d",hours,minutes,seconds);

Output is : Time is 00:00:06

A: I have converted secs to minutes.Hope this can help you.
    float playListMinsLocal=floorf(songObj.songTime.floatValue);
    float playListSecsLocal=songObj.songTime.floatValue-playListMinsLocal+.001;
    float playListTotalSecs=(playListMinsLocal*60)+(playListSecsLocal*100);
    playListMins+=(int)playListTotalSecs/60;
    playListSecs+=(int)playListTotalSecs%60;

A: Give a try to this:
int seconds = mySeconds % 60;
int minutes = (mySeconds / 60) % 60;
int hours = mySeconds / 3600;


text:
Q: Is it possible to finish an Activity through data binding in the XML? I have an ImageView (A back button) inside an activity and i want to finish the Activity by using data binding in the XML itself as such:
<ImageView
        android:id="@id/ImageView_fromAddItemActivity_BackIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:onClick = "@{ finish()}"
        app:srcCompat="@drawable/ic_back_dark"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

But it doesn't work. Anyone has an idea whether this is possible ?

A: For onClick() to work you need to use the following notation: android:onClick=@{() -> function()}.
What you could do is pass the Activity in the databinding as a variable, i.e.
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="activity"
            type="android.app.activity" />
    </data>
    <ConstraintLayout... /> <!-- UI layout's root element -->
</layout>

then do activity.finish(). I wouldn't do it that way though since you are tightly coupling the context with the data binding. You could instead go through a viewmodel which you can bind, then do the finish() through it.


text:
Q: Starting windows bundle from network-drive use not included JRE? I bundle a java program by using install4j and put the jre into the bundle as it is possible with install4j.
At our company we have the situation that every user must use a network share e.g. drive X: on windows where they start the java programm by using the EXE produced by install4j.
When we check with the process explorer on windows if the JRE is used or not we see that the local JRE of the machine is used and not the one from the drive X:
any experience?

A:

Thx!

I check this with your cmd argument and get errors.

[9:280] unpack done
[9:285] could not delete packed file (error 5)
[9:286] checking x:\appl\myapps\app\jre\lib\deploy.jar
[9:287] x:\appl\myapps\app\jre\bin\unpack200.exe
[9:288] -r "x:\appl\myapps\app\jre\lib\deploy.jar.pack" "x:\appl\myapps\app\jre\lib\deploy.jar"
[9:300] waiting for unpack200 to finish
[9:383] unpack done
[9:387] could not delete packed file (error 5)
....
**x:\appl\myapps\app has write protection.**
This happens 18 times for other jar files in the JRE too.
....
[11:25] Unpacking JRE done
[11:27] checkJavaExe (g:\appl\myapps\app\jre\bin\java.exe, [out], 2, 2, 1)
[11:28] file exists
[11:29] tempPath is C:\Users\myuser\AppData\Local\Temp\
[11:30] tempFile is C:\Users\myuser\AppData\Local\Temp\e4j4DF8.tmp
[11:672] Exit Code 1
[11:674] couldn't get version
[11:675] checkJavaExe returning 0
[11:677] Testing location  (type Y)
[11:678] checkJavaExe (C:\Program Files (x86)\Java\jre\bin\java.exe, [out], 2, 2, 0)
[11:679] file exists
...starting from now I see that the local JRE is used...

Why happen this? Write protection? Wrong install4j config?


text:
Q: Identity of return value of getOwnPropertyDescriptor handler for Javascript Proxy I have some very simple code:
var out = null

const handler = {
  getOwnPropertyDescriptor(target, prop) {
    out = Reflect.getOwnPropertyDescriptor(target, prop)
    return out
  }
}

const obj = new Proxy({foo: "bar"}, handler)
const desc = Object.getOwnPropertyDescriptor(obj, 'foo')
console.log(desc)
console.log(out)
console.log(desc == out)

When run under nodejs, v 18.03, this will result in false, which makes no sense to me: Usually, an object will retain identity on either side of a return. So two questions:

*

*Does anyone know why? (Is this a bug in node? A weird implementation detail? Working as intended?)

*Is there anywhere else where I have to watch out for an object not being the same after being returned?


text:
Q: Is it possible to use Google Apps Marketplace with Oauth2 and OpenID I have website which uses Oauth2 for communication with Google APIs. And it works fine.
Now i need to make it "Google Marketplace compliant" to be listed there. Googles docs says about Oauth or Federated Login, but it doesn't precised if Oauth2 works too.
Does anyone has experience in such integration? May i keep Oauth2 and add OpenID to work with Marketplace, or i have to rework it for Federated Login?
Thanks!

A: The answer is NO as of July 9, 2012. Google is in the process of adding OAuth2 for Apps Marketplace https://developers.google.com/identity-toolkit/v1/marketplace#oauth2

A: When you list your app in the marketplace, you will get a consumer key and secret which you can use for 2-Legged OAUTH for every google apps domain that installed your app. So the answer is YES.


text:
Q: Put http:// on hrefs missing a protocol in Angular I have been trying to figure out a solution to replace all hrefs that do not have http:// or https:// in front of a link with an appended version of the link with http:// on it.
Currently I have something like this:
static correctUrls(input: string): string {

  // get all hrefs from the input
  let urls = input.match(']* href="([^"]*)"/g');

  // if no urls return original input
  if (!urls) {
    return input;
  }

  // remove duplicate urls
  urls = urls.filter((item, pos) => {
    return urls.indexOf(item) === pos;
  });

  // if no urls in input
  if (!urls) {
    return input;
  }

  for (const url of urls) {

    // if url does not have https
    // tslint:disable-next-line: max-line-length
    if (!url.match('^ (http: \/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$')) {
      input = input.replace(url, 'https://' + url);
    }
  }
  return input;
}

Any help would be greatly appreciated. Please include an explanation of how your answer's regex works. I have found lots of similar questions to this one, but with all of the solutions I have found, when I try to do input.match it returns the matched href twice (if there is one), but if there are two hrefs then it returns rubbish.
Here is the input:

 We love
  Google
  and
  Facebook.

And the expected output:

 We love
  Google
  and
  Facebook.

A: The correct way of doing this in Angular is to use the DOMParser. Then you can select all elements with the anchor  tag. Then you can apply the regex to see if it has either http or https in front of it.
export class UrlCorrector {
  static correctUrls(input: string): string {

    const parser = new DOMParser();
    const document = parser.parseFromString(input, 'text/html');

    // get all anchor tags from the input
    const anchorTags = document.getElementsByTagName('a');

    // if no anchor tags return original input
    if (anchorTags.length === 0) {
      return input;
    }

    const urls: string[] = [];

    // iterate through all the anchor tags to find their urls
    // tslint:disable-next-line: prefer-for-of
    for (let i = 0; i < anchorTags.length; i++) {

      const href = anchorTags[i].href;
      let url = href;

      // if url has hostname in it, it's a href without http protocol
      if (href.includes(location.hostname)) {

        // get just the ending part e.g., `localhost:4200/submissions/facebook.com` will return `facebook.com`
        url = href.substr(href.lastIndexOf('/') + 1);
      }
      urls.push(url);
    }

    for (const url of urls) {

      // if url does not have a protocol append https:// to front
      // tslint:disable-next-line: max-line-length
      if (!url.match('^ (http: \/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$')) {
        input = input.replace(url, 'https://' + url);
      }
    }
    return input;
  }
}

A: Regex is the wrong too for the job. You're already in javascript - it's got an abundance of tools for DOM management, many of which do exactly what you want. Please, try to use these instead, they're much more applicable to your task!
If you really want to do it with regex, href="(?!https?:\/\/)()[^"]+" should do the job.

*

*href=" Look for href=" string to start the match

*(?!https?:\/\/) Assert there's no http:// or https:// at the start of the URL

*() Empty capture at the start of the URL you want to edit - insert your string here

*[^"]+" Match content up to the next quote mark; this is the rest of the URL

Demo
A sample Javascript program using this method:
var x = '
 We love Google and Facebook. Facebook. Facebook.
'
var urls = x.match('href="(?!https?:\/\/)()([^"]+)"')

console.log("https://" + urls[2])

'https://Facebook.com'


text:
Q: $http.get to synchronous AngularJS Can you help me please im new in angularJS,
i have a problem with Asynchrounous $http.get , i explain : i got data that i show in ngTable but in my html i got a empty table until i click to filter or to sort then i see my data.
i think its because i have a promise in my http.get. here my code to understand more ( sorry for my english)
'use strict';
(function() {
    angular
        .module('timeShareApp')
        .controller('homeController', homeController);

    function homeController($http, $scope, $filter, NgTableParams) {

    $scope.users =[];

$http.get('/api/users/').success(function(response) {
            $scope.users = response;

        });

       $scope.usersTable = new NgTableParams({
                page: 1,
                count: 10
            }, {
                total: $scope.users.length,
                getData: function ($defer, params) {
                      $scope.data = params.sorting() ? $filter('orderBy')($scope.users, params.orderBy()) : $scope.users;
                       $scope.data = params.filter() ? $filter('filter')($scope.data, params.filter()) : $scope.data;
                       $scope.data = $scope.data.slice((params.page() - 1) * params.count(), params.page() * params.count());
                       $defer.resolve($scope.data);
                }
            });

 }

   homeController.$inject = ["$http", "$scope", "$filter", "NgTableParams"];

})();

for info : code works perfectly except that promise that i want to convert to synchonous if you can help me please.
Thank you in advance

A: I think there is no problema on adding $scope.usersTable to me defined inside your promise resolve method. Have you tried that?

A: In most cases, there is no reason to keep any data outside the ng-table's scope. My advice is to not modify or reference any scope variables because this can cause some pretty hard to track timing issues.
Have a look at the really good ng-table docs, which mostly have a working sample for your use case. See the docs here
Depending on the place where your filtering / sorting happens, you need to adapt this, but the following should basically work:
$scope.loadData = function() { return $http.get('/api/users/') };

$scope.usersTable = new NgTableParams(
  {
    page: 1,
    count: 10
  }, {
    total: 0, // just the inital value - will be updated later on
    getData: function ($defer, params) {
      $scope.loadData().success(function (result) {
        // assuming your result has a total and a data field...

        // update the table params with the total amount of results
        // could also be result.length...
        params.total(result.total);

        // sort and filter your data using the params object here
        var data = result.data;

        // give back the control to the table
        $defer.resolve(data);
      });
    }
  }
);

Please be aware to also set the params.total whenever your server responds. Otherwise the pagination will not be visible.


text:
Q: Why SAM rule doesn't work on parameterless method // ok
val sam0: MySamWithEmptyParameter = () => 100

// doesn't work
//  val sam1: MySamWithParameterless = () => 100

trait MySamWithEmptyParameter {
  def receive(): Int
}

trait MySamWithParameterless {
  def receive: Int
}

Why sam1 fails to override the receive method? The scalac compile both of traits to same code.
abstract trait TestSAM$MySamWithEmptyParameter extends Object {
  def receive(): Int
};

abstract trait TestSAM$MySamWithParameterless extends Object {
  def receive(): Int
};

A: SI-10555 talks exactly about this. This was a simple design decision to only support an explicit empty parameter list, even though the two compile down to an empty parameter list anyway.
The relevant part of the Specification says (emphasis mine):

*

*the method m must have a single argument list;

This is indeed a bit awkward as eta expansion does work for methods with an empty parameter list.
Edit
Contacted the guys at Lightbend. Here is a response by Adrian Moors, Scala team lead:

The original reason was to keep the spec simple, but perhaps we should revisit. I agree it's surprising that it works for def a(): Int, but not in your example.
Internally, methods that don't define an argument list at all, and those that do (even if empty) are treated differently.
  This has led to confusion/bugs before — to name just one: https://github.com/scala/scala-dev/issues/284.
In 2.13, we're reworking eta-expansion (it will apply more aggressively, but ()-insertion will happen first). We've been back and forth on this, but the current thinking is:

*

*0-ary methods are treated specially: if the expected type is sam-equivalent to Function0, we eta-expand; otherwise, () is inserted (in dotty, you are required to write the () explicitly, unless the method is java-defined) — I'm still not sure about whether we should ever eta-expand here

*for all other arities, a method reference is eta-expanded regardless of the expected type (if there's no type mismatch, this could hide errors when you refactor a method to take arguments, but forget to apply them everywhere. However, since functions are first-class values, it should be easy to construct them by simplify referring to a method value).

  The upshot is that we can deprecate method value syntax (m _), since it's subsumed by simply writing m. (Note that this is distinct from placeholder syntax, as in m(, _).)
  (See also the thread around this comment: https://github.com/lampepfl/dotty/issues/2570#issuecomment-306202339)


text:
Q: BrowserSync does not automatically refresh the page with gulp-jade I recently created a workspace with gulp. Everything was working normally (auto-reload, sass compilation, minification, and more)
You can see the code on github
Today I wanted to add jade to the project. The compilation works well but browserSync does not refresh the page automatically
Here is my code
'use strict'

var gulp = require('gulp')
var jade = require('gulp-jade')
var sass = require('gulp-sass')
var cssmin = require('gulp-cssmin')
var rename = require('gulp-rename')
var prefix = require('gulp-autoprefixer')
var uglify = require('gulp-uglify')
var concat = require('gulp-concat')
var imagemin = require('gulp-imagemin')
var browserSync = require('browser-sync').create()

// Compile Jade
gulp.task('jade', function () {
  gulp.src('src/*.jade')
    .pipe(jade({
      pretty: true
    }))
    .pipe(gulp.dest('./dist'))
})

// Configure CSS tasks.
gulp.task('sass', function () {
  gulp.src('src/scss/**/*.scss')
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(prefix('last 2 versions'))
    .pipe(cssmin())
    .pipe(concat('styles.css'))
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('dist/css'))
    .pipe(browserSync.stream())
})

// Configure JS.
gulp.task('js', function () {
  gulp.src('src/js/**/*.js')
    .pipe(uglify())
    .pipe(concat('app.js'))
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('dist/js'))
    .pipe(browserSync.stream())
})

// Configure image stuff.
gulp.task('images', function () {
  gulp.src('src/img/**/*.+(png|jpg|gif|svg)')
    .pipe(imagemin())
    .pipe(gulp.dest('dist/img'))
    .pipe(browserSync.stream())
})

gulp.task('default', ['jade', 'sass', 'js', 'images'], function () {
  browserSync.init({
    server: './dist'
  })

  gulp.watch('src/*.jade', ['jade'])
  gulp.watch('src/scss/**/*.scss', ['sass'])
  gulp.watch('src/js/**/*.js', ['js'])
  gulp.watch('./dist/*.html').on('change', browserSync.reload)
})

A: I tested the code and found the error.
Browsersync gets injected into <head> element, therefore you need to have that element on your page (still its good to have html/head/body).
Implementing my suggestion from comment (about missing browserSync.stream()) and fixing your jade file to:
html
  head
  body
    h1 hello Jade

    ul
      li comment ça va
      li et toi ?

    .box salut comment tu vas ?

Solves the problem. BrowserSync now correctly gets inserted into the page :)


text:
Q: Stock with sending data with jQuery to PHP file I'm trying to send data via POST to PHP file..
$.get() - works fine, hovewer I couldn't tell the same about $.post() or $.ajax() with method post..
Here my code I wrote:
$('[name="update"]').click(function(){
    tr = $(this).parents('tr');
    u = [];
    u["username"] = tr.find('[name="u[username]"]').val();
    u["display_name"] = tr.find('[name="u[display_name]"]').val();
    u["type"] = tr.find('[name="u[type]"]').val();

    $.ajax({
        type: "POST",
        url: "../ajax-queries/update-user.php",
        data: {update:u},
        cache: false,
        success:  function(data){
           alert(data);
        }
     });

});

And PHP file looks like:
<?php
     print_r($_POST);
?>

Response I get:
Array(
)

Using latest jQuery lib... no ideas why not working.. any solutions you can offer?
Is that could be posible because of port:2014?
in case i tried and in :80 (same results)..

A: Because you aren't setting anything.
Try changing u to {}, like: u = {};

A: Array with key index is not an array, it's an object, try alert(typeof u).
sending an array with key index will fail in IE8.


text:
Q: I need to make an external link display as a popup window on a wordpress website I am trying to make a medium article popup similar to this link (from their site also). I want to stay on the same site I'm on but when clicking the link rather than going to the url the article is from, i want that content to show as a popup window on my url

A: you can use php onClick window.open("page path");
it will open the popup link in new window and your current page will stay as it is.

A: Use any popup appropriate to your site, use onClick event to call the modal and within the popup body use an iframe for the external link, this way the external link will load within your popup.


text:
Q: How to round up timedelta by seconds? I am trying to get time measurement of my script in format HH:MM:SS. datetime.timedelta does not have a strftime function. I want to get rid of the microsecond indication. duration is a timedelta object.
import datetime

start = datetime.datetime.now()

for i in range(100000000):
    pass

end = datetime.datetime.now()

duration = end - start

print(duration)

Output:
0:00:03.474106

But I need:
0:00:04

A: we take the duration (timedelta object) and minus its own microseconds from
itself, then store that in the variable duration.
import datetime

start = datetime.datetime.now()

for i in range(100000000):
    pass

end = datetime.datetime.now()

# duration = 0:00:03:962227
duration = end - start

# duration = 0:00:03:962227 - 0:00:00.962227
duration = duration - datetime.timedelta(microseconds=duration.microseconds)
# duration is now = 0:00:03

print(duration)

more info on timdelta and its arguments can be found at https://docs.python.org/3/library/datetime.html#datetime.timedelta

A: If you just want the get rid of the milliseconds portion of the duration, you can use floor division ('//') by a million and then multiply it back by a million:
print(duration // 1000000 * 1000000)

You can also create a new timedelta object from duration without the milliseconds attribute specified.
print(datetime.timedelta(duration.days, duration.seconds))

But if you want it to always round up instead, as suggested by the expected output of 0:00:04, you can get the number of seconds from the timedelta object by calling the total_seconds methods, use math.ceil to round up, and then construct a new timedelta object with it:
import math
print(datetime.timedelta(seconds=math.ceil(duration.total_seconds())))


text:
Q: what is the most effective way to find the modal values of a list? to be able to work with bimodal lists etc.
my attempts so far:
testlist = [1,2,3,3,2,1,4,2,2,3,4,3,3,4,5,3,2,4,55,6,7,4,3,45,543,4,53,4,53,234]

.
from collections import Counter

def modal_1(xs):
    cntr = Counter(xs).most_common()
    val,count = cntr[0]
    return (v for v,c in cntr if c is count)

print(list(modal_1(testlist)))
>>> [3, 4]

-- or perhaps something like --
def modal_2(xs):
       cntr = Counter(xs).most_common()
       val,count = cntr[0]
       return takewhile(lambda x: x[1] is count, cntr)

print(list(modal_2(testlist)))
>>> [(3, 7), (4, 7)]

Please do not answer - use numpy etc.
note :
Counter(xs).most_common(1)
returns the first 'modal' of n modal values. If there are two. It will only return the first. Which is a shame... because that would make this a whole lot easier.

ok, so I was actually quite surprised that one of my original options is actually a good way to do this. for anyone now wanting to find n modal numbers in a list, I would suggest the following options. Both of these functions work well on lists with over 1000 values
All of these return lists of (number,count), where count will be identical for all tuples. I think it is better to have this and then parse it to your hearts desire.
using takewhile:
from collections import Counter
from itertools import takewhile

def modal_3(xs):
    counter = Counter(xs).most_common()
    mx = counter[0][1]
    return takewhile(lambda x: x[1] == mx, counter)

print(list(modal_3(testlist)))
>>> [(3, 7), (4, 7)]

using groupby:
from collections import Counter
from itertools import groupby
from operator import itemgetter

def modal_4(xs):
    container = Counter(xs)
    return next(groupby(container.most_common(), key=itemgetter(1)))[1]

print(list(modal_4(testlist)))
>>> [(3, 7), (4, 7)]

and the final, pythonic, and fastest way:
def modal_5(xs):

    def _mode(xs):
        for x in xs:
            if x[1] != xs[0][1]:
                break
            yield x

    counter = collections.Counter(xs).most_common()

    return [ x for x in _mode(counter) ]

thank you to everyone for the help and information.

A: I think your second example is best, with some minor modification:
from itertools import takewhile
from collections import Counter

def modal(xs):
       counter = Counter(xs).most_common()
       _, count = counter[0]
       return takewhile(lambda x: x[1] == count, counter)

The change here is to use == rather than is - is checks for identity, which while true for some values as Python does some magic with ints in the background to cache them, won't be true all of the time, and shouldn't be relied upon in this case.
>>> a = 1
>>> a is 1
True
>>> a = 300
>>> a is 300
False

A: >>> testlist = [1,2,3,3,2,1,4,2,2,3,4,3,3,4,5,3,2,4,55,6,7,4,3,45,543,4,53,4,53,234]
>>> dic={x:testlist.count(x) for x in set(testlist)}

>>> [x for x in dic if dic[x]==max(dic.values())]

[3, 4]

A: What? takewhile but no groupby?
>>> from collections import Counter
>>> testlist = [1,2,3,3,2,1,4,2,2,3,4,3,3,4,5,3,2,4,55,6,7,4,3,45,543,4,53,4,53,234]
>>> cntr = Counter(testlist)
>>> from itertools import groupby
>>> list(x[0] for x in next(groupby(cntr.most_common(), key=lambda x:x[1]))[1])
[3, 4]


text:
Q: EclipseLink permanent connection I have a project that uses EclipseLink 2.1.3 under Tomcat 7.
What's bugging me is that the connection to the server doesn't persist through all of the app's life.
For a ServerSession to start I have to access the application manually.
Is there a way to automatically start a ServerSession when the application deploys and keep it running at all times ? So that I can access the application after a long idle time without having to wait ?
Thank you!
EDIT:
I have the following lines in persistence.xml
  <property name="eclipselink.jdbc.read-connections.min" value="5"/>
  <property name="eclipselink.jdbc.read-connections.max" value="10"/>
  <property name="eclipselink.jdbc.write-connections.min" value="6"/>
  <property name="eclipselink.jdbc.write-connections.max" value="12"/>

A: Server applications usually use a JDBC connection pool to get connections and reuse them. Depending on the pool you use, you may configure it to keep a given number of connections open.


text:
Q: Creating python plots on background With a single script, I have to produce dozens of figures with matplotlib using spyder. I would like spyder to create figures while I can work with other browsers or windows without interruption.  Here were the methods I tried.  Let us say that there are 40 plots to be created.  Each plot contains multiple subplots
(1) From How do I get interactive plots again in Spyder/IPython/matplotlib?.  I used %matplotlib inline.  The plots will be created inline at the end of the program.  However, the usage of computation memory keeps accumulating.  At some point, python will show an error message due to lack of memory and then crash.  The message is like: "More than 20 figures have been opened. Figures created through the pyplot interface (matplotlib.pyplot.figure) are retained until explicitly closed and may consume too much memory."
(2) Then, I use plt.close() to close each figure after saving it.  The memory issue is resolved.  However, even if the figure is not shown, every time python close a figure and open another one, all other browsers and windows will be affected.  If I am typing on a window, after the interruption, I have to click the window again in order to continue typing.
Previously, when I used MATLAB, I could simply specify h=figure and then set(h,'visible','off') to avoid this issue.  I wonder if I can do similar things with python.
Thank you for the help!


text:
Q: Gathering information from active browser tabs Let's assume that we have 2 tabs open (my website and the second).
I would like to know if there is any chance for my website to gather information like f.ex: link of the "second" website, while Im there (while it's active)?


text:
Q: Connecting MS SQL server 2012 I'm using MS SQL server 2012 on my homeserver.
I can connect to the server using localhost but not with my ISP ip adress if I'm at home. How can I local connect to SQL using my ISP ip adres when I'm at home.
Can someone please help me?

A: If you're trying to connect via a public address (the IP of your ISP), you need to ensure that you have an inbound connection through your router opened on port 1433 which is what SQL is answering on.
Q: Are you sure that you want to expose SQL directly to a public connection like that? You open yourself up to hacking and exploits.


text:
Q: Python Simple Grade Book Printing Error I need help with a python file to make a simple Grade Book print properly. I've gotten it to print but its not doing exactly what I need it to. The print results look like this,
{'Fred': '99', 'Fred2': '99', ...}
Ideally I'd like it to print just the name and grade next to each other, on a new line for each name / grade. Something like this:
"Name: Fred | Grade: 99"
I have to use a list / dictionary and need the while loop
Here is the best solution I have tried thus far:
student_grades = {}

entries = input('Would you like to enter a students name and grade? (Y/N): ')
entries = entries.lower()

while entries == "y":
    name = input('Enter a students name: ')
    grade = input('Enter the student\'s grade: ')
    #Put in dictionary
    student_grades[name] = grade
    #Print
    print(student_grades)
    entries = input('Would you like to enter a students name and grade? (Y/N)')
    entries = entries.lower()

else:
    names = list(student_grades.keys())
    grades = list(student_grades.values())
    print()
    print('     Grade Book     ')
    print('--------------------')
    print(student_grades)

A: for student,grade in student_grades.iteritems():
    print "Name:%s, Grade:%s"%(student,grade)

A: This is the Final Working code for anyone who may need it in the future! Thanks to all who helped!
student_grades = {}
entries = input('Would you like to enter a students name and grade? (Y/N): ')
entries = entries.lower()

while entries == "y":
    name = input('Enter a students name: ')
    grade = input('Enter the student\'s grade: ')
    #Put in dictionary
    student_grades[name] = grade
    #Print
    print(student_grades)
    entries = input('Would you like to enter a students name and grade? (Y/N): ')
    entries = entries.lower()

else:
    names = list(student_grades.keys())
    grades = list(student_grades.values())
    print()
    print('     Grade Book     ')
    print('--------------------')
    print()
    for name in student_grades:
        print("Name: "+name+"   "+"Grade: "+student_grades[name])


text:
Q: Usage of contemporary, casual, and elegant when describing an object in one sentence I came across this sentence and I got a mixed feeling about the usage of the below terms in one sentence describing a characteristic of an object.
Here is the full sentence:
"To achieve that the language must be contemporary, casual, and elegant this isn't the case today."
What bothered me here was a description of the language. I feel like contemporary and casual do not go well with elegant.
Or am I wrong?

A: There's no reason at all why language cannot be all three. I'd be more concerned about the absence of a full stop after elegant and of an initial capital letter for this.

A: Side note: That sentence is a run-on. There should be a period or a semi-colon between "elegant" and "this", or a disjunction such as "but", or the sentence should be re-worded.
But to your question: Basically, I agree. In context, the writer appears to be using the adjectives as if he were describing clothing or home decor. In that context, "casual" means "informal". "Elegant" means "tasteful, refined, dignified" etc. "Contemporary" means "current, modern".
I tend to think of "elegant" as almost the opposite of "casual"; "elegant" usually implies formal, fancy, etc. but without being ostentatious. I suppose by the dictionary definition, this isn't necessarily so, but that's the usual connotation. It would be very odd to say, "Alice looked elegant in her blue jeans, army boots, and sweat shirt." If someone said that they would almost certainly mean that her general bearing or appearance were such that even in the grungiest clothes she somehow still managed to look elegant, and not that blue jeans etc. constituted elegant attire.
To a lesser extent, "elegant" is generally understood to imply a certain level of traditionalism, and thus would tend to be an opposite of "contemporary". I don't think that connotation is as strong though. If someone said that furniture or clothes were "contemporary and elegant", that would likely be seen as unusual, but not as a paradox. Still, I'd expect they'd really say "contemporary BUT elegant".


text:
Q: mysql get name of id and parent id from another tabel? i have 2 table.
table1: [id, parent_id, name_id]
table2: [name_id, name]
i would like to show for every id the name connected to the name_id of table2 and the name of the parent (parent_id rapresent the id of the same table1)
Example:
table1:
id     parent_id   name_id
1          0         100
2          1         101

table1:
name_id    name
 100       food
 101       fruit

output:
id     parent_id   name_id   name_id   parent_name_id
1          0         100      food           0
2          1         101      fruit        food

For now, i'm here, with the name of the name_id
SELECT table1.id, table1.parent_id , table1.name_id , table2.name_it
FROM table1 join table2 on table1.name_id = table2.name_id
output:
id     parent_id   name_id   name_id
1          0         100      food
2          1         101      fruit

How can i get the parent_name_id? thanks

A: You can do multiple joins:
select t1.*, t2.name, t20.name parent_name
from table1 t1
inner join table2 t2 on t2.name_id = t1.name_id
left  join table1 t10 on t10.id = t1.parent_id
left  join table2 t20 on t20.name_id = t10.name_id

A: By using aliases, you can reference the same table twice, joining each id field.
SELECT a.id,
    a.name_id,
    b.name as name,
    a.parent_id,
    c.name as parent,
FROM table1 as a
join table2 as b on a.name_id = b.name_id
join table2 as c on a.parent_id = c.name_id

A: You can use multiple joins and give them alias names to work with. Something like that (untested)
SELECT table1.id, table1.parent_id , table1.name_id , table2.name_it, t2_parent.name as parent_name
FROM table1
join table2 on table1.name_id = table2.name_id
join table1 t1_parent on t1_parent.id = table1.parent_id
join table2 t2_parent on t1_parent.name_id = table2.name_id


text:
Q: Where are the Firefox close and minimise buttons when window is maximised? When I maximise a window in Ubuntu 14.0.4, I get the close and minimise buttons at the top left. Here's TeXStudio when it's maximised:

So why does this not happen with Firefox (58.0.2)?

I don't think this question is the same as this one, but to be honest I don't understand what that other one is asking.


text:
Q: How to retrive Custom Post Type Meta Fields in Custom WP_Query Can some one let me know How I can render the Custom Post Type Meta Fields (Meta-boxes).
I have a Custom Post Type Called "News" and I successfully added a metabox to my Custom Post Type called "News Info" which is suppose to store : A TextField = News Resource A Select option = News Type A check box

I can retrieve the Custom post Type "News"content using a custom Loop as:
<?php
 $args = array( 'post_type' => 'news');
 $loop = new WP_Query( $args );
 while ( $loop->have_posts() ) : $loop->the_post();
    the_title();
    echo '
';
    the_content();
    echo '
';
 endwhile;
?>

But I have no idea how to get the associated meta fields to "news" posts? trust me I Google this a lot but couldn't find any solution all of them just tried to render the Metabox on the admin page but no sample for presenting on the page!
Can you please let me know how I can get access and render the data on the page using the wp-query loop?
Thanks

A: Your solution may be found in http://codex.wordpress.org/Function_Reference/get_post_meta . To get the post's ID you may use get_the_ID().

A: To build upon SidGBF's answer, you can use get_post_meta(get_the_ID(),'YOUR_FIELD_NAME',true);
That is a little verbose if you're going to use it again and again, so it might be helpful to add this to your functions.php file:
function get_custom_field($field_name){
  return get_post_meta(get_the_ID(),$field_name,true);
}

Then you can just use get_custom_field('YOUR_FIELD_NAME').
If you'd like to print the value of the field, use echo get_custom_field('YOUR_FIELD_NAME')