text:
Q: Converting flatfile to JSON in Java I need to convert a flat file to a JSON file in Java.
My flat file looks like this:
customerInfo.firstName=abc
customerInfo.lastName=aaa
customerInfo.nickNames.0.name=bbb
customerInfo.nickNames.0.meaning=ccc

Here is the piece of code I am using:
JSONParser parser = new JSONParser();
Object obj = null;
try {
    //obj = parser.parse(new FileReader("src/main/resources/flatfileex.txt"));
    JSONObject jsonObject = (JSONObject) parser.parse(new InputStreamReader(new FileInputStream("src/main/resources/flatfileex.txt")));;
    String flattenedJson = JsonFlattener.flatten(jsonObject.toJSONString());
    System.out.println(flattenedJson);
} catch (FileNotFoundException | IOException | ParseException e) {
    e.printStackTrace();
}

I am using jsonflattener dependency for the above code:
<dependency>
    <groupId>com.github.wnameless</groupId>
    <artifactId>json-flattener</artifactId>
    <version>0.1.0</version>
</dependency>

Getting error while parsing the file Unexcexpected character [c] at position 0. How to resolve this?

A: Your input file looks like a Java properties file, so you could try this:
Properties prop = new Properties();
try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("content.txt")){
    prop.load(inputStream);
    String contentAsJson = new ObjectMapper().writeValueAsString(prop);
    System.out.print(contentAsJson);
} catch (IOException exception) {
    System.out.println("Something went wrong!");
}

If your file contains
customerInfo.firstName=abc
customerInfo.lastName=aaa
customerInfo.nickNames.0.name=bbb
customerInfo.nickNames.0.meaning=ccc

It will print
{"customerInfo.lastName":"aaa","customerInfo.firstName":"abc","customerInfo.nickNames.0.name":"bbb","customerInfo.nickNames.0.meaning":"ccc"}

I guess that from here you can use json-flattener.


text:
Q: Stone-Cech compactification of locales I'm reading 'Stone-Cech compactification of locales I' by Banaschewski and Mulvey. I have a question about lemma 6: I don't understand why it suffices to show that the ideals $h(x)$ and $g(x)$ are regular for every $x$. If $L$ were compact then $\bigvee h(x) = \bigvee g(x)$ would imply that h(x) = g(x). But $L$ is not compact.

A: I think you've found a gap in the paper - which surprises me, I could be missing something. To get the uniqueness you can observe that the image is dense, see IV Theorem 2.2 of Johnstone's "Stone Spaces" for an alternative proof.

redpajama_set_name: RedPajamaStackExchange


text:
Q: BST - Deleting a Node so I'm trying to solve a problem from log2base2.com involving deleting a node from BST. It works except when trying to delete a node with two children. I know I could simply replace the numbers and then delete the duplicate at the end, but what if my struct has more data than just key? So what am I doing wrong please?
#include<stdio.h>
#include<stdlib.h>

struct node
{
    int key;
    struct node *left;
    struct node *right;
};

int getRightMin(struct node *root)
{
    //Write your code here
    struct node *temp = root;

    while(temp->left!=NULL)
    {
        temp=temp->left;
    }

    return temp;

}

struct node *removeNode(struct node *root, int key)
{
    //Write your code here
    if(root == NULL){return NULL;}
    if(key<root->key){root->left = removeNode(root->left, key);}
    else if(key>root->key){root->right = removeNode(root->right,key);}
    else
    {
        if(root->left==NULL && root->right==NULL)
        {
            free(root);
            return NULL;
        }
        else if(root->left)
        {
            struct node *temp = root->left;
            free(root);
            return temp;
        }
        else if(root->right)
        {
            struct node *temp = root->right;
            free(root);
            return temp;
        }
        else
        {
            struct node *temp = getRightMin(root->right);
            temp->left = root->left;
            temp->right = root->right;
            root = temp;
            root->right = removeNode(root->right, temp->key);
        }
    }

    return root;
}

//Don't change the below code
struct node *getNewNode(int val)
{
    struct node *newNode = malloc(sizeof(struct node));
    newNode->key   = val;
    newNode->left  = NULL;
    newNode->right = NULL;

    return newNode;
}

struct node *insert(struct node *root, int val)
{
    if(root == NULL)
        return getNewNode(val);
    if(root->key < val)
        root->right = insert(root->right,val);
    else if(root->key > val)
        root->left = insert(root->left,val);

    return root;
}

void inorder(struct node *root)
{
    if(root == NULL)
        return;
    inorder(root->left);
    printf("%d ",root->key);
    inorder(root->right);
}

int main()
{
    struct node *root = NULL;
    root = insert(root,100);
    root = insert(root,50);
    root = insert(root,200);
    root = insert(root,150);
    root = insert(root,300);

    int key;
    scanf("%d",&key);

    root = removeNode(root,key);
    inorder(root);

    return 0;
}

TEST CASE 1:
INPUT: 200
EXPECTED OUTPUT: 50 100 150 300
ACTUAL OUTPUT: 50 100 150
TEST CASE 2:
INPUT: 100
EXPECTED OUTPUT: 50 150 200 300
ACTUAL OUTPUT: 50

A: You have to reorder conditional in removeNode() to:
        if(root->left==NULL && root->right==NULL)
        {
            free(root);
            return NULL;
        }
        else if (root->left && root->right)
        {
            struct node *temp = getRightMin(root->right);
            temp->left = root->left;
            temp->right = root->right;
            root = temp;
            root->right = removeNode(root->right, temp->key);
        }
        else if(root->left)
        {
            struct node *temp = root->left;
            free(root);
            return temp;
        }
        else // root->right != NULL
        {
            struct node *temp = root->right;
            free(root);
            return temp;
        }

It looks that (root->left && root->right) case was caught by (root->left) and
reference to root->right was lost.


text:
Q: how to make blur in flutter I want to make When I click the sign-up button on the login page, blur is applied to the entire page and I want to show a pop-up window.
When clicking, I changed the filter value by specifying the sigmaX, Y values of the background filter as variables.
However, this uses the stack to place the backgrounddropfilter in front of the entire screen scaffold widget.When this happens, the button cannot be clicked because it goes behind the background filter.
how can I solve it?
Scaffold widgets with blur applied and scaffold widgets without blur
Isn't there a way to make each one and then print it out when the button is pressed?
 Widget build(BuildContext context) {
    return Stack(children: [
      Scaffold(
        appBar: AppBar(
...

),
body:ButtonTheme(
                                    minWidth: 100.0,
                                    height: 50.0,
                                    child: ElevatedButton(
)
)

makeblur(a: )
)
);
}

class makeblur extends StatelessWidget {
  makeblur({required this.a});

  double a;

  @override
  Widget build(BuildContext context) {
    return Positioned.fill(
        child: BackdropFilter(
      filter: ImageFilter.blur(sigmaX: a, sigmaY: a),
      child: Container(
        color: Colors.transparent,
      ),
    ));
  }
}

A: The child component of backdrop filter is the part that will not be blurred. So you may have to place the button as the child of the backdrop filter
BackdropFilter(
      filter: ImageFilter.blur(sigmaX: a, sigmaY: a),
      child: Button(),//<-- button that you wish not to blur here.
    )

A: You can use this widget to have the effect, wrap your widget GlassMorphism
class GlassMorphism extends StatelessWidget {
  GlassMorphism({
    Key? key,
    required this.blur,
    required this.opacity,
    required this.child,
    BorderRadius? borderRadius,
  })  : _borderRadius = borderRadius ?? BorderRadius.circular(12),
        super(key: key);

  final double blur;
  final double opacity;
  final Widget child;

  final BorderRadius _borderRadius;

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: _borderRadius,
      child: BackdropFilter(
        filter: ImageFilter.blur(
          sigmaX: blur,
          sigmaY: blur,
        ),
        child: Container(
          decoration: BoxDecoration(
            color: ColorPallet.glassMorphism.withOpacity(opacity),
            borderRadius: _borderRadius,
            border: Border.all(
              color: ColorPallet.glassMorphism.withOpacity(.2),
            ),
          ),
          child: child,
        ),
      ),
    );
  }
}


text:
Q: SSH forced command parameters I'm attempting to write a script that verifies user permissions after a successful ssh login.
I'm doing this through an SSH forced command. I'd like to pass the script parameters (such as the user it is authenticating) but I'm not sure how I would do that.
Any help?

A: I figured this out on my own. You can pass parameters to the forced command script by setting environment variables and reading them in in the forced command script.

A: You can set a ForcedCommand in the sshd configuration file, or better inside an authorized_keys file of the respective user.
ssh executes sets the environment variable SSH_ORIGINAL_COMMAND to the complete commandline sent to the server and then executes ForcedCommand.
Writing scripts that make use of this environment variable for providing arguments has security implications, since an attacker might add e.g. ; rm -rf / at the end of the commandline.  Then first the ForcedCommand would be run, and then rm -rf /.
This article describes a script, which can be used to generically lock down allowed commandlines.  It also contains links to relevant information.
The mechanism is as follows:

*

*Put the script (only) as ForcedCommand

*Add allowed 'real' commands as parameters

*Add a rules file (.onlyrules) in the home directory of the respective user account, which restricts allowable parameters to the real command.

The only script reads the SSH_ORIGINAL_COMMAND checks if the command is a) allowed (in the list of parameters) b) is on the users PATH and then checks if the parameters pass the rules (in our case simple sed(1) scripts.
An example set up:
ForcedCommand /usr/local/bin/only ls

or authorized_keys:
command="/usr/local/bin/only ls" ssh-rsa AAAA...

.onlyrules
\:^ls /tmp$:{p;q}

This would only allow to send the command ls /tmp to the remote host.

A: SSH does not allow passing password through parameters (or even through pipe) it is made by design, and even described in man page. Only way of automated login through ssh is by file authentication.
I think you can try to compare password provided by user, with values in /etc/shadow. That should do the trick :)

A: Let's say your somehost.com server is configured to run the forced command your-script.sh for someuser.
If you do:
ssh someuser@somehost arg1 arg2 'arg3 with spaces' arg4

Then ssh will automatically generate the env variable SSH_ORIGINAL_COMMAND with the following value:
arg1 arg2 arg3 with spaces arg4

And then will call your-script.sh with that env variable. Note that you lose information about arguments with spaces, unfortunately.
Therefore, you could do something as follows in your-script.sh:
#!/usr/bin/env bash
set -Eeuo pipefail

echo 'Hello from your forced SSH command!'
echo "After joining with spaces all arguments you passed, I got '${SSH_ORIGINAL_COMMAND-}'."

WARNING: Be extremely careful on how you use the contents of the SSH_ORIGINAL_COMMAND variable, because it is a great attack surface for cyberattacks.
In particular, if you're using a shell script like in my example, NEVER use it in a way that would allow globbing and word splitting, and never perform eval on it or run it as a command, because that would be super unsafe.
Writing a safe shell script that processes arguments like this is hard. Make sure you know what you're doing. Also please use a tool like shellcheck to help you catch mistakes.
Of course, recall that the Forced SSH Command does not have to be a shell script. It can be a Python script for example, which is probably easier to do right (although of course you still have to pay attention).


text:
Q: How to write a complex logical condition correctly? I have 2 tables in Access: FACULTY and SGROUP.
FACULTY:

SGROUP:

I need to output SGROUP.GrpNo and FACULTY.FacNo under one condition ...
IIF (FACULTY.Fund> 20000 AND SGROUP.Rating> 10) OR (faculty group from building 6 AND SGROUP.Rating <70) OR (faculty group from building 5 AND SGROUP.Rating> 40)

