text:
Q: Terraform AWS Routing between 2 or more nodes on a private subnetwork I have a terraform plan (below) that creates a couple of nodes in a private VPC on AWS. Everything seems to work well, but I can't ssh or ping between the nodes in the VPC.
What am I missing from the following configuration to allow the 2 nodes in the private network to be able to talk to each other?
provider "aws" {
  region = "${var.aws_region}"
  access_key = "${var.aws_access_key}"
  secret_key = "${var.aws_secret_key}"
}

# Create a VPC to launch our instances into
resource "aws_vpc" "default" {
  cidr_block = "10.0.0.0/16"

  tags {
    Name = "SolrCluster1"
  }
}

# Create an internet gateway to give our subnet access to the outside world
resource "aws_internet_gateway" "default" {
  vpc_id = "${aws_vpc.default.id}"

  tags {
    Name = "SolrCluster1"
  }
}

# Grant the VPC internet access on its main route table
resource "aws_route" "internet_access" {
  route_table_id = "${aws_vpc.default.main_route_table_id}"
  destination_cidr_block = "0.0.0.0/0"
  gateway_id = "${aws_internet_gateway.default.id}"
}

# Create a subnet to launch our instances into
resource "aws_subnet" "private" {
  vpc_id = "${aws_vpc.default.id}"
  cidr_block = "10.0.1.0/24"

  # if true, instances launched into this subnet should be assigned a public IP
  map_public_ip_on_launch = true

  # availability_zone =

  tags {
    Name = "SolrCluster1"
  }
}

