text:
Q: Securing application with AspectJ vs SpringInterceptor This is a very tricky question, and I know it. Well, I'll do my best to clarify it.
I'm writing an API in Spring secured under JWTs and OAuth2 and I don't want to use the Spring Security layer. In other words, I want to create my own security layer with my own rules, etc...
That said, I've found two options to create this layer web abroad.

*

*AspectJ

*Spring Interceptors

AspectJ
With AspectJ I can create an aspect to wrap every method annotated with @MySecurityAnnotation(role="bar", permission="foo", group="blah") and grant that no user would invoke the joinPoint without the correct permission.
With this approach, the code got obfuscated because the AspectJ inject code to the .class final files. (please, correct me if I'm saying nonsense). On the other hand, I don't need to verify via reflection for the annotated types because the code is already wrapped.

Spring Interceptor
With the interceptor, as the name says, is created a single point of interception for every HandlerMethod and now I need to check in every request if the request points to a HandlerMethod as it should be in order to verify the users credentials.
So I think that this is slowly then the AspectJ implementation, because we need to check via reflection for the annotated methods to get the roles/permissions needed to access the endpoint.

Ok, I've explained both scenarios, now I just want to know which one would be the best and in which situation. There's someone who spend hours thinking about that, like me? Is there any other implementation not listed? Is there a better way to implement security in a Spring API without Spring Security layer? Please let me know.
Thanks for all that help.


text:
Q: Given 3 cross products of 3 vectors, how do you solve an expression of this format? If you're given:
$$a \times b = (2, -4, 2),\quad a \times c = (7, 13, -11),\quad b \times c = (1, 7, 1)$$
what properties of cross products or formulas can you use to solve $(2b - c) \times (3a + 5c)$?
I want to utilize how there is a $c$ common to both vector arithmetics but I am not sure how.

A: Just break it into pieces, using $a\times(b+c)=a\times b+a\times c$.
What do you know that relates $a\times b$ with $b\times a$?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the value only from the Hashtable in PowerShell? If I have a hastable $states = @{ 1 = 15; 2 = 5; 3 = 41 }, The result shows
Name                           Value
----                           -----
3                              41
2                              5
1                              15

I used $states.GetEnumerator() | sort value -Descending | select -Last 1 to find the minimum value that I need.
The result is:
Name                           Value
----                           -----
2                              5

However, I cannot use the value (5) as a new variable to do a calculation. This is due to the result cotains both name and value. Is there any method to get the minimum value only from the result?

A: Use the .Values property from the beginning:
$states.Values | Sort-Object -Descending | Select-Object -Last 1

Or expand the .Value property:
$states.GetEnumerator() | sort value -Descending | select -Last 1 -ExpandProperty Value


text:
Q: gem install error - json !Note : I have the latest compatible development kit downloaded and extracted.
Please help me how to solve it. Thanks

A: Try this -
 sudo gem install json --platform=ruby --verbose

A: Try,
gem install json --platform=ruby

And follow Development Kit steps


text:
Q: ssh: Allow root to login without password i want to login via ssh without password using root account.
I have problem with /etc/ssh/sshd_config file.
I set: PermitRootLogin without-password and StrctMode no but it doesn't work (i have to enter passphrase to key)
I have Ubuntu 16.04.

A: First the option "PermitRootLogin without-password" does not do what you think it does. This option does not allow you to log in without a password, it allows you to log in as root via any method other then password authentication.
Typically this would be ssh keys, but could include other methods such as kerberos.
Second, I highly suggest you continue to login as root with a key with a password. If you do not want to enter a password every time, add it to ssh agent. On the command line this would be ssh-add ~/.ssh/key_name. This is a one time entry of your key password and subsequently you do not need to enter a password.
After the above command you can simply
ssh root@server

If you want a key without a password , make a new key with an empty password on the client machine.
ssh-keygen

When it asks you for a password, just hit the Enter key without entering a password.
I suggest you give it a name rather then using the default.
You transfer the key with ssh-copy-id (you will need to log in to the server as root with a password to transfer the key).
ssh-copy-id -i ~/.ssh/your_key.pub root@server

You can then ssh in without a password
ssh -i ~/.ssh/your_key root@server

Once the key is working, go ahead and disable password authentication again.


text:
Q: Ruby regex for matching simpliest Ruby's regexes I want to match regexes (at least the basic ones, not all their possible kinds... for now...) in a text of Ruby script.
It's something like a... \/\^? oh my god... \$?\/[eimnosux]*
Maybe I need recursive regex here.

A: As I commented above, you'll need to parse Ruby to differentiate division slashes and regex delimiters. But for the simplest, SIMPLEST case without worrying about this, how about:
regex_match = %r{/(?:[^/\\]|\\.)+/[mgixo]*}

That is "A forward slash, followed by one or more things that either aren't a forward slash or a backslash, or are a backslash followed by something else, finally followed by a slash, and possibly some regex flags."


text:
Q: Get Hash "bytesize" in Crystal Lang My bad, there's no Hash#bytesize in Ruby.
I was wondering if there's a way to measure the size of any object, hash, or array.
EDIT#2 : Evaluation of comments
Benchmark does not seem to be deep measuring all instantiations.
require "benchmark"

class Animal
  def initialize
    @first_name = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    @last_name = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    @arr = Array(Int32).new
  end
end

struct Foobar
  property hola
end

animal = Benchmark.memory do
  Animal.new
end

puts "Animal used: #{animal}"

foobar = Benchmark.memory do
  Foobar.new
end

puts "Foobar used: #{foobar}"

array = Benchmark.memory do
  Array(Int32).new
end

puts "Array used: #{array}"

string = Benchmark.memory do
  String.new() + "Hello"
end

puts "String used: #{string}"

Outputs:
Animal used: 80
Foobar used: 0
Array used: 32
String used: 32

EDITED
Is there an equivalent for Ruby's Hash#bytesize in Crystal lang?
Ultimately, I would like to be able to measure the size of any object, hash, or array.


text:
Q: Corosync error "No interfaces defined" in a cluster member I am having an error starting corosync on a cluster member:
May 16 00:53:32 neftis corosync[19741]:  [MAIN  ] Corosync Cluster Engine ('2.3.4'): started and ready to provide service.
May 16 00:53:32 neftis corosync[19741]:  [MAIN  ] Corosync built-in features: dbus systemd xmlconf snmp pie relro bindnow
May 16 00:53:32 neftis corosync[19741]:  [MAIN  ] parse error in config: No interfaces defined
May 16 00:53:32 neftis corosync[19741]:  [MAIN  ] Corosync Cluster Engine exiting with status 8 at main.c:1278.
May 16 00:53:32 neftis corosync: Starting Corosync Cluster Engine (corosync): [FALL�]
May 16 00:53:32 neftis systemd: corosync.service: control process exited, code=exited status=1
May 16 00:53:32 neftis systemd: Failed to start Corosync Cluster Engine.
May 16 00:53:32 neftis systemd: Unit corosync.service entered failed state.
May 16 00:53:32 neftis systemd: corosync.service failed.
May 16 00:54:06 neftis systemd: Cannot add dependency job for unit firewalld.service, ignoring: Unit firewalld.service is masked.
May 16 00:54:06 neftis systemd: Starting Corosync Cluster Engine...
May 16 00:54:06 neftis corosync[19773]:  [MAIN  ] Corosync Cluster Engine ('2.3.4'): started and ready to provide service.
May 16 00:54:06 neftis corosync[19773]:  [MAIN  ] Corosync built-in features: dbus systemd xmlconf snmp pie relro bindnow
May 16 00:54:06 neftis corosync[19773]:  [MAIN  ] parse error in config: No interfaces defined
May 16 00:54:06 neftis corosync[19773]:  [MAIN  ] Corosync Cluster Engine exiting with status 8 at main.c:1278.
May 16 00:54:06 neftis corosync: Starting Corosync Cluster Engine (corosync): [FALL�]
May 16 00:54:06 neftis systemd: corosync.service: control process exited, code=exited status=1
May 16 00:54:06 neftis systemd: Failed to start Corosync Cluster Engine.
May 16 00:54:06 neftis systemd: Unit corosync.service entered failed state.

Here is my config on the three nodes but it is failing just in netfis which I added recently.
totem {
    version: 2
    secauth: off
    cluster_name: cluster-osiris
    transport: udpu
}

nodelist {
    node {
        ring0_addr: isis.localdoamin
        nodeid: 1
    }

    node {
        ring0_addr: horus.localdoamin
        nodeid: 2
    }

    node {
        ring0_addr: netfis.localdoamin
        nodeid: 3
    }
}

quorum {
    provider: corosync_votequorum
}

logging {
    to_syslog: yes
}

I am running a pacemaker, corosync, pcs cluster on CentOS 7.1 64. bits.
I searched on internet but It is not clear what is going on.
Could you help me?

A: Do the hostnames you have listed in your Corosync configuration resolve correctly? I would start by verifying that.
# host isis.localdoamin

Since, "domain", appears to be spelled incorrectly (or in a language I am ignorant of), I am going to guess that command fails? ;-)
Also, you could use the short hostname (without ".localdomain") or the IP addresses of the interfaces you'd like Corosync to bind to instead.

A: Had this error message because of proxmox added a record on loopback ip for my container hostname in /etc/hosts like that:
# --- BEGIN PVE ---
127.0.1.1 pgmaster
# --- END PVE ---

I have one more record in hosts for this name. Commented out loopback record and it is ok now.


text:
Q: Change price and calculate by quantity flutter I want to change the price according to the quantity contained in the item, but I get a problem like this where the price is not displayed. price in widget text RP not show from response, the price that should appear is the price that appears in the response log run console, Now it only shows - and also the price doesn't change

import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'package:sobatprambanan_app/model/cart.dart';
import 'package:http/http.dart' as http;

class CartPage extends StatefulWidget {
  // const CartPage({Key key}) : super(key: key);

  // String img;
  String name;
  // String description;
  String price;
  String deviceId;
  String unit;
  String quantity;

  CartPage({Key key, this.name, this.price, this.deviceId, this.unit, this.quantity}) : super(key: key);

  @override
  _CartPageState createState() => _CartPageState();
}

class _CartPageState extends State<CartPage> {

