text:
Q: Cannot get coordinates of simple success callback on getCurrentPosition function The getUserLocation() fires as well as the if statement. The navigator.geolocation.getCurrentPosition() function does not fire. I can't log anything inside that statement. I am not sure why nothing is happening..
Just logging in the arrow function. Nothing is showing there.
import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'google-map',
    templateUrl: './google-map.component.html',
    styleUrls: ['./google-map.component.css']
})
export class GoogleMapComponent implements OnInit {

  lat: number;

      lng: number;

      constructor() { }

      ngOnInit() {
        this.getUserLocation();

  }

   getUserLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition( position => {
          this.lat = position.coords.latitude;
          this.lng = position.coords.longitude;
      });
    }
  }

}

I need values for the lat/lng.

A: It requires that user consents to location sharing when
prompted by the browser.
If you see the error "The Geolocation service failed.", it means you probably did not give permission for the browser to locate you.
Check the api documentation.

A: Can you try to use Asyn Await
Also Window.navigator
async getUserLocation() {
    if (navigator.geolocation) {
    await window.navigator.geolocation.getCurrentPosition( position => {
          this.lat = position.coords.latitude;
          this.lng = position.coords.longitude;
      });
    }
  }

in my app I use the below code
 async getlocation() {
    if (window.navigator && window.navigator.geolocation) {
     await window.navigator.geolocation.getCurrentPosition(
        position => {
          console.log(position);
          return position;
        },
        error => {
          switch (error.code) {
            case 1:
              console.log('Permission Denied');
              break;
            case 2:
              console.log('Position Unavailable');
              break;
            case 3:
              console.log('Timeout');
              break;
          }
        }
      );
    }

  }

A: In order to use browser geolocation, you need the user to give consent. Otherwise, the call to the getCurrentPosition will silently fail.
Also, if the user is running your webapp, from latest Google Chrome browser,  you will need your website to work on HTTPS.


text:
Q: Scalar to array conversion I am looking at Perl script and I have a line:
my (@parmTypesList) = @$function_type_ref;

$function_type_ref is a string that is passed to the current function.
What does @$ means ?????

A: @$var is short for @{ $var } and equivalent to $var->@*. It is an array dereference.
It expects $var to hold a reference to an array, and it produces one of the following:

*

*In scalar context, the number of elements of the array

*In list context, the value of the elements of the array.

*When an array is expected (e.g. @$var = ..., push @$var, ...), the array itself.

In this case, it's the second.

Despite the name, in no way would a reference to a function work.
But a string might work, since a string can be used as a reference. In this situation, the string is expected to be the name of the variable. This is a horrible, horrible thing to do, so we tell Perl not to let us do this by using use strict; or use v5.12;.
Just to be clear: You should ALWAYS use use strict; or equivalent.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prime number upper bound I am reading some written notes about a proof I do not understand, maybe some informations are missing.
The result that has to be proved is the following:

if $p_n$ is the $n$-th prime number, then $p_n \leq 2^{n^2}$.

The proof is by induction on $n$, the case $n=1$ is trivial. So suppose $n>1$. There is $i \in \mathbb{N}$ such that
$$
2^i \leq p_n \leq 2^{i+1}.
$$
Then we consider a generic $m \leq p_n$, where $m=p_1^{\alpha_1} \cdots p_n^{\alpha_n} $ with $a_j \in \{0,1,\dots i\}$. Then (probably using the fact that there are $p_n$ naturals less or equal than $p_n$ and that $m$ is determined by $a_j$'s ??????) we get
$$
p_n \leq (i+1)^n
$$...
[CUT]
How do we get this last inequality?

A: What you write in parentheses is exactly the idea. Consider the set $S$ of natural numbers that can be written in the form $p_1^{\alpha_1}\cdots p_n^{\alpha_n}$ with each $\alpha_j \in \{0,1,\ldots,i\}$. Since each such expression is unique, this set is in bijection with the set of $n$-tuples $(\alpha_1,\ldots,\alpha_n)$ with each $\alpha_j \in \{0,1,\ldots,i\}$, of which there are $(i+1)^n$ elements. That is, $S$ has $(i+1)^n$ elements. However, every $m\leq p_n$ is in this set, as every $m \leq p_n$ can be written as a product of the primes $p_1,\ldots,p_n$. So $\{1,2,\ldots,p_n\} \subseteq S$, from which the inequality follows.


text:
Q: searching the string with the time in log file using shell script by passing variables I want to search a string and subtract the time that is found from the current time. When used, the script should show the lines from that time or from the very next log time frame.
I'm able to search the string and subtract the time from the current time, but it is searching the exact time and giving a result.
I want the script to look for the exact time. If the exact time is not found, it should show the result from whatever the nearest logged time to current time and it should show the log lines.
Expected Output:
If the both string and time not finding in log file, script should be intelligent to pick from the nearest log time and show result from that time to current time how many logs are there with that string.

A: The following script assumes you want to find the text in parameter 2, followed by :, followed by the date in parameter 3 formatted as YYYY-M-D-h:m:s, i.e. without leading zeroes, as per the snippet in your question.
#!/bin/bash

logfile="$1"
message="$2"
timestamp=$(printf '%d-%d-%d-%d:%d:%d' `date -d "$3" +"%Y %m %d %H %M %S"`)

if grep -q "^../../.. ..:..:.. $message : $timestamp\$" "$logfile"; then
  echo "OK: $message $timestamp found on $logfile"
else
  echo "CRITICAL - $message $timestamp not found on $logfile"
  exit 1
fi


text:
Q: Unique constraint violation thrown by sonarqube 5.6 analysis I've upgraded to sonarqube-5.6 and it seems to be working ok. One analysis is failing repeatedly though and the logs give this error.
016.07.28 21:57:03 ERROR [o.s.s.c.t.CeWorkerCallableImpl] Failed to execute task AVYzS8S3-v6iS1lU8Vlb
org.sonar.server.computation.component.VisitException: Visit failed for Component {key=XXX:src/test/resources,type=DIRECTORY}  located XXX(type=PROJECT)
    at org.sonar.server.computation.component.VisitException.rethrowOrWrap(VisitException.java:44) ~[sonar-server-5.6.jar:na]
    at org.sonar.server.computation.component.PathAwareCrawler.visit(PathAwareCrawler.java:52) ~[sonar-server-5.6.jar:na]
    at org.sonar.server.computation.component.PathAwareCrawler.visitChildren(PathAwareCrawler.java:87) ~[sonar-server-5.6.jar:na]
    at org.sonar.server.computation.component.PathAwareCrawler.visitImpl(PathAwareCrawler.java:70) ~[sonar-server-5.6.jar:na]
    at org.sonar.server.computation.component.PathAwareCrawler.visit(PathAwareCrawler.java:50) ~[sonar-server-5.6.jar:na]
    at org.sonar.server.computation.step.PersistComponentsStep.execute(PersistComponentsStep.java:77) ~[sonar-server-5.6.jar:na]
    at org.sonar.server.computation.step.ComputationStepExecutor.executeSteps(ComputationStepExecutor.java:64) ~[sonar-server-5.6.jar:na]
    at org.sonar.server.computation.step.ComputationStepExecutor.execute(ComputationStepExecutor.java:52) ~[sonar-server-5.6.jar:na]
    at org.sonar.server.computation.taskprocessor.report.ReportTaskProcessor.process(ReportTaskProcessor.java:75) ~[sonar-server-5.6.jar:na]
    at org.sonar.server.computation.taskprocessor.CeWorkerCallableImpl.executeTask(CeWorkerCallableImpl.java:81) [sonar-server-5.6.jar:na]
    at org.sonar.server.computation.taskprocessor.CeWorkerCallableImpl.call(CeWorkerCallableImpl.java:56) [sonar-server-5.6.jar:na]
    at org.sonar.server.computation.taskprocessor.CeWorkerCallableImpl.call(CeWorkerCallableImpl.java:35) [sonar-server-5.6.jar:na]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_101]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_101]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_101]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [na:1.8.0_101]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [na:1.8.0_101]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_101]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_101]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_101]
Caused by: org.apache.ibatis.exceptions.PersistenceException:
### Error updating database.  Cause: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (XXX.PROJECTS_KEE) violated

### The error may involve org.sonar.db.component.ComponentMapper.insert-Inline
### The error occurred while setting parameters
### SQL: INSERT INTO projects (kee, deprecated_kee, uuid, project_uuid, module_uuid, module_uuid_path, name, long_name,     qualifier, scope, language, description, root_id, path, copy_resource_id, person_id, enabled,     created_at, authorization_updated_at)     VALUES (?, ?, ?,     ?, ?, ?,     ?, ?, ?, ?,     ?, ?,     ?, ?, ?,     ?,     ?,     ?, ?)
### Cause: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (XXX.PROJECTS_KEE) violated

    at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:26) ~[mybatis-3.2.7.jar:3.2.7]
    at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:154) ~[mybatis-3.2.7.jar:3.2.7]
    at org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:141) ~[mybatis-3.2.7.jar:3.2.7]
    at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:51) ~[mybatis-3.2.7.jar:3.2.7]
    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:52) ~[mybatis-3.2.7.jar:3.2.7]
    at com.sun.proxy.$Proxy38.insert(Unknown Source) ~[na:na]
    at org.sonar.db.component.ComponentDao.insert(ComponentDao.java:278) ~[sonar-db-5.6.jar:na]
    at org.sonar.server.computation.step.PersistComponentsStep$PersistComponentStepsVisitor.persistComponent(PersistComponentsStep.java:171) ~[sonar-server-5.6.jar:na]
    at org.sonar.server.computation.step.PersistComponentsStep$PersistComponentStepsVisitor.persistAndPopulateCache(PersistComponentsStep.java:163) ~[sonar-server-5.6.jar:na]
    at org.sonar.server.computation.step.PersistComponentsStep$PersistComponentStepsVisitor.visitDirectory(PersistComponentsStep.java:135) ~[sonar-server-5.6.jar:na]
    at org.sonar.server.computation.component.PathAwareCrawler.visitNode(PathAwareCrawler.java:102) ~[sonar-server-5.6.jar:na]
    at org.sonar.server.computation.component.PathAwareCrawler.visitImpl(PathAwareCrawler.java:67) ~[sonar-server-5.6.jar:na]
    at org.sonar.server.computation.component.PathAwareCrawler.visit(PathAwareCrawler.java:50) ~[sonar-server-5.6.jar:na]
    ... 18 common frames omitted

EDIT: further investigation shows that removing the XML plugin prevents this error from occurring. The repository contains a single xml file src/test/resources/logback-test.xml and the offending directory is present in the sonar.tests property. This seems like it must be a defect to me.