I understand what they want from me, but I absolutely do not understand how a complex condition can be built on sql to solve this problem.
P.S: The rest of the database tables.
DEPARTMENT:

TEACHER:

SUBJECT:

ROOM:

LECTURE:

A: here you go my friend:
select
    *
from
    lecture l
inner join
    teacher t on t.tchno = l.tchno
inner join
    department d on d.depno = t.depno
inner join
    faculty f on f.facno = d.facno
inner join
    sgroup sg on sg.groupno = l.sbjno
inner join
    room r on r.roomno = l.roomno
where
    (f.Fund> 20000 AND sg.Rating> 10) OR
    (r.Building = 6 AND sg.Rating <70) OR
    (r.Building 5 AND sg.Rating> 40)


text:
Q: Not able to scrape content from myntra Was trying to scrape content from myntra with below given code, the same code is working fine for snapdeal, anyone can help me out where am i stucking ??
$url = 'www.myntra.com/tshirts/roadster/roadster-men-black-striped-polo-collar-t-shirt/1353945/buy?src=search&uq=false&q=men-tshirts&p=1';
         $request_headers = '[
                "Accept: text/xml,application/xml,application/xhtml+xml, text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
                "Accept-Encoding: gzip, deflate",
                "Connection: keep-alive",
                "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7",
                "Cache-Control: max-age=0",
                "Content-Type: text/html; charset=UTF-8",
            ]';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($curl,CURLOPT_USERAGENT,'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.9) Gecko/20100508 SeaMonkey/2.0.4');
        //curl_setopt($ch, CURLOPT_MAXREDIRS, 50);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FAILONERROR, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);

        $cl  = curl_exec($ch);
        //print_r($cl);
        if($cl === false){

             echo 'Curl error: '.curl_errno($ch). '-' . curl_error($ch);

        }else{
             $dom = new DOMDocument();

             $dom->loadHTML($cl);

             $xpath = new DOMXpath($dom);

             $pName = $xpath->query('//h1[@class="pdp-title"]/text()'); //pdp-title  pdp-e-i-head

             $pro   = $pName->item(0)->nodeValue;

             echo $pro;
             //var_dump($pName);
        }

while doing curl it is giving the error "Curl error: 47-Maximum (20) redirects followed",
as i am new to this basically not getting what to do next...
while removing if else condition it showing domnodeobject: value ommited,
Not gettting any clue , what's the actual cause of this problem.
i run curl on command prompt it was displaying the page correctly, but by hitting through browser it continuously giving error: "Curl error: 47-Maximum (20) redirects followed"..
Thanks in advance, waiting for suggestions....

A: There are 2 options:

*

*Render the JS content on the webpage. You can use PhantomJS to render. Check this tutorial http://shout.setfive.com/2015/03/30/7817/

*Parse directly the json file:
http://www.myntra.com/web/style/similar/Roadster-Men%20Black%20Striped%20Polo%20Collar%20T-shirt/1353945

A: Scraping Myntra can be easily done using nodejs. You can use cheerio to load and inject jquery and access all the elements you want and scrape them, you can also use fast-csv or some other npm library to export the data in your desired format. This approach is faster than phantom.js
Here is a great article on scotch.io to get you started
https://scotch.io/tutorials/scraping-the-web-with-node-js


text:
Q: How @Digits constraint (Bean Validation-JSR 303) supports String type? While studying BeanValidation from documented here, I came to know that @Digits supports String datatype. here the snap-shot from documentation.
package javax.validation.constraints;

/**
 * The annotated element must be a number within accepted range
 * Supported types are:
 *

 *
BigDecimal

 *
BigInteger

 *
String

 *
byte, short, int, long,
 * and their respective wrapper types

 *

 *

 * null elements are considered valid
 *
 * @author Emmanuel Bernard
 */

How can Digits behave for String type? On what base @Digit will validate to String type? Will it behave like digit regex validation (@Pattern)?

A: JSR-303 defines an interface so you should check what the implementation does. If you use Hibernate Validator, String's validator that supports @Digit constraint is defined in the DigitsValidatorForCharSequence class (note that the String class implements the CharSequence interface).
That implementations parses a given String and if it is a valid BigDecimal the validator returns true.
Here is the isValid method defined in the aforementioned class (and the private method that is used to parse the value):
public boolean isValid(CharSequence charSequence, ConstraintValidatorContext constraintValidatorContext) {
    //null values are valid
    if ( charSequence == null ) {
        return true;
    }

    BigDecimal bigNum = getBigDecimalValue( charSequence );
    if ( bigNum == null ) {
        return false;
    }

    int integerPartLength = bigNum.precision() - bigNum.scale();
    int fractionPartLength = bigNum.scale() < 0 ? 0 : bigNum.scale();

    return ( maxIntegerLength >= integerPartLength && maxFractionLength >= fractionPartLength );
}

private BigDecimal getBigDecimalValue(CharSequence charSequence) {
    BigDecimal bd;
    try {
        bd = new BigDecimal( charSequence.toString() );
    }
    catch ( NumberFormatException nfe ) {
        return null;
    }
    return bd;
}

Link to the source code: https://github.com/hibernate/hibernate-validator/blob/e20c12aa0aba6e2bf21a2da7cefd74d06c2e2710/engine/src/main/java/org/hibernate/validator/internal/constraintvalidators/bv/DigitsValidatorForCharSequence.java


text:
Q: Angular - Service Component Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
No index signature with a parameter of type 'string' was found on type '{}'.ts(7053)
Getting the above error message. Need help in this.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { GlobalDataSummary } from '../models/gloabl-data';

@Injectable({
  providedIn: 'root'
})
export class DataServiceService {

  private globalDataUrl = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/01-01-2021.csv'
  constructor(private http : HttpClient) { }
  getGlobalData(){
    return this.http.get(this.globalDataUrl, {responseType :'text'}).pipe(
      map(result=>{
        let data: GlobalDataSummary[] = [];
        let raw = {}
        let rows = result.split('\n');
        rows.splice(0 , 1);
        //console.log(rows);
        rows.forEach(row=>{
          let cols = row.split(/,(?=\S)/)

          let cs = {
            country : cols[3],
            confirmed : +cols[7],
            deaths : +cols[8],
            recovered : +cols[9],
            active : +cols[10],
          };
          let temp = raw[cs.country];
          if(temp)
          {
            temp.active = cs.active + temp.active
            temp.confirmed = cs.confirmed + temp.confirmed
            temp.deaths = cs.deaths + temp.deaths
            temp.recovered = cs.recovered + temp.recovered
            raw[cs.country] = temp;
          }else{
            raw[cs.country] = cs;
          }

        })

        return Object.values(raw);

      })
    )
  }
}

A: You are getting this error because you are assigning the values to raw dynamically whose type is not explicitly marked. This can be fixed by explicitly marking raw with any type. Change
let raw = {}

to
 let raw:any = {}

This would be a quick fix. A better fix to use proper typings. Create types for the raw object like this
interface Raw {
   [key: string]: CS;
}

Here we are creating a type for objects which will have string keys and vales will be of CS type. CS is what you are trying to assign to raw. You can name it as per your choice. Below is the type for CS.
interface CS {
    country: string;
    confirmed : number,
    deaths : number,
    recovered : number,
    active : number,
}

Assign the type like this:
let raw: Raw = {};

// This won't fail. This is just an example that is should work.
raw['India'] = {
     country: 'India',
    confirmed : 22,
    deaths : 0,
    recovered : 22,
    active : 0,
}


text:
Q: How to pass public key from parameter file in cloudformation template? I have defined the following a Cloudformation template, where I want to pass Public Key from a parameter file. The 'MyPublicKey' variable is of string type. I refer to this variable by using
EncodedKey !Ref MyPublicKey

under PublicKeyConfig as seen below.
AWSTemplateFormatVersion: "2010-09-09"

  Parameters:
    MyPublicKey:
      Type: String
      Description: 'Public key for some purpose'
      NoEcho: true

  Resources:
    CloudfrontPublicKey:
      Type: AWS::CloudFront::PublicKey
      Properties:
        PublicKeyConfig:
          CallerReference: 'some-caller-reference'
          Comment: 'Public key for signed url'
          Name: 'cloudfront-public-key'
          EncodedKey: !Ref MyPublicKey

    ...

The parameter.json file looks something like this. The public key was multi line in the original .pem file but I have added new lines character '\n' in the string whereever there is a line break.
[
  {
    "ParameterKey": "MyPublicKey",
    "ParameterValue": "-----BEGIN PUBLIC KEY-----\naaaa\nbbbb\n-----END PUBLIC KEY-----"
  },
]

When trying to update the stack, I get the following error:
Invalid request provided: AWS::CloudFront::PublicKey

It does not seem to be able to import the public key.

A: Based on comments an extra \n char was needed when passing the value and Ref should be replaced with Sub function for placing the string.
  Resources:
    CloudfrontPublicKey:
      Type: AWS::CloudFront::PublicKey
      Properties:
        PublicKeyConfig:
          CallerReference: 'some-caller-reference'
          Comment: 'Public key for signed url'
          Name: 'cloudfront-public-key'
          EncodedKey: !Sub "${MyPublicKey}"

Below is the inline key example:
Generate keys:
openssl genrsa -out private_key.pem 2048
openssl rsa -pubout -in private_key.pem -out public_key.pem

Cloudformationt template:
AWSTemplateFormatVersion: "2010-09-09"
Resources:
  CloudfrontPublicKey:
    Type: AWS::CloudFront::PublicKey
    Properties:
      PublicKeyConfig:
        CallerReference: 'some-caller-reference'
        Comment: 'Public key for signed url'
        Name: 'cloudfront-public-key'
        EncodedKey: |
          -----BEGIN PUBLIC KEY-----
          MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsG0grTw5uHbO4CkFVyqN
          lKLGd9ZJrj6l68QU20SzrF7jgQtzE7VKfHxWfzE5FDKF1qKVLT0mURjlRfRPUXaT
          sZYsnKv+cTYkraewdLqbVuN7JII2D/cEXTYRn7849kGKycl3YMXeJeBStbLSPWfh
          MNJZnlFnEX6DkYtwk0Ae0bQ3WT1Be/Xhe4pqSQsnU+InSDkIfA+4UTRLa0kTCgON
          8BjcNloJE3NbLYshQPconb8pA+3jjkMF0QAH6rtc452G7CuS3KBfVQwWUeWE77kK
          wQQir6YFvKP3pG8Ls55FxXBTCCNJl5LZcHt1D0cZmuoSLJj2mVzJgKGyLTdoIwAW
          6QIDAQAB
          -----END PUBLIC KEY-----

Listing keys:
aws cloudfront list-public-keys|jq .PublicKeyList.Items[1]

Output:
{
  "Id": "08ZCTRKADSADASDAS",
  "Name": "cloudfront-public-key",
  "CreatedTime": "2021-02-27T10:25:43.076Z",
  "EncodedKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsG0grTw5uHbO4CkFVyqN\nlKLGd9ZJrj6l68QU20SzrF7jgQtzE7VKfHxWfzE5FDKF1qKVLT0mURjlRfRPUXaT\nsZYsnKv+cTYkraewdLqbVuN7JII2D/cEXTYRn7849kGKycl3YMXeJeBStbLSPWfh\nMNJZnlFnEX6DkYtwk0Ae0bQ3WT1Be/Xhe4pqSQsnU+InSDkIfA+4UTRLa0kTCgON\n8BjcNloJE3NbLYscZmuoSLJj2mVzJgKGyLTdoIwAW\n6QIDAQAB\n-----END PUBLIC KEY-----\n",
  "Comment": "Public key for signed url"
}