  String deviceUniqueID = "Unknown";
  loadSharedPrefs() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      deviceUniqueID = (prefs.getString("deviceID")??"");
      print("Ini line 30: $deviceUniqueID");
    });
  }
  List<Cart> dataCart = [];
  Future<Map<String, dynamic>> getDataItems() async {
     var urlGetTransaksi = "http://192.168.0.13:8891/api/Transaksi/";
     SharedPreferences prefs = await SharedPreferences.getInstance();
     String salesmanID = prefs.getString("deviceID");
    final response = await http.get(Uri.parse(urlGetTransaksi+salesmanID));
    List<Cart> listItems = (json.decode(response.body)as List).map((e) => Cart.fromJson(e)).toList();
    for (int i = 0 ; i <listItems.length; i++){
      int number = listItems[i].quantity;
      _count.add(number);
    }
    this.setState(() {
      print(response);
      print("Ini 28: ${response.body}");
      print(listDataCartItems);
      dataCart = listItems;
      // result;
    });
  }
  List<Widget> listDataCartItems = [];

  RefreshController _refreshController =
  RefreshController(initialRefresh: false);

  List data;
  void _onRefresh() async{
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    getDataItems();
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }

  void _onLoading() async{
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    data.add((data.length+1).toString());
    if(mounted)
      setState(() {
        getDataItems();
      });
    _refreshController.loadComplete();
  }

 List<int> _count = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // getDataItems();
    loadSharedPrefs();
    getDataItems();

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.white,
        leading: IconButton(
          icon: Icon(
            Icons.chevron_left,
            color: Colors.black,
          ),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 11.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    "My Order",
                    style: Theme.of(context)
                        .textTheme
                        .display1
                        .apply(fontWeightDelta: 2, color: Colors.black),
                  ),
                  SizedBox(
                    height: 5.0,
                  ),
                  Expanded(
                    child: SmartRefresher(
                      enablePullDown: true,
                      enablePullUp: false,
                      header: WaterDropHeader(),
                      footer: CustomFooter(
                        builder: (BuildContext context,LoadStatus mode) {
                          Widget body;
                          if(mode==LoadStatus.idle) {
                            body = Text("pull up load");
                          }
                          else if(mode==LoadStatus.loading){
                            body =  CupertinoActivityIndicator();
                          }
                          else if(mode == LoadStatus.failed){
                            body = Text("Load Failed!Click retry!");
                          }
                          else if(mode == LoadStatus.canLoading){
                            body = Text("release to load more");
                          }
                          else{
                            body = Text("No more Data");
                          }
                          return Container(
                            height: 55.0,
                            child: Center(child:body),
                          );
                        },
                      ),
                      controller: _refreshController,
                      onRefresh: _onRefresh,
                      onLoading: _onLoading,
                      child: new ListView.builder(
                        itemCount: dataCart == null ? 0 : dataCart.length,
                        itemBuilder: (BuildContext context, int index) {
                          return new Container(
                            padding: EdgeInsets.all(7),
                            child: Card(
                              elevation: 3,
                              clipBehavior: Clip.antiAlias,
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.stretch,
                                children: [
                                  Container(
                                    padding: EdgeInsets.all(6),
                                    alignment: Alignment.centerLeft,
                                    child: Image.asset(
                                      "assets/images/promo1.png",
                                      height: 50,
                                      width: 50,
                                    ),
                                  ),
                                  Container(
                                    padding: EdgeInsets.all(6),
                                    alignment: Alignment.centerLeft,
                                    child: Text(
                                      dataCart[index].itemName??"",
                                      textAlign: TextAlign.left,
                                      style: TextStyle(
                                        color: Colors.blue,
                                        fontSize: 12,
                                      ),
                                    ),
                                  ),
                                  Container(
                                    padding: EdgeInsets.all(6),
                                    alignment: Alignment.centerLeft,
                                    child: Text(
                                      "Rp. ${dataCart[index].price}"??"",
                                      textAlign: TextAlign.left,
                                      style: TextStyle(
                                        fontSize: 12,
                                        color: Colors.blue,
                                      ),
                                    ),
                                  ),
                                  Center(
                                    child: Container(
                                      height: 5,
                                      child: Divider(
                                        thickness: 1,
                                        color: Colors.orange,
                                        indent: 5,
                                        endIndent: 5,
                                      ),
                                    ),
                                  ),
                                  SizedBox(
                                    height: 5,
                                  ),
                                  //Ini row button
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                    children: [
                                      //menambah quantity
                                      Center(
                                        child: GestureDetector(
                                          onTap: () {
                                            setState(() {
                                              _count[index] += 1;
                                              dataCart[index].price*=_count[index];
                                            });
                                          },
                                          child: Container(
                                            padding: const EdgeInsets.all(3),
                                            decoration: BoxDecoration(
                                              shape: BoxShape.rectangle,
                                              border: Border.all(),
                                            ),
                                            child: Icon(Icons.add,size: 12,),
                                          ),
                                        ),
                                      ),
                                      Center(
                                        child: Container(
                                          height: 60,
                                          child: VerticalDivider(
                                            thickness: 2,
                                            color: Colors.orange,
                                            endIndent: 20,
                                            indent: 5,
                                          ),
                                        ),
                                      ),
                                      Center(
                                        child: Container(
                                          height: 30,
                                          child: InkWell(
                                              child: Text(
                                                _count[index].toString()??"",
                                                style: TextStyle(
                                                  color: Colors.blue,
                                                ),
                                              ),
                                              onTap: () {}),
                                        ),
                                      ),
                                      Center(
                                        child: Container(
                                          height: 60,
                                          child: VerticalDivider(
                                            thickness: 2,
                                            color: Colors.orange,
                                            endIndent: 20,
                                            indent: 5,
                                          ),
                                        ),
                                      ),
                                      //mengurangi quantity
                                      GestureDetector(
                                        onTap: () {
                                          setState(() {
                                            _count[index]-= 1;
                                            dataCart[index].price -=_count[index];
                                          });
                                        },
                                        child: Container(
                                          padding: const EdgeInsets.all(3.0),
                                          decoration: BoxDecoration(
                                            shape: BoxShape.rectangle,
                                            border: Border.all(),
                                          ),
                                          child: Icon(Icons.remove,size: 12,),
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            child: Container(
              padding: EdgeInsets.all(15.0),
              color: Colors.grey[100],
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    "Payment",
                    style: Theme.of(context).textTheme.title,
                  ),
                  Expanded(
                    child: Container(
                      padding: const EdgeInsets.symmetric(vertical: 15.0),
                      child: ListView(
                        scrollDirection: Axis.horizontal,
                        shrinkWrap: true,
                        children: <Widget>[
                          ...List.generate(1, (i) {
                            return Container(
                              padding: const EdgeInsets.all(15.0),
                              margin: const EdgeInsets.only(right: 15),
                              alignment: Alignment.topLeft,
                              width: MediaQuery.of(context).size.width / 3,
                              decoration: BoxDecoration(
                                color: Colors.black,
                                borderRadius: BorderRadius.circular(5.0),
                              ),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Text(
                                    "**** 4832",
                                    style: Theme.of(context)
                                        .textTheme
                                        .title
                                        .apply(color: Colors.white),
                                  ),
                                  Spacer(),
                                  Text(
                                    "\$25.99",
                                    style:
                                    Theme.of(context).textTheme.title.apply(
                                      color: Colors.white,
                                    ),
                                  ),
                                  Image.asset("assets/images/mastercard.png"),
                                ],
                              ),
                            );
                          }),
                          InkWell(
                            onTap: () {},
                            child: Container(
                              margin: const EdgeInsets.symmetric(
                                vertical: 15.0,
                              ),
                              alignment: Alignment.center,
                              width: MediaQuery.of(context).size.width / 3,
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(5)),
                              child: Icon(Icons.add),
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                  SizedBox(height: 10,),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "Total Price",
                        style: Theme.of(context).textTheme.headline5,
                      ),
                      Text(
                        "RP. 20.000.000",
                        style: Theme.of(context).textTheme.headline5,
                      ),
                    ],
                  ),
                  SizedBox(height: 10,),
                  Container(
                    height: 50,
                    width: double.infinity,
                    child: RaisedButton(
                      child: Text(
                        "Confirm Payment",
                        style: Theme.of(context)
                            .textTheme
                            .button
                            .apply(color: Colors.white),
                      ),
                      onPressed: () {},
                      color: Colors.green,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(5.0),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}


text:
Q: How to make a matrix squared by filling it with zeroes in C I am currently trying to complete a m by n matrix (where m is greater than or equal to n) by filling it with columns of zeroes. The main problem is that my matrix is stored inside a double* and not a double**. So instead of my matrix looking like a 2d matrix it actually is a vector that sticks the rows of the matrix together in a single line.
Here is my poor attempt (I am quite new to the C programming language...)
void square_my_matrix(double* A, int n){//m is a global variable
    for(int i = 0; i < m; i++){
        for(int j = 0; j < m; j++){
            if(i*m+j > j*m+n) continue;
            else A[i*m+j] = 0.0;
}

int main(){
    double* A;
    A = malloc(m*n*sizeof(*A));
    buildMatrix(); //this fills my matrix with some data
    printMatrix(m,n,A); //this prints my matrix in a 2d fashion to make it clearer

    if(m>n){
        A = realloc(A, m*m*sizeof(*A));
        square_my_matrix(A, n);
    }
    printMatrix(m,m,A);
}

My first printMatrix gives
1.00 1.00
1.00 3.00
1.00 5.00
1.00 7.00

And after calling square_my_matrix I expect (when calling printMatrix again)
1.00 1.00 0.00 0.00
1.00 3.00 0.00 0.00
1.00 5.00 0.00 0.00
1.00 7.00 0.00 0.00

but I get this instead
1.00 1.00 1.00 3.00
0.00 5.00 1.00 7.00
0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00

I probably messed up something obvious but I can't figure out what.
Thank you for your help

A: Zeroing Added Memory (New Rows)
If I understand what you are doing, you can originally initialize all values in A to 0 by using calloc instead of malloc (which will set all bytes zero). Then following your realloc you can use memset() to zero the new memory you have allocated. (if you need to zero the added columns, then see the 2nd part of this answer)
You can zero the new memory allocated with realloc() with, e.g.
double*A;
A = calloc (m * n, sizeof *A);
if (A == NULL) {          /* validate EVERY allocation */
    perror ("calloc-A");
    exit (EXIT_FAILURE);
}

buildMatrix(); //this fills my matrix with some data
printMatrix(m,n,A); //this prints my matrix in a 2d fashion to make it clearer

if (m > n) {
    void *tmp = realloc (A, m * m * sizeof *A);  /* ALWAYS realloc with a temporary pointer */
    if (!tmp) {           /* validate EVERY allocation */
        perror ("realloc-A");
        exit (EXIT_FAILURE);
    }
    A = tmp;              /* assign reallocated block */
    /* set new memory zero */
    memset (A + m * n, 0, m * (m - n) * sizeof *A);

    // square_my_matrix(A, n);
}
printMatrix(m,m,A);

If you did want to use square_my_matrix(), then you would remove memset() above and use:
void square_my_matrix (double* A, int n)
{
    for (int i = n; i < m; i++)
        for (int j = 0; j < m; j++)
                A[i * m + j] = 0.0;
}

A short example putting it altogether and allowing you to choose between memset() by passing -DWMEMSET as a define, or by default using square_my_matrix(), you could do:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define m      10
#define nbegin  8

void square_my_matrix (double* A, int n)
{
    for (int i = n; i < m; i++)
        for (int j = 0; j < m; j++)
                A[i * m + j] = 0.0;
}

void printMatrix (int rows, int cols, double *A)
{
    /* check overflow in multiplication of rows * cols here */

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++)
            printf (" %3g", A[i * cols + j]);
                putchar ('\n');
    }
}

int main (void) {

    int n = nbegin,
        v = 1;
    double *A;

    A = calloc (m * n, sizeof *A);
    if (A == NULL) {          /* validate EVERY allocation */
        perror ("calloc-A");
        exit (EXIT_FAILURE);
    }

    // buildMatrix(); //this fills my matrix with some data
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            A[i * n + j] = v++;

    printMatrix (m,n,A); //this prints my matrix in a 2d fashion to make it clearer

    if (m > n) {
        /* ALWAYS realloc with a temporary pointer */
        void *tmp = realloc (A, m * m * sizeof *A);
        if (!tmp) {           /* validate EVERY allocation */
            perror ("realloc-A");
            exit (EXIT_FAILURE);
        }
        A = tmp;              /* assign reallocated block */
#ifdef WMEMSET
        /* set new memory zero */
        memset (A + m * n, 0, m * (m - n) * sizeof *A);
#else
        square_my_matrix(A, n);
#endif
    }
    printMatrix (m,m,A);

}

Example Use/Output
The output is the same regarless whether WMEMSET is defined:
$ ./bin/mxn2mm
   1   2   3   4   5   6   7   8
   9  10  11  12  13  14  15  16
  17  18  19  20  21  22  23  24
  25  26  27  28  29  30  31  32
  33  34  35  36  37  38  39  40
  41  42  43  44  45  46  47  48
  49  50  51  52  53  54  55  56
  57  58  59  60  61  62  63  64
  65  66  67  68  69  70  71  72
  73  74  75  76  77  78  79  80
   1   2   3   4   5   6   7   8   9  10
  11  12  13  14  15  16  17  18  19  20
  21  22  23  24  25  26  27  28  29  30
  31  32  33  34  35  36  37  38  39  40
  41  42  43  44  45  46  47  48  49  50
  51  52  53  54  55  56  57  58  59  60
  61  62  63  64  65  66  67  68  69  70
  71  72  73  74  75  76  77  78  79  80
   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0

Zeroing Only Last Columns
If you need to zero the added columns instead of the rows, then you will need to manually copy the original rows to the rows of a newly allocated block and then free the original. To do so, you will have to change square_my_matrix() to take the address of the pointer (a pointer-to-pointer) rather than a simple pointer which will allow you to update where A points within your function. For example:
void square_my_matrix (double **A, int n)
{
    double *b = calloc (m * m, sizeof *b);
    if (!b) {
        perror ("calloc-b");
        exit (EXIT_FAILURE);
    }

    for (int i = 0; i < m; i++)
        memcpy (b + i * m, *A + i * n, n * sizeof **A);

    free (*A);
    *A = b;
}

In essence, you are writing the custom realloc().
and then you would call the function as:
    square_my_matrix (&A, n);

Example Output
Then your output would be:
$ ./bin/mxn2mm
   1   2   3   4   5   6   7   8
   9  10  11  12  13  14  15  16
  17  18  19  20  21  22  23  24
  25  26  27  28  29  30  31  32
  33  34  35  36  37  38  39  40
  41  42  43  44  45  46  47  48
  49  50  51  52  53  54  55  56
  57  58  59  60  61  62  63  64
  65  66  67  68  69  70  71  72
  73  74  75  76  77  78  79  80
   1   2   3   4   5   6   7   8   0   0
   9  10  11  12  13  14  15  16   0   0
  17  18  19  20  21  22  23  24   0   0
  25  26  27  28  29  30  31  32   0   0
  33  34  35  36  37  38  39  40   0   0
  41  42  43  44  45  46  47  48   0   0
  49  50  51  52  53  54  55  56   0   0
  57  58  59  60  61  62  63  64   0   0
  65  66  67  68  69  70  71  72   0   0
  73  74  75  76  77  78  79  80   0   0

For completion, the updated main() in the example above would reduce to:
int main (void) {

    int n = nbegin,
        v = 1;
    double *A;

    A = calloc (m * n, sizeof *A);
    if (A == NULL) {          /* validate EVERY allocation */
        perror ("calloc-A");
        exit (EXIT_FAILURE);
    }

    // buildMatrix(); //this fills my matrix with some data
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            A[i * n + j] = v++;

    printMatrix (m,n,A);
    if (m > n)
        square_my_matrix (&A, n);
    printMatrix (m,m,A);
}

Look things over and let me know if you have further questions.


text:
Q: How to use whole list function argument in Erlang I can understand most of the [H|T] examples I read in the docs. I usually means that I want to use either the H or the T part of the list. What if I want to use the whole list instead. Sample code:
-module(module_variable).
-export([main/0, list_suffix/1]).

variable() -> [1, 2, 3, 4, 5].

list_suffix([_H|T]) ->
        lists:suffix(variable, T).

main() ->
        io:fwrite("~p~n", [list_suffix([4, 5])]).

The error I get is:
6> module_variable:list_suffix([1,[4, 5]]).
** exception error: bad argument
     in function  length/1
        called as length(variable)
     in call from lists:suffix/2 (lists.erl, line 205)

Help is appreciated.

A: You can use multiple values from the front of the list. You cannot skip an arbitrary number of values in the middle. Since in your code you don't know how many elements from the head you want to match ahead of time, pattern matching can't do this for you.
Some examples:
Setup:
1> A = [1, 2, 3, 4, 5].
[1,2,3,4,5]

Matches first 2 elements of list
2> [1, 2 | _ ] = A.
[1,2,3,4,5]
% Can pattern match to extract values
3> [B, C | _ ] = A.
[1,2,3,4,5]
4> B.
1
5> C.
2

Can match some constant values and also assign
6> [1, 2, D | _ ] = A.
[1,2,3,4,5]

Can match whole list
7> [1, 2, 3, 4, 5] = A.
[1,2,3,4,5]
% Can't skip over elements in the middle
8> [1, 2| [4, 5]] = A.
** exception error: no match of right hand side value [1,2,3,4,5]
% This works, though not useful most of the time:
9> [1, 2, 3 | [4, 5]] = A.
[1,2,3,4,5]
% Can assign every element
10> [B, C, D, E, F] = A.
[1,2,3,4,5]
11> E.
4
12> F.
5
% If you don't use a pipe, the length has to match exactly
13> [B, C, D, E] = A.
** exception error: no match of right hand side value [1,2,3,4,5]


text:
Q: sharpen The activator sharpen.core.Sharpen for bundle sharpen.core is invalid Am trying to run Sharpen to convert some Java code to c#. Below is the detail of the instruction I am following, environment and problem statement.
Instruction followed:

*

*http://www.pauldb.me/post/14916717048/a-guide-to-sharpen-a-great-tool-for-converting-java

*http://community.versant.com/documentation/reference/db4o-7.12/net2/reference/index_Left.html#CSHID=sharpen%2Fhow_to_setup_sharpen.htm|StartTopic=Content%2Fsharpen%2Fhow_to_setup_sharpen.htm|SkinName=RedVersant
Environment:

*

*Eclipse 4.2.0

*JDK 1.7 (jdk1.7.0_03)

Problem:
I am able to set up the project in Eclipse and run the build file to convert the code. While executing the target "sharpen-docs" of the build file it errors out with the following message in the eclipse configuration log.
Any help will be much appreciated. Thanks in advance.
!ENTRY org.eclipse.osgi 2 0 2012-07-31 13:23:04.507

!MESSAGE
!STACK 0
org.osgi.framework.BundleException: The activator sharpen.core.Sharpen for bundle sharpen.core is invalid
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:172)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:679)
    at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:381)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:300)
    at org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:440)
    at org.eclipse.osgi.internal.loader.BundleLoader.setLazyTrigger(BundleLoader.java:263)
    at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:236)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadClass(AbstractBundle.java:1212)
    at org.eclipse.core.internal.registry.osgi.RegistryStrategyOSGI.createExecutableExtension(RegistryStrategyOSGI.java:174)
    at org.eclipse.core.internal.registry.ExtensionRegistry.createExecutableExtension(ExtensionRegistry.java:905)
    at org.eclipse.core.internal.registry.ConfigurationElement.createExecutableExtension(ConfigurationElement.java:243)
    at org.eclipse.core.internal.registry.ConfigurationElementHandle.createExecutableExtension(ConfigurationElementHandle.java:55)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:191)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1414)
    at org.eclipse.core.launcher.Main.main(Main.java:34)
Caused by: java.lang.ClassNotFoundException: sharpen.core.Sharpen
    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:501)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:421)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:412)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    at org.eclipse.osgi.internal.loader.BundleLoader.loadClass(BundleLoader.java:340)
    at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:229)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:165)
    ... 25 more