text:
Q: Firebase realtime database setValue() not working I am trying to write some basic information about users to a Firebase realtime database, but when running setValue() nothing happens in the console and after many hours of trying I still can't figure out the problem.
This is the code in the fragment that calls the registerUser function:
registerButton.setOnClickListener {

        firstNameLayout.error = null
        lastNameLayout.error = null
        emailFieldLayout.error = null
        passwordFieldLayout.error = null

        var fieldCheck = true

        if(TextUtils.isEmpty(firstNameField.text)) {
            firstNameLayout.error = "Please Enter First Name";
            fieldCheck = false
        }
        if (TextUtils.isEmpty(lastNameField.text)) {
            lastNameLayout.error = "Please Enter Last Name"
            fieldCheck = false
        }
        if(TextUtils.isEmpty(emailField.text)) {
            emailFieldLayout.error = "Please Enter Email Address";
            fieldCheck = false
            // Todo: Make sure format is correct
        }
        if(TextUtils.isEmpty(passwordField.text)){
            passwordFieldLayout.error = "Please Choose a Password"
            fieldCheck = false
            // Todo: Stricter password requirements
        }
        if(!fieldCheck) {
            return@setOnClickListener
        }

        registerButton.startAnimation()

        val fName = firstNameField.text.toString().trim()
        val lName = lastNameField.text.toString().trim()
        val email = emailField.text.toString().trim()
        val password = passwordField.text.toString().trim()

        try {
            registerButton.doneLoadingAnimation(2, bitmap)
            (activity as LoginRegister).registerUser(email, password, fName, lName)

        } catch (e: Exception) {
            Toast.makeText(activity, e.message, Toast.LENGTH_SHORT).show()
            registerButton.revertAnimation()
        }

    }

This is the registerUser function body from the parent activity of the fragment:
fun registerUser(email: String, password: String, fName: String, lName: String) {
    //Registrerer med Firebase Authentication
    auth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                // Sign in success, update UI with the signed-in user's information
                Log.d(TAG, "createUserWithEmail:success")
                val user : FirebaseUser = task.result!!.user!!
                val uid: String = user.uid
                val dbUser = User(fName, lName, email)

                writeNewUser(uid, dbUser)

                val intent = Intent(this@LoginRegister, MainActivity::class.java)
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                intent.putExtra("user_email", email)
                intent.putExtra("user_first_name", fName)
                intent.putExtra("user_last_name", lName)
                startActivity(intent)
                finish()

            } else {
                // If sign in fails, display a message to the user.
                Log.w(TAG, "createUserWithEmail:failure", task.exception)
                Toast.makeText(baseContext, "Authentication failed.", Toast.LENGTH_SHORT).show()
            }
        }

}

This is the writeNewUser function body
fun writeNewUser(userId: String, user: User) {
    database = FirebaseDatabase.getInstance().getReference("Users").child(userId)
    database.child("users").child(userId).setValue(user)
}

The User object is instantiated from this kotlin class:
data class User(val fName: String? = null, val lName: String? = null, val email: String? = null) {
val firstName = fName?.capitalize(Locale.ROOT)
val lastName = lName?.capitalize(Locale.ROOT)
val emailAddress = email

}
Firebase:
Firebase nodes
Anyone know the reason behind this?

A: put the URL of database in the getInstance() was the solution for me, now it works perfect
example:
private val database = FirebaseDatabase.getInstance("https://conect-c91b3-default-rtdb.firebaseio.com/").getReference()

// to test if is working
database.child("users").setValue("test")

A: I solved it, I was using another database location than the default, and I didn't catch the fact that I needed to pass the database URL in the getInstance() method. Passing the correct database url fixed the issue

A: fun writeNewUser(userId: String, user: User) {
    database = FirebaseDatabase.getInstance().getReference("Users").child(userId)
    database.child("users").child(userId).setValue(user)
}

I guess you duplicate a couple of child nodes in above snippet as it implies a group of users has a single user, and this particular user has a group of users, doesn't make sense, so you can remove these duplicates:
fun writeNewUser(userId: String, user: User) {
    database = FirebaseDatabase.getInstance().getReference("Users").child(userId)
    database.setValue(user)
}

UPDATE:

The firebase nodes are case-sensitive, so change "Users" to lowercase "users"
fun writeNewUser(userId: String, user: User) {
    database = FirebaseDatabase.getInstance().getReference("users").child(userId)
    database.setValue(user)
}


text:
Q: Wiznet Wiz820io (W5200) Module - No data on MISO Line I had a working circuit with Wiznet W5100, but to get better performance I switched over to Wiznet W5200 (in Wiz820io module). This involved rewiring the pins, changing the register address and also the Read/Write code for the ethernet module as this chip supports Burst Write.
Datasheet here
However (this has me totally stumped), when I power on the circuit and read the registers that I have just written to (GATEWAY, IP etc), all I get is 0x00.
This is what I got using logic analyzer

The MISO line is just flat. No data being sent back to the master.
These are my read/write routines for the Ethernet module :
//OP CODES (TO BE OR'ED WITH UPPER 7 BITS OF ADDRESS)
#define W5200_WRITE             0x80
#define W5200_READ              0x00

//BURST WRITING FOR W5200. FOR DATA LENGTH = 1, DEFAULTS TO BYTE WRITE
void ETHERNET_WRITE(uint16_t address, uint8_t *data, uint16_t len)
{
    W5200_SS_LOW;       //SET W5200 SS LOW

    SPI_TXRX((address & 0xFF00)>>8); //WRITE HIGH BYTE OF 2 BYTE ADDRESS
    while(SPI_DATA_RECEIVED==0);

    SPI_TXRX((address & 0x00FF)); //WRITE LOW BYTE OF 2 BYTE ADDRESS
    while(SPI_DATA_RECEIVED==0);

    SPI_TXRX(W5200_WRITE | ((len & 0x7F00)>>8));    //WRITE OPCODE | DATA LENGTH (UPPER 7 BITS)
    while(SPI_DATA_RECEIVED==0);

    SPI_TXRX(len & 0x00FF); //DATA LENGTH (LOWER 8 BITS)
    while(SPI_DATA_RECEIVED==0);

    for(uint16_t i=0; i<len; i++)
    {
        SPI_TXRX(data[i]); //WRITE DATA
        while(SPI_DATA_RECEIVED==0);
    }

    W5200_SS_HIGH; //TURN BACK SS HIGH
}

//BURST READING FOR W5200. FOR DATA LENGTH = 1, DEFAULTS TO BYTE READ
void ETHERNET_READ(uint16_t address, uint8_t len, uint8_t* retval)
{
    W5200_SS_LOW;       //SET W5200 SS LOW

    SPI_TXRX((address & 0xFF00)>>8); //WRITE HIGH BYTE OF 2 BYTE ADDRESS
    while(SPI_DATA_RECEIVED==0);

    SPI_TXRX(address & 0x00FF); //WRITE LOW BYTE OF 2 BYTE ADDRESS
    while(SPI_DATA_RECEIVED==0);

    SPI_TXRX(W5200_READ | ((len & 0x7F00)>>8)); //READ OPCODE | DATA LENGTH (UPPER 7 BITS)
    while(SPI_DATA_RECEIVED==0);

    SPI_TXRX(len & 0x00FF); //DATA LENGTH (LOWER 8 BITS)
    while(SPI_DATA_RECEIVED==0);

    for(uint8_t i=0; i<len; i++)
    {
        SPI_TXRX(0x00); //WRITE DUMMY DATA TO READ DATA
        while(SPI_DATA_RECEIVED==0);
        retval[i] = SPI_RX_DATA;
    }
    W5200_SS_HIGH;  //SET SS HIGH
}

Initially I was powering this module using LM2950 33, but since it's max current output is 100mA, I moved over to LM317 adjustable LDO that is now powering the module with 3.14V
This is my ethernet intialization code
void ETHERNET_INIT(uint16_t ip_address, uint16_t subnet_address, uint16_t gateway_address, uint16_t mac)
{
    uint8_t val[6];
    uint8_t retval[6];
    uint8_t i;

    W5200_RESET_LOW;
    _delay_us(50);
    W5200_RESET_HIGH;
    for(i=0;i<20; i++)
    {
        _delay_ms(20);
    }

    val[0] = MR_RST;
    ETHERNET_WRITE(MR, val,1);
    ETHERNET_READ(MR, 1, retval);
    while(retval[0] !=0) {ETHERNET_READ(MR, 1, retval);}

    printf("*** Ethernet ****\r");

    //if(ETHERNET_DEBUG)
    //{
        ETHERNET_READ(MR, 1, retval);
        printf("Reading MR : %u\r", retval[0]);
    //}

    //set IP Address
    EEPROM_READ(ip_address, 4, retval);
    ETHERNET_WRITE(SIPR, retval, 4);
    //if(ETHERNET_DEBUG)
    //{
        ETHERNET_READ(SIPR, 4, retval);
        printf("IP Address : %u.%u.%u.%u\r",retval[0],retval[1],retval[2],retval[3]);

    //}

    //set subnet mask
    EEPROM_READ(subnet_address, 4, retval);
    ETHERNET_WRITE(SUBR, retval, 4);
    //if(ETHERNET_DEBUG)
    //{
        ETHERNET_READ(SUBR, 4, retval);
        printf("Subnet Mask : %u.%u.%u.%u\r",retval[0],retval[1],retval[2],retval[3]);
    //}

    //set gateway address
    EEPROM_READ(gateway_address, 4, retval);
    ETHERNET_WRITE(GWR, retval, 4);
    //if(ETHERNET_DEBUG)
    //{
        ETHERNET_READ(GWR, 4, retval);
        printf("Gateway ip Address : %u.%u.%u.%u\r",retval[0],retval[1],retval[2],retval[3]);
    //}

    //set mac address
    EEPROM_READ(mac, 6, retval);
    ETHERNET_WRITE(SHAR, retval, 6);
    //if(ETHERNET_DEBUG)
    //{
        ETHERNET_READ(SHAR, 6, retval);
        printf("mac Address : %02X.%02X.%02X.%02X.%02X.%02X\r",retval[0],retval[1],retval[2],retval[3],retval[4],retval[5]);
    //}

    //set interrupt high time
    val[0] = 1;
    ETHERNET_WRITE(INTLEVEL, val, 1);

    //set TX and RX memory to 2KB per socket
    //val[0] = 0x55;
    //ETHERNET_WRITE(RMSR, val, 1);
    //ETHERNET_WRITE(TMSR, val, 1);

    //set TX = 8Kb RX = 8Kb for Sock 0 & Sock 1
    val[0] = 0x08;
    ETHERNET_WRITE(SOCKET_0_REGISTER_BASE + SN_RX_MEMSIZE, val, 1);
    ETHERNET_WRITE(SOCKET_0_REGISTER_BASE + SN_TX_MEMSIZE, val, 1);
    ETHERNET_WRITE(SOCKET_1_REGISTER_BASE + SN_RX_MEMSIZE, val, 1);
    ETHERNET_WRITE(SOCKET_1_REGISTER_BASE + SN_TX_MEMSIZE, val, 1);
    val[0] = 0x00;
    ETHERNET_WRITE(SOCKET_2_REGISTER_BASE + SN_RX_MEMSIZE, val, 1);
    ETHERNET_WRITE(SOCKET_2_REGISTER_BASE + SN_TX_MEMSIZE, val, 1);
    ETHERNET_WRITE(SOCKET_3_REGISTER_BASE + SN_RX_MEMSIZE, val, 1);
    ETHERNET_WRITE(SOCKET_3_REGISTER_BASE + SN_TX_MEMSIZE, val, 1);
    ETHERNET_WRITE(SOCKET_4_REGISTER_BASE + SN_RX_MEMSIZE, val, 1);
    ETHERNET_WRITE(SOCKET_4_REGISTER_BASE + SN_TX_MEMSIZE, val, 1);
    ETHERNET_WRITE(SOCKET_5_REGISTER_BASE + SN_RX_MEMSIZE, val, 1);
    ETHERNET_WRITE(SOCKET_5_REGISTER_BASE + SN_TX_MEMSIZE, val, 1);
    ETHERNET_WRITE(SOCKET_6_REGISTER_BASE + SN_RX_MEMSIZE, val, 1);
    ETHERNET_WRITE(SOCKET_6_REGISTER_BASE + SN_TX_MEMSIZE, val, 1);
    ETHERNET_WRITE(SOCKET_7_REGISTER_BASE + SN_RX_MEMSIZE, val, 1);
    ETHERNET_WRITE(SOCKET_7_REGISTER_BASE + SN_TX_MEMSIZE, val, 1);

    //set RTR - retry time value register for timeout @ 2000us
    val[0] = 0x07;
    val[1] = 0xD0;
    ETHERNET_WRITE(RTR, val, 2);
    //if(ETHERNET_DEBUG)
    //{
        ETHERNET_READ(RTR, 2, retval);
        printf("rtr : %x:%x\r", retval[0], retval[1]);
    //}

    //set RCR - max retry count to 8
    val[0] = 0x08;
    ETHERNET_WRITE(RCR, val, 1);
    //if(ETHERNET_DEBUG)
    //{
        ETHERNET_READ(RCR, 1, retval);
        printf("rcr : %u\r", retval[0]);
    //}

    //enable mask for socket 1 interrupt
    val[0] = IMR_S1_INT;
    ETHERNET_WRITE(IMR, val, 1);
    if(ETHERNET_DEBUG)
    {
        ETHERNET_READ(IMR, 1, retval);
        printf("IMR : 0x%x\r",retval[0]);
    }
}