Public key creation in AWS cloudformation giving following error: Invalid request provided: AWS::CloudFront::PublicKey already answered.


text:
Q: Responsive div with width and height set I am using foundation 4 as a framework for my personal site (not 100% portfolio site, more as advertising myself as a freelancer) and I have a contact box with a background image set and these CSS styles applied:
#contact-box {width: 1052px;
      height: 400px;
      background-image: url('../images/contact-bg.png');
      margin-top: 150px;}

I want to make it so it scales down when you shrink the browser, but instead it just gives me a horizontal scrollbar and doesn't scale at all and I know it's because of the 1052px width set... So how would I code this out so it's responsive? If I use max width and max height it breaks the div and removes its bg image. The contact box has a contact form in it (which is responsive) along with a phone number, email, and 3 social icons.

A: I wanted to just leave a comment but I don't seem to have the option..
I don't know if this is the answer you want but I usually make background images scale to the window size with code like this:
width: 100%;
height: 400px;
background-image: url('../images/contact-bg.png');
background-size: 100%;
margin-top: 150px;

You can use that css code for div tags and the page body, although in my experimentation the width and height values are not necessary for the page body. Doing it this way will maintain the aspect ratio of your background image and should allow it to scale with the window.
Since the above example maintains the aspect ratio, the image will scale vertically to the point where it exceeds the size of the container it is in and will appear to be cut off on the bottom. Alternatively you can use:
width: 100%;
height: 400px;
background-image: url('../images/contact-bg.png');
background-size: 100% 400px;
margin-top: 150px;

The second argument for the background-size element will make sure the image never scales vertically at all. This method however will result in your background image being horizontally stretched whenever the window's width exceeds the aspect preserved width of the image you are using.
Hope this helps! :)

A: You can try this and modify it your according source taken from here http://css-tricks.com/perfect-full-page-background-image/
img.bg {
  /* Set rules to fill background */
  min-height: 100%;
  min-width: 1024px;

  /* Set up proportionate scaling */
  width: 100%;
  height: auto;

  /* Set up positioning */
  position: fixed;
  top: 0;
  left: 0;
}

@media screen and (max-width: 1024px) { /* Specific to this particular image */
  img.bg {
    left: 50%;
    margin-left: -512px;   /* 50% */
  }
}