Root exception:
java.lang.ClassNotFoundException: sharpen.core.Sharpen
    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:501)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:421)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:412)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    at org.eclipse.osgi.internal.loader.BundleLoader.loadClass(BundleLoader.java:340)
    at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:229)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:165)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:679)
    at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:381)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:300)
    at org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:440)
    at org.eclipse.osgi.internal.loader.BundleLoader.setLazyTrigger(BundleLoader.java:263)
    at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:236)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadClass(AbstractBundle.java:1212)
    at org.eclipse.core.internal.registry.osgi.RegistryStrategyOSGI.createExecutableExtension(RegistryStrategyOSGI.java:174)
    at org.eclipse.core.internal.registry.ExtensionRegistry.createExecutableExtension(ExtensionRegistry.java:905)
    at org.eclipse.core.internal.registry.ConfigurationElement.createExecutableExtension(ConfigurationElement.java:243)
    at org.eclipse.core.internal.registry.ConfigurationElementHandle.createExecutableExtension(ConfigurationElementHandle.java:55)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:191)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1414)
    at org.eclipse.core.launcher.Main.main(Main.java:34)
!ENTRY org.eclipse.osgi 4 0 2012-07-31 13:23:04.737
!MESSAGE Application error
!STACK 1
org.eclipse.core.runtime.CoreException: Plug-in sharpen.core was unable to load class sharpen.core.SharpenApplication.
    at org.eclipse.core.internal.registry.osgi.RegistryStrategyOSGI.throwException(RegistryStrategyOSGI.java:194)
    at org.eclipse.core.internal.registry.osgi.RegistryStrategyOSGI.createExecutableExtension(RegistryStrategyOSGI.java:176)
    at org.eclipse.core.internal.registry.ExtensionRegistry.createExecutableExtension(ExtensionRegistry.java:905)
    at org.eclipse.core.internal.registry.ConfigurationElement.createExecutableExtension(ConfigurationElement.java:243)
    at org.eclipse.core.internal.registry.ConfigurationElementHandle.createExecutableExtension(ConfigurationElementHandle.java:55)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:191)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1414)
    at org.eclipse.core.launcher.Main.main(Main.java:34)