Any ideas?

A: It's working now. It was the Reset line going from my AVR to the W5200 module. It was never going down to 0V, hence the unit was never getting resetted.
Not sure how I managed to screw up the i/o pin. Connecting the reset line to a different pin on the AVR solved the issue.


text:
Q: how to draw pie chart in php using chart.js? I have php file with some code..In that I have to display single pie chart as well as multiple pie charts for some cases.
How to draw those pie charts using charts.js file.
I dont have any idea about how to use that file for my chart with database data.
Please suggest me.
Thanks in advance.

A: Let's assume after the php code executes it spits the data using JSON.
Using Chart.js
you can initiate the chart using
var myPieChart = new Chart(ctx[0]).Pie(data,options);
and the data is like this
var data = [
    {
        value: 300,
        color:"#EEE",
        label: "Cars"
    },
    {
        value: 50,
        color: "#000",
        label: "Buses"
    }
]

It will draw the chart for you.
You also need an option object to override the various available options.


text:
Q: How solve this problem syntax error in UPDATE statement This problem at syntax error for update statement then I don't know how to solve this problem
Private Sub editStaff()

   Try
        If con.State = ConnectionState.Closed Then
            con.Open()
        End If

        If IDTextBox.Text <> "" And FirstTextBox.Text <> "" And SecondTextBox.Text <> "" And UsernameTextBox.Text <> "" And PasswordTextBox.Text <> "" Then
            strSQL = "update Staff set First_Name = '" & FirstTextBox.Text & "', " &
                "Second_Name = '" & SecondTextBox.Text & "', " & "Username = '" & UsernameTextBox.Text & "', " &
                "Password = '" & PasswordTextBox.Text & "'" & " where ID = " & CInt(IDTextBox.Text) & ""

            Dim cmd As OleDbCommand = New OleDbCommand(strSQL, con)
            Try
                cmd.ExecuteNonQuery()
                cmd.Dispose()
                con.Close()
                MessageBox.Show("Update Successful")
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
        End If
    Catch ex As Exception
        MessageBox.Show(ex.ToString)
    End Try
End Sub

A: For some reason your validation If did not include the ID text box. I added validation for this text box. The OrElse is a short circuit. As soon as it finds a True it stops checking the conditions and proceeds to the next line.
This code
        If con.State = ConnectionState.Closed Then
            con.Open()
        End If

is completely unnecessary if you keep your database objects local. Keeping them local allows you to ensure they are closed and disposed with Using...End Using blocks.
Don't open the connection until you need it which is directly before the .Execute... line. Use parameters to avoid Sql Injection. Also your Update statement is much easier to write without all the single quotes and double quotes and ampersands.
Caution In Access the order that the parameters appear in the Sql statement must match the order that they are added to the .Parameters collection.
Finally, you should NEVER store passwords as plain text. I will leave it to you to research salting and hashing and correct the code.
Private Sub editStaff()
    Dim i As Integer
    If Integer.TryParse(IDTextBox.Text, i) Then
        MessageBox.Show("ID text box must be a number")
        Return
    End If

    If IDTextBox.Text = "" OrElse FirstTextBox.Text = "" OrElse SecondTextBox.Text = "" OrElse UsernameTextBox.Text = "" OrElse PasswordTextBox.Text = "" Then
        MessageBox.Show("Please fill in all text boxes")
        Return
    End If
    Try
        Using con As New OleDbConnection("Your connection string")
            Dim strSQL = "Update Staff set First_Name = @FirstName, Second_Name = @SecondName, [Username] = @UserName, [Password] = @Password Where [ID] = @ID"
            Using cmd As New OleDbCommand(strSQL, con)
                With cmd.Parameters
                    .Add("@FirstName", OleDbType.VarChar).Value = FirstTextBox.Text
                    .Add("@SecondName", OleDbType.VarChar).Value = SecondTextBox.Text
                    .Add("@UserName", OleDbType.VarChar).Value = UsernameBox.Text
                    .Add("@Password", OleDbType.VarChar).Value = PasswordTextBox.Text
                    .Add("@ID", OleDbType.Integer).Value = CInt(IDTextBox.Text)
                End With
                con.Open()
                cmd.ExecuteNonQuery()
            End Using
        End Using
        MessageBox.Show("Update Successful")
    Catch ex As Exception
        MessageBox.Show(ex.ToString)
    End Try
End Sub


text:
Q: Android: finish() Activity Runtime Exception I am closing an activity via finish().
It works fine on several devices but on a Samsung Galaxy S3 Neo running Android 4.4 I get the following issue:
java.lang.RuntimeException
android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3706)
android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3724)
android.app.ActivityThread.access$1500(ActivityThread.java:169)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:136)
android.app.ActivityThread.main(ActivityThread.java:5476)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
dalvik.system.NativeStart.main(Native Method)
Caused by: android.util.Log.println_native(Native Method)
android.util.Log.e(Log.java:307)
com.ads.adstimer.fragment.Registration.RegistrationActivity.onDestroy(RegistrationActivity.java:214)
android.app.Activity.performDestroy(Activity.java:5623)
android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1123)
android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3693)
android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3724)
android.app.ActivityThread.access$1500(ActivityThread.java:169)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:136)
android.app.ActivityThread.main(ActivityThread.java:5476)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
dalvik.system.NativeStart.main(Native Method)

I have found two posts about that subject: First, Second
But they did not help me.
My activity code. Note that I am using AppIntro:
    public class RegistrationActivity extends AppIntro {

       private AsyncTaskRegisterInBackground registerPushToken;

       (...)

          @Override
            public void onDonePressed() {

               (...)
               if (regid.isEmpty()) {
                                registerPushToken = new AsyncTaskRegisterInBackground();
                                registerPushToken.setParams(activity, gcm, regid);
                                registerPushToken.execute();
                            }
               (...)

            }

    @Override
        public void onTaskCompleted(String responseRegid) {
            try {
                // load authToken from Server: JsonObjectRequest

 builderOnFailureDialog = new MaterialDialog.Builder(activity)
                        .title(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_title))
                        .content(onFailureDialogContent)
                        .positiveText(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_positive_text))
                        .negativeText(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_negative_text))
                        .onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                activity.finish();
                            }
                        });

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        try {
            onFailureDialog.dismiss();
            onSuccessDialog.dismiss();
        } catch (Exception e) {
            Log.e("Activity.onDestroy()", e.getMessage());
        }
    }

}

Or is the reason for the problem the async task running in background?

A: call finish() inside runOnUiThread().
i.e.
replace
finish();

with
runOnUiThread(new Runnable() {
                public void run() {
                    finish()

                }
            });


text:
Q: Exception in thread ArrayIndex I was doing some beginner programming with series and input but im having the same problem constantly.Cant find the solution.Basically what i want my program to do for now i input a list of numbers and print them out.And im getting the same error over and over whatever i change in program.Here is my code.
import java.util.Scanner;
public class Test437 {
public static void main(String[] args) {

  int limit = 25;
  int cnt;
  int addtion;
  double dbt; //Devided by two % 2

  Scanner input = new Scanner(System.in);
  int [] ya = new int[8];

  for(cnt = 0;cnt < ya.length;cnt++)
  {

      System.out.print("ya[" + cnt + "]= ");
      ya[cnt] = input.nextInt();

  }

      System.out.println(ya[cnt]);

  }
  }

Im getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
        at Test437.main(Test437.java:22)

A: System.out.println(ya[cnt]); this line is outside loop. Cnt is equal to an array size so it cannot be used in such way because there is no element in the array with such index.

A: cnt condition to leave the loop is to exceed the length therefore you get in indexoutofbounds

A: This line
        System.out.println(ya[cnt]);