and this is another method for doing this
#contact-box{
  background: url(images/bg.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

A: Set the width of #contact-box to width: 100%.


text:
Q: I Have G3 Users Complaining About My Navigation Drawer Being Unusable "unusable" as in being extremely laggy and almost can't get to all of the items because of how slow it is. I am really at a loss to what I am doing wrong with my implementation of the navigation drawer. I am using AppCompat v7's material theme, and using the viewholder pattern. The drawer consists of only images which are 600x232 and around 35kb each in size (stored locally in the app).
Here's a sample from my MainActivity
 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    . . .

    mColorIcons = getResources().getStringArray(R.array.color_icons);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    adapter = new MyPerformanceArrayAdapter(this, mColorIcons);
    // set a custom shadow that overlays the main content when the drawer opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

    mDrawerList.setAdapter(adapter);
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
    mDrawerList.setCacheColorHint(Color.TRANSPARENT); // not sure if this is required for you.
    mDrawerList.setFastScrollEnabled(true);
    mDrawerList.setScrollingCacheEnabled(false);
    . . .

And here is what MyPerformanceArrayAdaptor looks like
public class MyPerformanceArrayAdapter extends ArrayAdapter<String>{

 private final Activity context;
 private final String[] names;

  static class ViewHolder {
    public ImageView image;
  }

  public MyPerformanceArrayAdapter(Activity context, String[] names) {
    super(context, R.layout.drawer_list_item, names);
    this.context = context;
    this.names = names;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
        View rowView = convertView;
        // reuse views
        if (rowView == null) {
          LayoutInflater inflater = context.getLayoutInflater();
          rowView = inflater.inflate(R.layout.drawer_list_item, null);
          // configure view holder
          ViewHolder viewHolder = new ViewHolder();
          viewHolder.image = (ImageView) rowView
              .findViewById(R.id.image);
          rowView.setTag(viewHolder);
        }

        // fill data
        ViewHolder holder = (ViewHolder) rowView.getTag();
        String s = names[position];
        holder.image.setImageResource(context.getResources().getIdentifier(s, "drawable", context.getPackageName()));
        return rowView;
  }
}

I would appreciate any input on how to improve this. I am having no issues when testing on a 2013 Moto X (4.4.4), Nexus 5 (L), and Nexus 7 (L)(2013). I cannot think of what the issue could be that specifically pertains to the LG G3. There have been a few reports of it not performing well on the HTC M8 as well.
EDIT: Here is my drawer_list_item xml code
  <LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent">

  <ImageView
    android:id="@+id/image"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:adjustViewBounds="true"/>

</LinearLayout>

A: I can only suggest disabling things in the above code one by one and sending test builds to one of the more helpful users to try.

A: I was able to solve the issue by using Glide to load the images on the background thread.


text:
Q: Regular Expression statement to replace text inside two literals i have n line of code starting with
(21714,
(21715,

I want to replace the numeric values with NULL string to get
(NULL,
(NULL,

Please suggest the reqular expression I should use in Edit plus Find Replace functionality to achieve this.

A: It may looks like this (this example is written in js, but I don't think it is a problem):
'(21714, (21715, ...'.replace(/^(\([0-9]*\,\s\([0-9]*)/, "(NULL, (NULL");

A: I have tested these steps via EditPlus v3.41:
step1. Menu > Search > Replace
step2. click "More" button
step3. input pattern \([0-9]+, to "Find what"
step4. Replace with (NULL,

A: ^([0-9]*
I used this, it searched for occurrences:
(21714
(21715


text: Q: Power LED with integrated charging for li-ion cell I'm currently designing a BMS from scratch. I want to power a High Power LED with one single li-ion cell and through mains connection. The LED should shine when plugged in into the mains connection and simultaneously charge the li-ion battery (integrated charging). When plugged out from the mains connection the LED should shine uninterrupted and be powered by the li-ion cell. The li-ion cell should be removable. Does anyone know how I could realize it? I don't search for a circuit diagram, but just a general schematic.


text:
Q: How does a sender know it's the last one connected to the receiver? The design checklist for "Sender stops cast" states

When the last or only sender is connected to a receiver, tapping Disconnect stops the app running on the receiver[...]

On iOS, GCKDeviceManager leaveApplication and stopApplication respectively leave the app or kill it but with no regards for other senders being connected or not.
How does a sender know it's the last one connected?
Edit: I'm not using the custom receiver

A: You can do it within your receiver with castReceiverManager.getSenders().length

A: Right now you will need to have your own receiver (i.e. custom receiver) to do that and use the api that Angel had mentioned. In future, we plan to update the Styled Receiver to include that logic. In fact, right now, you cannot distinguish between an explicit or implicit disconnect, so if you want to implement the disconnection logic correctly, you have to use a custom receiver and use a custom namespace to send a message to the receiver when an explicit disconnect is attempted. Next release will address that issue as well.


text:
Q: Expected number of throws to get two 6's in a row I am trying to figure out the way to calculate the expected number of fair dice throws in order to get two 6's in a row.
I think the proper solution needs to account for the fact that single six might appear followed by some other number what can happen number of times until two sixes come one after another.
I don't know how to tackle this problem. Can anybody explain the method for this case please.

A: There is a trick that is very helpful in cases like these, when you have a process that stops when something specific happens, and we want to know the expected number of steps.
Let $X$ be our random variable (the number of throws to get two sixes in a row). We want $E(X)$. For future reference, I will also invent a new random variable, $Y$, which is basically the same, except that if the first throw is a six, then we count that as a success as well. Otherwise we want two sixes in a row.
As we begin, we haven't thrown any sixes yet. We will refer to this as the "scratch state". When we throw the die once, there's a $\frac56$ probability chance that we will end up in the scratch state again, except now we've thrown the die once. There's also a probability of $\frac16$ to end up in a state where our success is measured by the random variable $Y$ instead, except we've thrown the die once.
In other words: There's a $\frac56$ chance of ending up in the scratch state with an additional die throw already done, i.e. there is a $\frac56$ chance that we end up in a situation where the expected number of total throws is $1+E(X)$. There is also a $\frac16$ chance that we throw a $6$, which means we are in a situation where the expexted number of throws to success is $1+E(Y)$. We can put this into algebraic form the following way:
$$
E(X) = \frac56(1+E(X)) + \frac16(1+E(Y))
$$
Now, in oder to solve this, we need to find $E(Y)$. We will do a similar analysis there: There is a $\frac56$ chance of going back to the scratch state, except we've thrown the die once. There is also a $\frac16$ probability of our next throw being the winning throw. This gives us
$$
E(Y) = \frac56(1+E(X)) + \frac16(1)
$$
Now we have a system of two equations and the two unknowns $E(X)$ and $E(Y)$, which means we are able to solve and find our $E(X)$.

A: Perhaps it will be clearer if we proceed step by step. We shall denote a six by $S$
By the geometric distribution, expected number of trials for first $S,\;\;e_1 = 6$
Then $\frac16$ chance of getting $SS$, else back to scratch, so $e_2 = 6 +\frac16\cdot1 + \frac56(e_2 +1) \to\; e_2 = 42$
Added
We can proceed similarly for, say, $SSS$
$e_3 = 42 + \frac16\cdot1 + \frac56(e_3+1) \to\;e_3 = 258$


text:
Q: Printing data without knowing the type? I need to print some structure for debugging purposes.Since the code base is huge i am having difficulty locating the exact member I need to look into.Is there some way I could print out the entire structure? or atleast know what type of structure it is so that I can go back and look into it's definition?

A: Use a debugger.  Most debuggers give you an option to see the contents of an entire structure whenever you hit a breakpoint.  On *nix the most popular debugger is gdb, and on Windows the most popular IDE (which includes a debugger) is Visual Studio.  Both the sited I linked to have free-as-in-beer download links.
In gdb, you can set a breakpoint with the break command, and once you reach the breakpoint you can print the contents of the struct with the print command.  More specifically, you can compile with debugging data included (the -g flag in gcc), and then use
$ gdb debugging_executable
Some basic information about GDB gets printed here
> break main.c:100
> run
> print struct_variable

It's also worth looking into the step and continue commands.
In Visual Studio, you can set a breakpoint by double-clicking just to the left of the source line (there is a gray bar on the left side of the editor), and mouse over the variable name to inspect the contents once you reach the breakpoint.


text:
Q: NetBeans 7.0, how to go to end of line? I'm learning to really like vi, and can't stand writing code in netbeans anymore without being able to jump to the end of a line. It's killing me, and I can't find it in the shorcuts or even how to add it. Does anyone know what it is?

A: Go to Tools : Options : Keymap and search for "Insertion Point to End of Line" which mysteriously defaults to the End key. ;) You should be able to reassign any other shortcut to it.

A: U Can Use Ctrl+; to add semicolon at the end of Line and still in your position

Or
Ctrl+Shift+;

to add semicolon at the end of line and change position to new line.


text:
Q: Beginner Reading Python Programming Text: A Simple Game Keeps Returning AttributeError Very sorry in advance for the long paste.
The code is straight from the text. It may be due to class Scene, that seems to have the instruction to: subclass it and implement enter(). But I don't know what that means.
from sys import exit
from random import randint
from textwrap import dedent

class Scene(object):

    def enter(self):
        print("This scene is not yet configured.")
        print("Subclass it and implement enter()")
        exit(1)
# Skeleton code: a base class for Scene that will have
# the common things that all scenes do.

class Engine(object):

    def __init__(self, scene_map):
        self.scene_map = scene_map

    def play(self):
        current_scene = self.scene_map.opening_scene()
        last_scene = self.scene_map.next_scene('finished')

        while current_scene != last_scene:
            next_scene_name = current_scene.enter()
            current_scene = self.scene_map.next_scene(next_scene_name)

        # be sure to print out the last scene
        current_scene.enter()

class Death(Scene):

    quips = [
        "You died.  You kinda suck at this.",
        "Your Mom would be proud...if she were smarter.",
        "Such a luser.",
        "I have a small puppy that's better at this.",
        "You're worse than your Dad's jokes."

    ]

    def enter(self):
        print(Death.quips[randint(0, len(self.quips)-1)])

class CentralCorridor(Scene):

    def enter(self):
        print(dedent("""
            The Gothons of Planet Percal #25 have invaded your ship and
            destroyed your entire crew.  You are the last surviving member
            member and your last mission is to get the neutron destruct
            bomb from the Weapons Armory, put it in the bridge, and
            blow the ship up after getting into an escape pod.

            You're running down the central corridor to the Weapons
            Armory when a Gothon jumps out, red scaly skin, dark grimy
            teeth, and evil clown costume flowing around his hate
            filled body.  He's blocking the door to the Armory and
            about to pull a weapon to blast you.
            """))

        action = input("> ")

        if action == "shoot!":
            print(dedent("""
                Quick on the draw you yank out your blaster and fire
                it at the Gothon.  His clown costume is flowing and
                moving around his body, which throws off your aim.
                Your laster hits his costume but misses him entirely.
                This completely ruins his brand new costume his mother
                bought him, which makes him fly into an insane rage
                and blast you repeatedly in the face until you are
                dead.  Then he eats you.
                """))
            return 'death'

        elif action == "dodge!":
            print(dedent("""
                Like a world class boxer you dodge, weave, slip and
                slide right as the Gothon's blaster cranks a laser
                past your head. In the middle of your artful dodge
                your foot slips and you bang your head on the metal
                wall and pass out.  You wake up shortly after only to
                die as the Gothon stomps on your head and eats you.
                """))
            return 'death'

        elif action == "tell a joke":
            print(dedent("""
                Lucky for you they made you learn Gothon insults in
                the academy.  You tell the one Gothon joke you know:
                Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr,
                fur fvgf nebhaq gur ubhfr.  The Gothon stops, tries
                not to laugh, then busts out laughing and can't move.
                While he's laughing you run up and shoot him square in
                the head putting him down, then jump through the
                Weapon Armory door.
                """))
            return 'laster_weapon_armory'

        else:
            print("DOES NOT COMPUTE!")
            return 'central_corridor'

class LaserWeaponArmory(Scene):

    def enter(self):
        print(dedent("""
            You do a dive roll into the Weapon Armory, crouch and scan
            the room for more GOthon that might be hiding. It's dead
            quiet, too quiet.  You stand up and run to the far side of
            the room and find the neutron bomb in its container.
            There's a keypad lock on the box and you need the code to
            get the bomb out. If you get the code wrong 10 times then
            the lock closes forever and you can't get the bomb.  The
            code is 3 digits.
            """))

        code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
        guess = input("[keypad]> ")
        guesses = 0

        while guess != code and guesses <10:
            print("BZZZZEDDD!")
            guesses += 1
            guess = input("[keypad]> ")

        if guess == code:
            print(dedent("""
                The container clicks open and the seal breaks, letting
                gas out.  You grab the neutron bomb and run as fast as
                you can to the bridge where you must place it in the
                right spot.
                """))
            return 'the_bridge'
        else:
            print(dedent("""
                The lock buzzes one last time and then you hear a
                sickening melting sound as the mechanism is fused
                together.  You decide to sit there, and finally the
                Gothons blow up the ship from their ship and you die.
                """))
            return 'death'

class Finished(Scene):

    def enter(self):
        print("You won! Good job.")
        return 'finished'

class Map(object):

    scenes = {
        'central_corridor': CentralCorridor(),
        'laster_weapon_armory': LaserWeaponArmory(),
        'the_bridge': TheBridge(),
        'escape_pod': EscapePod(),
        'death': Death(),
        'finished': Finished()
    }

    def __init__(self, start_scene):
        self.start_scene = start_scene

    def next_scene(self, scene_name):
        val = Map.scenes.get(scene_name)
        return val

    def opening_scene(self):
        return self.next_scene(self.start_scene)

# Finally the code that runs the game by making a Map, handing that map to
# an Engine before calling play to make game work.
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()

I'm trying to understand what's going on here, but I don't see it. I've also deleted two of the larger classes because they don't seem to be at issue here.
EDIT: The return I'm putting in is:
(base) ➜  Python python ex43.py

Then,
dodge!

This returns:
Like a world class boxer you dodge, weave, slip and slide right as the Gothon's blaster cranks a laser past your head. In the middle of your artful dodge your foot slips and you bang your head on the metal wall and pass out.  You wake up shortly after only to die as the Gothon stomps on your head and eats you.

You're worse than your Dad's jokes. Traceback (most recent call last): File "ex43.py", line 283, in <module>
    a_game.play()   File "ex43.py", line 45, in play
    next_scene_name = current_scene.enter() AttributeError: 'NoneType' object has no attribute 'enter'

A: The enter method for the Death Scene doesn't return anything. In Python, all functions without an explicit return statement return None, which explains the error you're getting.
class Death(Scene):

    quips = [
        "You died.  You kinda suck at this.",
        "Your Mom would be proud...if she were smarter.",
        "Such a luser.",
        "I have a small puppy that's better at this.",
        "You're worse than your Dad's jokes."

    ]

    def enter(self):
        print(Death.quips[randint(0, len(self.quips)-1)])
        # NEED TO ADD RETURN LINE HERE <---

A: As the error says,
next_scene_name = current_scene.enter() AttributeError: 'Nonetype' object has no attribute 'enter'

That means that your current_scene variable is equal to None when you call current_scene.enter() in the play method. You need to make sure the variable current_scene is properly instantiated so that its not None. One way to debug this is to add a print(current_scene) line right after every mention of current_scene. This will tell you when its equal to None in your code.


text:
Q: How to convert SQL to LINQ with look-ahead (lead like query) I have a simple table like so:
[Timestamp] DATETIME,
[Value] NVARCHAR(50)

All [Timestamp] values are unique, but the [Value] is not unique.
I want to find when each [Value] starts and stops. I have the following T-SQL (SQL 2008), which seems to work fine, although any suggestions for improvement would be appreciated, as in a good pattern to implement the lead operator in pre-2012 T-SQL.

SELECT
    h1.[Value] AS 'Event ID',
    MIN(h1.[Timestamp]) AS 'Start Time',
    h2.[Timestamp] AS 'End Time',
    DATEDIFF(second, MIN(h1.[Timestamp]), h2.[Timestamp]) AS 'Duration (sec)'
FROM
    #RawHistory h1
    INNER JOIN
    #RawHistory h2
    ON h2.[Timestamp] =
    (
        SELECT TOP 1
            h3.[Timestamp]
        FROM
            #RawHistory h3
        WHERE
            h3.[Value] <> h1.[Value]
            AND
            h3.[Timestamp] > h1.[Timestamp]
        ORDER BY
            h3.[Timestamp] ASC
    )
GROUP BY
    h1.[Value], h2.[Timestamp]
ORDER BY
    MIN(h1.[Timestamp])

So, given this input:
Timestamp               Value
======================= ======
2013-12-18 20:26:00.000 Violet
2013-12-18 20:30:00.000 Red
2013-12-18 20:35:00.000 Red
2013-12-18 20:40:00.000 Orange
2013-12-18 20:50:00.000 Yellow
2013-12-18 21:00:00.000 Green
2013-12-18 21:05:00.000 Green
2013-12-18 21:07:00.000 Green
2013-12-18 21:10:00.000 Blue
2013-12-18 21:20:00.000 Indigo
2013-12-18 21:30:00.000 Violet
2013-12-18 21:30:05.000 Violet
2013-12-18 21:40:00.000 Red
2013-12-18 21:50:00.000 Orange
2013-12-18 22:00:00.000 Yellow
2013-12-18 22:10:00.000 Green

I expect this output:
Event ID Start Time              End Time                Duration (sec)
======== ======================= ======================= =============
Violet   2013-12-18 20:26:00.000 2013-12-18 20:30:00.000 240
Red      2013-12-18 20:30:00.000 2013-12-18 20:40:00.000 600
Orange   2013-12-18 20:40:00.000 2013-12-18 20:50:00.000 600
Yellow   2013-12-18 20:50:00.000 2013-12-18 21:00:00.000 600
Green    2013-12-18 21:00:00.000 2013-12-18 21:10:00.000 600
Blue     2013-12-18 21:10:00.000 2013-12-18 21:20:00.000 600
Indigo   2013-12-18 21:20:00.000 2013-12-18 21:30:00.000 600
Violet   2013-12-18 21:30:00.000 2013-12-18 21:40:00.000 600
Red      2013-12-18 21:40:00.000 2013-12-18 21:50:00.000 600
Orange   2013-12-18 21:50:00.000 2013-12-18 22:00:00.000 600
Yellow   2013-12-18 22:00:00.000 2013-12-18 22:10:00.000 600

Note that nothing is returned for the last instance of Green, as there is no 'End Date' yet.
However, what I am really interested in is being able to do the same type of query against a similar list of Values and Timestamps using LINQ in C#. Not against a SQL datasource, but against a list of POCO objects with a Value and a Timestamp property.
So, if I have a class similar to

class VT
{
    string Value { get; set; }
    DateTime Timestamp { get; set; }
}

And I have a
List<VT> vts

of these objects, what would be a linq statement on that List that would perform the same type of transformation?
I previously implemented this using a state machine pattern that kept track of when the value changes - something not obvious is that the time series data may have multiple entries for the same value in consecutive timestamps, as in
T1, Red
T2, Red
T3, Red
T4, Yellow
T5, Yellow
T6, Blue

and so on. The SQL works, since it looks for the timestamp of the next value that is not the same as the current value. Is this doable using Linq?
To be sure, in the above example with consecutive values, the end result should be:
Red, T1, T4
Yellow, T4, T6

So consecutive readings should be merged into a single reading. See how the SQL query looks for the next record that is a different value than the current record in the look ahead.
I edited the original dataset example to include repeating consecutive values. The output does not change.

A: You may achieve this using the ZIP-Statement with the same sequence skipped by one element as second input - that is your "look-ahead". However, it does not take into account, that there may be multiple consecutive events with the same value.
var firstList = new List<VT> {
   new VT { Value = "Violet", Timestamp = new DateTime(2013, 12, 18, 20, 26, 0) },
   new VT { Value = "Red", Timestamp = new DateTime(2013, 12, 18, 20, 30, 0) },
   new VT { Value = "Orange", Timestamp = new DateTime(2013, 12, 18, 20, 40, 0) },
   new VT { Value = "Yellow", Timestamp = new DateTime(2013, 12, 18, 20, 50, 0) }
};

var secondList = firstList.Skip(1);

var combined = firstList.Zip(secondList,
                               (first, second) => new {
                                      EventID = first.Value,
                                      StartTime = first.Timestamp,
                                      EndTime = second.Timestamp,
                                      Duration = (second.Timestamp - first.Timestamp).TotalSeconds});
}

This results in
EventID StartTime           EndTime             Duration
Violet  18.12.2013 20:26:00 18.12.2013 20:30:00 240
Red     18.12.2013 20:30:00 18.12.2013 20:40:00 600
Orange  18.12.2013 20:40:00 18.12.2013 20:50:00 600

The problem with multiple consecutive events of the same value can easily be solved using Reactive Extensions (RX). Just substitute types for firstList and secondList to IObservable<VT>. Then .Subscribe() to combined to get a stream completed events whenever a color chages. A call to DistinctUntilChanged will ensure that only events with different colours are passed on.
var firstList = new List<VT> {
  new VT { Value = "Violet", Timestamp = new DateTime(2013, 12, 18, 20, 26, 0) },
  new VT { Value = "Violet", Timestamp = new DateTime(2013, 12, 18, 20, 27, 0) },
  new VT { Value = "Violet", Timestamp = new DateTime(2013, 12, 18, 20, 29, 0) },
  new VT { Value = "Red", Timestamp = new DateTime(2013, 12, 18, 20, 30, 0) },
  new VT { Value = "Red", Timestamp = new DateTime(2013, 12, 18, 20, 34, 0) },
  new VT { Value = "Orange", Timestamp = new DateTime(2013, 12, 18, 20, 40, 0) },
  new VT { Value = "Yellow", Timestamp = new DateTime(2013, 12, 18, 20, 50, 0) }
}
.ToObservable().DistinctUntilChanged(vt => vt.Value);

var secondList = firstList.Skip(1);

var combined = firstList.Zip(secondList, (first, second) => new  {
                                                 EventID = first.Value,
                                                 StartTime = first.Timestamp,
                                                 EndTime = second.Timestamp,
                                                 Duration = (second.Timestamp - first.Timestamp).TotalSeconds});

combined.Subscribe();

This returns the expected result.
The DistinctUntilChanged simply removes all events from the stream that are identical according to the Value, so this effectively reduces the input to the input in the LINQ example above.


text:
Q: How do I scroll all content on top of keyboard? I want a container fix on top of the page and the rest of the screen should scroll up when the keyboard appears. I can make it scroll by using ListView but that way I can not fix my buttons on top.
body: Column(
  children: <Widget> [
    Container(
      //..... This should be fixed, contained buttons
    ),
    Container(
      // height: 300,
      child: Column(
        children: <Widget> [
          //Image Widget
          Container(
            child: TextField()
          )
        ]
      )
    )
  ])


text:
Q: Nginx reserve-proxy https and http connect error First of all, I have an nginx reserve-proxy for my development server. My development server has backend and frontend with docker containers. I use nginx, letsencrypt for https. When I go to my website ,
frontend go out with https and frontend(https) cannot connect to backend api(http). I'm nood in programming but please help me to find out more

A: You need to have both frontend and backend on https , if you will remove redirect from nginx file and access your site via http , you will see everything is working fine.
You need to re-install lets encrypt and when it prompts which domains it needs to cover  select both frontend and backend.
Hope it Helps .


text:
Q: Stack keeps pushing null instead of String value Java I'm working on a project where I have to push String values into a stack.  Whenever I push the first value into the stack it goes in with no problem, but after that any element I push turns into 'null'.  Here's some of my sample code
public void push (E element){

    if( isEmpty() ){
        stack = (E[]) new Object[1];
        stack[0] = element;
    } else {

        int size = stack.length + 1;
        E[] tmpStack = (E[]) new Object[size];

        for (int i = 0; i < stack.length - 1; i++ ) {

        tmpStack[i] = stack[i];
        }

        stack = tmpStack;

        tmpStack = null;

        stack[size - 1] = element;
        }

Here's how I've been calling the method:
String elementArray[] = str.split(",");

    for(int i = 0; i < elementArray.length; i++){
        stack.push(elementArray[i]);
    }

A: You have an off-by-one error. You're not copying the last element out of your source stack.
This:
for (int i = 0; i < stack.length - 1; i++ ) {

should be:
for (int i = 0; i < stack.length; i++ ) {

Bonus tip: Consider using System.arraycopy.


text:
Q: Moodle Plugin "Respondus" will not Authenticate since move to WSO2IS We moved our SSO services from F5 BigIp to WSO2 Identity Server. The moodle saml plugin we are using is OneLogin (https://moodle.org/plugins/auth_onelogin_saml).
Authentication works fine in most ways. Our issue is that we use an Moodle plugin named Respondus (Respondus 4.0, https://www.respondus.com/download/moodleserver.shtml). There is a client side application that an end user would post tests and quizzes directly into moodle.
This where the process fails, the client side application has fields for the user details to log into Moodle. Picture of error in app.
Any ideas would be greatly appreciated.

A: You have written, "Authentication works fine in most ways.".
Can you be more specific? What are the most ways you have checked?
What's your Moodle version?

A: This was an issue on the moodle plugin side with an incorrect value.


text:
Q: Unit testing in Xcode 3.1 I read the question on 'The best way to unit test Objective-C and followed the instructions, but no matter what I do, the Unit tests do not run.  Actually the entire program does not run, I get the following message.
dyld: Library not loaded: @rpath/SenTestingKit.framework/Versions/A/SenTestingKit Referenced from /Users/garethlewis/work/objc/UnitTesting/build/Debug/UnitTesting
Reason: image not found
I have set the DYLD_FALLBACK_FRAMEWORK_PATH variable, and also the XCInjectBundle as well as the DYLD_INSERT_LIBRARIES and added the variable -SenTest All.
I can't have the only installation of Xcode 3.1 that Unit testing fails on.
Can someone who has managed to get Unit Testing on Xcode 3.1 working give some details on what needs to be done.  It would help so much, with what I am trying to do.

A: You don't need to do this stuff to just run your tests.
If you're writing tests for an application, you should just need to set the Test Host and Bundle Loader build settings for your unit test bundle target and they will be run as part of your build.  If you're writing tests for a framework you don't even need to do that, just make sure your test bundle links against your framework.
I assume you're actually talking about debugging your tests, not just running them.  If so, it's important to give us the following information:

*

*what kind of tests — application or framework — you're trying to debug

*what environment variables you set, and what values you set them to

*what arguments you set (-SenTest All should be an argument, not environment variable)

*what the full error shown in your debug console is, not just the specific failure

That will help diagnose what's going on.
At first glance, it looks like you might have a typo in your DYLD_FALLBACK_FRAMEWORK_PATH because that determines where dyld will look for the SenTestingKit.framework binary if @rpath cannot be resolved.  Knowing what it's set to will probably help.
(PS - It's Xcode.)


text:
Q: When storing environment specific configuration variables in an AWS service, how do I do so? I would like to store some connection string variables that vary based upon environment.  How do I do so?

A: Store them in parameter store. See AWS Systems Manager Parameter Store for more details.
If you run a separate AWS account per environment (DEV, TEST, ...) then no problems. If you have a single account, you can structure your environment parameters into a hierarchy. See Organizing Parameters into Hierarchies for more details.


text:
Q: How to run jBehave tests on Multiple Browsers? I currently run the JBehave Selenium tests on current browser, I use the PropertyWebDriverProvider() to set up my browser.
There is my code:
public class PlayerLandingPageRunner extends JUnitStories {
private WebDriverProvider driverProvider = new PropertyWebDriverProvider();
private WebDriverSteps lifecycleSteps = new PerStoriesWebDriverSteps(driverProvider);
private Pages pages = new Pages(driverProvider);
private SeleniumContext context = new SeleniumContext();
private ContextView contextView = new LocalFrameContextView().sized(500, 100);

public PlayerLandingPageRunner() {
    if ( lifecycleSteps instanceof PerStoriesWebDriverSteps ){
        configuredEmbedder().useExecutorService(MoreExecutors.sameThreadExecutor());
        configuredEmbedder().useMetaFilters(asList("-skip"));
    }
}

@Override
public Configuration configuration() {
    Class<? extends Embeddable> embeddableClass = this.getClass();
    return new SeleniumConfiguration()
            .useSeleniumContext(context)
            .useWebDriverProvider(driverProvider)
            .useStepMonitor(new SeleniumStepMonitor(contextView, context, new SilentStepMonitor()))
            .useStoryLoader(new LoadFromClasspath(embeddableClass))
            .useStoryReporterBuilder(new StoryReporterBuilder()
                .withCodeLocation(codeLocationFromClass(embeddableClass))
                .withDefaultFormats()
                .withFormats(CONSOLE, TXT, HTML, XML));
}

...
How can I set it up to run on other browsers? IE, Chrome?
Thanks!

A: You should pass "browser" system property to JVM with one of the values described here.
Here is how you could set up your tests to run on Chrome.
If you are running in command line, just pass it like this
java -Dbrowser=chrome ...

If you are using Eclipse, open Run Configurations, select configuration you use for running tests and append into VM arguments text box -Dbrowser=chrome.


text:
Q: How can one stat an entire directory using a single command line starting with bash -c? How can one stat an entire directory using a single command line starting with bash -c?
This returns all files except for those prefixed with .
 bash -c "stat /path/todir/**"

This returns all files starting with . including . & .. which should be excluded.
bash -c "stat /path/todir/.*"

This works but not under bash -c and requires two lines
shopt -s dotglob
stat /path/todir/**

This too
stat /path/todir/!(.|..)

A: The extended glob options are visible only to the current shell and not to the sub-shells launched. You need to set them inside the sub-shell also for the glob option to be available. Also ** does a recursive descent only if another extended option globstar is set. For your requirement of the current directory alone, you can just use *
bash -c 'shopt -s dotglob; stat /path/todir/*'

Notice the use of single quotes around the entire shell shell command list. It is much more safe in a way you can avoid unnecessary variable expansion (passing a literal string) and use quoted strings with much ease.
If you have control over the part outside the '..' you can set the extended shell option in the invocation itself as
bash -O dotglob -c 'stat /path/todir/*'

That said, if an option to use external utilities like find is available, you could just do below which just excludes the . (current directory name) and includes all the files in the current directory and passes it stat in one shot.
find . ! -path . -exec stat {} +

A: bash -c -O extglob 'stat /path/todir/!(.|..)'

-O extglob enables additional pattern matching operators, including !(pattern-list) for negation.
[-+]O [shopt_option]
         shopt_option is one of the shell options accepted by the shopt builtin  (see
         SHELL  BUILTIN  COMMANDS  below). If shopt_option  is  present, -O sets the
         value of that option; +O unsets it.

If the extglob shell option is enabled using the shopt builtin, several extended pattern matching
operators  are recognized.  In the following description, a pattern-list is a list of one or more
patterns separated by a |.  Composite patterns may be formed using one or more of  the  following
sub-patterns:

      ?(pattern-list)
             Matches zero or one occurrence of the given patterns
      *(pattern-list)
             Matches zero or more occurrences of the given patterns
      +(pattern-list)
             Matches one or more occurrences of the given patterns
      @(pattern-list)
             Matches one of the given patterns
      !(pattern-list)
             Matches anything except one of the given patterns


text:
Q: how to make the gridview to print data from right to left gridview image
how to make the gridview to print data from right to left , I need column0 to the right and column1 and so on

A: You can set and bind the column order from your datasource declaratively. for example:
<asp:GridView ID="GridView1" runat="server">
    <Columns>
        <asp:BoundField DataField="Column1" HeaderText="Column1" />
    </Columns>
    <Columns>
        <asp:BoundField DataField="Column2" HeaderText="Column2" />
    </Columns>
    <Columns>
        <asp:BoundField DataField="Column3" HeaderText="Column3" />
    </Columns>
    <Columns>
        <asp:BoundField DataField="Column4" HeaderText="Column4" />
    </Columns>
</asp:GridView>

Where Column1 is a column in your datasource.
Repeat this for the other columns. The order will be left to right from Top to Bottom. So in this case to have column 2 where column 1 is. make sure the markup for Column 1 comes before column2

A: Hi I use a printpanel and make it print right to left.
I put my gridview in a panel tag like this:
<asp:Panel id="pnlContents" runat = "server" Direction="RightToLeft">
<asp:GridView ID="G1" runat="server" AutoGenerateColumns="false"  OnRowDataBound="MatchList_RowDataBound" Direction="RightToLeft">
                <Columns>
                <asp:BoundField HeaderText=" " />

                <asp:BoundField HeaderText="ID" DataField="ID" />

                <asp:BoundField HeaderText="first name" DataField="name" />

                <asp:BoundField HeaderText="last name" DataField="family" />

                <asp:BoundField HeaderText="father's name" DataField="father_name" />

            </Columns>
        </asp:GridView>

</asp:Panel>

and I use a button to print the gridview
<asp:Button ID="btnPrint" runat="server" Text="Print" OnClientClick = "return PrintPanel();" />

and this script to print

this line makes the print right to left

printWindow.document.dir = "rtl";


text:
Q: Why is delta time not working? (MonoGame, C#) I'm trying to make my game use delta time so it becomes independent of FPS. I had a go at doing it and compared them side-by-side:
https://youtu.be/XYC-AZbk0JE
But the player on the 144fps one still goes faster. My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace _2D_Game_Test.GameStates
{
public class TestState : GameState
{
    Vector2 velocity;
    Vector2 position;

    double change = 0;

    KeyboardState keyboardState;

    public override void Initialize()
    {
        velocity = new Vector2(0, 0);
        position = new Vector2((1280 / 2) - (Game.Bob.Width / 2), (720 / 2) - (Game.Bob.Height / 2));
    }

    public override void Update(GameTime gameTime)
    {
        if (Mouse.GetState().LeftButton == ButtonState.Pressed)
        {
            change = 0;
            velocity = new Vector2(0, 0);
            position = new Vector2((1280 / 2) - (Game.Bob.Width / 2), (720 / 2) - (Game.Bob.Height / 2));
        }

        double delta = gameTime.ElapsedGameTime.TotalSeconds;

        keyboardState = Keyboard.GetState();

        if (keyboardState.IsKeyDown(Keys.A))
        {
            if (change > 0)
            {
                change -= (10 * delta);
            }
            else if (change > -5f)
            {
                if (change - (5 * delta) < -5f)
                {
                    change = -5f;
                }
                else
                {
                    change -= (5 * delta);
                }
            }
        }
        else if (keyboardState.IsKeyDown(Keys.D))
        {
            if (change < 0)
            {
                change += (10 * delta);
            }
            else if (change < 5f)
            {
                if (change + (5 * delta) > 5f)
                {
                    change = 5f;
                }
                else
                {
                    change += (5 * delta);
                }
            }
        }

        if (keyboardState.IsKeyUp(Keys.A) && keyboardState.IsKeyUp(Keys.D))
        {
            if (change > 0)
            {
                if ((change -= (2 * delta)) < 0)
                {
                    change = 0;
                }
                else
                {
                    change -= (2 * delta);
                }
            }
            else if (change < 0)
            {
                if ((change += (2 * delta)) > 0)
                {
                    change = 0;
                }
                else
                {
                    change += (2 * delta);
                }
            }
        }

        velocity.X = (float)change;
        position += velocity;
    }

    public override void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(Game.Bob, position, Color.White);
        spriteBatch.DrawString(Game.Debug, "A and D up: " + (keyboardState.IsKeyUp(Keys.A) && keyboardState.IsKeyUp(Keys.D)), new Vector2(10, 10), Color.Black);
        spriteBatch.DrawString(Game.Debug, "A down: " + (keyboardState.IsKeyDown(Keys.A)), new Vector2(10, 30), Color.Black);
        spriteBatch.DrawString(Game.Debug, "D down: " + (keyboardState.IsKeyDown(Keys.D)), new Vector2(10, 50), Color.Black);
        spriteBatch.DrawString(Game.Debug, "Velocity modifier: " + velocity, new Vector2(10, 70), Color.Black);
        spriteBatch.DrawString(Game.Debug, "Current velocity: " + velocity.X, new Vector2(10, 90), Color.Black);
    }
}
}

What did I do wrong?
P.S: I'm positive it's not just my eyes playing with me. I can see the player going faster on 144fps than the one on 60fps.

A: The problem here is not the delta time itself.
When you are calculating the velocity change, you are applying the delta time perfectly.
The problem comes when you actually apply the velocity to the player itselft. Let's say you are at max velocity (5). Since you don't take into account the delta time while applying the velocity to the position, you'll apply the velocity way more often at 144fps than at 60fps. That's why the character seem to go faster.
You probably want to do something like:
position += velocity * delta;

That should fix your problem.


text:
Q: Playframework [1.2.7] dependencies failing We're experiencing a problem with play frameworks dependency management which was working fine a couple of days ago. We haven't made any configuration changes or changes to the dependency file but are getting the following errors on both our build server and locally (both located on different networks and ISP's).
:: problems summary ::
:::: WARNINGS
    module not found: vsvr1#minifymod;1.0.9

==== vsvr1: tried

  -- artifact vsvr1#minifymod;1.0.9!minifymod.jar:

  https://github.com/maklemenz/minifymod/raw/master/dist/minifymod-1.0.9.zip

    [NOT FOUND  ] play#recaptcha;1.3!recaptcha.zip(jar) (139ms)

==== playContributedModules: tried

  http://www.playframework.org/modules/recaptcha-1.3.zip

    [FAILED     ] play#excel;1.2.3!excel.zip(jar): Connection refused (520ms)

    [FAILED     ] play#excel;1.2.3!excel.zip(jar): Connection refused (520ms)

==== playContributedModules: tried

  http://www.playframework.org/modules/excel-1.2.3.zip

    ::::::::::::::::::::::::::::::::::::::::::::::

    ::          UNRESOLVED DEPENDENCIES         ::

    ::::::::::::::::::::::::::::::::::::::::::::::

    :: vsvr1#minifymod;1.0.9: not found

    ::::::::::::::::::::::::::::::::::::::::::::::

    ::::::::::::::::::::::::::::::::::::::::::::::

    ::              FAILED DOWNLOADS            ::

    :: ^ see resolution messages for details  ^ ::

    ::::::::::::::::::::::::::::::::::::::::::::::

    :: play#recaptcha;1.3!recaptcha.zip(jar)

    :: play#excel;1.2.3!excel.zip(jar)

    ::::::::::::::::::::::::::::::::::::::::::::::

:::: ERRORS
Server access Error: handshake alert:  unrecognized_name url=https://github.com/maklemenz/minifymod/raw/master/dist/minifymod-1.0.9.zip

Server access Error: Connection refused url=http://www.playframework.org/modules/recaptcha-1.3.zip

I cant seem to find a solution to this and so far its preventing us doing any new builds as the dependencies are missing. The failed files seems to change each time too and when manually trying to download them in a browser we can without a problem.
Has anyone seen this problem before?

A: As mentioned here you can use jvm option -Djsse.enableSNIExtension=false as workaround.


text:
Q: query returns unexpected results I feel like this search query is not working as I imagined it would. I want to be certain that the only items selected are those with ksisoldby identical (though case-insensitive, thus ILIKE) to $user. And the the other fields specified with the ANDs and ORs are possible ways this selection could be narrowed down.
"SELECT
id,
status,
customer_id,
shipping_address_id,
order_number,
reference,
ship_via_id,
order_date :: date,
due_date :: date,
created,
sales_tax,
freight,
taxable,
nontaxable,
job_name,
order_description,
ship_to_name,
ship_to_address1,
ship_to_address2,
ship_to_city,
ship_to_state,
ship_to_zipcode,
name,
address1,
address2,
city,
state,
zipcode,
act_ship_date,
ksisoldby
FROM sales_orders
WHERE ksisoldby ILIKE '".$user."'
AND (order_description ilike
'%".implode("%' AND order_description like '%", $search)."%')
OR (order_number ilike
'%".implode("%' AND order_number like '%", $search)."%')
OR (name ilike
'%".implode("%' AND name like '%", $search)."%')
OR (reference ilike
'%".implode("%' AND name like '%", $search)."%')
ORDER BY order_number DESC";

Have I done this correctly, and it is my data that is not set up correctly, or are these AND and/or OR statements overriding the WHERE clause? Thanks for the help.

A: The keyword here is operator precedence. AND binds before OR.
WHERE ksisoldby ILIKE '".$user."'
AND (
     order_description ilike '%".implode("%'
     AND order_description like '%", $search)."%')
  OR order_number ilike '%".implode("%'
     AND order_number like '%", $search)."%'
  OR name ilike '%".implode("%'
     AND name like '%", $search)."%'
  OR reference ilike '%".implode("%'
     AND name like '%", $search)."%'
    )

All items in the WHERE clause are evaluated to one boolean result. If you

want to be certain that the only items selected are those with ksisoldby identical [...] to $user

then you have to wrap the OR'ed criteria into parenthesis or they will offer alternative ways to qualify.
On the other hand, you can remove the parenthesis around the AND'ed pairs like I demonstrate.
I added (syntactically irrelevant) white space and line breaks to make it clearer.

BTW - as this came up in the comments - if you don't want all columns from the table, listing the ones you want (like you have it) is the optimal way.

I would also consider to use prepared statements (or server-side functions with parameters) instead of building one big query strings to prevent SQL injection. Your framework probably offers some way to do this. Or you can do it manually.
While you keep building query strings, use quote_literal() to sanitize user input.


text:
Q: How to search an Image file Is there anyway to check whether a particular image file exists in my iPhone. Lets say my image name is IMG_123.JPG. I want to search this image and if it exists I want to create a NSInputStream object using that File. If the image is not in NSBundle it can be saved in photo library or somewhere.
Please help me.
Thanks
UPDATE
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [pathArray objectAtIndex:0];
NSString* dataPath = [documentsDirectory  stringByAppendingPathComponent:@"IMG_2594.JPG"];

UPDATE  2
Getting the image when user click the picker image
copyOfOriginalImage = [UIImage imageWithCGImage:[[imageAsset defaultRepresentation] fullResolutionImage]];

Convert the image into NSData
imageData = UIImageJPEGRepresentation(copyOfOriginalImage, 1.0);

Then I convert it into base64
strEncoded=[imageData base64EncodedStringWithOptions:0];

A: Your image can be at documentdirectory or assets or appbundle in your application.
Images which are located in photolibrary, you can't called it part of your app's database.
So, you can check that your image is available in documentdirectory or any directory like tempdirectory or customdirectory if you have made like,
 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSFileManager *manager = [NSFileManager defaultManager];

NSArray *filesIndir = [manager contentsOfDirectoryAtPath:path error:nil];

if ([filesIndir containsObject:@"IMG_123.JPG"]) {

    NSLog(@"document directory contains : IMG_123.JPG");
}

It will check directly in document directory. If you are making custom directory in document directory then provide path of it.
Now If your image is in app bundle then you can check it like,
  UIImage *image = [UIImage imageNamed:@"IMG_123.JPG"];

if (image) {

    NSLog(@"yes image available in app bundle");
}

If your image is in assests then you can check it like,
   UIImage *image2 = [UIImage imageNamed:@"IMG_123"];

if (image2) {

    NSLog(@"yes image available in assets");
}

Now, for checking image is available in photo library, This is a bit critical task that you should have the list of all images and then you can check that it available or not. For that you have to use ALAssetsLibrary.
Refer This SO answer for managing this.
You can refer this so post also.


text:
Q: Is it possible to combine two or more different highstock charts into one? I would like to combine two chart types into one. For instance I would like to have at the top the candlestick (http://www.highcharts.com/stock/demo/candlestick-and-volume) and underneath it the column range (http://www.highcharts.com/stock/demo/columnrange)?

A: Yes it is possible, take look at the example: http://www.highcharts.com/stock/demo/candlestick-and-volume


text:
Q: Image button OnClientClick() event issue in ASP.net using C# I am having one Web page(First window). In that page I am having one image button, Which is having OnClientClick event. In that event I call a javascript method as OpenHelpWindow() i.e.
OnClientClick ="OpenHelpWindow()"

Now whenever I clicked that image button the event in the javascript method(OpenHelpWindow()) will get trigger and it will open the New help web window. Its working properly but the problem is, When I press Enter key then also the event will get fire and show me the help window. Now I want to stop the second window (Help window) opening when the Enter key pressed.
How can I resolve this problem?
My Code for the first web window Image button is,
.aspx code
.
.
<asp:ImageButton ImageUrl="~/Images/help.png" runat="server" ID="ibtnHelp"
                                AlternateText="Help" ToolTip="Help"  OnClientClick="OpenHelpWindow()" />
.
.

Javascript code for OpenHelpWindow() is
function OpenHelpWindow()
{
var newWin = null;
try
 {
    newWin = window.open("../Common/OpenHelpUrl.aspx");
    newWin.focus();
    return false;
 }
finally
 {
    newWin = null;
 }
}

A: Your ImageButton is the form's default button, which means that when the user presses Enter, that button automagically gets "pressed". This is standard ASP.NET behavior.
You can change this by adding the following attribute to your <ImageButton.../> tag:
UseSubmitBehavior="False"

Good luck!
EDIT
If this doesn't work (which it should!), then you can fool the browser by adding an invisible dummy button in your form:
<asp:Button ID="dummy" runat="server" Text="" OnClientClick="return false;" style="display:none;"/>

and then adding defaultButton="dummy" to your <form />.

A: Invalid postback or callback argument.  Event validation is enabled using  in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.


text:
Q: how to find distance and time calculation between two location in flutter I have multiple locations and current location, i want to find distance between my current location and other given location of google map flutter.
please provide any method or library which can easily calculate time and distance.I am Using this code but i can not find correct distance.
double _coordinateDistance(lat1, lon1, lat2, lon2) {
var p = 0.017453292519943295;
var c = cos;
var a = 0.5 - c((lat2 - lat1) * p) / 2 +
    c(lat1 * p) * c(lat2 * p) * (1 - c((lon2 - lon1) * p)) / 2;
return 12742 * asin(sqrt(a));}

A: use  https://pub.dev/packages/flutter_locations_distance package
add your multiple locations into lat and lon array and use this code
for(int i=0;i<locCount;i++){
double distance;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
  distance = await FlutterLocationsDistance().distanceBetween(currentLat,
currentLon, lat[i], lon[i]);
} on PlatformException {
  distance = -1.0;
}
}

and for each multiple locations you can get the distance between current location and other locations.
to get your current location use https://pub.dev/packages/location package.
for the time you can use https://pub.dev/packages/stop_watch_timer package


text:
Q: Reducing system of equations involving Erf, Error Function I have a system of equations:
$$1/2 + {\rm Erf}(x) - {\rm Erf}(\frac{x+y}{2})=0$$
$$-1/2 + {\rm Erf}(y) - {\rm Erf}(\frac{x+y}{2})=0,$$
Where $x \le y$ and ${\rm Erf}$ is the Error Function.
By ansatz I know that one solution is $(x,y)=(-{\rm Erf}^{-1}(1/2),{\rm Erf}^{-1}(1/2))$, but I can not manage to prove that this is the only solution, even though I strongly suspect it. My question therefore is how to prove uniquness.
One re-arrangement I have tried results in:
${\rm Erf}(\frac{x+y}{2}) = \frac{{\rm Erf}(x)+{\rm Erf}(y)}{2}$, which I am pretty sure is equivalent to $y=-x$ (apparent by implicit plot), but again I can not prove this. Proving that $y=-x$ for all solutions would imply the desired uniqueness.
Any advice on manipulation tactics for the error function would be much appreciated..!
Tagged as probability theory because of the relation to the Normal distribution CDF.

A: This can be solved as a problem in inequalities.
The desired implication
$$
{\rm Erf}\Bigl(\frac12(x+y)\Bigr) = \frac12\bigl({\rm Erf}(x) + {\rm Erf}(y)\bigr)
\Longleftrightarrow x + y = 0
$$
is not quite correct, because the hypothesis holds also for $x=y$;
but these are the only possibilities, which is enough to yield
the desired result.  Because the error function is odd, it is enough to prove:
Proposition. If $x$ and $y$ are real numbers such that $x+y > 0$ then
$$
{\rm Erf}\Bigl(\frac12(x+y)\Bigr) \geq \frac12\bigl({\rm Erf}(x) + {\rm Erf}(y)\bigr),
$$
with equality if and only if $x=y$.
Proof: Let $a = (x+y)/2$ and $b = (x-y)/2$.  Then $a>0$ and $x,y = a \pm b$,
and we claim
$$
\bigl({\rm Erf}(a+b) + {\rm Erf}(a-b)\bigr) - 2\phantom.{\rm Erf}(a) \leq 0,
$$
with equality iff $b=0$.  By symmetry we may assume $b\geq 0$.
Equality clearly holds for $b=0$.  We claim that the left-hand side (LHS)
is a decreasing function of $b$ for $b \geq 0$, which will prove that
it is negative for all $b>0$.  Indeed derivative of the LHS is
$$
\frac2{\sqrt{\pi}} \left( e^{-(a+b)^2} - e^{-(a-b)^2} \right)
= \frac2{\sqrt{\pi}} e^{-(a^2+b^2)} (e^{-2ab} - e^{+2ab}) < 0
$$
for $b>0$, QED.
(This uses the normalization of ${\rm Erf}(t)$ that has derivative
$(2/\sqrt\pi) \phantom. e^{-t^2}$.  There are other normalizations, but the proof
works in the same way.)

A: Here is another proof, arguably more elementary in that it only uses basic properties of $e^{-t^2}$.
Notice that the two original equations reduce to:
$$
\int_x^{(x+y)/2} e^{-t^2}dt = \frac{\sqrt{\pi}}{4}
, \hspace{0.3in}
\int_{(x+y)/2}^y e^{-t^2}dt = \frac{\sqrt{\pi}}{4},
$$
It is clear from this that we must have $y\ne x$.
With a variable substitution $a=(x+y)/2, b=(x-y)/2$, we also have:
$$
\int_{a-b}^{a} e^{-t^2} dt - \int_{a}^{a+b} e^{-t^2}dt =0.
$$
The following proposition then completes the proof.
Proposition.
For $f(t)$ integrable, positive, symmetric at $t=0$, and increasing for $t<0$, and $b \ne 0$,
$$
\int_{a-b}^{a} f(t)dt - \int_{a}^{a+b} f(t)dt =0
\hspace{0.2in} \Leftrightarrow \hspace{0.2in}
a=0.
$$
Proof.
The implication $\Leftarrow$ is straight forward.
To see the implication $\Rightarrow$, notice that a symmetry manipulation gives us (steps omitted):
$$
\int_{a-b}^{a} f(t)dt - \int_{a}^{a+b} f(t)dt =
\int_{-a}^{a} f(t)dt - \int_{b-a}^{b+a} f(t)dt.
$$
For $a=0$ this clearly equals $0$.
For $a>0$, the increasing property and symmetry give us that:
$$
\int_{-a}^{a} f(t)dt > \int_{b-a}^{b+a} f(t)dt.
$$
for all $b \ne 0$.
An analogous argument holds for $a<0$. QED.
I have not checked wether integrability and positivity are strictly necessary conditions on $f$ for the proposition to hold, but $f(t)=e^{-t^2}$ does have these properties, and generalizations I'm interested in relate to probability distributions, so these assumptions are fine for my purposes.


text:
Q: How to calculate the limit $\lim_{x\to +\infty}x\sqrt{x^2+1}-x(1+x^3)^{1/3}$ which involves rational functions?
Find $$\lim_{x\to +\infty}x\sqrt{x^2+1}-x(1+x^3)^{1/3}.$$

I have tried rationalizing but there is no pattern that I can observe.
Edit:
So we forget about the $x$ that is multiplied to both the functions and try to work with the expression $(x^2+1)^{1/2}-(x^3+1)^{1/3}.$ Thus we have, $$(x^2+1)^{1/2}-(x^3+1)^{1/3}=\frac{((x^2+1)^{1/2}-(x^3+1)^{1/3})((x^2+1)^{1/2}+(x^3+1)^{1/3})}{(x^2+1)^{1/2}+(x^3+1)^{1/3}}$$
$$=\frac{x^2+1-(x^3+1)^{2/3}}{(x^2+1)^{1/2}+(x^3+1)^{1/3}}=\frac{(x^2+1)^2-(x^3+1)^{4/3}}{(x^2+1)^{3/2}+(x^2+1)(x^3+1)^{1/3}+x^3+1+(x^3+1)^{2/3}(x^2+1)}=??$$

A: You can do it with Taylor expansions:
$x\left(1+x^{2}\right)^{1/2}-x\left(1+x^{3}\right)^{1/3}=
x^{2}\left(1+\frac{1}{x^{2}}\right)^{1/2}-x^{2}\left(1+\frac{1}{x^{3}}\right)^{1/3}
 =x^{2}\left(1+\frac{1}{2}\cdot\frac{1}{x^{2}}+o\left(\frac{1}{x^{2}}\right)\right)-x^{2}\left(1+\frac{1}{3}\cdot\frac{1}{x^{3}}+o\left(\frac{1}{x^{3}}\right)\right)
 =\frac{1}{2}-\frac{1}{3x}+o\left(1\right)
 \to\frac{1}{2}$

A: I like the Taylor expansion approach, but wondered if there was a more "Cal I" approach.
Using
$$
A-B = (A^{1/6} - B^{1/6})(A^{5/6} + A^{4/6}B^{1/6} + A^{3/6}B^{2/6} + \cdots + B^{5/6})
$$
with $A = (x^2+1)^3$ and $B = (1+x^3)^2$ gives
$$
\begin{multline*}
(x^2+1)^{1/2} - (x^3+1)^{1/3}\\
=\frac{(x^2+1)^3 - (x^3+1)^2}{(x^2+1)^{5/2}+ (x^2+1)^{2}(1+x^3)^{1/3} + \cdots + (1+x^3)^{5/3}}\\
=\frac{3x^4+2x^3+3x^2}{(x^2+1)^{5/2}+ (x^2+1)^{2}(1+x^3)^{1/3} + \cdots + (1+x^3)^{5/3}}
\end{multline*}
$$
Now
$$
\begin{multline*}
x((x^2+1)^{1/2} - (x^3+1)^{1/3})\\
=\frac{x^5(3+2/x+3/x^2)}{x^5((1+1/x^2)^{5/2}+ (1+1/x^2)^{2}(1+1/x^3)^{1/3} + \cdots + (1+1/x^3)^{5/3})}\\
\end{multline*}
$$
which goes to $3/6$ as $x\to \infty$.

A: Let's put $x=1/t$ so that $t\to 0^{+}$ and the expression under limit is transformed into $$\frac{\sqrt{1+1/t^{2}}-\sqrt[3]{1+1/t^{3}}}{t}=\frac{\sqrt{1+t^{2}}-\sqrt[3]{1+t^{3}}}{t^{2}}$$ and this can be expressed as a difference of two standard limits $$\lim_{t\to 0^{+}}\frac{(1+t^{2})^{1/2}-1}{t^{2}}-t\cdot \frac{(1+t^{3})^{1/3}-1}{t^{3}}$$ which equals $1/2-0(1/3)=1/2$. The standard limit formula $$\lim_{x\to 0}\frac{(1+x)^{n}-1}{x}=n$$ used above is a direct consequence of the more general limit formula $$\lim_{x\to a} \frac{x^n-a^n} {x-a} =na^{n-1}$$

A: Hint: Your expression equals
$$x^2[(1+1/x^2)^{1/2} - (1+1/x^3)^{1/3}].$$
Now use the fact that $(1+h)^p = 1 + ph +o(h)$ as $h\to 0.$ (This fact is equivalent to the statement that the derivative of $(1+x)^p$ at $x=1$ is $p.$)

A: This limit would be equal to $1/2$. See my demo :
$$
\lim_{x \to \infty} {x\sqrt{x^2+1}-x (x^3+1)^{1/3}} =
\lim_{x \to \infty} { x (\sqrt{x^2+1}-(x^3+1)^{1/3})}
$$
Now, let us see how much is each member, by Laurent-Taylor expansion :
$$
\sqrt{x^2+1} = x+ {1 \over {2x}} - {1 \over {8x^3}}+{1 \over {16x^5}}-...
$$
$$
(x^3+1)^{1/3} = x+ {1 \over {3x^2}} - {1 \over {9x^5}}+{5 \over {81x^8}}-...
$$
Resting this 2 members :
$$
\sqrt{x^2+1}-(x^3+1)^{1/3} = {1 \over {2x}}-{1 \over {3x^2}} - {1 \over {8x^3}}+({1 \over 16}+{1 \over 9}){1 \over x^5}-...
$$
Now we substitute this in our limit :
$$
\lim_{x \to \infty} { x (\sqrt{x^2+1}-(x^3+1)^{1/3})} =
\lim_{x \to \infty} { x ({1 \over {2x}}-{1 \over {3x^2}}-...)}= {1 \over 2}
$$


text:
Q: Why does the indicator in ttk.Menubutton not disappear? I wrote code with ttk.Menubutton, but I met a problem - the indicator does not disappear, although it was possible to remove it in tk.Menubutton.
Code
ttk.Menubutton:
import tkinter as tk
from tkinter import ttk

root = tk.Tk()

root.option_add("*Menu.borderWidth", "0")
root.option_add("*Menu.activeBorderWidth", "0")
root.option_add("*Menu.background", "black")

style = ttk.Style(root)

menu = tk.Menu(root)

btn_menu = ttk.Menubutton(root, text='fegvd')
btn_menu.pack()

file = tk.Menu(btn_menu, tearoff=0, foreground='white')
file.add_command(label='ГЫГ')

style.configure('TMenubutton', background='black', foreground='white', indicatoron=0, menu=file, direction='delow', state='active')

root.mainloop()

tk.Menubutton:
import tkinter as tk
from tkinter import ttk

root = tk.Tk()

root.option_add("*Menu.borderWidth", "0")
root.option_add("*Menu.activeBorderWidth", "0")
root.option_add("*Menu.background", "black")

menu = tk.Menu(root)

btn_menu = tk.Menubutton(root, text='fegvd')
btn_menu.pack()

file = tk.Menu(btn_menu, tearoff=0, foreground='white')
file.add_command(label='ГЫГ')

btn_menu.configure(background='black', foreground='white', indicator=0, menu=file, state='active')

root.mainloop()

Screenshots
ttk.Menubutton

tk.Menubutton

How to fix it?

A: The indicator does not disappear because the ttk theme does not have an indicatoron option and style.configure() simply ignores the invalid options instead of raising an error.
However you probably can get rid of the indicator using style.layout(). The solution below does not work with the default theme on OSX, but it works for 'clam' and 'alt'. You seem to be using Windows so maybe it will also work for the Windows theme, otherwise you can change theme.
If you look at the output of style.layout('TMenubutton'), you will have something like
[('Menubutton.border',
  {'sticky': 'nswe',
   'children': [('Menubutton.focus',
     {'sticky': 'nswe',
      'children': [('Menubutton.indicator', {'side': 'right', 'sticky': ''}),
       ('Menubutton.padding',
        {'expand': '1',
         'sticky': 'we',
         'children': [('Menubutton.label',
           {'side': 'left', 'sticky': ''})]})]})]})]

To get rid of the 'Menubutton.indicator', you can just remove it from the layout:
style.layout('TMenubutton', [('Menubutton.border',
  {'sticky': 'nswe',
   'children': [('Menubutton.focus',
     {'sticky': 'nswe',
      'children': [
       ('Menubutton.padding',
        {'expand': '1',
         'sticky': 'we',
         'children': [('Menubutton.label',
           {'side': 'left', 'sticky': ''})]})]})]})])

If you need other menubuttons with an indicator, you can replace 'TMenubutton' by a custom name, e.g. 'noindicator.TMenubutton' and do btn_menu.configure(style='noindicator.TMenubutton') to use this layout for this particular menubutton.


text: Q: Is it possible to perform factor analysis over an unstandardized matrix? I'm trying to do exploratory factor analysis (EFA) and it seems that all functions (in MATLAB, python or R) standardise the data matrix first. I was wondering if there is a way to perform factor analysis over the unstandardised matrix and thus obtain unstandardised scores.


text:
Q: Accessibility - focus order for radio selects with tool tips I have a group of 3 radio selects each radio select has a tool tip next to it. I'm not sure what order each of these should receive keyboard focus?

Should it be...
1. First radio select 2. First corresponding tool tip 3. Second radio 3. Second tool tip etc.

A: You don't really get a choice if you're using a native <input type='radio'>.  Even if your code looked like:
<input type="radio" name="pet" id="r1" value="dog">Dog tooltip 1

<input type="radio" name="pet" id="r2" value="cat">Cat tooltip 2

<input type="radio" name="pet" id="r3" value="fish">Fish tooltip 3

Once a radio button is selected, the group of radio buttons acts like one tabstop.  The active button determines where in the tab order it is.  In the case above, where "Cat" is selected, the tab order is "tooltip 1", radio group, "tooltip 2", "tooltip 3".  If "Dog" were selected, the order would be radio group, "tooltip 1", "tooltip 2", "tooltip 3".

A: Basicly, a tooltip isn't ment to be focusable normally, because you never interact with it per se directly.
Equally as for regular mouse users, the tooltip must appear for keyboard users and be spoken by screen readers.
However, as nothing happens when clicking on it and there is no real interaction with it, it's theortically non-sense to have it focusable.
You can use aria-live to make the text of the tooltip be spoken by screen readers when it appears on screen.


text:
Q: dynamic  refresh with javascript I'm trying to get an user input image to refresh say every two seconds. The javascript gets user input for an URL and the javscript adds it to the page. Then the images loaded need to refresh every 2 seconds but i can't get it to refresh properly without refreshing the whole page or reloading from the cache:
function getImg(){

var url=document.getElementById('txt').value;
var div=document.createElement('div');
div.className="imageWrapper";
var img=document.createElement('img');
img.src=url;
div.appendChild(img);
document.getElementById('images').appendChild(div);
return false;
}

setInterval(function(){
    $('img').each(function(){
       var time = (new Date()).getTime();
       $(this).attr("src", $(this).attr("src") + time );
    });
}, 2000);

any ideas?

A: When you need to force reload the resource, you have to add a dymmy queryString at the end of your url:

Javascript:
$('#img1').attr('src','myimg.png?dummy=23423423423');

and change the dummy value for each refresh

A: Your premise seems good, not sure why it isn't working. Why mixing and matching jQuery with non-jquery? This is a modification of your code, but it is a working example. You should be able to adapt it for your purpose.
http://jsfiddle.net/zr692/1/
You can create elements via jQuery easily. See the modified getImg function I created. Ia also switched from attr to prop which is the recommended means of accessing the src attribute in jQuery 1.7+.
function getImg() {
    var url = 'http://placehold.it/300x300/123456';
    var $div = $('
');
    var $img = $('', { src: url });
    $div.append($img);
    $('body').append($div);
}

getImg();

var interval = setInterval(function() {
    $('img').each(function() {
        var time = (new Date()).getTime();
        var oldurl = $(this).prop('src');
        var newurl = oldurl.substring(0, oldurl.lastIndexOf('/') + 1) + time.toString().substr(7, 6);
        $('#output').html(newurl);
        $(this).prop('src', newurl);
    });
}, 2000);

A: Put the image in a container as:

then simply update the content of the container as:
$('#container').html('');


text:
Q: MyBatis and SQL I want to insert data using MyBatis insert statement.
I have two tables empl_user and empl_user_group.
I want to insert value of first_name,Last_name,Email_address in empl_user and I want to insert brand_data in empl_user_group.
I want to do this using one insert query. Is this possible?
There is a column name User_Id which is common in both the tables.


text:
Q: Mathematical software for calculating Christoffel symbols, curvature, etc I'm looking for a Mathematical software that can do the following:
I put in a metric (some kind of a two-dimensional matrix), and the software calculates Christoffel symbols, Ricci curvatures, Paneitz operators, etc.
What software should I use? Can I do this somewhere online?


text:
Q: Uncertainties on parameters from maximum likelihood fitting I am trying to fit a model to binomially distributed data, which I have done via the maximum likelihood method. Normally I'm working with normally distributed data (or data which I can convince myself and occasionally others is normally distributed) and I'm a little confused about how to find asymmetric errors on my parameters. Usually I find uncertainties by scanning the space of the fitted parameters and finding the surface where the X^2 is one greater than the best fit value. I have found some unproven statements suggesting that this method is applicable regardless of whether one is using Gaussian maximum likelihood or not. Is this the case?

A: What you're describing is the Method of Support, which relies on the asymptotic property of the likelihood ratio statistic L, namely that -2L is has an approximate chi-square distribution.
A more direct method is to use the second derivatives of the log-likelihood function to obtain the observed Fisher information matrix.  The inverse of this matrix, evaluated at the point of maximum likelihood, is the estimated variance-covariance matrix for your model parameters.
I've had great success doing this in Mathematica, where the derivatives can be calculated on the fly without doing all the messy calculus by hand.


text:
Q: How to use Heroicons v2 in headlessui Hi i try use Heroicons in Headlessui but I encountered this error،how can i fix that?
Uncaught Error: You're trying to import @heroicons/react/solid/SelectorIcon from Heroicons v1 but have installed Heroicons v2. Install @heroicons/react@v1 to resolve this error.

A: Update: There are two ways to fix the error:

*

*install @heroicons/react@v1:
npm i @heroicons/react@v1

*Use react-icons instead of heroicons:
npm i react-icons


text:
Q: specify label's position to be above of the dropdown menu in html How can I specify the position of the label to be above the dropdown menu?
E.g.
<form action="/action_page.php">
  Choose a car:
  <select name="cars" id="cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
  </select>
  <input type="submit" value="Submit">
</form>

Is there any style argument in Choose a car: that would place it above the menu?
Thank you!

A: Because label is an inline element, you can't give it a size unless you change its display option to block or inline-block
 Choose a car:

MSDN explaination.

A: So far it worked this way:
Style should include display: inline-block and  width: 10em; and the label tag should close after the select tag.
<form action="/action_page.php">
  Choose a car:
  <select name="cars" id="cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
  </select>
  <input type="submit" value="Submit">
</form>

See here
I am still looking for a more thorough explanation to learn from!