Caused by: java.lang.ClassNotFoundException: sharpen.core.SharpenApplication
    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:501)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:421)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:412)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    at org.eclipse.osgi.internal.loader.BundleLoader.loadClass(BundleLoader.java:340)
    at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:229)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadClass(AbstractBundle.java:1212)
    at org.eclipse.core.internal.registry.osgi.RegistryStrategyOSGI.createExecutableExtension(RegistryStrategyOSGI.java:174)
    ... 17 more

A: For the records:
The problem got resolved after I install Java 6 .. thanks Anders for pointing towards this.


text:
Q: Why and how does this "for..in" statement work? I'm learning JavaScript via CodeCademy and am on the "Contact List" project; specifically, "Search For A Friend" lesson. It has me learning how Objects work and how to look within them.
The demonstrated code is as follows:
var friends = {};
friends.bill = {
  firstName: "Bill",
  lastName: "Gates",
  number: "(206) 555-5555",
  address: ['One Microsoft Way','Redmond','WA','98052']
};
friends.steve = {
  firstName: "Steve",
  lastName: "Jobs",
  number: "(408) 555-5555",
  address: ['1 Infinite Loop','Cupertino','CA','95014']
};

var list = function(obj) {
  for(var prop in obj) {
    console.log(prop);
  }
};

var search = function(name) {
  for(var prop in friends) {
    if(friends[prop].firstName === name) {
      console.log(friends[prop]);
      return friends[prop];
    }
  }
};

list(friends);
search("Steve");

So I understand that friends is an object and bill and steve are objects within friends. What I don't understand is how list and search functions look inside friends. I see that it uses a for/in loop... but after learning loops, I see no conditions and I see no iteration mechanism. I have no concept on how this for/in is actually working. Maybe if someone could provide an alternate of equivalent syntax; perhaps, even, if someone can explain in colloquial English why/how for/in works?
Thank you!
NOTE: Tagging as Language-Agnostic, because it's a higher-level programming/conceptual question, even if the syntax here is JavaScript.

A: There isn't really an equivalent alternate syntax; for (x in y) is the iteration mechanism.
It's analogous to
for ( x = 0; x < somearray.length; ++x )

in that it sets x to each index in turn. But since JS objects are, by definition, unordered, there's no guarantee you'll get the indices in any particular sequence.
There are no conditions. You'll hit every index. It's a different construct.
So if we have:
var obj = { 'a': 1, 'b': 2, 'c': 3 };

and say:
for ( var x in obj )
{
  console.log( x + ": " + obj[x] );   // prints "a: 1", etc.
}

then exactly once in that loop, x == "a". Exactly once, x == "b". Exactly once, x == "c". Only those, in no specified order.

A: In short, your for(var prop in obj), it is equivalent to while obj has items, get prop and do something with it (in plain English). So the loop will stop when there are no other "props" to be taken from "obj".
Here is a detailed explanation of the for/in loop: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

A: In your case for(var prop in friends) "prop" represents the keys. After you can use something like friends[prop].anyProperty.
It would be more meaningful to use:
 for(var key in friends)

About "for in" :
From Douglas Crockford's "Javascript The Good Parts" book :
The for in statement can loop over all of the property names in an object. The enumeration
will include all of the properties—including functions and prototype properties
that you might not be interested in—so it is necessary to filter out the values
youdon't want. The most common filters are the hasOwnProperty method and using
typeof to exclude functions:
var name;
for (name in another_stooge) {
 if (typeof another_stooge[name] !== 'function') {
   document.writeln(name + ': ' + another_stooge[name]);
 }
}

There is no guarantee on the order of the names, so be prepared for the names to
appear in any order. If you want to assure that the properties appear in a particular
order, it is best to avoid the for in statement entirely and instead make an array containing
the names of the properties in the correct order:
var i;
var properties = [
  'first-name',
  'middle-name',
  'last-name',
  'profession'
];

for (i = 0; i < properties.length; i += 1) {
  document.writeln(properties[i] + ': ' +
  another_stooge[properties[i]]);
}

By using for instead of for in, we were able to get the properties we wanted without
worrying about what might be dredged up from the prototype chain, and we got
them in the correct order.


text:
Q: UICollectionView cellForItemAt not called after InsertItems(at:) - How to preload next cell? I'm working on a horizontal UICollectionView with full screen cells.
Cells have WKWebview inside, which loads next cell's url.
When the next url loaded, the new cell is inserted.
extension ViewController {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: WebCell.reuseId, for: indexPath) as? WebCell else { fatalError("Unexpected indexPath") }

        cell.configure()
        cell.startLoadingURL(urls[indexPath.item])

        return cell
    }
}

extension ViewController: WebCellDelegate {
    func onNextURLLoaded(_ sender: WebCell, nextUrl: URL) {
        ...
        urls.append(nextUrl)
        horizontalCollectionView.performBatchUpdates({
            horizontalCollectionView.insertItems(at: [IndexPath(item: urls.count-1, section: 0)])
        }, completion: nil)

    }
}

What I want to do is - rendering next cell in advance.
The problem is - cellForItemAt method is not called after insertItems(at:).
But when I reduce cells' sizes so that next cell being visible, then cellForItemAt method is called and renders the next cell.
I want to preload next cell without reducing cell's size.
Is there any solutions?

A: you can use willDisplay cell method
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    <#code#>
}


text:
Q: How to pass multiple MySQL Queries in AWS Lambda Function at once I have a multiple MySQL queries created in Workbench. This query runs by one trigger only in Workbench. I would like this query to be embedded to my AWS Lambda Function but to no avail. I suspect that it is because it multiple queries at the same time.
Here's the code that I created but failed:
var mysql = require('mysql');
var config = require('./config.json');
var pool  = mysql.createPool({
       host     : config.dbhost,
       user     : config.dbuser,
       password : config.dbpassword,
       database : config.dbname
    });

exports.handler = (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;
  pool.getConnection(function(err, connection) {
      // Use the connection
      connection.query('DROP VIEW IF EXISTS view_table; \
                        CREATE VIEW view_table AS \
                            SELECT table3.field1, table1.field2 \
                            FROM table1 \
                            JOIN table2 ON table1.table2_id = table2.id \
                            JOIN table3 ON table1.table3_id = table3.id \
                            JOIN table4 ON item_var.table4_id = table4.id \
                            WHERE item_var.list_id = ? \
                            ORDER BY table1 ASC LIMIT 3 \
                        SELECT table4.field1, table2.field2, table2.field3, \
                            (SELECT field1 FROM view_table LIMIT 0, 1) AS field4, \
                            (SELECT field1 FROM view_table LIMIT 1, 1) AS field5, \
                            (SELECT field1 FROM view_table LIMIT 2, 1) AS field6 \
                        FROM table2 \
                        JOIN table4 ON table2.id = table4.id \
                        WHERE table2.id = ?', event['param1'], function (error, results, fields) {
      // And done with the connection.
      connection.release();
      // Handle error after the release.
      if (error) callback(error) ;
      else callback(null, results);
    });
  });
};

And here's the error message I got:
Response:
{
  "errorType": "Error",
  "errorMessage": "ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE VIEW view_table SELECT table3.field1,' at line 1",

I suspect the reason for this is Lambda does not accept multiple MySQL queries at the same time.
There are options I got here like,

*

*To use AWS SNS Notifications; or

*Create multiple lambda and trigger them one over the other.

Can anyone guide me how to do this properly?

A: This is entirely down to MySQL not supporting multi query, from what I can see you have 2 queries.
You should not try running in parallel based on what you've provided as you cannot guarantee the order, why not instead just perform as two seperate queries such as below.
var mysql = require('mysql');
var config = require('./config.json');
var pool  = mysql.createPool({
       host     : config.dbhost,
       user     : config.dbuser,
       password : config.dbpassword,
       database : config.dbname
    });

exports.handler = (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;
  pool.getConnection(function(err, connection) {
      // Use the connection
      connection.query('DROP VIEW IF EXISTS view_table;', function (error, results, fields) {
      // Handle error after the release.
      if (error) callback(error) ;
    });
      connection.query('CREATE VIEW view_table AS \
                            SELECT table3.field1, table1.field2 \
                            FROM table1 \
                            JOIN table2 ON table1.table2_id = table2.id \
                            JOIN table3 ON table1.table3_id = table3.id \
                            JOIN table4 ON item_var.table4_id = table4.id \
                            WHERE item_var.list_id = ? \
                            ORDER BY table1 ASC LIMIT 3;', function (error, results, fields) {
      // Handle error after the release.
      if (error) callback(error) ;
    });

      connection.query('SELECT table4.field1, table2.field2, table2.field3, \
                            (SELECT field1 FROM view_table LIMIT 0, 1) AS field4, \
                            (SELECT field1 FROM view_table LIMIT 1, 1) AS field5, \
                            (SELECT field1 FROM view_table LIMIT 2, 1) AS field6 \
                        FROM table2 \
                        JOIN table4 ON table2.id = table4.id \
                        WHERE table2.id = ?', event['param1'], function (error, results, fields) {
      // And done with the connection.
      connection.release();
      // Handle error after the release.
      if (error) callback(error) ;
      else callback(null, results);
    });
  });
};

The above would have you drop the view, and then perform the create view afterwards.


text:
Q: Handling POST request in go I am having trouble decoding POST request with gorilla/schema.
My code is creating a basic http server:
package main

import (
    "net/http"
    "gorilla/schema"
    "fmt"
    "log"
)

type Payload struct{
    slot_temp string
    data      string
    time      string
    device    string
    signal    string
}

func MyHandler(w http.ResponseWriter, r *http.Request) {
    err := r.ParseForm()

    if err != nil {
        fmt.Println("Error parsing form")
    }

    p := new(Payload)
    decoder := schema.NewDecoder()

    fmt.Println(r.PostForm)

    err = decoder.Decode(p, r.Form)

    if err != nil {
        fmt.Println("Error decoding")
    }
    fmt.Println(p.slot_temp)

}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", MyHandler)
    log.Fatal(http.ListenAndServe(":8082", mux))
}