is trying to access element at ya.Length index which does not exists.
In your example ya[8] contains elements at position from 0  to 7 (ya[0] ya[1] ... ya[7] and you're trying to access ya[8] bacuase cnt variable is 8 after the for statement ends.
Therefore the compiler throws an indexOutOfBounds exception.

A: The line:
System.out.println(ya[cnt]);

needs to be in a loop again to print out all the array values after accepting them:
for (cnt = 0;cnt < ya.length;cnt++) {
   System.out.println(ya[cnt]);
}

Alternatively, you could do:
System.out.println(Arrays.toString(ya));


text:
Q: schedule compliance and keeping technical supports and resolving issues I am an entrepreneur of a small software developer company. The flagship product is developed by myself and my company grew up to 14 people. One of pride is that we've never have to be invested or loaned.
The core development team is 5 people. 3 are seniors and 2 are juniors.
After the first release, we've received many issues from our customers. Most of them are bug issues, customization needs, usage questions and upgrade requests.
The issues from customers are incoming many times everyday, so it takes little time or much time of our developers. Because of our product is a software development kit(SDK) so most of questions can be answered only from our developers. And, for resolving bug issues, developers must be involved. Estimating time to resolve bug is hard. I fully understand it. However, our developers insist they cannot set the any due date of each project because they are busy doing technical supports and bug fixes by issues from customers everyday. Of course, they never do overwork.
I suggested them an idea to divide the team into two parts: one for focusing on development by milestones, other for doing technical supports and bug fixes without setting due days. Then we could announce release plan officially. After the finish of release, two parts exchange the role for next milestone.
However, they say they "NO, because it is impossible to share knowledge and design document fully." They still say they cannot set the release date and they request me to alter the due date flexibly. They does not fix the due date of each milestone. Fortunately, our company is not loaned and invested so we are not chocked. But I think it is bad idea to keep this situation. I know the story of ant and grasshopper.
Our customers are tired of waiting forever of our release date. Companies consume limited time and money. If flexible due date without limit could be acceptable, could they accept flexible salary day?
What is the root cause of our problem? All that I want is to fix and achieve precisely due date of each milestone without losing frequent technical supports.
I think there must be solution for this situation. Please answer me.
Thanks in advance.
PS. Our tools and ways of project management are Trello, Mantis-like issue tracker, shared calendar software and scrum(collected cards into series of 'small and high completeness' projects).

A: This is not something that my team does today but it's a proposed change to our process that I've been floating by other people for a little while (and I'm curious what the community thinks about this, so all comments welcome)...
You said your team is already doing scrum and have a backlog of work represented by cards. To a developer working on a new feature (new development) and getting it to work, is very similar to working on an existing broken feature (bug fixing) and getting it to work.  Work is work.
You, as a product owner, could treat bug fixing same way you treat new development tasks and prioritize them in the same backlog. Some bugs (or feature requests) can wait, others must be fixed. Some are very important, some can be fixed later. You can decide on these factors and put them in the appropriate place in the backlog and you can decide if they should be in current release or delayed till next one.
This way, as long as your team maintains point velocity, you should be able to get a rough idea of when the release is going to be completed.  All you have to do is plot a graph with two lines that interpolate the following data sets:

*

*Your team's story completion - how many cumulative points are completed each iteration

*Your teams's scope creep - total number of points which are part of the release. this number will obviously go up when you add bugs to be part of the release, but that's just a reflection of reality.

At a point in time where the two lines intersect is your estimated release date.
I agree with your developers that splitting the team is not ideal. Personally, I would hate to be isolated in maintenance land while the other part of my team drove the architecture and major design decisions without me. At the same time, if you feel that 2/5 developers should be dedicated to bug fixing, what about simply requiring that 40% of time (no more, no less) in a given iteration be dedicated exclusively to bugs, but the whole team would be involved?
Aside from figuring out the scheduling problem, as other mentioned, you as a team should also figure out the root cause of so many bugs coming in that they are affecting the schedule. Don't look for a solution yourself, instead hold a series of retrospective meetings and let the team drive the discussion. Work together to set reasonable quality goals/targets and then ask them for ideas on how to achieve them.
Don't know if your team is doing any of these today, but here some ideas:

*

*Design reviews - before jumping into work, have a quick peer review of the work ahead. This gives a chance for a second set of eyes to spot potential problems before they get into code, which is much more expensive to fix.

*Code review - With a help of code review tools (some are open source), code review process can be run very effectively. It'll help you share knowledge and identify potential problem areas before they even get into production code.

*QA - do you have a dedicated testing team or do developers do their own testing? I find that developers tend to get conditioned or "get used" to how software works and they start overlooking usability issues. Fresh set of eyes from end-user perspective can find all kinds of things.

*TDD/Automated unit tests - this one isn't easy and many teams have tried and failed at it. But if done right, it'll let you deliver components which would be much more solid and would not require your guys to come back to them month after month. Also for some engineers, who are not as detailed oriented, TDD can work wonders. I've worked with some guys who write decent code and produce functionality, but they consistently miss boundaries and what-if cases. I would argue that spending time up-front of writing test code would be a great investment vs. time spent after each one of those boundary cases is encountered by the customer and requires a fix after the release. With TDD, it's another opportunity to verify use case scenarios and then simply let developers loose. When tests pass, you'll be much more comfortable that you are releasing something with quality.

A: This is a common and challenging problem. Many customer issues are genuinely lengthy research projects in their own right, and until they are fully understood, it is just not possible to estimate the effort required to fix them.
One solution to this is to dedicate two developers at a time strictly to issue resolution, rotating the assignment to another pair of developers every three or four weeks.

A: I see a few issues here:

*

*Your software seems excessively buggy if your developers are being swamped with bug reports. You need to take a look (Root Cause Analysis) at the bugs being raised and see why they're occuring. If you don't do this you'll merely run into the same issues at each release.

*Measure the bug fixing process. Record the date the bug was raised, the date the investigation began, the date a suggested fix was found. See if there are blockers here.

*Is your documentation bad? Are your UIs unintuitive?

*You don't seem to have the resources to support more than one version of your product. There comes a point when you stop maintaining old releases of products unless there are exceptional circumstances (critical/showstopper bugs), and if a customer wants something in an old product you have to know when to tell them No/It's not worth fixing.

*You're the boss, if you want your employees to work in a new way they should. Listen to their protests but explain to them why things need to change and ask them if they can see alternatives.

A: If you have too many bugs in your current version, then dedicating resources to the next version (before reducing the bug count) is going to only add more bugs.
I'd make it a priority to

*

*prioritize the existing bugs

*find and fix the high priority ones

*perform a Root Cause Analysis to figure out why you're getting so many bugs

Tell your developers to SLOW DOWN.  Writing buggy code quickly is more damaging than writing stable code slowly.

A: The scenario is:

*

*Your team is fourteen people, with five developers.

*You are privately help and debt free.

*Your customer likes your product enough to engage with you instead of going to someone else.

*You have a technical business, and a non-technical person can't support the product.

*Your developers need their focus for features and bug fixes.

*Your developers don't want to alternate between feature development and bug fixes.

*You are busy developing, but have not had recent releases to customers.

*You have been favoring the creation of features to the correction of defects, maybe for a while now.

The answer is simple, but depending on whether your team has a mature attitude, unpleasant.

*

*You need to pay the technical debt to fix the bugs.

*You need to support customers using members of the team.

Your original instinct was probably correct.  Some team members need to work features and some bugs, alternating periodically.  If you went through the bug database and traced the defect to its author, that would be a way to assign the bugs and perhaps determine the duration of each person's rotation.  However, sometimes, the bug exists because the person writing the particular code didn't have the skill to write it.  This may be where your distinction between junior and senior team members can be of benefit.
WRT customer support, I recommend that you rotate that function as well.  If a small number of people work customer support, they will hear the same questions and provide the same answers, potentially building a database of FAQs.  Once you have written collateral for support, you can use less technical people to share it with customers.  There are many systems for automated customer support including Right Now Web which might be too expensive, but perhaps it can help you find leads to an open source alternative.  Not everyone on your team will have the talents needed for working with customers, so you may find you need to bite the bullet and if you have the skill, do it yourself.  At least for a while.


text:
Q: What is the steps of classification of imbalanced dataset? I need some help from anyone who is familiar with the problem I am facing.
I want to do a classification using SVM, Random Forest and Deep Neural Network(DNN) with two different datasets. One of my datasets is balanced and another one data is highly imbalanced. Below is the image of my dataset which is imbalanced for classification.

I want to compare the results of the classification for all machine learning used for both data. Which dataset is producing better results for classification. For balanced dataset, I've got no problem cause the way to handle it normally but for imbalanced I am a little bit confused.
My problem is that I am confused about what is the steps for doing the classification using the imbalanced data. From what I know is that to handle the imbalanced data, we should do sampling.
Do I have to classify first and get the results or should I do the oversampling first and classify and get the results? What are the proper steps in doing the classification with the imbalanced dataset? I hope anyone can help me with this because I am still new in this area.
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report

data=pd.read_csv("ImbalancedData.csv")

y = data.Class
x = data.drop('Class,axis=1)

x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.3)

A: Like said in the comments, I also think this question is not really suited for SO. But, still to help you, you have a few options:
1) you can take care of imbalance of the data - undersampling the majority class, upsample the minority class etc. You can check SMOTE.
2) for your train and test split, it's important to keep the distribution same between train and test in order to get good results that reflect the real data. Scikit-learn has StrattifySplit that lets you do that instead of regular train_test_split.
3) you can use specific models that are known to he working well with imbalanced data and solve it as if it's an anomaly detection problem. Check out Isolation Forests, Local Outlier Factor, Autoencoders (unsupervised) etc. that can give you better results. Keep in mind that there are many others and hyperparameters to tune.


text:
Q: Excel Visual Basic, How to stop freezing due to many API calls? I am using Visual Basic with excel to get some data from an API. I am running around 100 API calls in every iteration of a For-Each loop, each iteration will fill one row of data.
The problem is that, my excel freezes after completing around 4-5 rows!
I think the best solution for this problem is to have a delay of around 3 seconds between each API calls. This will also prevent rate-limiting errors from my API.
This is my current code -
For Each BidRow In Range("A2:A102")
        MyRequest.Open "GET", "https://api.someapi.com/values/" & Range("B" & RowNo)
        MyRequest.Send
        Set JsonBid = JsonConverter.ParseJson(MyRequest.ResponseText)
        Range("D" & RowNo).Value = JsonBid("key")
        RowNo = RowNo + 1
Next BidRow

JsonConverter is just another module.
Anyway, I do not know any way to do a delay of 3000 ms in Visual Basic, its quite easy to do that in Javascript with settimeout() function. Or maybe I have to some asynchronous coding technique here. I am lost trying a bunch of things now!
Any idea how to solve this?

A: You could use this sub to pause for a specified number of "whole" seconds:
Sub Pause(delaySeconds As Integer)
    Dim startTime As Single
    startTime = Timer
    Do While Timer < startTime + delaySeconds
        DoEvents    ' Yield to other processes
    Loop
End Sub

For example, Pause(3) will pause for 3 seconds.

However, are you sure that Excel is "freezing" in a non-recoverable way?  I use a lot of API's and I know that when I'm looping through a few hundred, it sure looks like Excel is crashing, but with a little patience, the process indeed finishes up.
Instead of pausing (and extending execution time of your sub by 100 × 3 seconds = 5 minutes), what if you added a line just before Next BidRow:
DoEvents

Edit re: API limit of 60 calls per second...
If the site that provides your API has a limit of 60 calls per minute, then your 100 calls should run in no less than 100 seconds.  I bet you're below that but you could make sure by timing the procedure.
Before your loop you could add:
Dim LoopStart as Single

LoopStart = Timer

...and then after the loop is completely finished, add a line:
MsgBox "Loop finished in " & Round(Timer - LoopStart,0) & " seconds."