# Security Group to Access the instances over SSH, and 8983
resource "aws_security_group" "main_security_group" {
  name = "SolrCluster1"
  description = "Allow access to the servers via port 22"

  vpc_id = "${aws_vpc.default.id}"

  // allow traffic from the SG itself for tcp
  ingress {
    from_port = 1
    to_port = 65535
    protocol = "tcp"
    self = true
  }

  // allow traffic from the SG itself for udp
  ingress {
    from_port = 1
    to_port = 65535
    protocol = "udp"
    self = true
  }

  // allow SSH traffic from anywhere TODO: Button this up a bit?
  ingress {
    from_port = 22
    to_port = 22
    protocol = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  // allow ICMP
  ingress {
    from_port = -1
    to_port = -1
    protocol = "icmp"
    cidr_blocks = ["0.0.0.0/0"]
  }

}

resource "aws_instance" "solr" {
  ami = "ami-408c7f28"
  instance_type = "t1.micro"

  # The name of our SSH keypair we created above.
  # key_name = "${aws_key_pair.auth.id}"
  key_name = "${var.key_name}"

  vpc_security_group_ids = ["${aws_security_group.main_security_group.id}"]

  # Launch the instances into our subnet
  subnet_id = "${aws_subnet.private.id}"

  # The connection block tells our provisioner how to communicate with the
  # resource (instance)
  connection {
    # The default username for our AMI
    user = "ubuntu"
    # The connection will use the local SSH agent for authentication.
    private_key = "${file(var.private_key_path)}"
  }

  /* provisioner "remote-exec" { */
  /*   inline = [ */
  /*     "sudo apt-get -y update", */
  /*     "sudo apt-get -y --force-yes install nginx", */
  /*     "sudo service nginx start" */
  /*   ] */
  /* } */

  tags {
    Name = "SolrDev${count.index}"
  }

  count = 2
}

A: Turned out I left out the egress rules for my subnet:
  egress {
    from_port = 1
    to_port = 65535
    protocol = "tcp"
    self = true
  }

  // allow traffic from the SG itself for udp
  egress {
    from_port = 1
    to_port = 65535
    protocol = "udp"
    self = true
  }


text:
Q: Wrong AlternativeAttributes "Key" values returned I am working with HERE geocoder and found that when using strictlanguagemode=true the values returned in AlternativeAttributes are always displaying the same "Key", mixing alternative names for multiple level objects.
For example, this request:
https://geocoder.api.here.com/6.2/geocode.json?app_id=....&app_code=....&language=en&strictlanguagemode=true&country=Spain&city=Palma

returns this response (as you can see, all AlternativeAttributes use the "Key":"city", but the response is mixing alternative names for the state, county and city:
{
  "Response": {
    "MetaInfo": {
      "Timestamp": "2019-04-16T15:50:30.385+0000"
    },
    "View": [
      {
        "_type": "SearchResultsViewType",
        "ViewId": 0,
        "Result": [
          {
            "Relevance": 1,
            "MatchLevel": "city",
            "MatchQuality": {
              "Country": 1,
              "City": 1
            },
            "Location": {
              "LocationId": "NT_It18KKa.DRNOAE.IP7p2rD",
              "LocationType": "point",
              "DisplayPosition": {
                "Latitude": 39.57149,
                "Longitude": 2.64694
              },
              "NavigationPosition": [
                {
                  "Latitude": 39.57149,
                  "Longitude": 2.64694
                }
              ],
              "MapView": {
                "TopLeft": {
                  "Latitude": 39.65717,
                  "Longitude": 2.56391
                },
                "BottomRight": {
                  "Latitude": 39.50374,
                  "Longitude": 2.84777
                }
              },
              "Address": {
                "Label": "Palma, Balearic Islands, Spain",
                "Country": "ESP",
                "State": "Balearic Is",
                "County": "Balearic Islands",
                "City": "Palma",
                "PostalCode": "07012",
                "AlternativeAttributes": [
                  {
                    "Key": "city",
                    "Value": "Illes Balears",
                    "Type": "baseName",
                    "Language": "CAT"
                  },
                  {
                    "Key": "city",
                    "Value": "Balear Uharteak",
                    "Semantics": "exonym",
                    "Language": "BAQ"
                  },
                  {
                    "Key": "city",
                    "Value": "Bale\u00e1rsk\u00e9 Ostrovy",
                    "Semantics": "exonym",
                    "Language": "CZE"
                  },
                  {
                    "Key": "city",
                    "Value": "Balearerne",
                    "Semantics": "exonym",
                    "Language": "DAN"
                  },
                  {
                    "Key": "city",
                    "Value": "Balearen",
                    "Semantics": "exonym",
                    "Language": "DUT"
                  },
                  {
                    "Key": "city",
                    "Value": "Baleaarit",
                    "Semantics": "exonym",
                    "Language": "FIN"
                  },
                  {
                    "Key": "city",
                    "Value": "Iles Bal\u00e9ares",
                    "Semantics": "exonym",
                    "Language": "FRE"
                  },
                  {
                    "Key": "city",
                    "Value": "Balearische Inseln",
                    "Semantics": "exonym",
                    "Language": "GER"
                  },
                  {
                    "Key": "city",
                    "Value": "Isole Baleari",
                    "Semantics": "exonym",
                    "Language": "ITA"
                  },
                  {
                    "Key": "city",
                    "Value": "Illes Balears",
                    "Semantics": "exonym",
                    "Language": "MAY"
                  },
                  {
                    "Key": "city",
                    "Value": "Balearene",
                    "Semantics": "exonym",
                    "Language": "NOR"
                  },
                  {
                    "Key": "city",
                    "Value": "Baleary",
                    "Semantics": "exonym",
                    "Language": "POL"
                  },
                  {
                    "Key": "city",
                    "Value": "Ilhas Baleares",
                    "Semantics": "exonym",
                    "Language": "POR"
                  },
                  {
                    "Key": "city",
                    "Value": "\u0411\u0430\u043b\u0435\u0430\u0440\u0441\u043a\u0438\u0435 \u041e\u0441\u0442\u0440\u043e\u0432\u0430",
                    "Semantics": "exonym",
                    "Language": "RUS"
                  },
                  {
                    "Key": "city",
                    "Value": "Islas Baleares",
                    "Semantics": "exonym",
                    "Language": "SPA"
                  },
                  {
                    "Key": "city",
                    "Value": "Balearerna",
                    "Semantics": "exonym",
                    "Language": "SWE"
                  },
                  {
                    "Key": "city",
                    "Value": "Balearske Ostrovy",
                    "Semantics": "exonym",
                    "Language": "CZX"
                  },
                  {
                    "Key": "city",
                    "Value": "Baleary",
                    "Semantics": "exonym",
                    "Language": "POX"
                  },
                  {
                    "Key": "city",
                    "Value": "Balearskie Ostrova",
                    "Semantics": "exonym",
                    "Language": "RUX"
                  },
                  {
                    "Key": "city",
                    "Value": "Illes Balears",
                    "Type": "baseName",
                    "Language": "CAT"
                  },
                  {
                    "Key": "city",
                    "Value": "Balearen",
                    "Semantics": "exonym",
                    "Language": "DUT"
                  },
                  {
                    "Key": "city",
                    "Value": "Iles Bal\u00e9ares",
                    "Semantics": "exonym",
                    "Language": "FRE"
                  },
                  {
                    "Key": "city",
                    "Value": "Balearische Inseln",
                    "Semantics": "exonym",
                    "Language": "GER"
                  },
                  {
                    "Key": "city",
                    "Value": "Isole Baleari",
                    "Semantics": "exonym",
                    "Language": "ITA"
                  },
                  {
                    "Key": "city",
                    "Value": "Balearene",
                    "Semantics": "exonym",
                    "Language": "NOR"
                  },
                  {
                    "Key": "city",
                    "Value": "Ilhas Baleares",
                    "Semantics": "exonym",
                    "Language": "POR"
                  },
                  {
                    "Key": "city",
                    "Value": "Islas Baleares",
                    "Semantics": "exonym",
                    "Language": "SPA"
                  },
                  {
                    "Key": "city",
                    "Value": "Balearerna",
                    "Semantics": "exonym",
                    "Language": "SWE"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Type": "baseName",
                    "Language": "CAT"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma de Mallorca",
                    "Type": "baseName",
                    "Semantics": "synonym",
                    "Language": "CAT"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "BAQ"
                  },
                  {
                    "Key": "city",
                    "Value": "\u5e15\u5c14\u9a6c",
                    "Semantics": "exonym",
                    "Language": "CHI"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "CZE"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "DAN"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "DUT"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "FIN"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "FRE"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "GER"
                  },
                  {
                    "Key": "city",
                    "Value": "\u03a0\u03ac\u03bb\u03bc\u03b1",
                    "Semantics": "exonym",
                    "Language": "GRE"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "ITA"
                  },
                  {
                    "Key": "city",
                    "Value": "\ud314\ub9c8",
                    "Semantics": "exonym",
                    "Language": "KOR"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "MAY"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "NOR"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "POL"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "POR"
                  },
                  {
                    "Key": "city",
                    "Value": "\u041f\u0430\u043b\u044c\u043c\u0430",
                    "Semantics": "exonym",
                    "Language": "RUS"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "SPA"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "SWE"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "CZX"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "GRX"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "KOX"
                  },
                  {
                    "Key": "city",
                    "Value": "Palma",
                    "Semantics": "exonym",
                    "Language": "POX"
                  },
                  {
                    "Key": "city",
                    "Value": "Pa Er Ma",
                    "Semantics": "exonym",
                    "Language": "PYN"
                  },
                  {
                    "Key": "city",
                    "Value": "Pal'ma",
                    "Semantics": "exonym",
                    "Language": "RUX"
                  }
                ],
                "AdditionalData": [
                  {
                    "value": "Spain",
                    "key": "CountryName"
                  },
                  {
                    "value": "Balearic Islands",
                    "key": "StateName"
                  },
                  {
                    "value": "Balearic Islands",
                    "key": "CountyName"
                  }
                ]
              }
            }
          }
        ]
      }
    ]
  }
}

Is this a Bug in the AlternativeAttributes response?
How should we differentiate between alternative names for state, county and city in this case?
Thanks!

A: Geocoder API now returns exonym results with different keys which are city , country, state and county when the option strictlanguagemode set to true.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot deploy cloud functions to Firebase. Request is missing required authentication credential I am currently trying to deploy my Cloud Functions to Firebase with firebase deploy --only functions but this does not seem to work, it never finishes the deploy. I tried debugging the deploy with the command firebase deploy --only functions --debug, this prints out all the requests with the url's that lead to the error messages. Whenever i click one of the url's of the requests it gives me this error:
{
  "error": {
    "code": 403,
    "message": "The request is missing a valid API key.",
    "status": "PERMISSION_DENIED"
  }
}

Some of the other url's give me this error:
{
  "error": {
    "code": 401,
    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

I can't really find anything useful online on how to fix this either. The articles that i did find did not help me though.
This is my index.js file where my Cloud Functions are:
const functions = require('firebase-functions');
const {firestore, auth} = require('./src/admin');

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.helloWorld = functions.https.onRequest((request, response) => {
 response.send("Hello from Firebase!");
});

This is my admin.js file where i define the serviceAccountKey and such:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const serviceAccount = require('../serviceAccountKey.json');

const app = admin.apps.length
  ? admin.app()
  : admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: functions.config().database.url || process.env.FIREBASE_CONFIG.databaseURL, // default firebase var
    storageBucket: functions.config().storage.bucket || process.env.FIREBASE_CONFIG.storageBucket // default firebase var
  });

module.exports = {
  app,
  firestore: app.firestore(),
  db: app.database(),
  storage: app.storage(),
  auth: app.auth()
};

I have used this exact code before on another project so i assume its a Firebase problem and not my code. In the end i expect my Cloud Functions to be deployed by calling the firebase deploy --only functions command without any authentication errors.
Can someone please tell me what i am doing wrong here?
UPDATE 22-2-2020 12:44 PM: I tried reinstalling and reconfiguring the firebase-tools. After doing that and running the command again it gave me this error:
There was an issue deploying your functions. Verify that your project has a Google App Engine instance setup at https://console.cloud.google.com/appengine and try again. If this
issue persists, please contact support.
!  functions: Upload Error: HTTP Error: 503, The service is currently unavailable.

Error: HTTP Error: 503, The service is currently unavailable.

The URL leads me to the page where you can setup your App Engine. Because i already set that up it says 'Your App Engine application has been created'. However whenever i click Get Started button again, i have to create a billing account to proceed. This is keeping me from deploying my Cloud Functions. Is there a way to use Cloud Functions with a billing account?


text:
Q: Read multiple files with SparkSession in Spark 2.0 In Spark 1.6 to read multiple files, I have used:
JavaSparkContext ctx;
ctx.textFile(filePaths);

With filePaths is the directory to files. For example we have:
/home/user/folderA/0.log,/home/user/folderB/0.log. Each path separates by comma character.
But, when I upgrade to Spark 2.0. Method
SparkSession sparkSession;
sparkSession.read().textFile(filePaths);

doesn't work. The code throws exception: Path does not exist:
Question: Is there any solution to read multiple files, from multiple paths in Spark 2.0 just like Spark 1.6?
Edit: I try to call the method like Spark 1.6 using:
sparkSession.sparkContext().textFile(filePaths, 1).toJavaRDD();

The problem will solved. But, Is there have another solution?


text:
Q: How to collect Strings read from file into a custom class using collect from Streams I have a custom class State
public class State {
    private double sum;
    private int count;
    public void inc(double d){
        sum+=d;
        count++;
    }
    public void add(State s){
        this.sum+=s.sum;
        this.count+=s.count;
    }
    public double average(){
        return sum/count;
    }
}

And I have a tester class for that class:
import java.io.*;
import java.util.Arrays;
import java.util.function.*;
import java.util.stream.*;
import java.nio.file.*;

public class StateTest {
    public static void main(String[] a) throws IOException{
        BiConsumer<State,Double> acc = (s,d)->s.inc(d);
        BiConsumer<State,State> comb = (s,s1)->s.add(s1);
        Stream<String> ss = Files.lines(Path.of(a[0]));
        //double avg = ss.mapToDouble(Double::valueOf).filter(b -> b <= 42.0f && b >= -42.0f).collect(//Dont know what to write here).average()
    }
}

for which I want to do the following:
Read out lines of doubles from a text file, convert them into Doubles, and collect them using .collect(Supplier, Accumulator, Combiner) method.
I am having trouble writing the supplier for State class. I don't also clearly get the meaning of this kind of .collect() and what does it mean to supply? I have to collect it into the State and then call .average() of the State function to get the average of the double.

A: Use .map() instead of .mapToDouble():
double avg = ss.map(Double::valueOf)
  .filter(b -> b <= 42.0f && b >= -42.0f)
  .collect(State::new, acc, comb).average();


text:
Q: Cauchy property and limit in two variables Let $(x_{n})_{n\in\mathbb{N}}$ be a sequence of real numbers with the property that
\begin{equation}
  \forall\varepsilon>0\quad\exists N\in\mathbb{N}\quad\forall\color{red}m
\color{red}>\color{red}n\geq N:\quad\lvert x_{n}-x_{m}\lvert<\varepsilon.
\end{equation}
Given the above, I would like to understand what the expression
\begin{equation}
  \lim_{\substack{m,n\to\infty\\ m>n}}\lvert x_{n}-x_{m}\rvert=0
\end{equation}
exactly means and why this ''Cauchy property'' suffices for $(x_{n})_{n\in\mathbb{N}}$ to admit a limit?

A: A double sequence $a_{m,n}$ is formally a function $\mathbb{N}\times\mathbb{N}\to\mathbb{R}$. We say $\lim\limits_{m,n\to\infty} a_{m,n}=a$ if:
$\forall\epsilon>0 \ \ \exists n_0\in\mathbb{N} \ \ \forall m,n\geq n_0: |a_{m,n}-a|<\epsilon$.
So this is a natural generalization of a regular limit. The condition that $(x_n)$ is Cauchy exactly means that $\lim\limits_{m,n\to\infty} |x_m-x_n|=0$, this is immediate from the definition.


text:
Q: Convert string preceeded with 0 to Json in Swift 4 I'm trying to encode an integer that starts with a 0 into JSON using swift 4.
I'm using a pretty standard JSONSerialization library, but for some reason, after converting the string to data using utf8, I cannot serialize it.
let code = "012345" // example code
let body = "{\"code\": " + code + "}"
let stringData = body.data(using: .utf8)!
let jsonArray = try? JSONSerialization.jsonObject(with: stringData, options : .allowFragments) [returns nil]
let data: Data? = try? JSONSerialization.data(withJSONObject: jsonArray as Any, options: .prettyPrinted)

Currently, the code breaks on the second to last line (starting with let jsonArray) and returns nil. Note that if I were to change code to "112345", there would be no error. Any help is appreciated, thanks!

A: Instead of manually creating string, use Dictionary and JSONSerialization to create data as below,
let code = "012345"
let body: [String: Any] = ["code": code]
do {
    let stringData = try JSONSerialization.data(withJSONObject: body, options: .sortedKeys)
    print(String.init(data: stringData, encoding: .utf8)!)
} catch {
    print(error)
}

Output

{"code":"012345"}


text:
Q: Configure data source in spring and mapping in hibernate Is it possible to configure to DataSource configuration in spring xml and keep the resource mapping in hibernate configuration file.

A: You can find an example in the Spring reference (http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#orm-hibernate).


text:
Q: How to handle redirections with codeigniter? im having problems starting a codeigniter project, the problem is that when i do something in a controller and then i want a page to display the result, an example: i have a form to add a item to the database, i get all the data in the controller and save it to database and then i want (if all went well) to redirect to the main page with a success msg, i was doing this with
$this->load->view('admin', $data);

the problem is that the url keeps saying admin/addItem so everytime the page gets refreshed it adds another item, now i found the:
redirect('admin','refresh');

but this only helps me when i dont need to display any msg because this function dont allow to send a $data var.
Any ideas?
Probably this is really easy to fix but i cant find a way to handle the flow of the application the way i want, any help is apreciated.
thanks ;)

A: Flashdata is your friend, follow that link and about halfway through the page you'll find the docs for flashdata.
Basically if your form functions are successful you set flashdata with your success message, $this->session->set_flashdata('success', 'You successfully did something, yay!');
Now redirect to your admin page. redirect('admin','refresh'); on your admin page check for existing flashdata and echo it to the user

A: Could be easy to fix or it could be also difficult to fix,
look at the documentation about uri routing http://codeigniter.com/user_guide/general/routing.html
In my test app i use this vars
$route['default_controller'] = "main";
$route['scaffolding_trigger'] = "";

main is a controller so if you visit your site it call at first the controller main
in your case i would use something like this
$route['admin/:num'] = "catalog/products";

This would redirect any access to admin/* to catalog/products
Be creative ;-)

A: I think you should instead use this aproach:
instead of calling the admin view or redirect the header, you should send the post from the form direct to the admin function, inside the admin function if the $_POST variable is not empty means that you should save the data in database calling other function in the same controller or in one model example:($this->save_data_in_database();) and send the result of it to the view again.
If the $_POST variable is empty you should call the admin view and send the data for message as NULL.
I send one example bellow:
View Admin: (Post Directly to the admin function in controller)
<html>
(...)
<body>

<?php echo $message_response; ?>

<form method="post" action="<domain>/index.php/admin" />
   <imput (...)
</form>

</html>

Controller:
function admin()
{
   if (isset($_POST['fieldname']))
        $data['message_response']=$this->save_data_in_database($params...);
   else
        $data['message_response']=NULL;

  $this->load->view('admin', $data);
}

function save_data_in_database($params...)
{

(save data to database etc...)

return (...message_to_display...);

}

Best Regards,
Pedro


text:
Q: IPhone 5s ITunes Radio not supported I try to listen to my iTunes Radio. And I'm currently on the latest iOS. And it says it's not supported. What's going on?

A: Do you fulfil these requirements?
Apple Music Radio requirements
To listen to Apple Music Radio, you need:

*

*iOS 8.4 or later on your iPhone, iPad, or iPod touch. Update your iPhone, iPad, or iPod touch.

*iTunes 12.2 or later on your Mac or PC. Get the latest version.

*An Apple ID.

Apple Music Radio is available only in select countries. Find out what's available in your country.
Apple Music Radio features vary by country.
In some countries, an Apple Music membership is required to listen to Apple Music Radio.
Source: https://support.apple.com/en-gb/HT204944


text:
Q: How to get a list of system sounds in Windows Phone 8? I'm working on an alarm app for Windows Phone 8 and I'd like to let the user pick from the available alarms tones (like the built-in "Alarms" app has). Is that set of sounds available to third-party apps? If so, how can I access it?

A: The list of built-in Alarm sounds isn't currently exposed for 3rd party apps. If this is something you'd like to see in future releases please open a new feature suggestion on wpdev uservoice with your usecase.


text:
Q: Restore Default Super Key Behavior (xkbmap) setxkbmap has always been a healthy bit of black magic as far as I'm concerned. I recently installed Dyalog APL. When I run the command dyalog, it globally changes my keyboard configuration to APL mode, which effectively disables my ability to use the Super key for anything else. Now, this is actually quite nice while I'm using APL. But then when I close the process, I'm left with a nigh-worthless Super key that can't do any of its usual functions, like switch between windows or open the Activities menu. So my question is, how do I change it back?
Specifically, here's the "normal" output of setxkbmap -print, on a fresh login.
xkb_keymap {
    xkb_keycodes  { include "evdev+aliases(qwerty)" };
    xkb_types     { include "complete"  };
    xkb_compat    { include "complete"  };
    xkb_symbols   { include "pc+us+us:2+inet(evdev)+capslock(ctrl_modifier)"};
    xkb_geometry  { include "pc(pc105)" };
};

(The caps lock/ctrl modifier is unrelated to this question, so feel free to ignore that)
When I run Dyalog, it changes my keyboard map, so setxkbmap -print becomes
xkb_keymap {
    xkb_keycodes  { include "evdev+aliases(qwerty)" };
    xkb_types     { include "complete"  };
    xkb_compat    { include "complete"  };
    xkb_symbols   { include "pc+us+apl(dyalog):2+us:3+inet(evdev)+group(win_switch)+capslock(ctrl_modifier)"    };
    xkb_geometry  { include "pc(pc105)" };
};

So what setxkbmap command(s) can I run to go from the second state back to the first one? I want to be able to get the default behavior of my Super key back, on demand.
I'm running Ubuntu 18.04.3 LTS, with Gnome 3.28.4 on X11, if any of that matters for the purposes of this question.

A: I don't believe you can use the output of setxkbmap -print for that,
but there are at least three other approaches to restore the default
keyboard state.
Option 0
Execute
xkbcomp "$DISPLAY" normal.xkb

while the keyboard is in its default state. Xkbcomp creates normal.xkb
file, the keyboard's complete default keymap. After you are done with Dyalog,
the keyboard state can be easily restored with
xkbcomp normal.xkb "$DISPLAY"

Option 1
From man keyboard, for Debian based systems:

 udevadm trigger --subsystem-match=input --action=change

Option 2
Retrieve from /etc/default/keyboard the relevant settings for
the setxkbmap command:
setxkbmap [-model xkb_model] [-layout xkb_layout] [-variant xkb_variant] [-option xkb_options]

For example, given this /etc/default/keyboard,
XKBMODEL="pc105"
XKBLAYOUT="us"
XKBVARIANT=""
XKBOPTIONS="caps:swapescape,terminate:ctrl_alt_bksp"

You would restore that default state with
setxkbmap -model 'pc105' -layout 'us' -option 'caps:escape,terminate:ctrl_alt_bksp'

A: What about using directly the APL keymap shipped with XKB?
Have a look into /usr/share/X11/symbols/apl, you can use it as a secondary layout.


text:
Q: Sending chunked files to save in mongodb I have 2 different servers for example (Server 1 , Server 2), In the first server I have golang app which splits files and sending to  second server which should save in mongodb via mgo.v2
Server 1:
func mainHandle(rw http.ResponseWriter, rq *http.Request) {

    fileToBeChunked := "/Users/IT/Desktop/4k.jpg"

    file, err := os.Open(fileToBeChunked)

    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    defer file.Close()

    fileInfo, _ := file.Stat()

    var fileSize int64 = fileInfo.Size()

    const fileChunk = 0.25 * (1 << 20) // 1 MB, change this to your requirement

    // calculate total number of parts the file will be chunked into

    totalPartsNum := uint64(math.Ceil(float64(fileSize) / float64(fileChunk)))

    fmt.Printf("Splitting to %d pieces.\n", totalPartsNum)

    var sent int
    prev_part := 0

    for i := uint64(0); i < totalPartsNum; i++ {

        partSize := int(math.Min(fileChunk, float64(fileSize-int64(i*fileChunk))))

        sent = sent + partSize
        partBuffer := make([]byte, partSize)
        //fileBuffer := make([]byte, fileSize)

        //fmt.Printf("File size is %d \n",fileBuffer)
        fmt.Printf("Part size is %d \n",partSize)

        file.Read(partBuffer)

        client := &http.Client{}
        req, _ := http.NewRequest("PUT", "http://localhost:8011/upload/23", bytes.NewReader(partBuffer))
        req.Header.Set("Content-Range", "bytes "+strconv.Itoa(prev_part) + "-"+strconv.Itoa(sent-1)+"/"+strconv.FormatInt(fileSize,10))
        req.Header.Set("Content-Length", strconv.Itoa(partSize))
        res, _ := client.Do(req)
        prev_part = sent
        fmt.Println(res)

    }

}

Server 2
func UploadFileChunk(rw http.ResponseWriter,rq *http.Request) {

    fmt.Println(rq.Header["Content-Range"])
    cnt_range:=rq.Header["Content-Range"]
    file:=createFileByName("asd")
    if(checkFileChunkIndex(cnt_range[0])) {
        buf, err := ioutil.ReadAll(rq.Body)
        if err!=nil {log.Fatal("request",err)}

        file.Write(buf)
    } else {
        file.Close()
    }
}

func checkFileChunkIndex(cnt_r string ) bool {

    re := regexp.MustCompile(`([a-z]+) ([[:alnum:]]+)-([[:alnum:]]+)/([[:alnum:]]+)`)

    component:= re.FindStringSubmatch(cnt_r)

    filesize,_:= strconv.Atoi(component[4])
    last_chunk,_:= strconv.Atoi(component[3])
    return filesize - last_chunk - 1 > 0
}

func createFileByName(fname string ) *mgo.GridFile {
    if(!file_created) {
        _File,err:= db.GridFS("fs").Create("112233")
        File = *_File
        if err != nil {
            panic(err)
        }
        file_created = true
        return &File
    }
    return &File
}

For testing I have send a file with size 4mb, but after 3rd request , as a response I have got the following error

fatal error: sync: unlock of unlocked mutex

Here is the full error response
fatal error: sync: unlock of unlocked mutex

goroutine 7 [running]:
runtime.throw(0x144de3d, 0x1e)
    /usr/local/go/src/runtime/panic.go:596 +0x95 fp=0xc42004b8c0 sp=0xc42004b8a0
sync.throw(0x144de3d, 0x1e)
    /usr/local/go/src/runtime/panic.go:585 +0x35 fp=0xc42004b8e0 sp=0xc42004b8c0
sync.(*Mutex).Unlock(0xc4200ca8c0)
    /usr/local/go/src/sync/mutex.go:113 +0xa4 fp=0xc42004b908 sp=0xc42004b8e0
sync.(*Cond).Wait(0x162c4e8)
    /usr/local/go/src/sync/cond.go:56 +0x6c fp=0xc42004b938 sp=0xc42004b908
gopkg.in/mgo%2ev2.(*GridFile).insertChunk(0x162c4e0, 0xc42018a000, 0x3fc00, 0x40000)
    /Users/IT/go/src/gopkg.in/mgo.v2/gridfs.go:623 +0x1b3 fp=0xc42004ba48 sp=0xc42004b938
gopkg.in/mgo%2ev2.(*GridFile).Write(0x162c4e0, 0xc420678000, 0x40000, 0x7fe00, 0x40000, 0x0, 0x0)
    /Users/IT/go/src/gopkg.in/mgo.v2/gridfs.go:595 +0x2d6 fp=0xc42004baf0 sp=0xc42004ba48
go_storage/files.UploadFileChunk(0x15faf80, 0xc4202e4380, 0xc42000b000)
    /Users/IT/go/src/go_storage/files/files.go:249 +0x23b fp=0xc42004bba8 sp=0xc42004baf0
net/http.HandlerFunc.ServeHTTP(0x1459710, 0x15faf80, 0xc4202e4380, 0xc42000b000)
    /usr/local/go/src/net/http/server.go:1942 +0x44 fp=0xc42004bbd0 sp=0xc42004bba8
github.com/gorilla/mux.(*Router).ServeHTTP(0xc42001a320, 0x15faf80, 0xc4202e4380, 0xc42000b000)
    /Users/IT/go/src/github.com/gorilla/mux/mux.go:114 +0x10c fp=0xc42004bcd0 sp=0xc42004bbd0
net/http.(*ServeMux).ServeHTTP(0x162bee0, 0x15faf80, 0xc4202e4380, 0xc42000ae00)
    /usr/local/go/src/net/http/server.go:2238 +0x130 fp=0xc42004bd10 sp=0xc42004bcd0
net/http.serverHandler.ServeHTTP(0xc420096dc0, 0x15faf80, 0xc4202e4380, 0xc42000ae00)
    /usr/local/go/src/net/http/server.go:2568 +0x92 fp=0xc42004bd58 sp=0xc42004bd10
net/http.(*conn).serve(0xc4200cd2c0, 0x15fb7c0, 0xc420016ac0)
    /usr/local/go/src/net/http/server.go:1825 +0x612 fp=0xc42004bfc8 sp=0xc42004bd58
runtime.goexit()
    /usr/local/go/src/runtime/asm_amd64.s:2197 +0x1 fp=0xc42004bfd0 sp=0xc42004bfc8
created by net/http.(*Server).Serve
    /usr/local/go/src/net/http/server.go:2668 +0x2ce

goroutine 1 [IO wait]:
net.runtime_pollWait(0x23a0e40, 0x72, 0x0)
    /usr/local/go/src/runtime/netpoll.go:164 +0x59
net.(*pollDesc).wait(0xc4200556b8, 0x72, 0x0, 0xc4200bcee0)
    /usr/local/go/src/net/fd_poll_runtime.go:75 +0x38
net.(*pollDesc).waitRead(0xc4200556b8, 0xffffffffffffffff, 0x0)
    /usr/local/go/src/net/fd_poll_runtime.go:80 +0x34
net.(*netFD).accept(0xc420055650, 0x0, 0x15f6ec0, 0xc4200bcee0)
    /usr/local/go/src/net/fd_unix.go:430 +0x1e5
net.(*TCPListener).accept(0xc42000e0a0, 0xc4200cd340, 0x13c96c0, 0xffffffffffffffff)
    /usr/local/go/src/net/tcpsock_posix.go:136 +0x2e
net.(*TCPListener).AcceptTCP(0xc42000e0a0, 0xc420049df0, 0xc420049df8, 0xc420049de8)
    /usr/local/go/src/net/tcpsock.go:215 +0x49
net/http.tcpKeepAliveListener.Accept(0xc42000e0a0, 0x1459ca8, 0xc4200cd2c0, 0x15fb880, 0xc420019c80)
    /usr/local/go/src/net/http/server.go:3044 +0x2f
net/http.(*Server).Serve(0xc420096dc0, 0x15fb280, 0xc42000e0a0, 0x0, 0x0)
    /usr/local/go/src/net/http/server.go:2643 +0x228
net/http.(*Server).ListenAndServe(0xc420096dc0, 0xc420096dc0, 0x15f60c0)
    /usr/local/go/src/net/http/server.go:2585 +0xb0
net/http.ListenAndServe(0x143fbf7, 0x5, 0x0, 0x0, 0xc420110360, 0xc420019230)
    /usr/local/go/src/net/http/server.go:2787 +0x7f
main.main()
    /Users/IT/go/src/go_storage/main.go:24 +0x358

goroutine 17 [syscall, locked to thread]:
runtime.goexit()
    /usr/local/go/src/runtime/asm_amd64.s:2197 +0x1

goroutine 5 [select]:
gopkg.in/mgo%2ev2.(*mongoCluster).syncServersLoop(0xc42000a800)
    /Users/IT/go/src/gopkg.in/mgo.v2/cluster.go:394 +0x3a3
created by gopkg.in/mgo%2ev2.newCluster
    /Users/IT/go/src/gopkg.in/mgo.v2/cluster.go:78 +0x188

goroutine 22 [semacquire]:
sync.runtime_SemacquireMutex(0xc4200f20e4)
    /usr/local/go/src/runtime/sema.go:62 +0x34
sync.(*Mutex).Lock(0xc4200f20e0)
    /usr/local/go/src/sync/mutex.go:87 +0x9d
gopkg.in/mgo%2ev2.(*mongoSocket).Acquire(0xc4200f20e0, 0x0)
    /Users/IT/go/src/gopkg.in/mgo.v2/socket.go:242 +0x31
gopkg.in/mgo%2ev2.(*Session).acquireSocket(0xc4200e04e0, 0x0, 0x0, 0x0, 0x0)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:4419 +0x475
gopkg.in/mgo%2ev2.(*Collection).writeOp(0xc420019f20, 0x139efa0, 0xc4200e8000, 0x100e501, 0x0, 0x0, 0x0)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:4603 +0xd6
gopkg.in/mgo%2ev2.(*Collection).Insert(0xc420019f20, 0xc420010070, 0x1, 0x1, 0x0, 0x0)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:2437 +0xac
gopkg.in/mgo%2ev2.(*GridFile).insertChunk.func1(0x162c4e0, 0xc42033c000, 0x3fc3e, 0x40000)
    /Users/IT/go/src/gopkg.in/mgo.v2/gridfs.go:642 +0xe8
created by gopkg.in/mgo%2ev2.(*GridFile).insertChunk
    /Users/IT/go/src/gopkg.in/mgo.v2/gridfs.go:650 +0x460

goroutine 19 [sleep]:
time.Sleep(0x37e11d600)
    /usr/local/go/src/runtime/time.go:59 +0xf9
gopkg.in/mgo%2ev2.(*mongoServer).pinger(0xc4200f2000, 0x1)
    /Users/IT/go/src/gopkg.in/mgo.v2/server.go:301 +0x293
created by gopkg.in/mgo%2ev2.newServer
    /Users/IT/go/src/gopkg.in/mgo.v2/server.go:89 +0x166

goroutine 21 [semacquire]:
sync.runtime_SemacquireMutex(0xc4200f20e4)
    /usr/local/go/src/runtime/sema.go:62 +0x34
sync.(*Mutex).Lock(0xc4200f20e0)
    /usr/local/go/src/sync/mutex.go:87 +0x9d
gopkg.in/mgo%2ev2.(*mongoSocket).readLoop(0xc4200f20e0)
    /Users/IT/go/src/gopkg.in/mgo.v2/socket.go:582 +0x40a
created by gopkg.in/mgo%2ev2.newSocket
    /Users/IT/go/src/gopkg.in/mgo.v2/socket.go:194 +0x259

goroutine 9 [semacquire]:
sync.runtime_SemacquireMutex(0xc4202d2044)
    /usr/local/go/src/runtime/sema.go:62 +0x34
sync.(*Mutex).Lock(0xc4202d2040)
    /usr/local/go/src/sync/mutex.go:87 +0x9d
gopkg.in/mgo%2ev2.(*mongoSocket).SimpleQuery(0xc4200f20e0, 0xc4202e4000, 0x6, 0x143fbe3, 0x5, 0xc4202d2031, 0xb)
    /Users/IT/go/src/gopkg.in/mgo.v2/socket.go:367 +0x28b
gopkg.in/mgo%2ev2.(*Database).run(0xc4200bc8e0, 0xc4200f20e0, 0x13d0f00, 0xc4202d4040, 0x13cbb00, 0xc4202e2000, 0xc4200f2000, 0xc4200f20e0)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:3261 +0x1b3
gopkg.in/mgo%2ev2.(*Collection).writeOpCommand(0xc420019f20, 0xc4200f20e0, 0xc4200e2000, 0x139efa0, 0xc4202d6000, 0x1010001, 0x23685a8, 0x0, 0x100c420028638)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:4786 +0x1db
gopkg.in/mgo%2ev2.(*Collection).writeOp(0xc420019f20, 0x139efa0, 0xc4202d6000, 0x100e501, 0x0, 0x0, 0x0)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:4645 +0x6dc
gopkg.in/mgo%2ev2.(*Collection).Insert(0xc420019f20, 0xc4202d2000, 0x1, 0x1, 0x0, 0x0)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:2437 +0xac
gopkg.in/mgo%2ev2.(*GridFile).insertChunk.func1(0x162c4e0, 0xc420290000, 0x3fc3e, 0x40000)
    /Users/IT/go/src/gopkg.in/mgo.v2/gridfs.go:642 +0xe8
created by gopkg.in/mgo%2ev2.(*GridFile).insertChunk
    /Users/IT/go/src/gopkg.in/mgo.v2/gridfs.go:650 +0x460

goroutine 12 [semacquire]:
sync.runtime_SemacquireMutex(0xc4200e6074)
    /usr/local/go/src/runtime/sema.go:62 +0x34
sync.(*Mutex).Lock(0xc4200e6070)
    /usr/local/go/src/sync/mutex.go:87 +0x9d
gopkg.in/mgo%2ev2.(*mongoSocket).SimpleQuery(0xc4200f20e0, 0xc4202e40e0, 0x6, 0x143fbe3, 0x5, 0xc4200e6060, 0xb)
    /Users/IT/go/src/gopkg.in/mgo.v2/socket.go:367 +0x28b
gopkg.in/mgo%2ev2.(*Database).run(0xc4200bc8e0, 0xc4200f20e0, 0x13d0f00, 0xc4200ee080, 0x13cbb00, 0xc4202e2060, 0x2, 0xc42005e400)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:3261 +0x1b3
gopkg.in/mgo%2ev2.(*Collection).writeOpCommand(0xc420019f20, 0xc4200f20e0, 0xc4200e2000, 0x139efa0, 0xc420018d20, 0x1010001, 0x2304558, 0x46, 0x8700c420023638)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:4786 +0x1db
gopkg.in/mgo%2ev2.(*Collection).writeOp(0xc420019f20, 0x139efa0, 0xc420018d20, 0x100e501, 0x0, 0x0, 0x0)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:4645 +0x6dc
gopkg.in/mgo%2ev2.(*Collection).Insert(0xc420019f20, 0xc420010060, 0x1, 0x1, 0x0, 0x0)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:2437 +0xac
gopkg.in/mgo%2ev2.(*GridFile).insertChunk.func1(0x162c4e0, 0xc42013a000, 0x3fc3e, 0x40000)
    /Users/IT/go/src/gopkg.in/mgo.v2/gridfs.go:642 +0xe8
created by gopkg.in/mgo%2ev2.(*GridFile).insertChunk
    /Users/IT/go/src/gopkg.in/mgo.v2/gridfs.go:650 +0x460

goroutine 38 [IO wait]:
net.runtime_pollWait(0x23a0f00, 0x77, 0x4)
    /usr/local/go/src/runtime/netpoll.go:164 +0x59
net.(*pollDesc).wait(0xc4200fa068, 0x77, 0x15f84c0, 0x15f4540)
    /usr/local/go/src/net/fd_poll_runtime.go:75 +0x38
net.(*pollDesc).waitWrite(0xc4200fa068, 0xc420392ef2, 0x2edd1)
    /usr/local/go/src/net/fd_poll_runtime.go:84 +0x34
net.(*netFD).Write(0xc4200fa000, 0xc420382000, 0x3fcc3, 0x40000, 0x10ef2, 0x15f84c0, 0x15f4540)
    /usr/local/go/src/net/fd_unix.go:340 +0x34d
net.(*conn).Write(0xc4200ea008, 0xc420382000, 0x3fcc3, 0x40000, 0x0, 0x0, 0x0)
    /usr/local/go/src/net/net.go:193 +0x70
gopkg.in/mgo%2ev2.(*mongoSocket).Query(0xc4200f20e0, 0xc420181878, 0x1, 0x1, 0x0, 0x2)
    /Users/IT/go/src/gopkg.in/mgo.v2/socket.go:525 +0x2ad1
gopkg.in/mgo%2ev2.(*mongoSocket).SimpleQuery(0xc4200f20e0, 0xc4200f21c0, 0x6, 0x143fbe3, 0x5, 0xc420010631, 0xb)
    /Users/IT/go/src/gopkg.in/mgo.v2/socket.go:363 +0x22a
gopkg.in/mgo%2ev2.(*Database).run(0xc4200bc8e0, 0xc4200f20e0, 0x13d0f00, 0xc4202d4140, 0x13cbb00, 0xc4200f6000, 0x1444391, 0xc42002a800)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:3261 +0x1b3
gopkg.in/mgo%2ev2.(*Collection).writeOpCommand(0xc420019f20, 0xc4200f20e0, 0xc4200e2000, 0x139efa0, 0xc4200e8000, 0x1010001, 0x2306a28, 0x0, 0x800c4204a3e38)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:4786 +0x1db
gopkg.in/mgo%2ev2.(*Collection).writeOp(0xc420019f20, 0x139efa0, 0xc4200e8000, 0xc4200e6001, 0x0, 0x0, 0x0)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:4645 +0x6dc
gopkg.in/mgo%2ev2.(*Collection).Insert(0xc420019f20, 0xc4200e6000, 0x1, 0x1, 0x0, 0x0)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:2437 +0xac
gopkg.in/mgo%2ev2.(*GridFile).insertChunk.func1(0x162c4e0, 0xc4204d8000, 0x3fc3e, 0x40000)
    /Users/IT/go/src/gopkg.in/mgo.v2/gridfs.go:642 +0xe8
created by gopkg.in/mgo%2ev2.(*GridFile).insertChunk
    /Users/IT/go/src/gopkg.in/mgo.v2/gridfs.go:650 +0x460

goroutine 24 [semacquire]:
sync.runtime_SemacquireMutex(0xc4200f20e4)
    /usr/local/go/src/runtime/sema.go:62 +0x34
sync.(*Mutex).Lock(0xc4200f20e0)
    /usr/local/go/src/sync/mutex.go:87 +0x9d
gopkg.in/mgo%2ev2.(*mongoSocket).Acquire(0xc4200f20e0, 0x0)
    /Users/IT/go/src/gopkg.in/mgo.v2/socket.go:242 +0x31
gopkg.in/mgo%2ev2.(*Session).acquireSocket(0xc4200e04e0, 0x0, 0x0, 0x0, 0x0)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:4419 +0x475
gopkg.in/mgo%2ev2.(*Collection).writeOp(0xc420019f20, 0x139efa0, 0xc4202d6000, 0x100e501, 0x0, 0x0, 0x0)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:4603 +0xd6
gopkg.in/mgo%2ev2.(*Collection).Insert(0xc420019f20, 0xc4202d2010, 0x1, 0x1, 0x0, 0x0)
    /Users/IT/go/src/gopkg.in/mgo.v2/session.go:2437 +0xac
gopkg.in/mgo%2ev2.(*GridFile).insertChunk.func1(0x162c4e0, 0xc4205f8000, 0x3fc3e, 0x40000)
    /Users/IT/go/src/gopkg.in/mgo.v2/gridfs.go:642 +0xe8
created by gopkg.in/mgo%2ev2.(*GridFile).insertChunk
    /Users/IT/go/src/gopkg.in/mgo.v2/gridfs.go:650 +0x460

goroutine 14 [IO wait]:
net.runtime_pollWait(0x23a0d80, 0x72, 0x7)
    /usr/local/go/src/runtime/netpoll.go:164 +0x59
net.(*pollDesc).wait(0xc420055728, 0x72, 0x15f84c0, 0x15f4540)
    /usr/local/go/src/net/fd_poll_runtime.go:75 +0x38
net.(*pollDesc).waitRead(0xc420055728, 0xc420016b11, 0x1)
    /usr/local/go/src/net/fd_poll_runtime.go:80 +0x34
net.(*netFD).Read(0xc4200556c0, 0xc420016b11, 0x1, 0x1, 0x0, 0x15f84c0, 0x15f4540)
    /usr/local/go/src/net/fd_unix.go:250 +0x1b7
net.(*conn).Read(0xc42000e0a8, 0xc420016b11, 0x1, 0x1, 0x0, 0x0, 0x0)
    /usr/local/go/src/net/net.go:181 +0x70
net/http.(*connReader).backgroundRead(0xc420016b00)
    /usr/local/go/src/net/http/server.go:656 +0x58
created by net/http.(*connReader).startBackgroundRead
    /usr/local/go/src/net/http/server.go:652 +0xdf

Process finished with exit code 2

I have found that in the write  function there is a code look like this
file.assertMode(gfsWriting)
    file.m.Lock()
    debugf("GridFile %p: writing %d bytes", file, len(data))
    defer file.m.Unlock()

    if file.err != nil {
        return 0, file.err
    }

A: You are making a copy of the GridFile returned by GridFS.Create for no reason. Don't copy the struct, just return the pointer you are given.
GridFile contains private fields which cannot be copied, like a sync.Mutex and a sync.Cond. Running go vet on your code should catch these errors for you.


text:
Q: Help solving for log likelihood I need help solving the log-likelihood for the following problem:

The solution is below:

I'm curious about the steps to take in the process. I understand that we multiply the entire pmf n times, which gives us the n in the exponent, but I'm curious about where the x-bar and y-bar come from. Also, is this a common joint pmf?
Thanks!

A: So, for some PDF and observed datapoints, the likelihood function is simply the product of the PDF for each observed datapoint.
$L(\theta | x) = \prod_{x=1,..,n, y=1,..,n} f(x, y | \theta_1, \theta_2)$
The log likelihood is (you guessed it!) simply the log of the product of the PDF. Now, one property of logs is that log(xyz) = log(x) + log(y) + log(z). So, the loglikelihood can be expressed as the sum of log PDF, instead of the product of the PDF.
$$log(L(\theta | x)) = \sum_{x=1,...,n,y=1,...,n} log(f(x, y | \theta_1, \theta_2) $$
Now, we use this same property of logs to rewrite the PDF. I'm going to leave that to you, but you'll use two properties:
1) $log(a * b) = log(a) + log(b)$
2) $log(a^b) = b * log(a)$
Now, where does the $\bar{x}$ come in? Well, $\bar{x}$ is the average value for x. In this solution, it's really a convenient way of rewriting the sum of x. For any series x, $\sum x = n * \bar{x}$.


text:
Q: Prolog DCG: Writing programming language lexer I'm trying for the moment to keep my lexer and parser separate, based on the vague advice of the book Prolog and Natural Language Analysis, which really doesn't go into any detail about lexing/tokenizing. So I am giving it a shot and seeing several little issues that indicate to me that there is something obvious I'm missing.
All my little token parsers seem to be working alright; at the moment this is a snippet of my code:
:- use_module(library(dcg/basics)).

operator('(')  --> "(".      operator(')')  --> ")".
operator('[')  --> "[".      operator(']')  --> "]".
% ... etc.

keyword(array)    --> "array".
keyword(break)    --> "break".
% ... etc.

It's a bit repetitive but it seems to work. Then I have some stuff I don't completely love and would welcome suggestions on, but does seem to work:
id(id(Id)) -->
    [C],
    {
        char_type(C, alpha)
    },
    idRest(Rest),
    {
        atom_chars(Id, [C|Rest])
    }.
idRest([C|Rest]) -->
    [C],
    {
        char_type(C, alpha) ; char_type(C, digit) ; C = '_'
    },
    idRest(Rest).
idRest([]) --> [].

int(int(Int)) --> integer(Int).

string(str(String)) -->
    "\"",
    stringContent(Codes),
    "\"",
    {
        string_chars(String, Codes)
    }.
stringContent([C|Chars]) -->
    stringChar(C), stringContent(Chars).
stringContent([]) --> [].

stringChar(0'\n) --> "\\n".
stringChar(0'\t) --> "\\t".
stringChar(0'\") --> "\\\"".
stringChar(0'\") --> "\\\\".
stringChar(C) --> [C].

The main rule for my tokenizer is this:
token(X) --> whites, (keyword(X) ; operator(X) ; id(X) ; int(X) ; string(X)).

It's not perfect; I will see int get parsed into in,id(t) because keyword(X) comes before id(X). So I guess that's the first question.
The bigger question I have is that I do not see how to properly integrate comments into this situation. I have tried the following:
skipAhead --> [].
skipAhead --> (comment ; whites), skipAhead.

comment --> "/*", anything, "*/".
anything --> [].
anything --> [_], anything.

token(X) --> skipAhead, (keyword(X) ; operator(X) ; id(X) ; int(X) ; string(X)).

This does not seem to work; the parses that return (and I get many parses) do not seem to have the comment removed. I'm nervous that my comment rule is needlessly inefficient and probably induces a lot of unnecessary backtracking. I'm also nervous that whites//0 from dcg/basics is deterministic; however, that part of the equation seems to work, it's just integrating it with the comment skipping that doesn't seem to.
As a final note, I don't see how to handle propagating parse errors back to the user with line/column information from here. It feels like I'd have to track and thread through some kind of current line/column info and write it into the tokens and then maybe try to rebuild the line if I wanted to do something similar to how llvm does it. Is that fair or is there a "recommended practice" there?
The whole code can be found in this haste.

A: It currently still looks a bit strange  (unreadableNamesLikeInJavaAnyone?), but in its core it is quite solid, so I have only a few comments about some aspects of the code and the questions:

*

*Separating lexing from parsing makes perfect sense. It is also a perfectly acceptable solution to store line and column information along with each token, leaving tokens (for example) of the form l_c_t(Line,Column,Token) or Token-lc(Line,Column) for the parser to process.

*Comments are always nasty, or should I say, often not-nesty? A useful pattern in DCGs is often to go for the longest match, which you are already using in some cases, but not yet for anything//0. So, reordering the two rules may help you to skip everything that is meant to be commented away.

*Regarding the determinism: It is OK to commit to the first parse that matches, but do it only once, and resist the temptation to mess up the declarative grammar.

*In DCGs, it is elegant to use | instead of ;.

*tokenize//1? Come on! That's just tokens//1. It makes sense in all directions.

A: I have this code to support error reporting, that itself must be handled with care, sprinkling meaningful messages and 'skip rules' around the code. But there is not ready-to-use alternative: a DCG is a nice computation engine, but it cannot compete out-of-the-box with specialized parsing engines, that are able to emit error messages automatically, exploiting the theoretical properties of the targeted grammars...
:- dynamic text_length/1.

parse_conf_cs(Cs, AST)   :-
    length(Cs, TL),
    retractall(text_length(_)),
    assert(text_length(TL)),
    phrase(cfg(AST), Cs).
....
%%  tag(?T, -X, -Y)// is det.
%
%   Start/Stop tokens for XML like entries.
%   Maybe this should restrict somewhat the allowed text.
%
tag(T, X, Y) -->
    pos(X), unquoted(T), pos(Y).
....

%%  pos(-C, +P, -P) is det.
%
%   capture offset from end of stream
%
pos(C, P, P) :- text_length(L), length(P, Q), C is L - Q.

tag//3 is just an example usage, in this parser I'm building an editable AST, so I store the positions to be able to properly attribute each nested part in an editor...
edit
a small enhancement for id//1: SWI-Prolog has specialized code_type/2 for that:
1 ?- code_type(0'a, csymf).
true.

2 ?- code_type(0'1, csymf).
false.

so (glossing over literal transformation)
id([C|Cs]) --> [C], {code_type(C, csymf)}, id_rest(Cs).

id_rest([C|Cs]) --> [C], {code_type(C, csym)}, id_rest(Cs).
id_rest([]) --> [].

depending on your attitude to generalize small snippets, and the actual grammar details, id_rest//1 could be written in reusable fashion, and made deterministic
id([C|Cs]) --> [C], {code_type(C, csymf)}, codes(csym, Cs).

% greedy and deterministic
codes(Kind, [C|Cs]) --> [C], {code_type(C, Kind)}, !, codes(Kind, Cs).
codes(Kind, []), [C] --> [C], {\+code_type(C, Kind)}, !.
codes(_, []) --> [].

this stricter definition of id//1 would also allow to remove some ambiguity wrt identifiers with keyword prefix: recoding keyword//1 like
keyword(K) --> id(id(K)), {memberchk(K, [
    array,
    break,
...
]}.

will correctly identify
?- phrase(tokenize(Ts), `if1*2`).
Ts = [id(if1), *, int(2)] ;

Your string//1 (OT: what unfortunate clash with library(dcg/basics):string//1) is an easy candidate for implementing a simple 'error recovery strategy':
stringChar(0'\") --> "\\\\".
stringChar(0'") --> pos(X), "\n", {format('unclosed string at ~d~n', [X])}.

It's an example of 'report error and insert missing token', so the parsing can go on...


text:
Q: this.props is not a function in the componentDidUpdate() I'm facing a weird problem, there's probably a simple thing I didn't noticed but I'm not able to pass through this bug. Here's my case:
In the child, a counter is updated onClick. What I'm trying to do is fire a props function to togle the state of the parent.
In the child:
  componentDidUpdate(){
    if(this.state.counter === 3){
      return this.props.isFullBackgroundHomePage();
    }else{
      return;
    }
  }

In the parent:
  renderHomePage = () => {
    if(this.state.isHomePage
      && this.state.home_page !== null){
      return (
        <HomePage
          isFullBackgroundHomePage={this.isFullBackgroundHomePage}
          triggerSeeAllSection={this.triggerSeeAllSection}
          {...this.state}
        />
      )
    }else{
      return null;
    }
  }

  isFullBackgroundHomePage = () => {
    this.setState({
      isFullBackgroundHomePage: !this.state.isFullBackgroundHomePage
    })
  }

Now, this is what appears in the browser when the counter is at 3:
TypeError: this.props.isFullBackgroundHomePage is not a function
Link to the browser log: https://ibb.co/vcMW3wL

A: In
<HomePage
  isFullBackgroundHomePage={this.isFullBackgroundHomePage}
  triggerSeeAllSection={this.triggerSeeAllSection}
  {...this.state}
/>

you are overwriting prop isFullBackgroundHomePage using {...this.state} thus its not a function anymore rather a true/false boolean value at the consuming component. In your consuming component if you need both, you should rename state or prop value.
Very common issue unintentionally overwriting props using spread, gets the best of developer musing around what the heck is going on but to avoid such issues, consider using separate naming for function and state value to separate concerns.


text:
Q: Java applet for file upload(no limit).direct upload from local dorectory to server I want to make a java applet, it will update all the files in my local directory to a web server. There is no limit for files. I am new to making applets.
I have no applet interface.
I have some files in my c drive those should be uploaded directly in to web server.
This should be done automatically.

A: Because of java applet security restrictions, it is impossible to read the local files, because you don't want an applet uploading sensitive information, do you? If you want this to work, you have to sign the applet, and users have to agree to run the signed applet and give it more permissions.


text:
Q: laravel install getting key generate error in ubunto OS I am install "Laravel Framework version 5.2.26" but i am getting error for key generate in my ubuntu os
user@CN43:/var/www/html/laravel_1$ php artisan key:generate

  [ErrorException]
  file_get_contents(/var/www/html/laravel_1/.env): failed to open stream: No
  such file or directory

So i have check that directory .env file is not there but .env.example file only there so i created that file and update database name, database username, database password after that "php artisan key:generate" command is worked that key was generated above 32 characters and its get [base64:somethingsstrings with above 32 characters] i think some installation issues is there.
my laravel site is not opening. what i do mistake?

A: Run this command and make .env file from .env.example file:
cp .env.example .env
php artisan key:generate

Now it's generate the key. Don't create new .env file.

A: Rename .env.example to .env and fill all properties.

If you install Laravel via Composer, this file will automatically be
  renamed to .env. Otherwise, you should rename the file manually

https://laravel.com/docs/5.0/configuration#environment-configuration


text:
Q: Serving gzipped static resources (.gz files) I'm new to Salesforce and working on a Angular2 + SF web application. I'm serving my JS files via StaticResources.
main.js is quite big though (ng2 + app). I was planning to increase performance by using gzip compression. I'm able to upload .gz file to SF, but couldn't read its contents.
Is there any way to serve a .gz file via Static Resources? Any way to decompress it? Is it worth it?

A: Salesforce automatically applies compression to Static Resources. So there's no need for you to Gzip your Javascript files manually. You can just upload the originals.
In the screenshot below, you can see the compressed size for this JS file was 3.4KB, around half of the original 8.2KB. In the response headers, you can see the Content-Encoding: gzip header.
> GET https://c.na35.visual.force.com/resource/1480279804000/axios

< HTTP/1.1 200 OK
< P3P: CP="CUR OTR STA"
< Cache-Control: public
< Expires: Wed, 11 Jan 2017 20:51:22 GMT
< Content-Type: text/javascript;charset=UTF-8
< Last-Modified: Sun, 27 Nov 2016 20:50:04 GMT
< Content-Encoding: gzip
< Transfer-Encoding: chunked


text:
Q: Spring kafka multiple consumers result combination I have producer which produces some messages(10 for example).
There are n partitions and a consumer group with n consumers.
Kafka system will distribute the messages among the consumers.
How do I combine the messages of all the consumers in one place so that I have 10 messages.
I am using Kafka with Spring.

A: Create a consumer group with only one consumer, then you will get the records from all the partitions in one place.


text:
Q: QtAV in QT in QML i am using QtAV but getting this error so please help me:
QQmlApplicationEngine failed to load component
qrc:/main.qml:4 plugin cannot be loaded for module "QtAV": Cannot load library /home/intel/Qt5.7.0/5.7/gcc_64/qml/QtAV/libQmlAV.so: (libswresample.so.2: cannot open shared object file: No such file or directory)
at qrc:/main.qml:4 import QtAV1.6
using linux

A: The application cannot find your requested plugin.
You need to check if your import path is set correctly. If this is the case: please check if the plugin is installed correctly. You can use
export QML_IMPORT_TRACE=1

to check which import pathes are set.
And make sure, that all dependncies are installed as well. For instance libswresample ( see https://ffmpeg.org/libswresample.html )


text:
Q: Can't get UIImage to draw to the card front on the SuperCard example in cs193p I'm doing the ITunesU cs193p course. I'm trying to get the following code to draw the image to the card front, as shown in the example from SuperCard, but for some reason the image is not being drawn to the UIView.  Some help would be appreciated.
//using an image for the face of the card, i'm going to look it up to see if it exists

if (self.faceUp){
    UIImage *faceImage = [UIImage imageNamed:[NSString stringWithFormat:@"%@%@", [self rankAsString], self.suit]];

    NSLog(@"the faceImage is %@", faceImage);
    if (faceImage) {
    //i'm defining where and how big this is going to be   // the 1.0 - the scale factor, basically means 90% of the card size that i'm going to use
        CGRect imageRect =CGRectInset(self.bounds,
                                  self.bounds.size.width * (1.0-self.faceCardScaleFactor),
                                  self.bounds.size.height * (1.0-self.faceCardScaleFactor));

        [faceImage drawInRect:imageRect];

    } else {
        [self drawPips];
    }

I tried the following and got it to work using a dictionary:
if (self.faceUp){

    //renamed some png pictures and imported them into the Images.xcassets folder
    NSDictionary *cardImages=@{@"J":@"jack.png",@"Q":@"queen.png",@"K":@"king.png"};
    UIImage *faceImage = [UIImage imageNamed:[NSString stringWithFormat:@"%@", [cardImages        valueForKey:[self rankAsString]]]];
    if (faceImage) {. . . .

But I'm still not sure why the earlier code didn't pull in the images. For example, the name of the king of hearts image as shown in the Image.Xassets is "K♥".  When I downloaded the code from the Stanford site, I also couldn't get it to draw the image to the view, so I'm wondering if others have had this problem.
Thanks.

A: I had the same problem. I think I have selected different symbol or it was some sort of characters encoding issue. What fixed my problem was to rename the image with the same symbol I have inserted (copy-paste). Another decision is to get the same character from image filename and to use it in your code.

A: I had the same issue. This was because the suit if image name has different character set with the suit you use in the code. I renamed all image names with followed suit and it worked.
+ (NSArray *)validSuits
{
    return @[@"♥",@"♦",@"♠",@"♣"];
}


text:
Q: How to type double acute characters using compose I cannot find the compose key sequence for double acute vowels like ő, and I need them a lot when typing in Hungarian.
I don't want to switch to a Hungarian keyboard layout as I type in Dvorak and having to switch to qwerty/qwertz every now and then would not be easy.
The keys seem to be listed here, but I can't find a way to type them.

A: On my system ő is <compose> <=> <o>:
    $ grep "Multi.*DOUBLE ACUTE" /usr/share/X11/locale/en_US.UTF-8/Compose
    <Multi_key> <equal> <O>                 : "Ő"   U0150 # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE
    <Multi_key> <equal> <o>                 : "ő"   U0151 # LATIN SMALL LETTER O WITH DOUBLE ACUTE
    <Multi_key> <equal> <U>                 : "Ű"   U0170 # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE
    <Multi_key> <equal> <u>                 : "ű"   U0171 # LATIN SMALL LETTER U WITH DOUBLE ACUTE
    <Multi_key> <equal> <Cyrillic_U>        : "Ӳ"   U04F2 # CYRILLIC CAPITAL LETTER U WITH DOUBLE ACUTE
    <Multi_key> <equal> <Cyrillic_u>        : "ӳ"   U04F3 # CYRILLIC SMALL LETTER U WITH DOUBLE ACUTE

Make sure you have the basics of XCompose working before trying the more advanced ones or creating your own.


text:
Q: How to generate JSON and XML from same entity classes? I have the below class structure.
@XmlSeeAlso({Phone.class, Address.class})
abstract class ContactInfo {

}

@XmlRootElement(name="address")
class Address extends ContactInfo {
    private String street;

    public String getStreet() {
      return street;
    }

    public void setStreet(String street) {
      this.street = street;
    }
}

@XmlRootElement(name="phone")
class Phone extends ContactInfo {
    private String mobile;

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}

class Contact {
    private ContactInfo contact;

    @XmlElementRef
    public ContactInfo getContact() {
        return contact;
    }

    public void setContact(ContactInfo contact) {
        this.contact = contact;
    }
}

@XmlRootElement(name="user")
class User {
    private String name;
    private Contact contact;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Contact getContact() {
        return contact;
    }
    public void setContact(Contact contact) {
        this.contact = contact;
    }
}

When I convert this to XML using JAXB, I am getting the below structure.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user>
    <contact>
        <phone>
            <mobile>8971829749</mobile>
        </phone>
    </contact>
    <name>Halley</name>
</user>

Where as my JSON looks a bit different.
{
  "User" : {
    "name" : "Halley",
    "contact" : {
      "contact" : {
        "mobile" : "8971829749"
      }
    }
  }
}

The root element user, and phone is not at all present in my sub JSON structure.
While JAXB is honouring the XMLRootElement annotation, Jackson is not. Any idea why and how I can rectify this?
I need to generate JSON and XML from the same entity classes.

A: you can use

*

*@JsonRootName as class level annotation

*and ObjectMapper to configure serialization to use root element.

mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);

Using JsonRootName is optional unless you want to have different element name than XML.

A: As Jackson is ignoring the element name provided via @XmlRootElement, the Jackson annotations @JsonTypeInfo and @JsonSubTypes should be used to specify which ContactInfo type is Address or Phone. See https://stackoverflow.com/a/6543330/6911095 for an example.


text:
Q: How to create folder structure inside Azure Storage Container using PowerShell I have created the storage account along container in Azure using ARM templates. But I want to create folder structure inside the container using PowerShell script.
For example:
Folder1>SubFolder1>
Folder2>SUbFolder2>
…… etc
So, can anyone pls suggest me on this.

A: There are no directories inside Azure Storage Container. You can create a single container, and then, blobs inside of it.
Alternatively, you can use to include '/' in the blob name.
Eg:
account/container/2020/09/24/sample.txt
where "2020/09/24/sample.txt" is the blobname

A: You can't create the directories inside the Container
All blobs must reside in a blob container, which is simply a logical grouping of blobs. An account can contain an unlimited number of containers, and each container can store an unlimited number of blobs. You can include the / in the container name ("folder/1.txt"). You can create a folder structure
This SO thread may help you in your scenario
Creating an Azure Blob Hierarchy

A: You can create the folder structure using the below PowerShell Script.
#connecting to Storage account
$storageAccount = Get-AzStorageAccount -ResourceGroupName "<ResourceGroupName>"
-AccountName "<storage account>"
$ctx = $storageAccount.Context
# Passing Container name
$filesystemName = "<Container>"
# directory  to be created
$folders1= @('folder1/folder2/folder3','folder4/folder5/folder6')
$FolderArray = ""
for ($i = 0; $i -le ($folders1.length - 1); $i += 1){
    $dirname =""
    $path =""
    $filter=""
    $FolderArray =$folders1[$i].Split("/")
    for ($j = 0; $j -le ($FolderArray.length - 1); $j += 1){
        $dirname = $dirname+$FolderArray[$j]+"/"
        #print Directory name
        $dirname
        $path = $path + $(if ($j -eq 0) {"/"} else { "" })
        $filter =  $filter + $(if ($j -eq 0) {""} else { "/" })+ $FolderArray[$j]
        # Check the directory is exist or not
        $present = Get-AzDataLakeGen2ChildItem -Context
        $ctx -FileSystem $filesystemName -Path $path |
        Where-Object {$_.Name -eq "$($filter)"} -ErrorAction SilentlyContinue
        # Create directory
        if (! $present)
        {
            New-AzDataLakeGen2Item -Context $ctx -FileSystem
           $filesystemName -Path $dirname -Directory
            Write-Host "The directory $dirname is created"
        }
        # Show the existing folder
        else
        {
            Write-Host "Folder named  $dirname  already exists"
            Get-AzDataLakeGen2ChildItem -Context $ctx -FileSystem
            $filesystemName -Path $path
        }
        $path = $(if ($path -eq "/"){$FolderArray[$j]} else {""}) +
        $(if ($path -ne "/"){$path +"/"} else {""}) +
        $(if ($path -ne "/"){$FolderArray[$j]} else {""})

    }
}


text:
Q: How do you create an association table with an auto increment primary key in SQLAlchemy for Flask? I am trying to create a virtual version of the board game Mastermind in Flask. Since I need to store information about the current game state, I am using SQLAlchemy with SQLite to achieve this goal.
A game has a random generated code that the user has to guess. This code consists of various colors that could be duplicate. Because a color can be used for multiple games, it is a many-to-many relationship. So what I have done is created an association table between Game and Color.
game_colors = db.Table("game_colors",
    db.Column("id", db.Integer, primary_key=True),
    db.Column("game_id", db.Integer, db.ForeignKey("game.id")),
    db.Column("color_id", db.Integer, db.ForeignKey("color.id"))
)

I have added an id field as the primary key so that a color combination from a game can consist of duplicate colors. Now the strange part is that when I commit my changes to the database after adding a few duplicate colors to a game, they will not be saved. It seems like it is not making use of the id field at all.
How can I make the id field the primary key or make sure that I can store duplicate colors in this association table?

A: So what I did is change the Table to a Model.
class GameColor(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    game_id = db.Column(db.Integer, db.ForeignKey('game.id'), nullable=False)
    color_id = db.Column(db.Integer, db.ForeignKey('color.id'), nullable=False)

    game = db.relationship('Game', back_populates='game_colors')
    color = db.relationship('Color', back_populates='game_colors')

In this model the id field is actually being used and all duplicate records are saved after committing the changes. This solution is not as viable as I would have hoped, since you can't directly call all the colors a game may have. In this case you'd have to loop over game.game_colors and then call the color from each game_color.


text:
Q: How to add or disable(remove)md-disable-backdrop pragmatically in md-sidenav Is it possible to remove md-disable-backdrop attribute from HTML ?
The md-sidenav md-disable-backdrop attribute is not added when i open the side navigation. The i make a selection from the form i just displayed in the side navigation and now i want to add the md-disable-backdrop attribute to the md-sidenav
<md-sidenav md-component-id="right" class="md-sidenav-right md-whiteframe-4dp" md-disable-backdrop id="rightSideNav">

A: Here you go - CodePen
If you inspect the md-sidenav element you will see the md-disable-backdrop attribute toggled. Note: this won't toggle the backdrop, which is what I suspect you actually want.
Markup

  <md-content flex="" layout-padding="">

        <md-button ng-click="toggleRight()" ng-hide="isOpenRight($event)" class="md-primary">
          Toggle right
        </md-button>

  </md-content>
  <md-sidenav id="mySideNav" class="md-sidenav-right md-whiteframe-4dp" md-component-id="right">
    <md-content ng-controller="RightCtrl" layout-padding="">
      <md-button ng-click="close()" class="md-primary">
        Close Sidenav Right
      </md-button>
      <md-button ng-click="toggleMdDisableBackdrop()">Toggle md-disable-backdrop</md-button>
    </md-content>
  </md-sidenav>

JS
angular
  .module('MyApp',['ngMaterial'])
  .controller('AppCtrl', function ($scope, $mdSidenav, $element) {
    $scope.mdDisableBackdrop = false;
    $scope.sideNav = angular.element($element[0].querySelector('#mySideNav'));

    $scope.toggleRight = function() {
      $mdSidenav('right')
        .toggle()
        .then(function () {
      });
    }
  })
  .controller('RightCtrl', function ($scope, $mdSidenav) {
    $scope.close = function () {
      $mdSidenav('right').close();
    };

    $scope.toggleMdDisableBackdrop = function () {
      if ($scope.mdDisableBackdrop) {
        $scope.sideNav.removeAttr('md-disable-backdrop');
      }
      else {
        $scope.sideNav.attr("md-disable-backdrop", "true");
      }
      $scope.mdDisableBackdrop = !$scope.mdDisableBackdrop;
    };
  });


text:
Q: How to access Node instance object from outside process? I am trying to automate some testing for my web app using node + jsdom providing a headless browser instance. I spent a few days getting a node instance to join a session that was previously done manually via a test html stripped down page. This exposed the session object & its API to various test js files.
The issue right now is that Im not sure what's the best way to use this node instance to test my web app. The only immediate option I am seeing is to put the tests also on the node instance & have it set to run the tests after the session has been joined on node.
I have not done anything too advance with node before so I am wondering if there is a way to gain access to an node instance object from outside the process?
Or maybe there's a better way of doing this that I cannot see


text:
Q: query strings - use row ids or human readable values? I'm building a form and I wonder if there is a significant advantage in showing values in a more human readable format; e.g:

index.php?user=ted&location=newyork

Rather than:

index.php?user=23423&location=34645

On the one hand, having the query string a little more readable allows the user and search engines to better understand where they are, but this also creates a little more work on the server side, as I'll have to track down the associated rows through something other than their unique id.
For example, first find what the id of 'newyork' is before being able to work on other rows that require the location_id. I always prefer to give the db as little work as possible.
Edit: decided to go with readability. I figure I can always use the mysql query cache to speed things up if necessary.

A: Use human readable values when you can. Just be sure to sanitise the input.
Edit: Yes, this can and should still be done for SEO purposes (if its worth it to you) if you have lots of choices. Even if the user has lots of choices, you should know what they are (or what the limits are) so that you can properly sanitise the input. For instance, if they are choosing states, you can know all 50. If they are just making up their own text, make sure on your end that its only text.

A: A good rule of thumb is to store data as id's and display it as human readable text etc.

A: Depends on your goals.
If you are talking about something like a blog where you want everyone to see everthing (and find it easily), then the human/search engine readable format is a no brainer.
If these pages are locked behind a login then it doesn't much matter. You can do what is easier on the database.
For most internet apps, I'd err to the side of readability since that will help with search engines as well.

A: You shouldn't worry about the efficiency for any typically sized application on any reasonable database engine. Write your app for users, not for query optimizers. QO's can more easily take care of themselves. Deal with optimization in the unlikely event you start seeing a problem.

A: I am going to come from a different direction.  In my opinion a URL should be readable if want the user to be able to use the URL to change their parameters by editing the URL instead of using the UI.  An example would be https://www.coolreportingapp.com/accountReport.jsp?account=ABC&month=200911 .  In this example, the user can "easily" change the account or month they looking at without messing with the UI.  This of course means you need to validate the URL params each and every time, which you should do anyway.  If you don't want the user to alter the URL params, you need to obfuscate and hash values and use the hash to verify they haven't.

A: Seriously, IMHO, in your example, none is more readable than the other. Do normal users know that "&" is a separator from "variables" in "user=ted&location=newyork&"? Do they need to know that exists something like a variable? Having this in mind, what's the difference in showing numbers or words?
If you really want readable urls you should build SEO Friendly urls (human readable). Remember that even a "dashes vs underscores" simple question matters in the end.


text:
Q: Show that $|f(p_n)|<10^{-3}$ whenever $n>1$ but that $|p-p_n|<10^{-3}$ requires that $n>1000$. Let $f(x)=(x-1)^{10}$.
The root of the equation , $p=1$.
The approximates of the root, $p_n=1+\frac{1}{n}$
Show that $|f(p_n)|<10^{-3}$ whenever $n>1$ but that $|p-p_n|<10^{-3}$ requires that $n>1000$.
I started to solve it by the following way:
$|p-p_n|<10^{-3}\Rightarrow |1-(1+\frac{1}{n})|<10^{-3}\Rightarrow |\frac{1}{n}|<10^{-3}\Rightarrow |n|>1000\Rightarrow n>1000$
And
$f(p_n)=[(1+\frac{1}{n})-1]=\frac{1}{n}$; whenever $n>1$
But how to show
$|f(p_n)|<10^{-3}$ ?

A: You forgot the power of $10$ when you computed $f(p_n)$.

A: Show that $|f(pn)|<10^{-3}$ whenever $n>1$
$F(x)=(x-1)^{10}$ then $f(pn) =((1+1/n)-1)^{10} => |f(pn)| =(1/n)^{10}$
And $n>1$ then $|f(pn)| < = (1/2)^{10} = 1/1024$ and $1/1024 <10^{-3 }$


text:
Q: Real basic question about Sharepoint users I cannot seem to get how this is done.
I've read a bit about using AD, so I assume that Sharepoint can be set up to authenticate against AD?
Besides AD, is it possible to manually enter users and groups in Sharepoint to be used for authentication purposes?
Is it possible to use the two together?

A: Yes, you can use both AD users and groups to authenticate and authorize users inside of SharePoint.


text:
Q: Difficulty allocating dynamic URLs to pages from database I have a large number of mostly static pages which I've put into a database. I'm trying to retrieve these and dynamically generate a URL (similar to this: http://railscasts.com/episodes/117-semi-static-pages-revised. My model:
 class Page < ActiveRecord::Base

validates_uniqueness_of :permalink

  def to_param
    permalink
  end
end

Pages Controller:
class PagesController < ApplicationController
  before_action :set_page, only: [:show, :edit, :update, :destroy]

  # GET /pages
  # GET /pages.json
  def index
    @pages = Page.all
  end

  # GET /pages/1
  # GET /pages/1.json
  def show
    @page = Page.find_by_permalink!(params[:id])
  end

  # GET /pages/new
  def new
    @page = Page.new
  end

  # GET /pages/1/edit
  def edit
    @page = Page.find_by_permalink!(params[:id])
  end

  # POST /pages
  # POST /pages.json
  def create
    @page = Page.new(page_params)

    respond_to do |format|
      if @page.save
        format.html { redirect_to @page, notice: 'Page was successfully created.' }
        format.json { render :show, status: :created, location: @page }
      else
        format.html { render :new }
        format.json { render json: @page.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /pages/1
  # PATCH/PUT /pages/1.json
  def update
    respond_to do |format|
      if @page.update(page_params)
        format.html { redirect_to @page, notice: 'Page was successfully updated.' }
        format.json { render :show, status: :ok, location: @page }
      else
        format.html { render :edit }
        format.json { render json: @page.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /pages/1
  # DELETE /pages/1.json
  def destroy
    @page.destroy
    respond_to do |format|
      format.html { redirect_to pages_url, notice: 'Page was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_page
      @page = Page.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def page_params
      params.require(:page).permit(:name, :permalink, :content)
    end
end

Routes:
resources :pages, except: :show
resources :products
root to: 'products#index'
get ':id', to: 'pages#show', as: :page

I know there have been some updates on the way that rails generates scaffolds but I just can;t work out what needs to change to make this work? I'm getting errors thrown up both the routes, but was previously getting an error with  @page = Page.find_by_permalink!(params[:id])as well. It was saying that the method was missing but I couldn't see how. I also know I could use something like refinerycms but I really want to try and learn this stuff so any help much appreciated!
ERRORS FROM ROUTES:
Invalid route name, already in use: 'page' You may have defined two routes with the same name using the `:as` option, or you may be overriding a route already defined by a resource with the same naming. For the latter, you can restrict the routes created with `resources` as explained here: http://guides.rubyonrails.org/routing.html#restricting-the-routes-created

FULL TRACE:
ctionpack (4.1.5) lib/action_dispatch/routing/route_set.rb:430:in `add_route'
actionpack (4.1.5) lib/action_dispatch/routing/mapper.rb:1489:in `add_route'
actionpack (4.1.5) lib/action_dispatch/routing/mapper.rb:1466:in `decomposed_match'
actionpack (4.1.5) lib/action_dispatch/routing/mapper.rb:1447:in `block in match'
actionpack (4.1.5) lib/action_dispatch/routing/mapper.rb:1437:in `each'
actionpack (4.1.5) lib/action_dispatch/routing/mapper.rb:1437:in `match'
actionpack (4.1.5) lib/action_dispatch/routing/mapper.rb:630:in `map_method'
actionpack (4.1.5) lib/action_dispatch/routing/mapper.rb:591:in `get'
config/routes.rb:5:in `block in <top (required)>'
actionpack (4.1.5) lib/action_dispatch/routing/route_set.rb:337:in `instance_exec'
actionpack (4.1.5) lib/action_dispatch/routing/route_set.rb:337:in `eval_block'
actionpack (4.1.5) lib/action_dispatch/routing/route_set.rb:315:in `draw'
config/routes.rb:1:in `<top (required)>'
activesupport (4.1.5) lib/active_support/dependencies.rb:241:in `load'
activesupport (4.1.5) lib/active_support/dependencies.rb:241:in `block in load'
activesupport (4.1.5) lib/active_support/dependencies.rb:232:in `load_dependency'
activesupport (4.1.5) lib/active_support/dependencies.rb:241:in `load'
railties (4.1.5) lib/rails/application/routes_reloader.rb:40:in `block in load_paths'
railties (4.1.5) lib/rails/application/routes_reloader.rb:40:in `each'
railties (4.1.5) lib/rails/application/routes_reloader.rb:40:in `load_paths'
railties (4.1.5) lib/rails/application/routes_reloader.rb:16:in `reload!'
railties (4.1.5) lib/rails/application/routes_reloader.rb:26:in `block in updater'
activesupport (4.1.5) lib/active_support/file_update_checker.rb:75:in `call'
activesupport (4.1.5) lib/active_support/file_update_checker.rb:75:in `execute'
railties (4.1.5) lib/rails/application/routes_reloader.rb:7:in `execute'
railties (4.1.5) lib/rails/application/finisher.rb:83:in `block (2 levels) in <module:Finisher>'
activesupport (4.1.5) lib/active_support/callbacks.rb:438:in `instance_exec'
activesupport (4.1.5) lib/active_support/callbacks.rb:438:in `block in make_lambda'
activesupport (4.1.5) lib/active_support/callbacks.rb:184:in `call'
activesupport (4.1.5) lib/active_support/callbacks.rb:184:in `block in simple'
activesupport (4.1.5) lib/active_support/callbacks.rb:185:in `call'
activesupport (4.1.5) lib/active_support/callbacks.rb:185:in `block in simple'
activesupport (4.1.5) lib/active_support/callbacks.rb:185:in `call'
activesupport (4.1.5) lib/active_support/callbacks.rb:185:in `block in simple'
activesupport (4.1.5) lib/active_support/callbacks.rb:86:in `call'
activesupport (4.1.5) lib/active_support/callbacks.rb:86:in `run_callbacks'
actionpack (4.1.5) lib/action_dispatch/middleware/reloader.rb:83:in `prepare!'
actionpack (4.1.5) lib/action_dispatch/middleware/reloader.rb:71:in `call'
actionpack (4.1.5) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
actionpack (4.1.5) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
actionpack (4.1.5) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
railties (4.1.5) lib/rails/rack/logger.rb:38:in `call_app'
railties (4.1.5) lib/rails/rack/logger.rb:20:in `block in call'
activesupport (4.1.5) lib/active_support/tagged_logging.rb:68:in `block in tagged'
activesupport (4.1.5) lib/active_support/tagged_logging.rb:26:in `tagged'
activesupport (4.1.5) lib/active_support/tagged_logging.rb:68:in `tagged'
railties (4.1.5) lib/rails/rack/logger.rb:20:in `call'
actionpack (4.1.5) lib/action_dispatch/middleware/request_id.rb:21:in `call'
rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
rack (1.5.2) lib/rack/runtime.rb:17:in `call'
activesupport (4.1.5) lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call'
rack (1.5.2) lib/rack/lock.rb:17:in `call'
actionpack (4.1.5) lib/action_dispatch/middleware/static.rb:64:in `call'
rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
railties (4.1.5) lib/rails/engine.rb:514:in `call'
railties (4.1.5) lib/rails/application.rb:144:in `call'
rack (1.5.2) lib/rack/lock.rb:17:in `call'
rack (1.5.2) lib/rack/content_length.rb:14:in `call'
rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'
/usr/local/rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/webrick/httpserver.rb:138:in `service'
/usr/local/rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/webrick/httpserver.rb:94:in `run'
/usr/local/rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/webrick/server.rb:295:in `block in start_thread'
This error occurred while loading the following files:
   /home/ubuntu/workspace/traditional_cleaning/config/routes.rb


text:
Q: Opening iOS App from Custom URL in QRCode I want to open my app from a URL from QRScan , which is common when your custom URL looks like this "myappname://productid". my problem is that I want my app to open from a Website type URL which is something like this "https://myappname.com/productid"
How can i achieve this ?

A: This can be achieve by using universal links. For simplicity and high level implementation I will recommend you to use Firebase's dynamic link product. It is very well documented and more over its free to use.
Before you began I think you might need apple developer account.
Steps

*

*Create a project and an app on the firebase console.

*From the left menu under the Grow section select dynamic links.

*Create a domain as per your preferences e.g. https://yourapp.page.link

*Now goto apple developer portal and edit your app id and enable associated domains for it.

*Now open and select your xcode project under the project navigator section on the left side.

*Then goto signing and capabilities section and click on add capability

*Add the associated domains in you capabilities.

*Then Add your created domain in it like this: applinks:yourapp.page.link

*Make sure to add your team id and app id in the firebase console.

*Now depending on your requirement you can create fixed dynamic link through firebase console or alternatively you can use their api to create links. in case your link is user specific or you want to add unique info in each link.

*Now when someone click on the link depending on the platform the link behave accordingly as per the parameters provided during the link creation process.
These are just high level steps for detailed implementation and available options you can always refer to the dynamic link documentation


text:
Q: Linux USB stick shows white noise screen on machine with AMD graphics card I installed Kubuntu 18.04 on a flash drive (I had 2 flash drives, one with the installer ISO from which I installed linux onto the other one) on a machine with an NVIDIA graphics card (GTX770, i7 4770K). The idea was to have a portable persistent operating system.
The problem is, when I try to boot from the stick on another machine with an AMD graphics card (HD7870, i5 4570) it shows the Kubuntu splash screen followed by corrupted white noise.
I already tried the following parameters in the GRUB menu: radeon.nomodeset=0 and nomodeset xforcevesa acpi=off nolapic (basically a hail mary), the last one resulted in a persisent black screen (display was on though).
I did not install a proprietary NVIDIA driver (in fact I did not install any driver), so as far as I'm aware the kernel should just be able to load the suitable drivers, right? I also could not access other TTYs using CTRL+ALT+F1-9.


text:
Q: UTC Timestamp conversion I am working with an application where I have DateAndTimePicker, from which I can get date and time in a specified format. Now I need to convert this date and time string to UTC timestamp format. I tried a lot but couldn't find the solutions.
UTC format should be like this "2015-05-01T08:56:53.891Z"
I tried code like this
public static String getdateUTCFormat(String date, String time) {
    try {

        DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date utcDate = utcFormat.parse(date + time);

        Log.v("Date And Time-----------",utcDate.toString());
        return utcDate.toString();

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}


text:
Q: Select record if exist in one table, else select from another I'm writing a report for quotes. The quote table have a copy to track the change history, so every time someone change the quote table the old values are salved in this history table.
I want to include a field in my report named Original Due Date, which will show what is the original due date for the quote. If there is a record in the history table, it should get the first due date from there. Otherwise it should get the due date from the original table.
Here is some sample of the records I have in my tables.
Table 1:
|ID | Order  | Due Date   |
|1  | C1234  | 15/01/2000 |
|2  | C1235  | 15/02/2000 |
|3  | C1236  | 15/03/2000 |
|4  | C1237  | 15/04/2000 |

History Table:
|ID | Order  | Due Date   |
|1  | C1234  | 02/01/2000 |
|2  | C1234  | 05/01/2000 |
|3  | C1236  | 05/03/2000 |
|4  | C1236  | 07/03/2000 |

Expected results:
|ID | Order  | Original Due Date   |
|1  | C1234  | 02/01/2000          |
|2  | C1235  | 15/02/2000          |
|3  | C1236  | 05/03/2000          |
|4  | C1237  | 15/04/2000          |

This is the code I've tried, which does not work because my subquery return more than 1 value.
 select case when exists (select 1 from quoteheader qh inner join quoteheaderhistory qhh on QH.QH_RecordID = QHH.QH_RecordID)
        then (select QHH.QH_RFQ_Date from quoteheader qh inner join quoteheaderhistory qhh on QH.QH_RecordID = QHH.QH_RecordID)
        else QH.QH_RFQ_Date
        end,
    * from quoteheader qh inner join quoteheaderhistory qhh
          on QH.QH_RecordID = QHH.QH_RecordID

A: This should work:
DECLARE @tblO TABLE(ID INT,[Order] VARCHAR(10),DueDate DATE);
INSERT INTO @tblO VALUES(1,'C1234','20000115'),(2,'C1235','20000215'),(3,'C1236','20000315'),(4,'C1237','20000415');

DECLARE @tblH TABLE(ID INT,[Order] VARCHAR(10),DueDate DATE);
INSERT INTO @tblH VALUES(1,'C1234','20000102'),(2,'C1234','20000105'),(3,'C1236','20000305'),(4,'C1236','20000307');

WITH MinHistoricalDates AS
(
    SELECT MIN(DueDate) AS MinHistDat,[order]
    FROM @tblH
    GROUP BY [order]
)
SELECT orig.ID
      ,orig.[order]
      ,ISNULL(mhd.MinHistDat,orig.DueDate) AS DueDateResolved
FROM @tblO AS orig
LEFT JOIN MinHistoricalDates AS mhd ON mhd.[order]=orig.[order]

A: try:
select [Order],[DueDate] from quoteheader
where [Order] not in
(select [Order] from
(select [Order],MIN(DueDate) as DueDate
from quoteheaderhistory
group by [Order]) a
)

union all

select [Order],MIN(DueDate) as DueDate
from quoteheaderhistory
group by [Order]

although the join answer might work better for you, depending on your data

A: Here's what I was talking about in my comment:
DECLARE @A TABLE ([ID] INT, [Order] CHAR(5), [DueDate] DATE)
DECLARE @H TABLE ([ID] INT, [Order] CHAR(5), [DueDate] DATE)

INSERT INTO @A VALUES
(1, 'C1234', '01/15/2000'),
(2, 'C1235', '02/15/2000'),
(3, 'C1236', '03/15/2000'),
(4, 'C1237', '04/15/2000')

INSERT INTO @H VALUES
(1, 'C1234', '01/02/2000'),
(2, 'C1234', '01/05/2000'),
(3, 'C1236', '03/05/2000'),
(4, 'C1236', '03/07/2000')

SELECT
    [header].[ID],
    [header].[Order],
    [DueDate] = ISNULL(MIN([history].[DueDate]), MIN([header].[DueDate]))
FROM
    @A [header]
    LEFT JOIN @H [history] ON [header].[Order] = [history].[Order]
GROUP BY
    [header].ID, [header].[Order];

EDIT:  Shnugo's answer has a better execution plan, though; go with that one.

A: Alternatively, you could also do a left join and use windowed function version of MIN to achieve your result:
select distinct
     t1.id,
     t1.[order],
     COALESCE(min(ht.Due_Date) OVER (partition by t1.[order] order by t1.id)
    ,min(t1.due_date) OVER (partition by t1.[order] order by t1.id)) as Original Due Date
from table1 t1
left join history_table ht on ht.[Order] = t1.[Order];

SQL Fiddle Demo

A: Try this:
SELECT _order, min(due_date) as due_date
FROM history JOIN table1 USING (_order)
GROUP BY _order

This solution ignores the id, but you can easily generate after getting appropiate values.


text:
Q: how to connect asp.net core MVC project to local DB using Entity Framework Core on ubuntu desktop I'm Building an asp.net core application using Entity Framework Core on Ubuntu 16.04 desktop.
I have SQL Server installed and running.
I've run the command "-dotnet ef migrations Initial" successfully. I'm prepared to run "-dotnet ef database update" to allow EF to connect to and create the table in the database but I'm receiving this error on the terminal:

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: TCP
  Provider, error: 25 - Connection string is not valid)

it's a local DB so I'm thinking I don't need a TCP provider, right?
how do I tell EF to connect to SQL server?

A: Specify your connection string on appsettings.json file
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=YOUR_SERVER_NAME;Database=DBNAME;User Id=sa;Password=PASSWORD;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}


text:
Q: Azure web apps auto-swap notifications I'm using a deployment slot called warmup on my Azure web app with the auto-swap feature. My deployment process is as follows:

*

*Octopus Deploy creates a release and deploys to the warmup slot

*Auto-swap warms up the slot and swaps to production as soon as the app is warmed up

Is there a way to get notified when an auto-swap operation finishes? I'd like to get notified both when the operation succeeds or when it fails.

A: You can add post-deployment web hooks via the kudu site: https://<yoursite>.scm.azurewebsites.net/WebHooks
I don't think this will notify you of the swap, but it'll at least let you know the deployment completed successfully.
You can find more details here:
http://blogs.msdn.com/b/webdev/archive/2015/10/04/receive-webhooks-from-azure-alerts-and-kudu-azure-web-app-deployment.aspx
If you'd like to get notified of an auto-swap operation specifically you can submit a feature request here:
http://feedback.azure.com/forums/169385-web-apps-formerly-websites