I test i with
curl -X POST -H 'application/x-www-form-urlencoded' -d "slot_temp=34&data=22ltime=1495092909&device=1B3C29&signal=18.63" localhost:8082

But I get the following output
map[device:[1B3C29] signal:[18.63] slot_temp:[34] data:[22] time:[1495092909]]

// content of map and a blank line instead if the value of p.slot_temp

The content of the structure field is never printed.
I guess there is an issue with the decoder, but I can't figure out what is wrong.
Thanks

A: Change your struct fields name to uppercase. Your decoder is external package and it doesn't have access to your struct
package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/schema"
)

type Payload struct {
    Slot_temp string
    Data      string
    Time      string
    Device    string
    Signal    string
}

func MyHandler(w http.ResponseWriter, r *http.Request) {
    err := r.ParseForm()

    if err != nil {
        fmt.Println("Error parsing form")
    }

    p := new(Payload)
    decoder := schema.NewDecoder()

    fmt.Println(r.PostForm)

    err = decoder.Decode(p, r.Form)

    if err != nil {
        fmt.Println("Error decoding")
    }
    fmt.Println(p.Slot_temp)

}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", MyHandler)
    log.Fatal(http.ListenAndServe(":8082", mux))
}


text:
Q: Open linked images in comments within the android app Currently if someone links to an image linked in a comment it opens the browser to view it.
I think it should open the image within the app. Particularly if it's a stack exchange imgur link.


text:
Q: Unable to access API key in Heroku Config Vars from Javascript app I am trying to deploy a simple static app consisting of HTML, CSS, and Javascript files to Heroku. I have added "dummy" composer.json and index.php files as well, to allow the static file to reside in Heroku. When I go to the hosted page, I see a blank screen. The console window shows  as shown below. The files are linked to my GitHub repo, so I am using a .gitignore file to exclude my API key, and saving the API key in Config Vars in Heroku. The app is not finding the API key and throwing the error.
Uncaught ReferenceError: MAPBOX_KEY is not defined                 logic.js:68
    at createMap (logic.js:68)
    at createFeatures (logic.js:56)
    at logic.js:9
    at d3.min.js:3
    at Object.<anonymous> (d3.min.js:7)
    at d.call (d3.min.js:4)
    at XMLHttpRequest.e (d3.min.js:7)

So far I have tried the following:

*

*Added API key directly in Heroku under Settings/Config Vars

*Used console window to add key heroku config:add MAPBOX_KEY=pk.eyJ1I.....

*Disabled the cache the web page

*Ran Empty Cache and Hard Reload on web page

*Ran heroku config in the console and received following error:
heroku config
»   Error: Missing required flag:
»     -a, --app APP  app to run command against
»   See more help with --help

I have searched the documentation and stack overflow and can't find anything about API keys with Javascript in Heroku. Do I need to add additional code to my .js or .html file for the app to find the key on the Heroku server? Below is a portion of the .js code down to the line of the error.
// +++++ Leaflet Challenge +++++

// store API endpoint inside queryUrl
var queryUrl = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.geojson";

// make API call to USGS and perform a GET request to the query URL
d3.json(queryUrl, function(data) {
   // after a response, send the data.features object to the createFeatures function
   createFeatures(data.features);
});

// Circle radius function
function circleSize(magnitude) {
   return magnitude **2 * 2000
};

// Circle color function by depth
function circleColor(depth) {
   switch (true) {
      case (depth > 90):
         return "#d73027"; //red
      case (depth > 70):
         return "#fc8d59"; //darkorange
      case (depth > 50):
         return "#fee08b"; //lightorange
      case (depth > 30):
         return "#d9ef8b"; //yellow
      case (depth > 10):
         return "#91cf60"; //yellowgreen
      default:
         return "#1a9850"; //green
   }
};

function createFeatures(earthquakeData) {

   // define a function and run once for each feature in the features array
   // give each feature a popup describing the place and time of the earthquake
   var earthquakes = L.geoJSON(earthquakeData, {
      onEachFeature: function(feature, layer) {
         layer.bindPopup("
Magnitude: " + feature.properties.mag +"

Depth: " + feature.geometry.coordinates[2] + " km

Location: " + feature.properties.place + "

" + new Date(feature.properties.time) + "
");
      },

      pointToLayer: function(feature, latlng) {
         return new L.circle(latlng, {
            radius: circleSize(feature.properties.mag),
            fillColor: circleColor(feature.geometry.coordinates[2]),
            color: "black",
            weight: .5,
            fillOpacity: 0.8
         })
      }
   });

   // send earthquakes layer to the createMap function
   createMap(earthquakes);
}

function createMap(earthquakes) {

   // define lightmap layer
   var lightmap = L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
      attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
      tileSize: 512,
      maxZoom: 18,
      zoomOffset: -1,
      id: "mapbox/light-v10",
      accessToken: MAPBOX_KEY
   });

Thank you ahead of time for any help you can provide. This is my first experience deploying to Heroku, so it's all new to me.

A: Heroku config variables are the classic environment variables at operative system(linux, mac, windows) which are designed to be accessed from backend languages who has access to the operative system like: java, php, nodejs, ruby, python, etc
According to your snippets, you need to read this environment var in your vanilla javascript which is called from your html in some web browser, which is IMPOSSIBLE
Vanilla javascript or pure javascript is not allowed to access to some operative system resources like environment variables in this case.
Check this link to understand how variables works in vanilla javascript:
How to use variable substitution in Frontend js applications like backend applications?
Quick Solution
in your php code read this var before the web renderization at operative system layer, because php is able to do that:
Php is not my best skill but I am sure that it has several options to inject this var into the static html or javascript
If not, you could use a trivial string replacement in the static file:
im_your_file.js
zoomOffset: -1,
id: "mapbox/light-v10",
accessToken: @@MAPBOX_KEY@@

another_php_file.php
replaceStringInFile("@@MAPBOX_KEY@@")

Dirty solution
Use this replace content in file in another php file and call it from some heroku step before the app startup
You could perform this file replacement using pure bash and call it in some heroku step
Elegant solution
Webapck variable injection
Best solution
Instead of read directly the var in your javascript, yo must publish a  kind of rest endpoint in your php app like /settings.php. This endpoint must return this and other variables as json.
In you javascript file, instead to ise directly the variable, consume the /settings.php and you will havr the required variable in your javascript code.


text:
Q: How can we check if the log output is using STDOUT in Rails 4? In Rails, we can put this in development.rb if we are outputting the logs in the console:
config.logger = ActiveSupport::Logger.new(STDOUT)

So in Rails 5.x we can check if the log output is using STDOUT by using the code below:
# Returns true if the logger destination matches one of the sources which is STDOUT
ActiveSupport::Logger.logger_outputs_to?(Rails.logger, STDOUT)

Here's the documentation: https://github.com/rails/rails/blob/492b9b413d3aa3a9bf3bf986ae25c7f90ec1ab62/activesupport/lib/active_support/logger.rb#L16
My question now is how can we check if the log output is using STDOUT in Rails 4? Because this script
ActiveSupport::Logger.logger_outputs_to? is not available in Rails 4.
Any ideas on this? Your help would be greatly appreciated. Thanks.

A: Since the ActiveSupport::Logger.logger_outputs_to?() is not available in Rails 4, I just created a function.
def self.logger_stdout
   logdev = ::Rails.logger.instance_variable_get(:@logdev)
   logger_source = logdev.dev if logdev.respond_to?(:dev)
   sources = [$stdout]
   found = sources.any? { |source| source == logger_source }
end


text:
Q: Mocking library functions when unit testing chef custom resource I have created a very simple custom resource in Chef, and inside that resource is some simple logic. The logic in question calls out to some custom helper methods.
I can build the resource, and execute it as part of a recipe - but if I would like to unit test the behaviour within the resource itself to ensure the flow is correct. As such, I want to be able to mock the behaviour of those helper functions so that I can direct the resource behaviour. Unfortunately, I can't get this to work.
My recipe looks like this:
my_resource 'executing' do
    action :execute
end

The resource looks like this:
action :execute do
  if my_helper?(node['should_be_true'])
    converge_by "Updating" do
      my_helper_method
    end
  end
end

action_class do
  include CustomResource::Helpers
end

The functions are simple:
module CustomResource
  module Helpers
    def my_helper?(should_be_true)
      should_be_true
    end

    def my_helper_method
      hidden_method
    end

    def hidden_method
      3
    end
  end
end

When I try to mock the behaviour of these in my ChefSpec tests, I get errors:
it 'executes' do
  allow(CustomResource::Helpers).to receive(:my_helper?).and_return(true)
  expect(CustomResource::Helpers).to receive(:my_helper_method)
  expect { chef_run }.to_not raise_error
end

Failure/Error: expect(CustomResource::Helpers).to receive(:my_helper_method)

   (CustomResource::Helpers).my_helper_method(*(any args))
       expected: 1 time with any arguments
       received: 0 times with any arguments

Any ideas what I'm doing wrong in my mocking?
Thanks in advance!

A: Managed to make this work by changing the mocking method... Those module functions are added into the action_class, and therefore at runtime they are methods on that specific instance of the resource's ActionClass. Not sure if my solution is right/ideal - but it does work:
include CustomResource::Helpers

<snip>