If you exceed the limit, most API's would simply return an error and resume normally in a second or two.  I'm sure there are exceptions out there depending on the fine print of the API you're using like in theory the site could charge your credit card for the excessive calls (which would need to be agreed upon in advance) or could potentially ban your IP after repeated abuse (which I've never seen.)
For example, the Google Maps Geocoding API has a very generous "standard" limit:

2,500 free requests per day, and,
50 requests per second.

By default, calls in excess of this will return a (temporary) error, unless you Enable Billing to unlock higher quotas:

2,500 free requests in a day, and then,
  you will be billed at $0.50 USD / 1000 additional requests, up to 100,000 daily

(Source)

You could make sure each iteration of the loop takes at least one second with something like this:
For Each BidRow In Range("A2:A102")
    loopStart = Timer 'reset timer for each loop
    MyRequest.Open "GET", "https://api.someapi.com/values/" & Range("B" & RowNo)
    MyRequest.Send
    Set JsonBid = JsonConverter.ParseJson(MyRequest.ResponseText)
    Range("D" & RowNo).Value = JsonBid("key")
    RowNo = RowNo + 1
    Do While Timer < loopStart + 1
        DoEvents    ' Yield to other processes if under 1 second has passed
    Loop
Next BidRow


text:
Q: Can I empty-base optimize mutable data? I have a class template which looked like this:
template<typename T, typename Mutex, typename SomePolicy>
class my_class {
public:
  T f() const {
    resource_lock a_lock(some_mutex);
    return some_policy.some_operation(some_data);
  }
private:
  T             some_data;
  mutable Mutex some_mutex;
  SomePolicy    some_policy;
};

If not used concurrently, we have a dummy mutex type which has all the member functions as inlined empty functions and no data. There are policies that have per-instance data and those that do not have any data.
This is library code and it turns out that this class template gets used in application code where the extra bytes matter which are needed for the data members some_mutex and some_policy even when they are empty classes. So I want to make use of the empty base optimization. For the policy, this is easy:
template<typename T, typename Mutex, typename SomePolicy>
class my_class {
public:
  T f() const {
    resource_lock a_lock(the_data.some_mutex);
    return the_data.some_operation(the_data.some_data);
  }
private:
  struct data : SomePolicy {
    T             some_data;
    mutable Mutex some_mutex;
  };
  data the_data;
};

However, given that some_mutex is mutable, I don't know how to make it a base class without making the_data, and thus all data, mutable, thereby completely taking over the compiler's responsibility to protect me from silly constness mistakes.
Is there a way to make a turn a mutable data member into a base of a non-mutable data member's class?

A: No, a base class cannot be mutable. But...

thereby completely taking over the compiler's responsibility to protect me from silly constness mistakes.

...that's not necessarily the result of that. You can still let the compiler help you, by creating accessor functions instead of using your data structure directly. And you can name it in such a way that it should be obvious to everyone that those accessor functions are the only supported interface to the data.
mutable struct : SomePolicy, Mutex {
  T some_data;
} _dont_use_directly;

T &some_data() { return _dont_use_directly.some_data; }
const T &some_data() const { return _dont_use_directly.some_data; }

SomePolicy &some_policy() { return _dont_use_directly; }
const SomePolicy &some_policy() const { return _dont_use_directly; }

Mutex &some_mutex() const { return _dont_use_directly; }

A: What you could do is use a mutex wrapper and specialize it for the empty mutex for which you then can perform the EBCO.
class EmptyMutex{
    void lock() const {};
    void unlock() const {};
};

template< class MUX>
class MutexWrapper {
    mutable MUX mux;
public:
    void lock() const {mux.lock();};
    void unlock() const { mux.unlock() ;};
};

template<>
class MutexWrapper<EmptyMutex> : public EmptyMutex {};

template<typename T, typename Mutex, typename SomePolicy>
class my_class {
public:
    T f() const {
        resource_lock a_lock(the_data);
        return the_data.some_operation(the_data.some_data);
    }
private:
    struct data : SomePolicy ,MutexWrapper<Mutex> {
        T             some_data;

    };
    data the_data;
};

The caveat of this solution is, that - inside a const memberfunction - while you can use the lock() and unlock() functions directly, you can only pass const references to the MutexWrapper as parameters.
So in this case, your resource_lock would have to take a const reference to a MutexWrapper - when one would expect (and rightly so) that it actually changes the state of the mutex. This is quite missleading for someone, who doesn't know how MutexWrapper is implemented.
For that reason I think it is more sensible to just const_cast the mutex when needed instead of using a wrapper:
template<typename T, typename Mutex, typename SomePolicy>
class my_class {
public:
    T f() const {
        resource_lock a_lock(getNonConstMuxRef());
        return the_data.some_operation(the_data.some_data);
    }
private:
    struct data : SomePolicy, Mutex {
        T  some_data;
    };
    data the_data;
    Mutex& getNonConstMuxRef() const { return const_cast<my_class<T, Mutex, SomePolicy>*>(this)->the_data; }
};

A: Assuming your std::tuple implements the empty base optimization (do check), then this might help:
mutable std::tuple<T, Mutex, SomePolicy> raw;
T          const& data()   const { return std::get<0>(raw); }
T               & data()         { return std::get<0>(raw); }
Mutex           & mutex()  const { return std::get<1>(raw); }
SomePolicy const& policy() const { return std::get<2>(raw); }
SomePolicy      & policy()       { return std::get<2>(raw); }

basically we put the optimization into a .raw mutable member that we never otherwise access (as a bonus, tuple's access is messy).  Then we create reference-accessors that enforce const.
You may also want to:
my_class(my_class const&  )=default;
my_class(my_class      && )=default;
my_class&operator=(my_class const&  )=default;
my_class&operator=(my_class      && )=default;

to be explicit that my_class const&& is not in play.  This also assumes that T and other types have well-behaved copy ctors and the like.  (as in, they don't have a T(T&) ctor or operator= that feels overly entitled about the non-const-ness of the rhs)


text:
Q: cmis query not giving result on redhat server My Query is :
SELECT * FROM cmis:document WHERE CONTAINS('PATH:\"/app:company_home/st:sites/*\"')

This Query is working fine in **Windows and Ubantu also ** but it is not working on Red Hat server.

Is I am missing any property or anything else.
Please help for the same.


text:
Q: How do I dynamically label my ggplot within a for loop? I want the title of each of my plots to be labeled by the contents of my list: "namesvector" instead of just "Scatterplot"
Also bonus question, par(mfrow = c(2,2)) isnt printing all 4 plots side by side, but individually.
 par(mfrow = c(2, 2))
namesvector <- list("Start", "Week_1", "Week_3", "Week_5")
for (i in 4:ncol(data_3)) {
  print(
    ggplot(data_3, aes(
      y = data_3[, i], x = Biomass, color = Tissue
    )) +
      geom_point() + geom_smooth(method = "lm") +
      labs(title = "Scatterplot", x = "Biomass", y = "Isotopic Signature")
  )
}

A: For printing a variable into your title, you need to use paste(), as explained here:
Inserting function variable into graph title in R
Does this help you?


text:
Q: Series expansion of $e^x$ I don't understand why a solution of
$$e^{rdt}(u+d)-ud-e^{2rdt}=\sigma^2dt$$
is
$$u=e^{\sigma \sqrt{dt}} \space \space \space \space\text{and}\space \space\space \space d=e^{-\sigma \sqrt{dt}}$$
My text says only that "Neglecting the terms of order $dt^2$ and higher, a solution of the equation is $u=e^{\sigma \sqrt{dt}}$ and $d=e^{-\sigma \sqrt{dt}}$. Please note: we are using the series expansion $e^x=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+...$".
Could you show me the passages to arrive at $\sigma^2dt$? Thanks in advance.

A: With $u=e^{\sigma \sqrt{dt}}$ and $d=e^{-\sigma \sqrt{dt}}$ and using the series expansion we have $$ e^{rdt}(u+d)-ud-e^{2rdt}=e^{rdt}\big(e^{\sigma \sqrt{dt}}+e^{-\sigma \sqrt{dt}}\big)-1-e^{2rdt}$$
$$=(1+rdt+...)(1+\sigma \sqrt{dt}+\sigma^2\frac{dt}{2}+...+1-\sigma \sqrt{dt}+\sigma^2\frac{dt}{2}+...)-1-(1+2rdt+...)$$
$$=(1+rdt+...)(2+\sigma^2dt+...)-1-(1+2rdt+...)$$
$$=2+\sigma^2dt+2rdt-2-2rdt=\sigma^2 dt$$
after neglecting terms of order $dt^2$ and higher.


text:
Q: How to use ConfigParser with virtualenv? I wrote a tool that looks in several places for an INI config file: in /usr/share, /usr/local/share, ~/.local/share, and in the current directory.
c = ConfigParser.RawConfigParser()
filenames = ['/usr/share/myconfig.conf',
             '/usr/local/share/myconfig.conf',
             os.path.expanduser('~/.local/share/myconfig.conf'),
             os.path.expanduser('./myconfig.conf')]
parsed_names = c.read(filenames)
for name in parsed_names:
    print 'using configuration file: ' + name

I have started using virtualenv and now my setup.py script installs myconfig.conf into /path/to/virtual/env/share/. How can I add this path to the list of paths searched by ConfigParser when the path to the virtualenv will be different each time? Also, if I installed to a virtualenv, should I still search the system /usr/share and /usr/local/share directories?

A: You should be able to get the venv share path with
os.path.join(sys.prefix, 'share', 'myconfig.conf')

Including /usr/share or /usr/local/share would depend on your application and if multiple installations by different users would be more likely to benefit or be harmed by global machine settings.  Using the above code would include '/usr/share/myconfig.conf' when using the system python so it is probably safer to not include it explicitly.


text:
Q: How do I get a contact's sales from Salesforce using the API? I'm looking through the API for Salesforce and trying to get familiar with it for a project I'll be working on.
Everything looks fine, I can get a Contact, a Case, an Event, a Lead, etc.
The only thing I don't see in the API is a way to get the actual sales data for a contact. I figured it would be one of the main methods available, but I can't find anything about it.
I don't know if there's a different name for a Sale object, or if I have to use some other method. Can someone lead me in the right direction?

A: SalesForce refers to sales data as an Opportunity. Opportunities move through stages. To tell if an Opportunity has been converted to a sale you can check Opportunity.IsWon field.
As you can see here, you can find opportunities for a contact using the many-to-many OpportunityContactRole table. (OpportunityContactRole.ContactId <-> Opportunity.Id).


text:
Q: How to tell Bootstrap Carousel to go to a specific index? I'm using Bootstrap and Bootstrap Carousel in a project.
I would like to know if there's any way to make the Carousel navigate to a specific slide.
For example, something like:
$('myCarousel').to(2);

Does anybody know a way to do this?

A: From the documentation:

.carousel(number) Cycles the carousel to a particular frame (0 based,
  similar to an array).

So I think it should be:
 $('myCarousel').carousel(2);

A: Select the element of your carousel with jQuery and use the .carousel() method:
$("#myCarousel").carousel(2);

This would take you to the third slide.


text:
Q: How can we open show date picker according to Central European Standard Time in flutter? In a flutter, I want to show the date picker according to Central European Standard Time. How can I do that?
Any help would be appreciated.
DateTime? newDate = await showDatePicker(
          context: context,
          initialDate: DateTime.now(),
          firstDate: DateTime(1900),
          lastDate: DateTime(2040),
          helpText: 'Select Date',
          cancelText: "CANCEL",
          confirmText: "SAVE",
          initialDatePickerMode: DatePickerMode.day,
          selectableDayPredicate: _decideWhichDayToEnable,
          builder: (context, child) {
            return Theme(
              data: Theme.of(context).copyWith(
                textButtonTheme: TextButtonThemeData(
                  style: TextButton.styleFrom(
                    primary: colorPrimary, // button text color
                  ),
                ),
              ),
              child: child!,
            );
          },
        ).then((value) {
          if (value != null) {
            setState(() {
              date = DateFormat('dd-MM-yyyy').format(value);
              isDateSelected = true;
              _affiliateReward.currentState!.refreshData();
            });
          }
          return null;
        });
        if (newDate == null) return;
        setState(() {
          dateFrom = newDate;
        });

So, the above code is used to select the date for transaction. but Central European Standard time. How can we change that in flutter?
bool _decideWhichDayToEnable(DateTime day) {
    if ((day.isAfter(DateTime.now().subtract(const Duration(days: 36500))) &&
        day.isBefore(DateTime.now().add(const Duration(days: 0))))) {
      return true;
    }
    return false;
  }

A: If I understand you correctly this is not really showDatePicker related but rather DateTime. Inside your showDatePicker you can set the initialDate (you use DateTime.now() thats why the timezone of you system devices gets used unless it is not anchored to UTC).
Since basic flutter DateTime only supports local or UTC time you need to convert the selected timestamp to CET.
There are probably two approaches you could choose from:

*

*Use a package with timezone support like this.
You can then convert the selected timestamp into your desired timezone. This probably makes sense if you do a lot of different timezone related operations.

*Do the timezone conversion by yourself:
You can take the selected value from your showDatePicker - make sure that it is UTC with value.toUtc() and add/subtract the specific time to convert into your desired timezone. For instance:
if (value != null) {
   setState(() {
      const utc = value.toUtc();
      // Central Europe Standard Time is UTC + 01:00
      var cetTimeStamp = utc.add(Duration(hours: 1)));
      // do whatever you need
   });
}

Since flutter datetime only supports local time and UTC you do not explicitly know that this timestamp is CET. From an engineering point of view this is a quite unclean. Also if you send this object anywhere the timezone is still UTC. You can ofcourse also get the DateTime as string and add the timezone to that string. How ever in such cases I'd recommened to use a third party package as I mentioned above.


text:
Q: How to get data of already purchase subscription **I have implement in app purchase in to my app and I want to get details of already purchase subscription's sku data and currant status.
with this data I want to use for proration and cancel
is there any way to find this**


text:
Q: Performance problems with tkinter canvas The following is my code for generating a 60x60 grid of Canvases.  I need to be able to individually target these items and change the colour individually, this however is a minimal version of what needs to be accomplished in my larget problem. Essentially what I'm asking is - because in terms of performance this grid is both slow to load, and makes the program overall sluggish, if there is any better way to do this in Tkinter that would be more efficient.
Thanks.
from tkinter import *

WINDOW = Tk()
WINDOW.state('zoomed')
grid = []

for n in range(0, 60):
    grid.append([])
    for i in range(0,60):
        grid[n].append(Canvas(WINDOW, bg="#222", height="10", width="10", highlightthickness="1"))
        grid[n][i].grid(row=n, column=i)


text:
Q: File Buffer Size Too Small I am trying to make a small program in C which reads in a file and calculates a CRC on the contents. I created the program in netbeans and in the IDE everything works. When I build the project with GCC and run the generated exe the program fails when reading in the file. The file is 1.3 Mb.
When reading in the file I eventually get the error "Internal error: TP_NUM_W_BUFS too small: 50"
My read code is fairly simple, it does very little line processing.
while (fgets(line, HEX_LINE_LENGTH, fp))
{
        int len = strlen(line);
        line[len] = line[len-1];
        line[len-1] = '\r';
        memcpy(&hex_lines[num_lines], line, HEX_LINE_LENGTH);
        num_lines++;
        printf("%s\n", line);
        memset(line, 0, HEX_LINE_LENGTH);
}

I am seeing a new issue. When reading in my file via the netbeans IDE everything works fine. When I compile the program from a command line with
g++ main.c crc_calculator.c crc_calculator.h -o crc

I get a crc.exe file. Running this will read in my file but will report that twice as many lines have been read than actually exist.


text:
Q: The method getPreferenceManager() is undefined for the type BatteryService in android app I am making a service so I have service class which is extended from Service. I am getting a checkbox from PreferenceScreen and based on whether it is checked or not I perform an action. To get CheckBoxPreference I use getPreferenceManager() method. But it has red underline. When I hover over it shows me this error The method getPreferenceManager() is undefined for the type BatteryService. When I use the same code in my main class then it works. Here is my code
public int onStartCommand(Intent intent, int flags, int startId) {
    initNotification();

    final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("cbAlarm");

    checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                public boolean onPreferenceChange(Preference preference,
                        Object newValue) {
                    if (newValue.toString().equals("true")) {
                        Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_LONG).show();
                        registerReceiver(batteryInfoReceiver, new IntentFilter(
                                Intent.ACTION_BATTERY_CHANGED));
                    } else if (newValue.toString().equals("false")) {
                        stopService(new Intent(getBaseContext(),
                                BatteryService.class));
                        Toast.makeText(getApplicationContext(),
                                "Unchecked", Toast.LENGTH_SHORT).show();
                    }
                    return true;
                }
            });
    return START_STICKY;
}