it 'executes' do
  allow_any_instance_of(Chef::Resource::ActionClass).to receive(:my_helper?).and_return(true)
  expect_any_instance_of(Chef::Resource::ActionClass).to receive(:my_helper_method)
  expect { chef_run }.to_not raise_error
end

I did look into avoiding the 'any instance of' mock, but then I got into problems and gave up - clearly the ActionClass has a lot of behaviour that I don't want to have to worry about.

A: This is unfortunately very difficult given how ChefSpec works. You need to stub it on any instance of your resource, because that's the actual receiver. If you can use a module method instead, that is slightly easier. I take it you're already require_relative-ing your library file or the code would fail differently. However there is no way to do that for a custom resource because they are DSL-y and Ruby can't load them directly. The simplest option is generally to not test this kind of thing. Put code in the helper methods that checks if a node attribute is set and use that value if it is (specifics depend on the exact case), and then set that in your test. It's gross and annoying though, which is part of why Halite exists.


text:
Q: Google maps issue using App Inventor Information here about the problem: The problem I am having with google app inventor is
bring text from a text box into google maps and having google maps try and find my location.
Screen shots:
http://s1164.photobucket.com/albums/q572/drebin8933/?start=all
-Thank you for your time.

A: I think... you can not do what you want to do currently.
Here is the Intents List http://developer.android.com/guide/appendix/g-app-intents.html
The Intent that runs Google Map uses a geo: URI in the DataUri
Look for Show a map for a location here http://appinventor4all.org/docs/learn/reference/other/activitystarter.html


text:
Q: 'fetch' in PDO gets only one result I have this code:
$sql = new PDO('mysql:host=localhost;dbname=b', 'root', 'root');
$f = $sql->query('select * from user');
$sql->setFetchMode(PDO::FETCH_ASSOC);

while($row = $f->fetch()){
     print_r($row);
}

The output is
Array
(
    [id] => 1
    [name] => turki
    [mail] => ablaf
    [pass] => 144
)
Array
(
    [id] => 2
    [name] => wrfwer
    [mail] => fwerf
    [pass] => werf
)

And that's what I really want. But if I do this
<?php
    $sql = new PDO('mysql:host=localhost;dbname=b', 'root', 'root');
    $f = $sql->query('select * from user');
    $f->setFetchMode(PDO::FETCH_ASSOC);
    print_r($f->fetch());
?>

The output is
Array
(
    [id] => 1
    [name] => turki
    [mail] => ablaf
    [pass] => 144
)

It has one result, but I have two rows in the table; why is that?

A: Fetch should be used to display the next row from the database result.
To get all rows, you should use fetchAll();

*

*PDOStatement::fetch — Fetches the next row from a result set

*PDOStatement::fetchAll() — Returns an array containing all of the result set rows

Change your example to:
<?php
    $sql = new PDO('mysql:host=localhost;dbname=b', 'root', 'root');
    $f = $sql->query('select * from user');
    $f->setFetchMode(PDO::FETCH_ASSOC);
    print_r($f->fetchAll());
?>

or if you want use PDOStatement::fetch to
<?php
    $sql = new PDO('mysql:host=localhost;dbname=b', 'root', 'root');
    $sth = $sql->query('select * from user');
    while($row = $sth->fetch(PDO::FETCH_ASSOC))
    {
      print_r($row);
    }
?>

A: In that case use fetchAll.
$result = $f->fetchAll();
print_r($result);

A: PDOStatement::fetch only retrieves one record from a PDOStatement object (wherever its pointer is) which is why you have to loop through fetch.

A: The fetch() method only returns a single record and sets the internal pointer to point to the next record. You are expecting from this method what it cannot return.
Perhaps try a different method like fetchAll:
<?php
    $sth = $dbh->prepare("SELECT name, colour FROM fruit");
    $sth->execute();

    /* Fetch all of the remaining rows in the result set */
    print("Fetch all of the remaining rows in the result set:\n");
    $result = $sth->fetchAll();
    print_r($result);
?>

A: $f->fetch() moves the internal result pointer to the next value (if it exists). That's why you get all the values when you call it in while();.

A: $f->fetch() - Will get one row
$f->fetchAll() - Will get all rows


text:
Q: How can I take a .avi file from a webcam and transform it into a .mat file for use in matlab? I am using a commercial webcam (GearHead) which records .avi video files.  I want to analyze the individual frames of the .avi file  matlab code, but the series of frames first need to be in .mat format. I don't need/want audio. How can I convert the .avi file to a .mat file?
thank you.

A: In older versions of MATLAB you can use the command aviread to read an .avi file into MATLAB. In newer versions the preferred method is to use VideoReader. Once you've read it in, you can save the data to a .mat file.


text:
Q: How to get limit records with in Clause I have a following query
I am getting id as a string
SELECT * from table_name
where id in (1,2,3,4)
order by created desc
limit 0,4

this Query is giving me only 4 records
i want to get 4 records from each id
Any idea ?

A: select * from
(
    SELECT * from table_name where id = 1 order by created desc limit 4
    union all
    SELECT * from table_name where id = 2 order by created desc limit 4
    union all
    SELECT * from table_name where id = 3 order by created desc limit 4
    union all
    SELECT * from table_name where id = 4 order by created desc limit 4
) tmp
order by created desc


text:
Q: AnythingSlider: how to restart slideshow I'm starting the slideshow in a pop up div by clicking a button using $('#slider2').data('AnythingSlider').startStop(true);
Stopping the slideshow by $('#slider2').data('AnythingSlider').startStop(false);
When I click the same button to show again it simply continues from the slideshow that was stopped before. I want the whole slideshow to restart again. How can I do that ?

A: when restarting, do this:
$('#slider2').anythingSlider(1); // Reset to first slide
$('#slider2').data('AnythingSlider').startStop(true);


text:
Q: jQuery .combobox() set autofocus jQuery has .focus method(), In autocomplete I just set focus with "autofocus : true", like this :
$('#AutoCompleteId').autocomplete({
        autoFocus: true
    });

however I'm using .combobox() jQuery, not autocomplete, how can I set auto focus in .combobox() jQuery?
thanks in advance...


text:
Q: ImageButton in an HorizontalSrollView have a frame I have this Layout:
<HorizontalScrollView android:id="@+id/card_images_horizontalscroll"
   android:layout_height="wrap_content"
   android:layout_width="wrap_content"
   android:scrollbars="none"
   android:visibility="invisible"
   >

    <LinearLayout android:id="@+id/card_images_layout"
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    >

     <ImageButton
      android:id="@+id/card_image"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:background="@drawable/icona"
      android:
     />

    </LinearLayout>

  </HorizontalScrollView>

But I meet this issues: the image are enclose by a frame which I don't want, what's wrong?!
Like this:

Thanks so much!
I tried to change XML with this runtime code but I have the same issues:
b = new ImageButton(this);
            b.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
            b.startAnimation(alpha_animation);
            b.setImageBitmap(myBitmap);

I tried also to follow the suggestion for change ImageButton in Button, but can I set at runtime the image source?

A: You can add the image to the ImageButton with:
android:src="@drawable/icona"
and then set the background to null like this:
android:background="@null"

A: Replace your ImageButton with a Button with the background you want:
<Button
  android:id="@+id/card_image"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:background="@drawable/icona"/>


text:
Q: Request Python GraphQl I get an error when making a request of this type:
{'errors': [{'message': 'Variable "$input" of required type "AccountBindBankCardInput!" was not provided.', 'locations': [{'line': 1, 'column': 24}], 'extensions': {'code': 'BAD_USER_INPUT'}}]}

Payload data on website looks like this:
My payload looks like:
payload = {"operationName": "CreateBinding",

"input": '{lang: "ru", domainSfx: "ru", templateTag: "desktop/form", returnPath: "https://id.yandex.ru/pay", regionId: 1}',

"query": "mutation CreateBinding($input: AccountBindBankCardInput!) {\n  accountBindBankCard(input: $input) {\n    status\n    url\n    __typename\n  }\n}"}

A: The $input values needs to be passed in a variables block; see the graphql.org "Serving over HTTP" page (this wire format is not part of the GraphQL spec).  Within that, the value of variables needs to be a structured JSON object, not a serialized string.
Assuming you're going to serialize payload to JSON before sending it over the wire, this should look like:
payload = {
  "operationName": "CreateBinding",
  "variables": {
    "input": {
      "lang": "ru",
      "domainSfx": "ru",
      "templateTag": "desktop/form",
      "returnPath": "https://id.yandex.ru/pay",
      "regionId": 1
    },
  },
  "query": """
mutation CreateBinding($input: AccountBindBankCardInput!) {
  accountBindBankCard(input: $input) {
    status
    url
    __typename
  }
}
"""
}


text:
Q: Google Maps and DART I am new to DART. Is it possible to use Google Maps Javascript API on DART? If its not directly possible now, is there any other alternate way?

A: You can now use google_maps package available on pub. This library allows you to use Google Maps JavaScript API from dart scripts.
Simply add the dependency to your pubspec.yaml

dependencies:
  google_maps: ">=1.0.1 <2.0.0"

Include the Maps API JavaScript using a <script> tag.
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

Then you can use Google Maps from dart scripts. Here's a simple exemple :
import 'dart:html';
import 'package:google_maps/google_maps.dart';

void main() {
  final mapOptions = new MapOptions()
    ..zoom = 8
    ..center = new LatLng(-34.397, 150.644)
    ..mapTypeId = MapTypeId.ROADMAP
    ;
  final map = new GMap(query("#map_canvas"), mapOptions);
}

A: Currently you need to use postMessage from Dart if you want to communicate with JavaScript (this will eventually change). So for now you'll need to add some JavaScript code to your app that mediates messages to and from Google maps JS API and Dart:
function googleMapsCallback(s) {
   window.postMessage(JSON.stringify(s), '*');
}

And then in your Dart code:
class GoogleMap {
  GoogleMap() {
     window.on.message.add(received, false);
  }

  received(MessageEvent e) {
    var data = JSON.parse(e.data);
    // do stuff with google maps data
  }
}

Alternativly you can use Google Maps REST API directly from Dart using XMLHttpREquest

A: Dart now has a JavaScript interoperability library: http://www.dartlang.org/articles/js-dart-interop/
One of the examples on that page is how to interoperate with Google Apps.


text:
Q: Problems with Cosmic Cuttlefish and Gnome lockscreen (may be related to AMD gpu) Ever since I upgraded to Cosmic Cuttlefish, one of my three computers (Ryzen 1700 CPU, Radeon RX 550 graphics card) is experiencing some very strange symptoms. Overall, it runs smoothly with the exception that when I'm using Gnome on Xorg, logging back in after suspend is extremely slow. The computer will quickly resume and show me the Gnome lockscreen. However, the lockscreen is unresponsive and will not allow me to login. The monitors then automatically power off. If I'm lucky, they will turn back on after a minute or two and I finally get to login. However, other times I have to force reboot the computer. When checking the system log, I found an error message related to amdgpu (pasted at bottom).
I tried the following:

*

*Disabling the lockscreen (i.e., no password to login). Same symptoms (except, when the screen finally comes back after a minute or two I don't have to type my password).

*Switching to Gnome on Wayland. Much faster time from resume to logging in. However, more frequent amdgpu errors (thereby requiring a restart).

What's the easiest way to fix this? I'm pretty frustrated because I chose AMD over Nvidia due to the fact AMD supports open-source. Yet, this seems to be related to AMD's drivers.

Nov 07 19:50:48 phoenix kernel: [drm:generic_reg_wait [amdgpu]] *ERROR* REG_WAIT timeout 10us * 3000 tries - dce110_stream_encoder_dp_blank line:927
Nov 07 19:50:48 phoenix kernel: WARNING: CPU: 15 PID: 3598 at drivers/gpu/drm/amd/amdgpu/../display/dc/dc_helper.c:254 generic_reg_wait+0xe4/0x160 [amdgpu]
Nov 07 19:50:48 phoenix kernel: Modules linked in: rfcomm pci_stub vboxpci(OE) vboxnetadp(OE) vboxnetflt(OE) vboxdrv(OE) ccm xt_CHECKSUM iptable_mangle ipt_MASQUERADE iptable_nat nf_nat_
Nov 07 19:50:48 phoenix kernel:  ccp mac_hid sch_fq_codel parport_pc ppdev lp parport sunrpc ip_tables x_tables autofs4 btrfs xor zstd_compress raid6_pq libcrc32c algif_skcipher af_alg d
Nov 07 19:50:48 phoenix kernel: CPU: 15 PID: 3598 Comm: gnome-shell Tainted: G        W  OE     4.18.0-10-generic #11-Ubuntu
Nov 07 19:50:48 phoenix kernel: Hardware name: System manufacturer System Product Name/PRIME B450-PLUS, BIOS 0409 08/24/2018
Nov 07 19:50:48 phoenix kernel: RIP: 0010:generic_reg_wait+0xe4/0x160 [amdgpu]
Nov 07 19:50:48 phoenix kernel: Code: a9 44 8b 45 20 48 8b 4d 18 89 de 44 89 4d d4 8b 55 10 48 c7 c7 d0 b3 b2 c0 e8 28 c7 a8 ff 41 83 7c 24 20 01 44 8b 4d d4 74 02 <0f> 0b 48 83 c4 18 44
Nov 07 19:50:48 phoenix kernel: RSP: 0018:ffffbe084338f798 EFLAGS: 00010297
Nov 07 19:50:48 phoenix kernel: RAX: 0000000000000000 RBX: 000000000000000a RCX: 0000000000000000
Nov 07 19:50:48 phoenix kernel: RDX: 0000000000000000 RSI: ffffa0a21efd64b8 RDI: ffffa0a21efd64b8
Nov 07 19:50:48 phoenix kernel: RBP: ffffbe084338f7d8 R08: 000000000005e2a3 R09: 0000000000010200
Nov 07 19:50:48 phoenix kernel: R10: 0000000000000004 R11: ffffffffab78480d R12: ffffa0a1fe838000
Nov 07 19:50:48 phoenix kernel: R13: 0000000000000bb9 R14: 0000000000010000 R15: 0000000000000000
Nov 07 19:50:48 phoenix kernel: FS:  00007fd746c48400(0000) GS:ffffa0a21efc0000(0000) knlGS:0000000000000000
Nov 07 19:50:48 phoenix kernel: CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
Nov 07 19:50:48 phoenix kernel: CR2: 0000286ba76df9e0 CR3: 00000003d05a6000 CR4: 00000000003406e0
Nov 07 19:50:48 phoenix kernel: Call Trace:
Nov 07 19:50:48 phoenix kernel:  dce110_stream_encoder_dp_blank+0x12f/0x1a0 [amdgpu]
Nov 07 19:50:48 phoenix kernel:  dce110_blank_stream+0x57/0x90 [amdgpu]
Nov 07 19:50:48 phoenix kernel:  core_link_disable_stream+0x57/0x220 [amdgpu]
Nov 07 19:50:48 phoenix kernel:  dce110_reset_hw_ctx_wrap+0xcd/0x1e0 [amdgpu]
Nov 07 19:50:48 phoenix kernel:  ? pp_dpm_dispatch_tasks+0x48/0x60 [amdgpu]
Nov 07 19:50:48 phoenix kernel:  dce110_apply_ctx_to_hw+0x52/0xa30 [amdgpu]
Nov 07 19:50:48 phoenix kernel:  ? amdgpu_pm_compute_clocks+0x17/0x20 [amdgpu]
Nov 07 19:50:48 phoenix kernel:  ? pplib_apply_display_requirements+0x1c3/0x1d0 [amdgpu]
Nov 07 19:50:48 phoenix kernel:  ? dce110_set_bandwidth+0x1d2/0x200 [amdgpu]
Nov 07 19:50:48 phoenix kernel:  dc_commit_state+0x306/0x5b0 [amdgpu]
Nov 07 19:50:48 phoenix kernel:  ? drm_calc_timestamping_constants+0x109/0x150 [drm]
Nov 07 19:50:48 phoenix kernel:  amdgpu_dm_atomic_commit_tail+0x37f/0xe40 [amdgpu]
Nov 07 19:50:48 phoenix kernel:  ? _cond_resched+0x19/0x30
Nov 07 19:50:48 phoenix kernel:  ? wait_for_completion_timeout+0x38/0x140
Nov 07 19:50:48 phoenix kernel:  ? _cond_resched+0x19/0x30
Nov 07 19:50:48 phoenix kernel:  ? wait_for_completion_interruptible+0x35/0x1a0
Nov 07 19:50:48 phoenix kernel:  commit_tail+0x42/0x70 [drm_kms_helper]
Nov 07 19:50:48 phoenix kernel:  drm_atomic_helper_commit+0x113/0x120 [drm_kms_helper]
Nov 07 19:50:48 phoenix kernel:  amdgpu_dm_atomic_commit+0x87/0xa0 [amdgpu]
Nov 07 19:50:48 phoenix kernel:  drm_atomic_commit+0x4a/0x50 [drm]
Nov 07 19:50:48 phoenix kernel:  drm_atomic_connector_commit_dpms+0xe0/0x100 [drm]
Nov 07 19:50:48 phoenix kernel:  drm_mode_obj_set_property_ioctl+0x187/0x2b0 [drm]
Nov 07 19:50:48 phoenix kernel:  ? drm_mode_obj_find_prop_id+0x40/0x40 [drm]
Nov 07 19:50:48 phoenix kernel:  drm_ioctl_kernel+0xa4/0xf0 [drm]
Nov 07 19:50:48 phoenix kernel:  drm_ioctl+0x227/0x400 [drm]
Nov 07 19:50:48 phoenix kernel:  ? drm_mode_obj_find_prop_id+0x40/0x40 [drm]
Nov 07 19:50:48 phoenix kernel:  amdgpu_drm_ioctl+0x4f/0x90 [amdgpu]
Nov 07 19:50:48 phoenix kernel:  do_vfs_ioctl+0xa8/0x620
Nov 07 19:50:48 phoenix kernel:  ksys_ioctl+0x67/0x90
Nov 07 19:50:48 phoenix kernel:  __x64_sys_ioctl+0x1a/0x20
Nov 07 19:50:48 phoenix kernel:  do_syscall_64+0x5a/0x110
Nov 07 19:50:48 phoenix kernel:  entry_SYSCALL_64_after_hwframe+0x44/0xa9
Nov 07 19:50:48 phoenix kernel: RIP: 0033:0x7fd7518d23c7
Nov 07 19:50:48 phoenix kernel: Code: 00 00 90 48 8b 05 c9 3a 0d 00 64 c7 00 26 00 00 00 48 c7 c0 ff ff ff ff c3 66 2e 0f 1f 84 00 00 00 00 00 b8 10 00 00 00 0f 05 <48> 3d 01 f0 ff ff 73
Nov 07 19:50:48 phoenix kernel: RSP: 002b:00007ffc4956e528 EFLAGS: 00000246 ORIG_RAX: 0000000000000010
Nov 07 19:50:48 phoenix kernel: RAX: ffffffffffffffda RBX: 00005567d4e163e0 RCX: 00007fd7518d23c7
Nov 07 19:50:48 phoenix kernel: RDX: 00007ffc4956e560 RSI: 00000000c01864ba RDI: 000000000000000b
Nov 07 19:50:48 phoenix kernel: RBP: 00007ffc4956e560 R08: 0000000000000003 R09: 00005567d4e23930
Nov 07 19:50:48 phoenix kernel: R10: 00005567d4e12778 R11: 0000000000000246 R12: 00000000c01864ba
Nov 07 19:50:48 phoenix kernel: R13: 000000000000000b R14: 00007ffc4956e760 R15: 00007fd75268e8d0
Nov 07 19:50:48 phoenix kernel: ---[ end trace 0f20eacb3142b4af ]---


text:
Q: Pexpect and Bluetooth Low Energy notifications I am trying to automate the command line tool gatttool on a Raspberry Pi 3.
I am able to continually receive bluetooth notifications while using the tool manually: keying in the commands line by line using interactive mode.
However, with pexpect I am only able to receive several lines of notifications.
After setting up the correct write sequences to the bluetooth server, the Python script is as shown below:
while True:
    self.con.expect('\n')

This was done to flush to the logfile (sys.stdout)
Are there any buffer settings that might have tripped me up?
Any guidance will be very much appreciated.

A: Turns out that the default setting for "delaybeforesend" was too fast for the bluetooth device.
Slowing it down to 1 second before sending each command helped to resolve the issue.


text:
Q: Set size on Selectize.js Couldn't find any example or help at Selectize.js I really don't know if its possible, but I wold like to set it size like a normal Html select tag before the user choose an option.

<select class="Campo" id="selMedicacao" name="selMedicacao" size="5">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
  <option value="4">Option 4</option>
  <option value="5">Option 5</option>
  <option value="6">Option 6</option>
  <option value="7">Option 7</option>
  <option value="8">Option 8</option>
</select>

A: Solution was to create on an tab click event
$("#aProcedimento").on('click', function () {
    funPesProcPaciente(document.frmProcedimento);
});

the element after selectize.js script ran
function funPesProcPaciente(objForm) {
  var strXML = '../xxx/xxxxxxxxxx.xml.asp?cabxml=s&paciente=' +
  $('#intPaciente').val();
  var selProcPaciente = document.createElement("SELECT");
  funMontaComboXMLHistorico(document.getElementById('xmlProcedimento'), selProcPaciente, strXML, 'procedimento', 'A', 'numero', 'A', 'texto', 0, 0, document, '');
  selProcPaciente.setAttribute('size', '7');
  selProcPaciente.setAttribute('class', 'divPedido');
  selProcPaciente.setAttribute('id', 'divPedido');
  objselProcPaciente = document.getElementById('selProcPaciente')
  objselProcPaciente.innerHTML = '';
  objselProcPaciente.appendChild(selProcPaciente);
  strXML, 'requisicao', 'A', 'numero', 'A', 'texto', 0, 0, document);
}