How can I solve this problem? Help Please

A: The getPreferencesManager() function is not available on Service derived objects - only  on PreferenceActivity or PreferenceFragment derived objects where you likely copied the above code from, or individual Preference objects.
If you only wanted to sample the value of the checkbox preference when your service starts, use something like:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean alarm = sp.getBoolean("cbAlarm", false);    // defaulting to false

However, I'm guessing from your Listener code that you also want to be notified if the user changes the setting.  That would mean keeping onPreferenceChange in the PreferenceActivity/PreferenceFragment, and sending the service a message.  For that, consider something like Android best way to communicate from an Activity to a Service / Engine, or simply start/stop the whole service if it has nothing to do when the Alarm is off!


text:
Q: Get table names from a database I've searched through a bunch of websites and I have not come across any code or tutorial which has gone through the specifics of obtaining the table names from a single database.
Assuming I have 4 databases and I want the names of all the tables within the database called mp21, what query can I use?

A: In MySQL this will list all databases:
show databases;

For each of these you can do:
use <database_name>;

and then
show tables;

A: In SQL SERVER, you can just use -
select * from sys.tables

A: SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'

A: use mp21
SELECT name FROM dbo.sysobjects WHERE xtype = 'U'

A: I used this query:
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'

It gives me table name as well as sysDiagram(database diagram generated for that database)

A: if you are asking about .net code then You need SMO :
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

public static List<Table> GetTables(string connection, string databaseName)
        {
            if (String.IsNullOrEmpty(connection))
                throw new ArgumentException("connection is null or empty.", "connection");

            Server srv = getServer(connection);
            return srv.Databases[databaseName].Tables.Cast<Table>().ToList();
        }

A: Here is the MySQL query you asked.
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='mp21'


text:
Q: Creating S3 signed URLs in node.js I'm using knox module to https://github.com/LearnBoost/knox to create signed URLs for files on S3, something I've done with PHP SDK before.
I can delete files from my bucket, but I'm getting SignatureDoesNotMatch error when I try the generated URLs for files with private ACL.
Code looks like this
var knox = require('knox');
var s3Client = knox.createClient({
key: '*****',
secret: '*****',
bucket: '*****'
});
function getS3Url(filename) {
var expires = new Date();
expires.setMinutes(expires.getMinutes() + 30);
return s3Client.signedUrl(filename, expires);
}
console.log(getS3Url('file.txt'));

What am I doing wrong?

A: Turns out I was missing the leading '/' on filename, signature matches now.


text:
Q: A better Propel query I have 4 tables:

*

*branches (contains branch info)

*offered_class_types (each branch has a set of classes it has available)

*class_sessions (each class type has its session, like day, evening, and night)

*class_dates (each date corresponds to a session)

So my flow: each date corresponds to a session (by a code that links the two directly) which corresponds to a type by two things 1. a branch id and 2. a class name (branches can offer the same class types which can have the same sessions). Each class type corresponds to the branches table using that same branch id it used to correspond with the sessions table.
I would like to turn this code into a one query, instead of the two it is now. Prior to switching to Propel it was in a single query.
$class = ClassDatesQuery::create()->findPk(160);
$classSession = $class->getOfferedSessionsRelatedByCode();
$classType = OfferedClassTypesQuery::create()
   ->filterByType($classSession->getClassname())
   ->filterByBranchid($classSession->getBranchid())
   ->find();

A: A simple query, similar to the one below would have surficed, if only you had a simple relationship between the two tables:
$classType = OfferedClassTypesQuery::create()
  ->useClassDatesQuery()
    ->filterByPk(160)
  ->endUse()
  ->filterByXXX(YYY)
  ...
  ->find();

The complication is that you have more than one join condition, and those conditions are unknown before the query.
There are at least two(2) alternative approaches to this.
Option One:
Write your raw SQL query, and run it against your DB connection, and then manually hydrate the results set with the appropriate object/class wrapper like below:
$db = Propel::getConnection();
$sql = 'SELECT OfferedClassTypes.* FROM ...';
$query = $db->prepare($sql);
$formatter = new PropelObjectFormatter();

// Here you specify the class that matches
// the expected results set
$formatter->setClass('OfferedClassTypes');
$classType = $formatter->format($query);

Notice the OfferedClassTypes.*, because you only need columns from that table, so that you can hydrate by the matching Object
Option Two:
Put your raw SQL query into a view, quote:

Propel custom sql for view tables

So you'd maybe define your view like this:
CREATE VIEW ViewOfferedClassTypes AS
  SELECT
    ClassDates.ID as ClassDateID,
    OfferedClassTypes.*
    ...

Then in your schema you'd have:
<table
  name="ViewOfferedClassTypes"
  phpName="ViewOfferedClassTypes"
  readOnly="true"
  skipSql="true">
  <!-- More columns from the OfferedClassTypes table -->
  <column name="ClassDateID" ... /><!-- From ClassDates table -->
</table>

Note the ClassDateID column, so you can use in your filter:
$classType = ViewOfferedClassTypesQuery::create()
  ->filterByClassDateID(160)
  ->find();

Option 1 is quick and dirty, while option 2 is more elaborate yet cleaner/more organised.
I hope this helps, and good luck.


text:
Q: PYTHON || PHP : Is there a way to understand the mood of a string? everyone.
I need this, if the user enters some string I want to understand the mood of that string:

*

*happy

*sad

*angry

*calm

It mustn't be exact like this, but I need something more precise than just positive/negative which comes with semantic analysis. Something that will give me about 4-5 mood options.

A: You can create a dictionary of both the types of words after that give them equal weight age. After that,check the occurrence of listed words and calculate their weight age of string based on occurrence of words.


text:
Q: Which "weasels" is Ron referring to? Harry frightens Malfoy's gang using his invisibility cloak:

Ron: Those weasels! Never told me about any Marauder's Map.
Hermione: He won't keep it. He'll turn it over to Professor
McGonagall.

Which "weasels" is Ron referring to?

A: Ron is annoyed that Fred and George - who just handed Harry the Map - have never told him, their own brother, about the map. He's annoyed at them for opting to tell Harry and not him about it, so he's calling them weasels.
Seeing as their last name is "Weasley", "weasels" is probably an insult that's been levied very often at every member of their family. It's a safe fallback for an insult directed at his brothers for not telling him about something, especially considering that "weasel", when used in this context, means somebody who's sneaky or sly... such as hiding a magical map from your brother.


text:
Q: How to scaffold controller to a domain class from plugin? I installed a plugin and want to scaffold a domain class from the plugin. For my project-own domain classes Foo I add scaffold = true to FooController. If I try this it shows up in the list of controllers but there are no views generated (404 error). I imported the class inside the controller.
Any idea what is wrong or how to fix this?

A: Try to scaffold using class name:
static scaffold = DomainClassFromPlugin

A: If you are the plugin editor, you should be able to add the scaffolding plugin in your BuildConfig.groovy
  compile ":scaffolding:2.0.1"

then should be to run your generate or generate-all commands against the domain class to have the controller and/or views created.
Now If you do do not have access to the plugin source, from the app that uses the plugin that has the domains that you want to scaffold I do not think you will be able to. You will have to code that yourself.


text:
Q: Coding with Sublime Text 2 Simple question, I just started coding with Sublime Text 2 on windows, and I want to change little things, like when I am writing an if statement such as if (i > 0), immediately after I type the "0", my cursor is between the "0" and ")", so if I hit enter, I want it to jump to after the ")". I am used to eclipse so I want to know how I can get the settings to mimic those of eclipse. I have tried editing the settings text files but couldn't find what I was looking for.

A: Try adding the following to your User key bindings (accessible through Preferences -> Key Bindings - User)
{ "keys": ["enter"], "command": "move", "args": {"by": "characters", "forward": true},
  "context": [
    { "key": "selection_empty", "operator": "equal", "operand": true },
    { "key": "preceding_text", "operator": "not_regex_match", "operand": "[[:space:]]*", "match_all": true },
    { "key": "following_text", "operator": "regex_contains", "operand": "^[\\)]", "match_all": true },
    { "key": "auto_complete_visible", "operator": "equal", "operand": false }
]}

edit: Update regex to only match parentheses.


text:
Q: Create a chart with 5 lines, despite Salesforce's limitation of 2 I have a custom object with fields:

*

*Date

*Measurement A

*Measurement B

*Measurement C

*Measurement D

*Measurement E

I want to create a line graph with X-axis: the date (field 1) and 5 lines, for fields 2 - 6.
For some insane reason, Salesforce limits the number of Y values to just 2! But: when grouping data, it is possible to create graphs that have an arbitrary amount of Y values.
Is there some way in which I can create a grouping on my object that allows me to create a 5-line chart? I am using plain Lightning, not the Analytics license.
Update: I found the free Lightning Web Chart.js Component in the AppExchange, but to display more than one line in a graph, you need to code in JS. Simply using it with app builder is not an option with dynamic data.

A: If you don't mind static graphs (i.e., not interactive, you can still dynamically generate them), you could look at https://quickchart.io/ which allows you to create graphs images given a bunch of JSON parameters


text:
Q: Shared workbook hangs when opening and saving I have a shared Excel file with 14 people having access. The spreadsheet has been fine for a while, however, in the last 2 weeks, opening and saving the spreadsheet hangs for a good 4 to 5 minutes. Any ideas how to solve this problem?

A: Shared excel sheets tend to grow to significant size as more and more revisions get put in. I've had success in shrinking them back to a manageable size by turning off shared edit mode and saving and then turning shared edit mode back on.

A: I have resolved this problem with a macro here. I also have my sheets force macro use by hiding the sheets unless macros are enabled.
How do you prevent corruption of shared Excel files?


text:
Q: Using REST Assured, how can I check if a field is present or not in an array of json objects type of response? I need to validate that a response like the one below contains some fields. I am not interested in the fields value - just that the keys exist.
For example I want to check that the key "id" is present in this type of response. How would I accomplish that?
[
   {
      "id":"1",
      "title":"Title",
      "details":"details",
      "benefit":"Welcome",
      "expirationTimestamp":1549995900,
      "notice":"some text",
   }
]

If I do
given()
  .spec(reqSpec).
when()
  .get().
then()
  .body("$", hasKey("id"));

I get an error like this:
java.lang.AssertionError: 1 expectation failed.
JSON path $ doesn't match.
Expected: map containing ["id"->ANYTHING]
  Actual: [{blabla=something, id=1, details=details, etc=etc}]

Please, can someone explain to me how this should work?

A: Try this:
given()
  .spec(reqSpec).
when()
  .get().
then()
  .body("[0]", hasKey("id"));

Groovy GPath is used in Rest Assured. You can take a look at their guide here
Also there's a good tutorial here


text:
Q: How can I use REPL with CPS function? I've just encountered withSession :: (Session -> IO a) -> IO a of wreq package. I want to evaluate the continuation line by line, but I can't find any way for this.
import Network.Wreq.Session as S
withSession $ \sess -> do
  res <- S.getWith opts sess "http://stackoverflow.com/questions"
  -- print res
  -- .. other things

In above snippet how can I evaluate print res in ghci? In other words, can I get Session type in ghci?

A: Wonderful question.
I am aware of no methods that can re-enter the GHCi REPL, so that we can use that in CPS functions. Perhaps others can suggest some way.
However, I can suggest an hack. Basically, one can exploit concurrency to turn CPS inside out, if it is based on the IO monad as in this case.
Here's the hack: use this in a GHCi session
> sess <- newEmptyMVar :: IO (MVar Session)
> stop <- newEmptyMVar :: IO (MVar ())
> forkIO $ withSession $ \s -> putMVar sess s >> takeMVar stop
> s <- takeMVar sess
> -- use s here as if you were inside withSession
> let s = () -- recommended
> putMVar stop ()
> -- we are now "outside" withSession, don't try to access s here!

A small library to automatize the hack:
data CPSControl b = CPSControl (MVar ()) (MVar b)

startDebugCps :: ((a -> IO ()) -> IO b) -> IO (a, CPSControl b)
startDebugCps cps = do
   cpsVal <- newEmptyMVar
   retVal <- newEmptyMVar
   stop   <- newEmptyMVar
   _ <- forkIO $ do
      x <- cps $ \c -> putMVar cpsVal c >> takeMVar stop
      putMVar retVal x
   s <- takeMVar cpsVal
   return (s, CPSControl stop retVal)

stopDebugCps :: CPSControl b -> IO b
stopDebugCps (CPSControl stop retVal) = do
   putMVar stop ()
   takeMVar retVal

testCps :: (String -> IO ()) -> IO String
testCps act = do
   putStrLn "testCps: begin"
   act "here's some string!"
   putStrLn "testCps: end"
   return "some return value"

A quick test:
> (x, ctrl) <- startDebugCps testCps
testCps: begin
> x
"here's some string!"
> stopDebugCps ctrl
testCps: end
"some return value"


text:
Q: Benign ELF dataset I'm working on IoT malware classification using machine learning, currently I have a dataset consists of 1137 malicious ELF samples and they support different CPU architectures (i.e. intel, MIPS, ARM, SPARC, Motorola). So now trying to find out a set of benign ELF samples in order to perform the classification. I found .deb, .bin, and .RPM but I don't think I can do the classification using them.
Also I found benign ELFs, but the problem majority of them are supporting ARM arch, with few samples support Intel.
Can you please advise me whether I can proceed with analyzing the other file extensions, and if you are aware of ELF repositories.

A:
Can you please advise me whether I can proceed with analyzing the other file extensions, and if you are aware of ELF repositories.

You can extract ELF files from .deb and .rpm packages:
mkdir aa && dpkg -x foo.deb aa
mkdir bb && rpm2cpio bar.rpm | (cd bb; cpio -idm; )

Analyzing .debs and .rpms directly is likely to teach your classifier that anything that is ELF is malicious, and anything that is no ELF is not; which isn't a very useful classifier.


text:
Q: Customize starting index in LiveChart I am trying to draw a simple LineSeries with LiveChart. Because computer/array index by default starts with 0, and human (non-programmer) starts counting with 1, so I like to display the value's index starting with 1 (i.e. index+1), but could not figure out how to do this.
I read the LiveChart documentation on Types and Configurations, and tried to get a mapper of index + 1 into the SeriesCollection but I get an invalid argument error: cannot convert from 'LiveCharts.Configurations.CartesianMapper' to 'LiveCharts.Definitions.Series.ISeriesView'
var mapper1 = new CartesianMapper<double>()
        .X((value, index) => index + 1)
        .Y((value, index) => value);

sc = new SeriesCollection
{
    new LineSeries
    {
        Values = new ChartValues<double>()  {1,2,3,4,1,2,3,4,1,2},
    },
    mapper1
};

A: I can answer this only because I have had to tinker with LiveCharts myself, not because I got it from their documentation (although I did find it embedded here)
If you want to set a mapper specifically for one series, you can add it to the delcaration as follows:
var mapper1 = new CartesianMapper<double>()
        .X((value, index) => index + 1)
        .Y((value, index) => value);

sc = new SeriesCollection(mapper1)
{
    new LineSeries
    {
        Values = new ChartValues<double>()  {1,2,3,4,1,2,3,4,1,2},
    }
};

Alternatively, there is a way to set a global mapper for specific data types, e.g. if you're using MeasureModel:
var mapper = Mappers.Xy<MeasureModel>()
            .X(model => model.DateTime.Ticks)   //use DateTime.Ticks as X
            .Y(model => model.Value);           //use the value property as Y

//lets save the mapper globally.
Charting.For<MeasureModel>(mapper);

That example is from here.


text:
Q: 400 Bad Request when URL contains %25 I am using CakePHP and am facing the issue only with %25 encoded character. For other escaped symbols like %22 etc the URL rewriting seems to be perfectly fine.
SO question reports similar problem with CodeIgniter but the solution is something that cannot be directly applied to my use case as the ModRewrite rules are not the same.
Can someone please help me with equivalent changes in CakePHP changes?
Thanks!

A: You can use the same solution as this question, but maintain the QSA part:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,B,L]
</IfModule>


text:
Q: How to colour the edges after using sobel filter? I am using sobel filter for edge detection. How to illustrate the gradient direction with color coding. For example, horizontal edges with blue and vertical edges with yellow?
Thank you.