text:
Q: Does Pelops and Hector support IPv6? I am using pelops to retrieve data from cassandra cluster which has all its servers running on IPv6.
While running this program getting following error.
Exception in thread "main" java.lang.RuntimeException: exception while checking if MBean is registered, com.scale7.cassandra.pelops.pool:type=PooledNode-testkeyspace-2001:1c11:90:111:2:6:8:10
        at org.scale7.cassandra.pelops.JmxMBeanManager.isRegistered(JmxMBeanManager.java:58)
        at org.scale7.cassandra.pelops.pool.PooledNode.<init>(PooledNode.java:66)
        at org.scale7.cassandra.pelops.pool.CommonsBackedPool.addNode(CommonsBackedPool.java:415)
        at org.scale7.cassandra.pelops.pool.CommonsBackedPool.<init>(CommonsBackedPool.java:137)
        at org.scale7.cassandra.pelops.pool.CommonsBackedPool.<init>(CommonsBackedPool.java:88)
        at org.scale7.cassandra.pelops.pool.CommonsBackedPool.<init>(CommonsBackedPool.java:76)
        at org.scale7.cassandra.pelops.Pelops.addPool(Pelops.java:48)
        at com.opera.osp.client.CassandraClient.<init>(Unknown Source)
        at com.opera.osp.validation.OSPDataValidator.main(Unknown Source)
Caused by: javax.management.MalformedObjectNameException: Invalid character ':' in value part of property
        at javax.management.ObjectName.construct(ObjectName.java:602)
        at javax.management.ObjectName.<init>(ObjectName.java:1403)
        at org.scale7.cassandra.pelops.JmxMBeanManager.isRegistered(JmxMBeanManager.java:54)
        ... 8 more

Does pelops have support for IPv6.If not I am planning to migrate to Hector but does Hector has this support either?

A: It looks like an issue unrelated to IPv6, if you use the IPv6 address in the MBean's name, escape it (for example replace it with "_").
I would assume they otherwise support IPv6 because Java does and they must be using Java's network API.


text:
Q: Duplicate in same row in different columns i have a table like this:
CREATE TABLE #my_table (
  intID int IDENTITY (1, 1),
  num_1 varchar(100) NOT NULL,
  num_2 varchar(100) NOT NULL,
  num_3 varchar(100) NOT NULL,
  num_4 varchar(100),
  num_5 varchar(100),
  isDuplicate char(1) DEFAULT 'N'
)

INSERT INTO #my_table (num_1, num_2, num_3, num_4, num_5)
  VALUES ('a', 'b', 'c', 'd', 'e')
INSERT INTO #my_table (num_1, num_2, num_3, num_4, num_5)
  VALUES ('a', 'b', 'c', 'd', 'e')
INSERT INTO #my_table (num_1, num_2, num_3, num_4, num_5)
  VALUES ('a', 'b', 'c', 'd', 'e')
INSERT INTO #my_table (num_1, num_2, num_3, num_4, num_5)
  VALUES ('a', 'b', 'a', 'd', 'e')
INSERT INTO #my_table (num_1, num_2, num_3, num_4, num_5)
  VALUES ('a', 'b', 'a', 'd', 'e')
INSERT INTO #my_table (num_1, num_2, num_3, num_4, num_5)
  VALUES ('a', 'b', 'c', 'd', 'c')

I need to find duplicates in columns and get the row number which is duplicate.
my result should be
duplicate rows last 3 rows and is duplicate flag should be updated to 'Y'

A: This could also do the trick:
UPDATE #my_table
    SET isDuplicate = 'Y'
WHERE intID IN (
    SELECT intID FROM #my_table
    WHERE EXISTS
       (SELECT 1
        FROM (VALUES
                   (num_1)
                  ,(num_2)
                  ,(num_3)
                  ,(num_4)
                  ,(num_5)) AS X (n)
        WHERE NULLIF(n, '') IS NOT NULL
        GROUP BY n
    HAVING COUNT(*)>1
   )
)

More information about table value constructors you can find here.

A: This should do the trick :
select  num_1, num_2, num_3, count(*)
from #my_table
group by num_1, num_2, num_3
having count(*) > 1

Regards

A: This would set the duplicate column in the table to 'Y' if its a duplicate, you can the query from that
UPDATE #my_table
SET isDuplicate = 'Y'
WHERE intID IN
(
    SELECT intID
    FROM
    (
        SELECT intID, num_1, num_2, num_3,num_4, num_5,
               RANK() OVER(PARTITION BY num_1, num_2, num_3, num_4, num_5 ORDER BY intID ASC) AS [rank]
        FROM #my_table
    ) a
    WHERE [rank] > 1
);

A: Try this:
UPDATE #my_table
SET isDuplicate =
CASE
    WHEN
    (select count(*)
    from #my_table t2
    where t2.intID <> #my_table.intID
    and t2.num_1 = #my_table.num_1
    and t2.num_2 = #my_table.num_2
    and t2.num_3 = #my_table.num_3
    and t2.num_4 = #my_table.num_4
    and t2.num_5 = #my_table.num_5
 ) > 0 then 'Y'
 ELSE 'N'
 END


text:
Q: Why implementation of interface methods only within optional class body of an enum constant causes compilation error? Why compilation of the code below results in error?
public class Test {
    public static void main(String[] args) {
        TestEnum.INSTANCE.run();
    }
}

enum TestEnum implements Runnable {
    INSTANCE {
        @Override public void run() {}
    };
}

$ javac Test.java
Test.java:3: cannot find symbol
symbol  : method run()
location: class TestEnum
        TestEnum.INSTANCE.run();
                         ^

A: It is the problem of Oracle JDK 1.6 compiler. With OpenJDK and with Oracle JDK 1.7 it works fine.


text:
Q: Save input field text displays over bootstrap datepicker I have a ASP.net MVC4 project where the bootstrap date pickers recently stopped working as intended in Chrome, they work fine in IE.
This image shows the issue I'm having.

My bundleconfig looks as follows:
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-1.12.4.js",
                    "~/Scripts/jquery-ui-1.12.1.js"
                    )
                    );

        bundles.Add(new ScriptBundle("~/bundles/createTimeRequest").Include(
                    "~/Scripts/createTimeRequest.js"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*"));

        bundles.Add(new ScriptBundle("~/bundles/moment").Include(
                    "~/Scripts/moment.js"));

        bundles.Add(new ScriptBundle("~/bundles/Calendar").Include(
                                "~/Scripts/fullcalendar.js"));

        // Use the development version of Modernizr to develop with and learn from. Then, when you're
        // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
        bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                    "~/Scripts/modernizr-*"));

        bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                  "~/Scripts/bootstrap.js",
                  "~/Scripts/jquery.dataTables.js",
                  "~/Scripts/dataTables.jqueryui.js",
                  "~/Scripts/dataTables.foundation.js",
                  "~/Scripts/dataTables.bootstrap.js",
                  "~/Scripts/dataTables.buttons.min.js",
                  "~/Scripts/bootstrap-datepicker.js",
                  "~/Scripts/buttons.print.min.js",
                  "~/Scripts/respond.js"));

        bundles.Add(new StyleBundle("~/Content/css").Include(
                   "~/Content/themes/base/jquery.ui.all.css",
                   "~/Content/themes/base/jquery.ui.base.css",
                   "~/Content/themes/base/jquery.ui.theme.css",
                   "~/Content/dataTables.bootstrap.css",
                   "~/Content/jquery.dataTables.css",
                   "~/Content/dataTables.foundation.css",
                   "~/Content/dataTables.jqueryui.css",
                   "~/Content/bootstrap.css",
                   "~/Content/bootstrap-datepicker.css",
                  // "~/Content/themes/base/datepicker.css",
                   "~/Content/fullcalendar.css",
                   "~/Content/site.css",
                   "~/Content/buttons.dataTables.min.css"
                  ));

The javascript file that tells the input field to be a datepicker via a class reference looks as follows:
var year = (new Date).getFullYear();
$(function () {
    $('.datepicker').datepicker({
        orientation: "right",
        startDate: new Date(year, 0, 1),
        //endDate: new Date(year, 11, 31)
    });

    $('.dpManager').datepicker({
        orientation: "right",
        endDate: '+365d'
    });

})

And the razor syntax in the view is as follows:

Select company: @Html.ListBox("Company", (MultiSelectList)ViewBag.Company, new { @class = "form-control", size = 9 })

                @Html.Label("Start Date:")
                @Html.Editor("sDateTime", new { htmlAttributes = new { @class = "dpManager form-control" } })

                @Html.Label("End Date:")
                @Html.Editor("eDateTime", new { htmlAttributes = new { @class = "dpManager form-control" } })

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/createTimeRequest")
}

This is my layout file:

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

   ........
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

This just happened this week, perhaps chrome rolled out a new update? You can see the datepicker is showing up but the saved input takes precedence for whatever reason. I tried updating my jquery & jquery ui. Only thing I didn't try yet was to update bootstrap. Not sure if I want to try that and break other things.
Any help is greatly appreciated.

A: I advice you to use autocomplete=off
<input autocomplete=off />

How do you disable browser Autocomplete on web form field / input tag?