A: Since you can specify whether you want horizontal or vertical edge detected (check here), you could perform 2 filtering operations (one horizontal and the other vertical) and save each resulting image, then concatenating them to form a final, 3-channels RGB image.
The RGB color code for yellow is [1 1 0] and that of blue is [0 0 1], so in your case the vertical edge image will occupy the first 2 channels whereas the horizontal edge image will occupy the last channel.
Example:
clear
clc
close all

A = imread('circuit.tif');

[r,c,~] = size(A);

EdgeH = edge(A,'Sobel','Horizontal');
EdgeV = edge(A,'Sobel','Vertical');

%// Arrange the binary images to form a RGB color image.
FinalIm = zeros(r,c,3,'uint8');

FinalIm(:,:,1) = 255*EdgeV;
FinalIm(:,:,2) = 255*EdgeV;
FinalIm(:,:,3) = 255*EdgeH;

figure;

subplot(1,2,1)
imshow(A)

subplot(1,2,2)
imshow(FinalIm)

Output:


text:
Q: creating pdf from obj c for an iphone app I need to generate a PDF file on click of a button that pdf should takes the contents from database and I have to view my generated PDF file once its generated how can I do this? can anyone guide me to some good material for this? Thanks in advance.

A: You should start from iOS Developer Library:
PDF Document Creation, Viewing, and Transforming


text:
Q: How to get a tap position in ARKit? I am trying to tap the screen and get tap position then I can fire the bullet from the position I tap.
I searched and tried many ways such as below but it doesn't work
guard let pointOfView = sceneView.pointOfView else { return }

let transform = pointOfView.transform
let orientation = SCNVector3(-transform.m31, -transform.m32, -transform.m33)
let scnView = sender.view as! ARSCNView
let holdLocation = sender.location(in: scnView)
let estimatedPlane: ARRaycastQuery.Target = .existingPlaneInfinite
let alignment: ARRaycastQuery.TargetAlignment = .any

guard let query = scnView.raycastQuery(from: holdLocation,
                                   allowing: estimatedPlane,
                                  alignment: alignment)
else { return }

let results = scnView.session.raycast(query)
guard let pointResult = results.first else { return }

let pointTransform =  SCNMatrix4(pointResult.worldTransform)

let pointLocation = SCNVector3(pointTransform.m41,
                               pointTransform.m42,
                               pointTransform.m43)

let pointPosition = orientation + pointLocation

Can anyone help to tell me how to do it? Highly appreciate it.


text:
Q: Adding style element to SVG in Vue component I'm writing a Vue component that dynamically renders an SVG. Usually <style> tags are not allowed in Vue templates, but is there any way to allow it in this particular situation?
The following will either throw an error, or generate an svg without the style tag, depending on how your project is setup (Code Sandbox):
<template>
  <svg :width="svgWidth" :height="svgHeight">
    <style>rect{fill:red}</style>
    <rect :height="rectHeight" :width="rectWidth" />
  </svg>
</template>

One obvious workaround is to use inline styling for all elements, but for convenience I wonder if it possible to tell Vue to leave the style tag inside the svg tag alone?
(I'm generating both style and SVG elements dynamically, so it would make for a more readable code and a much smaller rendered SVG element.)
I'd like to make the SVG self-contained, i.e. keeping the style tag inside the rendered image.

A: To use <style> tags with svgs, you can prefix them by svg:.
Working example:
<template>
  <svg width="100" height="100">
    <svg:style>rect{fill:red;}</svg:style>
    <svg:rect width="20" height="30" />
  </svg>
</template>

Please note that I changed the attributes of your rect as it displayed an empty (0x0) rectangle.


text:
Q: Enable dotnet feature flag Visual Studio Code I would like to know, how I can enable the dotnet feature flag in VSC. I am programming an extension and therefore I need some variables from datatype dotnet.
Do you know how to do this?


text:
Q: Is libevent required for building memcached for windows? I accidentally deleted my previous post.  Could I know exactly why I should compile libevent to be able to build memcached?  Actually, I can already use memcached for windows without compiling libevent and I also installed memcached as a service.  Nothing odd happens.

A: This is old but just for the record: you installed the exe that already have the lib included. You would need libevent library if you're trying to build the exe from the source code.

A: Libevent is one of the easiest things I've had to compile on Windows-- at least using Mingw. If you want really easy, just use the memcached binary available at Northscale labs website: http://labs.northscale.com/memcached-packages/


text:
Q: how to data-bind knockout js viewmodel to jquery dynamically created rows Within my page which is bound to the viewmodel I have a section where the user can add elements to the page The elements are a filter section comprised of a few value fields and a select element that needs to be databound to the viewmodel.
Running the select option inline in the html it works fine. However once I pull it out and add it to the jquery that adds the filter control it fails to bind. I realize this is due in part to the view model already being bound and I have tried to call apply bindings again but this fails as well.
I can't use the foreach as I have in other areas because this section is optional. Users do not have to add filters if they don't want to which is why I went the jquery route.
Can anyone provide some suggestions on how to re-bind the select element to the view model once the page has already rendered or is there a better approach using just Knockout to accomplish this?
code:
html

                <select data-bind="options: SelectedAttributes(), optionsText: function(SelectedAttributes){ return SelectedAttributes.NameHierarchy() + '.' + SelectedAttributes.LabelName() },  optionsCaption:'Select a Field...'">
                </select>

                    <input type="button" value="Add A Filter" title="Add A Filter" class="special" id="add" />

jQuery
function CreateFilterRow() {
        $("
<select class='queryterm' name='condition'><option  value='AND'>AND</option><option value='OR'>OR</option></select>" +
    "<select data-bind='options: SelectedAttributes(), optionsCaption:'Select a Field...'></select>  <select name='operator'class='operClass'><option value='EQUALS' id='opt1'>Equals</option><option id='opt1' value='CONTAINS'>Contains</option><option id='opt2' value='DOES NOT CONTAIN'>Does Not Contain</option><option id='opt3' value='LIKE'>Like</option><option id='opt4' value='BETWEEN'>Between</option></select>  <input type='text' class='queryterm' name='fieldValue1' id='fieldvalue1' value='' size='25' />  RemoveAdd
").appendTo('#filterBuilder');
    };

    //orignal add row button
    $(document.body).on('click', '#add', function (event) {
        CreateFilterRow();
        ko.applyBindings(ReportWriterViewModel);
    });

The jquery block here is just the insertion of fields into the DOM and the event click. The apply bindings is invoked further up the line. I omitted the KO code as that works everywhere else so I know the issue is not in the Vm but in injecting these elements post VM initalization.
I have also tried to use the applyBindings and using the dom element name with no luck
 ko.applyBindings(ReportWriterViewModel , document.getElementById('filterSection'));

Thanks in advance,
-cheers

A: I would indeed use a foreach binding. After all, the observable array can have zero entries if the user hasn't clicked "Add" yet. Knockout is designed to handle this kind of dynamic UI.
Use something like this on your view model:
ReportObject.filterRows = ko.observableArray();
ReportObject.addFilterRow = function () {
    ReportObject.filterRows.push({});
};
ReportObject.removeFilterRow = function (filterRow) {
    ReportObject.filterRows.remove(filterRow);
}

And something like this in your HTML:

            Remove

        <input data-bind="click: addFilterRow" type="button" value="Add A Filter" title="Add A Filter" class="special" />


text:
Q: How to install packages before given date with zypper? We cannot find the parameter for it in the man pages, but maybe there is a solution for it:
Question: How can we install packages before a given date? So not the up-to-date version of a package, but an older one that was issued before a given date.
Selecting them one-by-one by hand is too slow.

A: I doubt you'll be able to install before a given date. I tried setting the system date backwards and that doesn't work. Nor is there an option you can pass to rpm which is what zypper uses underneath.
So the only approach I can think of is to set up a local RPM repository for SuSe, and fill that with those packages before a certain date and use that. To find out what was available at a certain date archive.org may be useful.
See this for how to set up a local OpenSuSE repository.

A: zypper search -s --match-substrings may be the best search option you can have. However, it doesn't really search package build date in the RPM.  I think what you try to do is pull/install all updates released before certain date.
What I did was manually pull packages, host them with a Repo.  My repo is on a CentOS host.  It was created with createrepo. In the zypper .repo file, specify "type=yum".

A: I assume that you want to install a specific version of package before the up-to-date one.
For example with MozillaFirefox, when searching for MozillaFirefox packages with the following command:
zypper se -t package -s MozillaFirefox
The output will be (i586 packages and other not related one has been truncated):

v | MozillaFirefox                     | package | 38.0.1-30.1 | x86_64 | openSUSE-13.2-Update
  v | MozillaFirefox                     | package | 37.0.2-27.1 | x86_64 | openSUSE-13.2-Update
  v | MozillaFirefox                     | package | 37.0.1-23.1 | x86_64 | openSUSE-13.2-Update
  v | MozillaFirefox                     | package | 36.0.4-18.1 | x86_64 | openSUSE-13.2-Update
  v | MozillaFirefox                     | package | 36.0-14.2   | x86_64 | openSUSE-13.2-Update
  v | MozillaFirefox                     | package | 35.0-9.1    | x86_64 | openSUSE-13.2-Update
  v | MozillaFirefox                     | package | 34.0.5-5.4  | x86_64 | openSUSE-13.2-Update
  i | MozillaFirefox                     | package | 33.0-2.1    | x86_64 | openSUSE-13.2-Oss
  i | MozillaFirefox                     | package | 33.0-2.1    | x86_64 | openSU

As we can see, MozillaFirefox version 33.0-2.1 has been installed on this system and the latest one is 38.0.1-30.1.
If you wan do not want to install the latest version, and just want to install a version up to version 36.0 then all you have to do is call zypper in do it for you.
The syntax is:

zypper in 'Mozillafirefox.x86_64<36.0

You can also install the i586 architectural package
zypper in 'Mozillafirefox.i586<36.0
Or you can let zypper does selection package architecture for you
zypper in 'Mozillafirefox<36.0
Then zypper will install version 35.0-9.1 which is closest to version 36.0.

zypper also provides support for '>, <=, >=, etc'; you can see it with zypper help in.

Hope this is what you are looking for and hope this help.


text:
Q: How to use same Onedrive service object in different files of Android project? I am using Onedrvie SDK for my android project.I have successfully login and get the elements from onedrive in one of my fragament. I need to use the same IOneDriveClient oject (IOneDriveClient ) in another file. How I can achieve this? I am using folllowing code.. Simply I want to create "oneDriveClient" in one activity and want use the same from other activites (fragments)...
final IClientConfig oneDriveConfig = new DefaultClientConfig.createWithAuthenticators(
                                        msaAuthenticator,
                                        adalAuthenticator);

final IOneDriveClient oneDriveClient = new OneDriveClient
                                        .Builder()
                                        .fromConfig(oneDriveConfig)
                                        .loginAndBuildClient(getActivity());