text:
Q: angular - assigning from directive I have an Angular directive that behaves like ng-include, just with tabs.
So it has a hierarchical scope (scope: true).
To get and set parent scope's variable value I use $parse:
var modelFn = $parse(attrs.ngModel);
getting works fine like this var value = modelFn(scope) even scope.$eval(attrs.ngModel),
but assigning doesn't change the value on the parent scope, it actually creates a variable on the current scope:
modelFn.assign(scope, { ... });
This is frustrating, any help?
Thanks in advance!
Update:
Here's an example
HTML:
<myDirective ng-model="myData"></myDirective>
Directive:
{
replace: false,
scope: true,
template: '<button ng-click="changeData()"></button>

'
link: function(scope, element, attrs){
var modelFn = $parse(attrs.ngModel);
var value = modelFn(scope);
scope.templateUrl = data.replace('a', 'b');
scope.changeData = function(){

// Problem is here, assignment is on the current scope and not parent ( or parent's parent and etc..)
modelFn.assign(scope, {name: 'new Value'});
}
}
}

A: In javascript object have prototype.
When you specify scope: true you told the directive to have a scope prototypically inherited from the parent scope.
That means that you get to have a special link to the parent scope (the prototype), where you can access all is values and objects, and all is methods, until... you try to write stuff for those values, objects and methods.
You can see prototype has fallback, when there is no value/object/method on your object, it will try to look at is prototype.
But when you want to set a value/object/method, you'r actually setting it on your object not is prototype, and so your parent scope values/objects/methods nether change.
A bit of code to illustrate :
https://gist.github.com/bcharp/712d6d9bfaf55b3c5d81
An interesting fact to know is that if you change one of the value of an object access through the prototype, it will be change in the prototype object.
So for your current trouble, you can simply change your direct access value say $scope.title = "My title"; by $scope.properties = {title:'My title'}; and access it through $scope.properties.title when you change it inside your object (directive inherited scope), it will be change in his prototype (parent scope).
I hope it's clear.

A: Why don't you just pass the variable to the directive using two-way binding? The following will bind myParam so that when you change it in the directive it will also change on the calling scope:
.directive('myDirective', function() {
  return {
    scope: {
      myParam: '='
    },
    templateUrl: 'template.html',
    controlle: MyCtrl

... etc...

};
})

HTML:
<my-directive my-param = "foo"><my-directive/>


text:
Q: occupation of area or space I'm writing an article and I have used the following sentence,
The switched-capacitor technology is used to replace the large resistors which can't be used in ICs because of their large occupation of area.
However, I feel that large occupation of area is wrong, because I googled it and their was nothing similar.
Any suggestions?
Thanks,

A: If your sole concern is the cumbersome phrase "large occupation of area," I think TRomano's suggestion of "large space requirements" is good.
I would consider tightening up the whole sentence though.  Perhaps:
The smaller switched-capacitor technology replaces the large resistors, whose space requirements prevent their use in ICs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating a record on a index page in Ember js I wanna to generate create record on index page without going to other route. The editing part works successfully. When i click on add record i have 500 error. It says
undefined method `income_url' for #<Api::IncomesController:0x007fcf1f6407f8>

My create.handlebars which i render with view on index page is

  Income name

    {{view Ember.TextField valueBinding="newIncomeName"}}

    <input type="submit" value="Add" {{action submit content}}>

My route.js.coffee is:
EmberMoney.Router.reopen
  location: 'history'

EmberMoney.Router.map ->
  @resource 'incomes', ->
    @route 'index' # this route is used for creating new records

EmberMoney.IncomesRoute = Ember.Route.extend
  model: ->
    EmberMoney.Income.find()

EmberMoney.IncomesEditRoute = Ember.Route.extend
  setupController: (controller, model) ->
    if model.get('transaction') == @get('store').get('defaultTransaction')
      transaction = @get('store').transaction()
      transaction.add model
    controller.set('content', model)

  deactivate: ->
    @modelFor('incomes.edit').get('transaction').rollback()

  events:
    submit: (record) ->
      record.one 'didUpdateRecord', =>
        @transitionTo 'index'
      record.get('transaction').commit()

EmberMoney.IncomesIndexRoute = Ember.Route.extend
  model: ->
    EmberMoney.Income.createRecord()
  setupController: (controller, model) ->
    controller.set('content', model)

  events:
    submit: (record) ->
      record.on "didCreate", =>
        @transitionTo 'index'
      record.get('transaction').commit()

My api/incomes_controller.rb is:
class Api::IncomesController < ApplicationController
    respond_to :json

    def index
      respond_with Income.all
    end

    def show
      respond_with Income.find(params[:id])
    end

    def create
      respond_with Income.create(params[:income])
    end

    def update
      respond_with Income.update(params[:id], params[:income])
    end

    def destroy
      respond_with Income.destroy(params[:id])
    end
end

Thanks a lot for help.

A: In this case, you'd need to specify the namespace for the responder. Try:
http://api.rubyonrails.org/classes/ActionDispatch/Routing/PolymorphicRoutes.html
class Api::IncomesController < ApplicationController
    respond_to :json

    def index
      respond_with :api, Income.all
    end

    def show
      respond_with :api, Income.find(params[:id])
    end

    def create
      respond_with :api, Income.create(params[:income])
    end

    def update
      respond_with :api, Income.update(params[:id], params[:income])
    end

    def destroy
      respond_with :api, Income.destroy(params[:id])
    end
end


text:
Q: How to contain jQuery datepicker within div? UPDATES: I tried the suggestions below but they did not work.
I want to contain the calendar within the white div with a dark grey border (class = "profileEdit"), and only have its overflow viewable by scrolling. Right now, it's spilling onto profileEdit's parent divs.
SELECTED HTML

            <input type="text" class="form-control" id="usernameEdit" placeholder="Damon">

            <form class="habitForm">

MY EXERCISE HABIT

                        <select>
                            <option value="0">Before</option>
                            <option value="1">After</option>
                            <option value="2">During</option>
                            <option value="3">Every time</option>
                            <option value="4">When</option>
                        </select>

                    <input type="text" class="form-control" id="triggerEdit" placeholder="breakfast">

,

trigger

I will

.

exercise

is my reward.

reward

            </form>

Remind me to perform habit

                    <input type="checkbox">

                <form class="reminderControls">
                    Start:

                        <input type="text" id="datepicker" value="">

                </form>

            <button id="saveButton">Save</button>

DATEPICKER JQUERY
$(function () {
$("#datepicker").datepicker();
});

DATEPICKER CSS
.profileEdit {
text-align: center;
padding: 1.5rem;
margin: 3rem 1.5rem;
border: grey solid;
border-radius: 3px;
overflow-y: scroll;
position: relative;
}

#ui-datepicker-div {
position: absolute;
width: 280px;
font-family: frutigerLight;
}

.ui-widget-header.ui-widget-header {
background: none;
background-color: white;
border: none;
}

UPDATE: Solution works, but messes up spacing: The space between the "Starts" toggles on and off as well.

A: You can use an inline datepicker and control its visibility with JavaScript:

$(function() {
    $('.dateParent').datepicker({ inline: true, altField: '#datepicker' });
  $('#datepicker').focus(function(event) {
    event.preventDefault();
    $('.ui-datepicker').addClass('shown');
    return false;
  });
  $(document).click(function(event) {
    if(!$(event.target).is('.dateParent *'))
      $('.ui-datepicker').removeClass('shown');;
  });
});
.profileEdit {
  text-align: center;
  padding: 1.5rem;
  margin: 3rem 1.5rem;
  border: grey solid;
  border-radius: 3px;
  position: relative;
}

.ui-datepicker {
  visibility: hidden;
  height: 0;
  margin: 1rem auto;
}
.ui-datepicker.shown {
  visibility: visible;
  height: initial;
}

.ui-widget-header.ui-widget-header {
  background: none;
  background-color: white;
  border: none;
}

<link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css" type="text/css">

  <input type="text" class="form-control" id="usernameEdit" placeholder="Damon">

  <form class="habitForm">

MY EXERCISE HABIT

        <select>
          <option value="0">Before</option>
          <option value="1">After</option>
          <option value="2">During</option>
          <option value="3">Every time</option>
          <option value="4">When</option>
        </select>

      <input type="text" class="form-control" id="triggerEdit" placeholder="breakfast">

,

trigger

I will

.

exercise

is my reward.

reward

  </form>

Remind me to perform habit

      <input type="checkbox">

    <form class="reminderControls">
      Start:

        <input type="text" id="datepicker" value="">

    </form>

  <button id="saveButton">Save</button>

A: Try to remove height attr from calendar element. If it doesnt work check this jQuery UI inline Datepicker auto-resize to parent container

A: As a UX designer I'd think that you want to either make the containing DIV larger (personally think a popup like the calendar shouldn't extend outside it's container) or possibly change the direction that the calendar control opens in relative to the mouse position. If your trigger control is at the bottom of it's container you have the calendar pop upwards instead of down.


text:
Q: Failed to execute Task error with msbuild step I just installed the latest version of sonarqube on my server and did a test run on my project with the sonar-scanner executable. This works.
In the next step, i'm creating a new VSTS Build Definition with the existing SonarQube build steps.

When I trigger this build, it fails in the last step, after the report has been uploaded to my SonarQube server:
VSTS build log

SonarQube server log

I don't know why this happens, because the sonar-scanner is working just fine. I'm using the same parameters in my MS Build step.

A: Looks like your VSTS task is pending completion of the Background Task on SonarQube server side, as per this log in your first screenshot:

Waiting on the sonarqube server to finish processing in order to determine the quality gate status

(note: this is a log from the VSTS task itself, not from the SonarQube Scanner which did finish successfully)
The problem is that the Background Task actually fails with an error as per your second screenshot. The failure corresponds to bug SONAR-8013 (fix to be released in upcoming SonarQube 6.1).


text:
Q: Database connection pool and database connection? I have created a desktop application and I have connect it to a MySQL database with a database connection (bean/class) and I can CRUD.  I have seen on the NetBeans site that they create a connection pool on a web application.
Is a connection pool the same with the class/bean on a desktop application?
Does this mean that i create a bean/class like a desktop application that is connected with to DB model(MVC), or do i have to do something else?
On a Glassfish server you do the connection pool with a wizard; on Apache you do not.  Do I have to create the DB connection bean for Apache?
What are the practices (beans, something else?) to connect a DB to a web application?
I have also read about Hibernate, but I don't understand the use of it.  Where can hibernate help?  I mean, it's ORM, but what can Hibernate do for me so that my code is easier?  I think I'm missing the point of ORM

A: Hibernate will help you with your transaction management. It will enable you to open several different connections to the database, and also give you warnings when you are using unavailable objects (like beans that gets pulled in from different threads).
A concrete example of where Hibernate's ORM will make your code easier is when you are querying the DB. Instead of writing the standard SQL queries as strings, you can use Criteria-queries.

A: In Java, DB connections always use a JDBC driver. No DB that I know of allows to run more than a single SQL command over a single connection at the same time, so each connection becomes bottleneck if your application can run several SQL commands at the same time (the usual case for web servers where hundreds of users can interact with the database at the same time).
UPDATE: What I'm saying is: You can easily daisy-chain commands over a single connection (like UPDATE ... ; COMMIT) but you can't send two UPDATE commands at the same time -- you always have to wait for the first command to complete before you can send the next. Some databases allow to send several commands in a single query but they are executed one after the other and not all at the same time. Think about it: If you could run several commands concurrently over a single connection, how would you know in which order they were executed?
On top of that, creating DB connections is expensive for most DBs. Hence they are created in advance during application startup and held in a pool. As soon as you "connect" to the database with the pooled JDBC driver, it picks an unused connection from the pool and returns it. That (almost) takes no time. When you "close" the connection, it's returned to the pool.
As an additional benefit, the pool can keep the connections alive. So you never need to worry about connection errors when you need a new connection (well, as long as the DB is running).
From the application side, this is either transparent (most JDBC drivers either pool internally today or they have a pooling API). If your JDBC driver doesn't, you can always use a pool like DBCP. The pool handles all the nasty details and you write your application against the pool API instead of using JDBC directly. The docs will tell you how to do it.
How Hibernate is a different beast. Hibernate is a layer on top of JDBC that can transform POJOs into SQL and back.
So instead of saying INSERT INTO data(ID, VALUE) values (?, ?), you can say
class Pojo { long id; String value; }
Pojo demo = new Pojo();
demo.value = "Test";

session.persist(demo);

and Hibernate will create the SQL for you and send it to the DB. At this stage, it doesn't make your life easier. Hibernate starts to shine when you change your Pojos:
class Pojo { long id; String value;
    String name; // Oops ... forget the name
}
Pojo demo = new Pojo();
demo.name = "John";
demo.value = "Test";

session.persist(demo);

Hibernate will change the DB definition accordingly and update all the SQL commands it needs to load and save the objects.


text:
Q: Socket connection between Java and Python - struct.unpack error I'm sending int by using DataOutputStream to Python via a socket but the data I receive at the Python part occasionally gets corrupted and I get the following error:

unpack requires a string argument of length 4

Not to mention that I run the Java part repeatedly. I have no idea why this happens. Please help.
Here is the Java part:
public static void main(String[] args) {

        Socket sock = null;
        DataOutputStream out = null;

        try {
            sock = new Socket("192.168.0.104", 1234);
            out = new DataOutputStream(sock.getOutputStream());

            out.writeInt(2);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                sock.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

And here is the Python part:
import socket
import struct

host = '192.168.0.104'
port = 1234
backlog = 5
size = 4
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(backlog)
while 1:
    client, address = s.accept()
    data = client.recv(size)
    unpacked = int(struct.unpack('>i', data)[0])
    if data:
        print unpacked
    client.close()

Here is the output:
2
2
2
Traceback (most recent call last):
  File "test_socket1.py", line 20, in <module>
    unpacked = int(struct.unpack('>i', data)[0])
struct.error: unpack requires a string argument of length 4

A: From Python's documentation:
socket.recv(bufsize[, flags])
Receive data from the socket. The return value is a string representing the data received. The maximum amount of data to be received at once is specified by bufsize. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero.
The size you passed into recv is the maximum size. So at the point of reading, as long as there is data in the buffer, the function will return that number of bytes immediately. So you could be parsing a 3-byte string into an integer (which requires 4 bytes).
I suggest you check the length of bytes received. If less than 4, sleep a few milliseconds and try again. Finally, you concatenate all segments into one before parsing.
[EDIT]
Found this post talking about something similar:
Python socket recv from java client
Also, I need to correct what I said earlier. You don't need to sleep a few milliseconds (aka, explicitly calling time.sleep(a_few_milliseconds) , you can immediately call recv again, it will block until there is new data. If new data actually arrives in a few microseconds, you don't waste a few milliseconds in sleeping.


text:
Q: how to add search box on the table in grafana dashboard I have a table. I need to add a search box to get the data based on a column name. how to add a search box in the table panel.im using grafana with sql server plug in.
query
SELECT top 1000  * FROM Data
 order by A_id desc

A: See feature was requested, but seems never was implemented https://github.com/grafana/grafana/issues/3919
But you can enable columns filter
https://grafana.com/docs/grafana/latest/visualizations/table/filter-table-columns/

A: To enable filter option open any Grafana dashboard in edit mode.
On the right side panel there is tab called Table, under this there is option to enable column filter.
Enable it and save it, now you can see filter icon on panel.
Click filter icon to see available options.


text:
Q: Compare two array of object to its value, unit test Suppose I have two similar array, how can I write unittest to check if these array has the same values.  And these values are equal. I use mocha and enzyme for unit testing. What is the best way to compare this value?
const devices = [{
        deviceType: 'Tag',
        deviceId: 1,
        name: 'Tag For Sending and alarm',
        version: '',
        location: 'Room1',
        lastAliveMessage: '',
        deviceStatus: 'Active',
        actions: 'offline',

    },{
        deviceType: 'Tag1',
        deviceId: 2,
        name: 'Tag For Sending and alarm2 ',
        version: '',
        location: 'Room2',
        lastAliveMessage: '',
        deviceStatus: 'Active',
        actions: 'offline',
    }]

const devices2 = [{
        deviceType: 'Tag',
        deviceId: 1,
        name: 'Tag For Sending and alarm',
        version: '',
        location: 'Room1',
        lastAliveMessage: '',
        deviceStatus: 'Active',
        actions: 'offline',

    },{
        deviceType: 'Tag1',
        deviceId: 2,
        name: 'Tag For Sending and alarm2 ',
        version: '',
        location: 'Room2',
        lastAliveMessage: '',
        deviceStatus: 'Active',
        actions: 'offline',
    }]

 data.forEach(item => {
                devices.forEach(device =>{
item.deviceId.should.be.equal(device.deviceId))
                })
            })

A: If you are using Chai you can use deep.equal check if the arrays of the objects are the same. It will work even if the order of the keys in the object are not the same between the two.
expect(devices).to.deep.equal(devices2)

A: devices.forEach((device, index) => {
     data[index].deviceType.props.children.should.be.equal(device.deviceType)
     data[index].deviceId.props.children.should.be.equal(device.deviceId)
        })


text:
Q: Spring 3.2-HIbernate3-Tiles - Display Tag not working I searched a lot on web, And I found how to use display tag with spring. But my problem is different am developing a travel agency app using spring as above mentioned version. And I am trying to use the below mentioned display tag version. Without these jars my app is running fine.
I am using itext-1.3.jar, displaytag-1.2.jar, displaytag-export-poi-1.2.jar, jcl104-over-slf4j-1.4.2.jar and poi-3.2-FINAL.jar
But whenever I include these jars in my app I am getting the following error. Please help me.
HTTP Status 500 - javax.servlet.ServletException: Servlet.init() for servlet spring-dispatcher threw exception

type Exception report

message javax.servlet.ServletException: Servlet.init() for servlet spring-dispatcher threw exception

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: javax.servlet.ServletException: Servlet.init() for servlet spring-dispatcher threw exception
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:455)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

javax.servlet.ServletException: Servlet.init() for servlet spring-dispatcher threw exception
    org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:750)
    org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:720)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:72)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

java.lang.NoSuchMethodError:

    org.slf4j.spi.LocationAwareLogger.log(Lorg/slf4j/Marker;Ljava/lang/String;ILjava/lang/String;Ljava/lang/Throwable;)V
        org.apache.commons.logging.impl.SLF4JLocationAwareLog.debug(SLF4JLocationAwareLog.java:99)
        org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:118)
        javax.servlet.GenericServlet.init(GenericServlet.java:158)
        org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:750)
        org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:720)
        org.apache.jsp.index_jsp._jspService(index_jsp.java:72)
        org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
        org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
        org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

    note The full stack trace of the root cause is available in the Apache Tomcat/7.0.52 logs.

Thanks in advance.


text:
Q: using autocomplete with commas in a field I'm trying to use autocomplete with a field with commas in it. When I type the comma it will ignore it, and won't return anything. So far I have this:
index.cfm

<cfform action="autosuggest.cfm" method="post">
  Artist:
  <cfinput type="text" name="artist" size="50" autosuggest="cfc:autosuggest.findartist({cfautosuggestvalue})" autosuggestminlength="4" maxresultsdisplayed="5" />

</cfform>

autosuggest.cfc
<cfcomponent output="false">

    <cffunction name="findartist" access="remote" returntype="string">
        <cfargument name="search" type="any" required="false" default="">

        <cfset var local = {} />

        <cfquery name="local.query" datasource="#application.datasource#" >
            select      DISTINCT artist
            from        items
            where       artist like <cfqueryparam cfsqltype="cf_sql_varchar" value="#ucase(arguments.search)#%" />
            order by    artist
        </cfquery>

        <cfreturn valueList(local.query.artist)>
    </cffunction>

</cfcomponent>

When I try to search for example Brown,James it doesn't return anything. What do I need to put in it to return results with commas.
Thanks

A: One option is to have your function return an array, instead of a string. Then delimiters are not an issue.
   <cffunction name="findartist" access="remote" returntype="array">
      ...
      <cfreturn listToArray(valueList(local.query.artist, chr(30)), chr(30))>
   </cffunction>

Update:
As Raymond pointed out, the only sure-fire way to avoid delimiter issues on the CF side is not to use them.  Instead loop through the query to build the array, ie:
   <cffunction name="findartist" access="remote" returntype="array">
       ...
       <cfset local.arr = []>
       <cfloop query="local.query">
           <cfset arrayAppend(local.arr, local.query.artist)>
       </cfloop>

       <cfreturn local.arr>
   </cffunction>


text:
Q: How to remove placeholder text in JavaScript? I have written some code to remove the input placeholder text and it works as expected. The problem I have is how do I reset the value of placeholder after it has been removed?

const input = document.getElementById('input');

if (input.placeholder) {
  input.addEventListener('focus', (e) => {
    input.placeholder = '';
  });
} else {
  input.placeholder.preventDefault()
};

  <input type="text" class="input" id="input" placeholder="Enter your todo : ">
  <button class="btn" id="btn">Submit</button>

 Todo list :

A: I think this solution should work for you!
It will just reset your placeholder value.

const input = document.getElementById('input');

if (input) {
   // it will remove placeholder value on focus and store with dataset variable
  input.addEventListener('focus', (e) => {
    input.dataset.placeholder = input.placeholder
    input.placeholder = '';
  });

  // it will reset placeholder value on blur by dataset variable
  input.addEventListener('blur', (e) => {
    input.placeholder = input.dataset.placeholder;
  });
}else{
  console.log("input is not defined",input);
}

  <input type="text" class="input" id="input" placeholder="Enter your todo : ">
  <button class="btn" id="btn">Submit</button>

 Todo list :


text: Q: Can I initialize a InitialSessionSpace from a session configuration file? I host a Powershell runspace in c#, but would like the session configuration file mechanism to configure my runspace. Is it possible to use session configuration files from your c# code, without interpreting the file from custom code? Session configuration files are described at https://technet.microsoft.com/en-us/library/hh847838.aspx


text:
Q: Use std::lock to protect return statement? As I understood, std::lock locks section under its scope. But what if access to variable is performed in return statement? Example:
// Looks safe...
bool foo
{
    std::lock_guard<decltype(myMutex)> tLock(myMutex);
    if (bar == 123)
    {
        return true;
    }
    else
    {
        return false;
    }
}

// Is it safe?
bool foo
{
    std::lock_guard<decltype(myMutex)> tLock(myMutex);
    return bar == 123;
}

A: Destructor is called after the return,
so you are fine in both cases.


text:
Q: Why will my list of network interfaces not print? I'm trying to print a list of network interfaces (eventually to store them in a String array of some kind). The following code will only print the list of interfaces if the
    String[] networkInterfaces = new String[Collections.list(nets).size()];

line is not there. It will print the entire list if that single line is not there.
    Enumeration<NetworkInterface> nets = null;
    try {
        nets = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        e.printStackTrace();
    }
    System.out.println(Collections.list(nets).size());
    String[] networkInterfaces = new String[Collections.list(nets).size()];

    for (NetworkInterface netint : Collections.list(nets)) {
        System.out.println(netint.getName());
    }

Sorry for lack of tags on this question, I wasn't sure what was appropriate. Any idea why this occurs? I've modified it such that the collection is saved into an ArrayList (which seems to be fine)
    ArrayList<NetworkInterface> netints = Collections.list(nets);

but I'm still curious as to why the other way didn't work. Thanks :)

A: In short it's because an Enumeration is a stateful iterator.
The first time that you call Collections.list(nets), this library method will loop through the nets enumeration, pulling out elements until the enumeration has no more to return.  This works as expected, and the returned list is as you'd expect.
However, on the next line you call Collections.list(nets) again.  This pulls all of the elements from nets, which is now exhausted, and so "correctly" creates an empty list from an enumeration with no (more) elements.
One way to fix this problem would be to immediately convert nets into a list, and then reference that list everywhere.  So you could change the start of your code to:
List<NetworkInterface> nets = null;
try {
    nets = Collections.list(NetworkInterface.getNetworkInterfaces());
}
...

And then just reference the nets list later on instead of wrapping an enumeration each time.


text:
Q: TSQL Subtracting ROW_NUMBER() I'm having trouble getting this to work. Its Paging centered on a certain row @Row offset by 2 and 5.
DECLARE @Row INT;
SET @Row = CONVERT(INT, (SELECT RowNumber FROM TopScores WHERE Name = 'Rafa'));

SELECT RowNumber, Name, HighScore
FROM TopScores
OFFSET (@Row-2) ROWS
FETCH NEXT 5 ROWS ONLY;

If I could somehow embed the local variable statement within the second and get rid of the variable, that would be preferred, but I can't get anything to work.

Msg 102, Level 15, State 1, Line 6
  Incorrect syntax near '@Row'.
Msg 153, Level 15, State 2, Line 7
  Invalid usage of the option NEXT in the FETCH statement.

To add a bit more context, here's the view "TopScores"
CREATE VIEW TopScores AS
   SELECT
      ROW_NUMBER() OVER (ORDER BY HighScore DESC) AS RowNumber,
      Name, HighScore
   FROM
      [dbo].[LeaderBoards]

A: I figured it out.
From the documentation: "•ORDER BY is mandatory to use OFFSET and FETCH clause."
CREATE PROCEDURE [dbo].[RetrieveRelOffset]
    @LowerOffset INT,
    @UpperOffset INT,
    @Name NVARCHAR(10)
AS
BEGIN
    --Stops the message that shows the count of the number of rows affected by a RSQL statement
    --or stored procedure from being returned as part of the result set.
    SET NOCOUNT ON;

    DECLARE @Row INT;
    SET @Row = CONVERT(INT, (SELECT RowNumber FROM TopScores WHERE Name = @Name)) - @LowerOffset;

    SELECT Name, HighScore
    FROM TopScores
    ORDER BY HighScore
    OFFSET @Row ROWS
    FETCH NEXT @UpperOffset ROWS ONLY;
END;


text:
Q: Multiple ordering in Laravel Yajra datables I can't figure out how to implement several rules of ordering in my Yajra Datatable.
I have table of rides history and there I have a status column which has several enum values (completed, cancelled, scheduled, started). I need to implement following rules for my datatable.

*

*if status =SCHEDULED, display them on top of the list, sorted by
schedule_at asc

*if status != SCHEDULED or CANCELLED (so normal active/completed ride) -
display based on assigned_at column

*if status = CANCELLED & assigned_at is not null - display based on
assigned_at

*if status = CANCELLED & assigned_at is null - display based on
updated_at

in this method I load my requests
    public function getRequests(Request $request){
    $data = UserRequests::RequestHistory();
    if ($request->ajax()) {
        return Datatables::of($data)
            ->addColumn('options', function ($data) {
                return (string) view('admin.request.optionsRequest', ['request' => $data]);
            })
            ->rawColumns(['options'])
            ->make(true);
    }}

database query
    public function scopeRequestHistory($query){
    return $query->orderBy('user_requests.created_at', 'desc')
        ->with('user','payment','provider', 'scheduled_assigned_provider');}

here is datatable on frontend
$('#table-request').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('requests.list') }}",
        columns: [
            {data: 'id', name: 'id',"searchable": false },
            {data: 'booking_id', name: 'booking_id'},
            {data: 'user_id', name: 'user_id'},
            {data: 'provider_id', name: 'provider_id'},
            {data: 'user.first_name',name: 'user.first_name'},
            {data: 'user.last_name',name: 'user.last_name'},
            {data: 'provider.first_name',name: 'provider.first_name'},
            {data: 'provider.last_name',name: 'provider.last_name'},
            {data: 'assigned_at', name: 'assigned_at', render: function(d) {
                    return moment(d).format("DD.MM.YYYY HH:mm:ss");
                }
            },
            {data: 'schedule_at', name: 'schedule_at', render: function(d) {
                if (moment(d).format("DD.MM.YYYY HH:mm:ss")=='Invalid date')
                    return '--';
                else
                    return moment(d).format("DD.MM.YYYY HH:mm:ss");
                }
            },
            {data: 'status', name: 'status', "searchable": false },
            {data: 'is_scheduled', name: 'is_scheduled', "searchable": false },
            {data: 'payment.total', name: 'payment.total', "searchable": false, render: function ( data, type, row ) {

                if(data===undefined)
                {
                    return 'N/A';
                }
                else
                    return '€' + data;}},
            {data: 'payment_mode', "searchable": false },
            {data: 'paid', name: 'paid', render: function ( data, type, row ) {

                    if(data===undefined)
                    {
                        return 'Paid';
                    }
                    else
                        return 'Not Paid';}},
            {data: 'options'},
        ],
        searchCols: [
            null,
            null,
            { "search": $.urlParamUser('search'),"regex": true },
            { "search": $.urlParamProvider('search'),"regex": true },
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
        ],
        "aaSorting": [0,'desc'],
        "columnDefs": [{
            "targets": '_all',
            "defaultContent": "N/A"
        }],
    });


text:
Q: Excel Table References I have the following data formatted as a table in Excel:
First Name  Last Name   Full Name
Simon       King        Simon King
Antoine     French      Antoine French

In cell C2 I have the formula C2 (Excel 2007):
 =Table1[[#This Row],[First Name]]& " "&Table1[[#This Row],[Last Name]]

which returns Simon King
However on Excel 2010 the following formula returns the same result:
=[@[First Name]]&" "&[@[Last Name]]

Is there a different referencing technique in newer versions of Excel or is there a setting as to what syntax can be used. I have a macro which users the latter, but won't work on some other users' Excel. The issue is that I use the latter in macro which creates an error in later versions.

A: In Excel 2016: The referencing technique is =[@FirstName]&" "&[@LastName].
Also from your post, I presume you are trying to set the above formula for C2,C3...Cn column values using macro. In that case, how about using a macro that does the same without setting the formula.
Sub concatName()
Worksheets("Sheet5").Select
Dim LastRow As Long
    With ActiveSheet
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With
For i = 2 To LastRow
    Cells(i, 3).Value = Cells(i, 1).Value & " " & Cells(i, 2).Value
End Sub


text:
Q: PGBrowser Get tinder token from facebook Rewriting this project: https://github.com/tarraschk/TinderAutoLike in PHP using PGBrowser.
My code :
<?php
require 'pgbrowser.php';

$b = new PGBrowser();
$tinder_url = "https://www.facebook.com/v2.6/dialog/oauth?redirect_uri=fb464891386855067%3A%2F%2Fauthorize%2F&scope=user_birthday,user_photos,user_education_history,email,user_relationship_details,user_friends,user_work_history,user_likes&response_type=token%2Csigned_request&client_id=464891386855067";
$email = "***Email***";
$pass = "***Password***";
$page = $b->get($tinder_url);
$form = $page->form(0);
$form->set('email',$email);
$form->set('pass',$pass);
$page = $form->submit();
$submit = $page->form(0);
$page = $submit->submit();
var_dump($page);

?>

Problem : Not returning the access_token

A: Here is the answer
<?php
require 'pgbrowser.php';

$b = new PGBrowser();
$tinder_url = "https://www.facebook.com/v2.6/dialog/oauth?redirect_uri=fb464891386855067%3A%2F%2Fauthorize%2F&scope=user_birthday,user_photos,user_education_history,email,user_relationship_details,user_friends,user_work_history,user_likes&response_type=token%2Csigned_request&client_id=464891386855067";
$email = ""; //email here
$pass = ""; //pass here
$page = $b->get($tinder_url);
$form = $page->forms(0);
$form->set('email',$email);
$form->set('pass',$pass);
$page = $form->submit();
$submit = $page->forms(0);
$page = $submit->submit();
$page =  var_export($page,true);
$access_token = explode("access_token=",$page);
$access_token = explode("&expires_in",$access_token[1]);
echo $access_token[0];

?>


text:
Q: Equivalent to Application.ScreenUpdating Property in office-js Excel add-in I am inserting a lot of data into a sheet and the screen flickers when doing so. In VBA and com add-ins there's a property I can set to delay the updates until they're finished.
Is there an equivalent to Application.ScreenUpdating Property in office-js add-ins for excel?

A: There is no equivalent for it in Office.js -- not yet, at any rate.  There are a number of technical issues that prevent this (FWIW, if you're curious, try toggling ScreenUpdating in VBA while you have a taskpane open; you'll see what I mean).
There are some longer-term ideas that may help with this issue, but to be very transparent, I would expect that it's months and months away.  That said, I do encourage you to file a suggestion on https://officespdev.uservoice.com/ (or search if one already exists) and describe your scenario and/or link to a video of the issue you're currently seeing, so we can get it up on folks' radar.

A: See --> https://learn.microsoft.com/en-us/office/dev/add-ins/excel/performance#suspend-screen-updating
Note: The example is horrible...
Application.suspendScreenUpdatingUntilNextSync() gives error 'Application' is undefined
Use:
context.workbook.application.suspendScreenUpdatingUntilNextSync()

I noticed a dramatic improvement


text:
Q: Stabilizers and Quotients of a Nilpotent Lie Algebra Let $\frak{g}$ be a finite-dimensional complex nilpotent Lie algebra. What conditions on $\xi\in\frak{g}$ ensure the existence of a (canonical or non-canonical) surjective morphism $\frak{g}\rightarrow\frak{g}_{\xi}$ of complex Lie algebras? Also, what are some of the known decomposition theorems for finite-dimensional complex nilpotent Lie algebras?

A: A well-known decomposition theorem for nilpotent Lie algebras is the weight space
decomposition, studied by R. Carles, L. J. Santharoubane and others (in the nilpotent case).
Here $L$ is a finite-dimensional nilpotent
Lie algebra over an algebraically closed field of characteristic zero, and $Der(L)$ its
derivation algebra, $T$ a torus on $L$, that is, a commutative subalgebra
of $Der(L)$ consisting of semisimple endomorphisms. This defines naturally a linear representation of $L$, and the elements of $T$ can be diagonalized simultaneously. Therefore
we have the decomposition
$$
L=\bigoplus_{\alpha \in T^{*}}L^{\alpha},
$$
where $L^{\alpha}$ is the set of $x\in L$ with $t(x)=\alpha (t)x$ for all $t\in T$. The equivalence class of a weight system is an invariant of $L$. It has been studied intensively for nilpotent Lie algebras, e.g., for the classification in low dimensions, and for
the cohomology of nilpotent Lie algebras.


text:
Q: Spring Boot and Proguard I have a simple Spring Boot 1.5.3 application that I am trying to obfuscate with Proguard 5.x using proguard-maven-plugin. I have the following proguard.conf.
-injars ../$FINAL_NAME$/WEB-INF/lib/$FINAL_NAME$.jar

-outjars ./

-optimizations !class/marking/final
-dontoptimize

-adaptresourcefilenames **.properties
-adaptresourcefilecontents **.properties,META-INF/MANIFEST.MF

-dontshrink
-dontoptimize
-dontobfuscate
-dontusemixedcaseclassnames
-dontpreverify
-verbose

-keep public class com.test.blah.OnboardingApp {
  public static void main(java.lang.String[]);
}
-keep public class * extends org.springframework.boot.web.support.SpringBootServletInitializer

-keep class com.test.blah**.dto.** {
  void set*(***);
  *** get*();
}

-keepclassmembers class * {
  @org.springframework.beans.factory.annotation.Autowired *;
  @org.springframework.beans.factory.annotation.Qualifier *;
  @org.springframework.beans.factory.annotation.Value *;
  @org.springframework.beans.factory.annotation.Required *;
  @org.springframework.context.annotation.Bean *;
  @org.springframework.context.annotation.Primary *;
  @org.springframework.boot.context.properties.ConfigurationProperties *;
  @org.springframework.boot.context.properties.EnableConfigurationProperties *;
  @javax.inject.Inject *;
  @javax.annotation.PostConstruct *;
  @javax.annotation.PreDestroy *;
}

-keep @org.springframework.stereotype.Service class *
-keep @org.springframework.stereotype.Controller class *
-keep @org.springframework.stereotype.Component class *
-keep @org.springframework.stereotype.Repository class *
-keep @org.springframework.cache.annotation.EnableCaching class *
-keep @org.springframework.context.annotation.Configuration class *
-keep @org.springframework.boot.context.properties.ConfigurationProperties class *
-keep @org.springframework.boot.autoconfigure.SpringBootApplication class *

-allowaccessmodification
-keepattributes Exceptions,InnerClasses,Signature,Deprecated,SourceFile,LineNumberTable,LocalVariable*Table,*Annotation*,Synthetic,EnclosingMethod
-keepattributes *Annotation*
-keepattributes Signature
-keepattributes Exceptions
-keepattributes InnerClasses

-keepparameternames
-keepdirectories com.test.blah
-keepdirectories org.springframework.boot.autoconfigure

-keepclassmembernames class * {
  java.lang.Class class$(java.lang.String);
  java.lang.Class class$(java.lang.String, boolean);
}

-keepclassmembers enum * {
  public static **[] values();
  public static ** valueOf(java.lang.String);
  public static ** fromValue(java.lang.String);
}

-keepnames class * implements java.io.Serializable
-keepclassmembernames public class com.test.blah.config.liquibase.AsyncSpringLiquibase

-keepclassmembers class * implements java.io.Serializable {
  static final long serialVersionUID;
  private static final java.io.ObjectStreamField[] serialPersistentFields;
  !static !transient <fields>;
  !private <fields>;
  !private <methods>;
  private void writeObject(java.io.ObjectOutputStream);
  private void readObject(java.io.ObjectInputStream);
  java.lang.Object writeReplace();
  java.lang.Object readResolve();
}

-keepclassmembers class * {
  @org.springframework.beans.factory.annotation.Autowired <fields>;
  @org.springframework.beans.factory.annotation.Autowired <methods>;
  @org.springframework.security.access.prepost.PreAuthorize <methods>;
}

Im loading proguard.conf with,
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>${maven-antrun-plugin.version}</version>
    <executions>
        <execution>
            <phase>process-classes</phase>
            <goals>
                <goal>run</goal>
            </goals>
            <configuration>
                <target>
                    <mkdir dir="${project.build.directory}/proguarded" />
                    <copy file="proguard.conf" todir="target/proguarded" />
                    <replace file="${project.build.directory}/proguarded/proguard.conf"
                             token="$FINAL_NAME$" value="${project.build.finalName}" />
                </target>
            </configuration>
        </execution>
    </executions>
</plugin>

<plugin>
    <groupId>com.github.wvengen</groupId>
    <artifactId>proguard-maven-plugin</artifactId>
    <version>${proguard-maven-plugin.version}</version>
    <executions>
        <execution>
            <phase>prepare-package</phase>
            <goals>
                <goal>proguard</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <proguardInclude>${project.build.directory}/proguarded/proguard.conf</proguardInclude>
        <libs>
            <lib>${java.home}/lib/rt.jar</lib>
            <lib>${java.home}/lib/jce.jar</lib>
            <lib>${java.home}/lib/jsse.jar</lib>
        </libs>
    </configuration>
</plugin>

I have no problems generating the war file artifact. However when I deploy to a tomcat instance I get the following error,
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration$LiquibaseConfiguration': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot find changelog location: class path resource [db/changelog/db.changelog-master.yaml] (please add changelog or check your Liquibase configuration)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:137)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:409)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1620)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:372)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
    at org.springframework.boot.web.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:151)
    at org.springframework.boot.web.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:131)
    at org.springframework.boot.web.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:86)
    at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:169)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5196)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 10 more
Caused by: java.lang.IllegalStateException: Cannot find changelog location: class path resource [db/changelog/db.changelog-master.yaml] (please add changelog or check your Liquibase configuration)
    at org.springframework.util.Assert.state(Assert.java:70)
    at org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration$LiquibaseConfiguration.checkChangelogExists(LiquibaseAutoConfiguration.java:92)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:311)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:134)
    ... 42 more

In my application I am loading the Liquibase bean with,
@Configuration("databaseConfiguration")
@EnableJpaRepositories("com.test.blah.repository")
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableTransactionManagement
@EnableElasticsearchRepositories("com.test.blah.repository.search")
public class DatabaseConfiguration {

    private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);

    @Inject
    private Environment env;

    @Bean
    public SpringLiquibase liquibase(DataSource dataSource, LiquibaseProperties liquibaseProperties) {
        // Use liquibase.integration.spring.SpringLiquibase if you don't want Liquibase to start asynchronously
        SpringLiquibase liquibase = new AsyncSpringLiquibase();
        liquibase.setDataSource(dataSource);
        liquibase.setChangeLog("classpath:config/liquibase/master.xml");
        liquibase.setContexts(liquibaseProperties.getContexts());
        liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
        liquibase.setDropFirst(liquibaseProperties.isDropFirst());
        if (env.acceptsProfiles(Constants.SPRING_PROFILE_NO_LIQUIBASE)) {
            liquibase.setShouldRun(false);
        } else {
            liquibase.setShouldRun(liquibaseProperties.isEnabled());
            log.debug("Configuring Liquibase");
        }
        return liquibase;
    }
}

Can anyone please suggest why Im seeing the error ?

A: The trick was to use -keepdirectories as mentioned in https://www.guardsquare.com/en/proguard/manual/usage#iooptions
If anyone else runs into this, I just added this to the above proguard.conf and removed the filters.
So instead of,
-keepdirectories com.test.blah
-keepdirectories org.springframework.boot.autoconfigure

I simply have,
-keepdirectories

Which seems to cover all directories.


text:
Q: Missing input output annotations gradle 7.3 issue with java 17 I have upgraded to Gradle 7.3 to make it compatiple with Java17.I keep getting the below error for task buildDocker
Task :buildDocker FAILED
FAILURE: Build failed with an exception.

*

*What went wrong:
Some problems were found with the configuration of task ':buildDocker' (type 'DockerTask').

*

*In plugin 'docker' type 'se.transmode.gradle.plugins.docker.DockerTask' property 'apiEmail' is missing an input or output annotation.
Reason: A property without annotation isn't considered during up-to-date checking.
Possible solutions:

*

*Add an input or output annotation.

*Mark it as @Internal.

Please refer to https://docs.gradle.org/7.3/userguide/validation_problems.html#missing_annotation for more details about this problem.

*In plugin 'docker' type 'se.transmode.gradle.plugins.docker.DockerTask' property 'apiPassword' is missing an input or output annotation.
Reason: A property without annotation isn't considered during up-to-date checking.
Possible solutions:

*

*Add an input or output annotation.

*Mark it as @Internal.

Please refer to https://docs.gradle.org/7.3/userguide/validation_problems.html#missing_annotation for more details about this problem.

*In plugin 'docker' type 'se.transmode.gradle.plugins.docker.DockerTask' property 'apiUsername' is missing an input or output annotation.
Reason: A property without annotation isn't considered during up-to-date checking.
Possible solutions:

*

*Add an input or output annotation.

*Mark it as @Internal.

Please refer to https://docs.gradle.org/7.3/userguide/validation_problems.html#missing_annotation for more details about this problem.

*In plugin 'docker' type 'se.transmode.gradle.plugins.docker.DockerTask' property 'applicationName' is missing an input or output annotation.
Reason: A property without annotation isn't considered during up-to-date checking.
Possible solutions:

*

*Add an input or output annotation.

*Mark it as @Internal.

Please refer to https://docs.gradle.org/7.3/userguide/validation_problems.html#missing_annotation for more details about this problem.

*In plugin 'docker' type 'se.transmode.gradle.plugins.docker.DockerTask' property 'baseImage' is missing an input or output annotation.
Reason: A property without annotation isn't considered during up-to-date checking.
Possible solutions:

*

*Add an input or output annotation.

*Mark it as @Internal.

The task written is build.gradle is
task buildDocker(type: Docker, dependsOn: build) {
applicationName = 'api'
dockerfile = file('src/docker/Dockerfile')
doFirst {
copy {
from file('src/docker')
from war
into stageDir
}
}
}

A: There is no fix for this issue yet from the transmode team, the plugin was last updated 6years ago, and the last official release by them was 1.2.
Please see the below article in gradle forum, where they suggest to look for an alternative.
https://discuss.gradle.org/t/missing-an-input-or-output-annotation/41061


text:
Q: Using Python threading to monitor sensors Objective: Use threading to build independent Python sensor classes to handle communication between Raspberry Pi and Arduino sensors and some basic data processing.
Background:
I have an Arduino MEGA with some sensors on it, and a Raspberry Pi 3 running python. The Pi sends a request to the Arduino to read one of its sensor values. My Arduino has encoders, motors, lights, pumps, etc, so I have created a generalized python class to handle each type of peripheral.
Each python class will read the raw sensor value, store it in a log, and do some calculations.
import time
import numpy as np

class Encoder(object):
    def __init__(self, hex_address):
        self.hex_address = hex_address
        self.log = []

    def read(self):
        observation = (time.time(), raw_value())
        log.append(observation)

    def raw_value(self):
        ...Communication code...
        return value

    def speed(self, over=1.0):
        times = [obs[0] for obs in self.log if time.time() - obs[0] < over]
        rates = [obs[1] for obs in self.log if time.time() - obs[0] < over]
        return np.polyfit(times, rates, 1)[0]

I then have the main loop of my program
enc = Encoder('\x04')

while True:
    print enc.read()
    print enc.speed()
    times.sleep(1)

The Problem:
In this setup, for the Encoder() class to really function properly, something has to call enc.read() at a semi-regular basis, or else data points won't get added to the log.
Further, what if various parts of my program call enc.read(). Now I'm getting more or less data depending on when and where I call enc.read().
Also, every time I call enc.speed(), my Pi has to calculate another np.polyfit, even if the data hasn't changed.
The Goal: implement threading to launch a new thread for each sensor object.
That way they run independently of my main thread. I would like to start() the sensor, and then have it add new data to the log by calling read() every X ms. Further, I may implement an update() method that does the reading and all the calculations each time it's called.
What I need help with:
I have played around with some threaded classes, but am having a lot of trouble weaving threading into this sample code.


text:
Q: I wonder, how do they find my wordpress themes and plugins I wonder, how websites like https://wpsec.com can find my wordpress themes and plugins.
When I tried to access the directory mydomain.com/wp-content/themes/my-theme, I got 404 but how do they get this.
Are my firewalls and security malewares plugins are useless?

A: After thinking about this my conjecture on how this works is this:
Almost all plugins/themes have .css and/or .js files. For plugins these are stored in the plugin's installation directory - .../wp-content/plugins/some-plugin-directory. The URLs of the HTTP requests for these would look this - httpx://some.host.com/wp-content/plugins/some-plugin-directory/js/some-javascript-file.js. From these requests wpsec can extract 'some-plugin-directory' which is what WordPress uses to identify a plugin. If the plugin is in the WordPress repository then wpsec can download the entire plugin and provide more information. If the plugin is proprietary then wpsec probably only has access to the publicly accessible .js and .css files. On my installation I have a proprietary plugin and wpsec found the installation directory - 'some-plugin-directory' but did not report the version probably because it cannot access the readme.txt or any of the .php files. So, if this conjecture is correct if a plugin only has PHP i.e. no .css, no .js and also no images stored in its installation directory then wpsec should not be able to detect it. Of course the same reasoning applies to themes.


text:
Q: Adaptive controllers for stiff ODE and DAE integrators I'm looking for adaptive controllers (adaptive in both step size and order) for stiff integrators.  I have asymptotically correct error estimates for the current method and all candidate methods of order 1 higher and lower than the current method.  My naive controllers have occasional problems with either oscillating between different methods despite smooth long-term behavior, or getting stuck (e.g. with a high order method and unreasonably short time steps).
For the curious, these are IRKS general linear methods, see Butcher, Jackiewicz, and Wright 2007.

A: Have a look at chapter 8 of Jackiewicz's book, especially section 8.10 for a general background.  There's some matlab code by Podhaisky too, used to do this, but no control here.
And then, the theses of Butcher's recent student are here, which discuss implementation details, in particular Huang's chapter 3 should be very useful to you.
Older fortran code by Hairer do implement both order and stepsize control: see RADAU and DR_RADAU here, it's not for IRKS but gives a well-tested framework that could be suitably modified.

A: The paper "Automatic control and adaptive time-stepping" by G. S\"oderlind http://www.maths.lth.se/na/staff/gustaf/numart.pdf might be useful. It deals mainly with stepsize control.


text:
Q: Closing a document's window and opening a new one, without closing the document My app is document-based, but the "document" consists of two folders, not one file. The document's initial window contains a couple of file pickers and a button; the action closes that window and opens a new one showing the results of the operation between the two folder hierarchies. (The two windows are significantly different in size; keeping both views in a tabless tabview and switching with that would be non-trivial.)
Here's the code from my action method that closes the file-pickers window and opens the results window:
[self retain];
NSArray *existingWindowControllers = [[[self windowControllers] copy] autorelease];
for (NSWindowController *windowController in existingWindowControllers) {
    [windowController setShouldCloseDocument:NO];
    [windowController close];
    [self removeWindowController:windowController];
}
[self addWindowController:[[[NSWindowController alloc] initWithWindowNibName:@"ProjectFoldersDocument" owner:self] autorelease]];
[self showWindows];
[self release];

(I added the retain and release messages in a failed attempt to solve the problem.)
My problem is that the document gets released and deallocated after this action method finishes, despite my telling the initial window controller not to close the document. (That was another failed attempt to solve the problem.)
So, how can I replace the first window with another, for the same document, without the document dying off?

A: I finally solved this by switching the removeWindowController: and close messages:
[self removeWindowController:windowController];
[windowController close];

This would suggest that the window controller was closing its document on close. I don't know why, because I'd told it not to on the immediately-previous line.
I also removed the explicit retain and release messages. The problem did not return.


text:
Q: Rails 4.1 enum query I am seeing Rails generate the wrong query value when I use an enum col value in a where clause, like this (self added for clarity). dominant_product_strategy is an enum.
def some_model_method_on_myModel
   MyModel.where(dominant_product_strategy: self.dominant_product_strategy)
end

This produces the correct value (again, self just added for clarity):
MyModel.where(dominant_product_strategy: self.attributes["dominant_product_strategy"])

I'm guessing that Rails sees the enum as a string, and then converts to a integer value of zero. Ughhhhh!
Am I missing something?
This also works:
MyModelwhere(dominant_product_strategy: MyModel.dominant_product_strategies[dominant_product_strategy])

A: It seems to be that you have answered your question by yoursef. Enum variables is a hash:
{str1: int1, str2: int2, ...}

The value (integer) is storing in DB, and the string is just representation of the int value. When you call self.dominant_product_strategy, you get the representation (string) of dominant_product_strategy column storing as integer in DB.
I think that your first working solution (self.attributes["dominant_product_strategy"]) is fine.


text:
Q: Creating a Script File to Call a Shortcut That Has a Complex Target and Closing the End Dialog Window I am a moderately educated novice computer enthusiast and am remotely mildly educated in vbscript and I need help. Here  is the order of events...
I used Winaero Tweaker on my PC (running Windows 10 Home) to create an elevated shortcut to a virtual CD running an unlock program for my WD Passport Drive.
Normally, I click a shortcut to the program on the drive, say "yes" to UAC, then click the resulting end window telling me the drive is unlocked.
The Winaero elevated shortcut works beautifully except it leaves the end window open.
Here is the target:
C:\WINDOWS\system32\cmd.exe /c start "" schtasks.exe /run /tn "WD Drive Unlock.exe_-943894699"

So, I thought I might try a VB script calling the shortcut, then simply entering {esc} or ~ to close the window.  Simple.  NOT.  I cannot get the window to close, God Save the Queen.
My attempt using the elevated shortcut (H-IT.lnk):
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\USERS\OWNER\DESKTOP\H-IT.lnk"  & Chr(34), 0
WScript.Sleep 1500
WshShell.AppActivate "wd drive"
WshShell.SendKeys "{esc}"
Set WshShell = Nothing

This executes the shortcut just like the shortcut executes the shortcut, but the resulting program window entitled "WD Drive Unlocked"  remains OPEN (just like the shortcut).
So, I thought, why not utilize the shortcut's target and circumvent the shortcut all together....for me a midnight nightmare. Here's my embarrassing attempt (intro to VB was 20 yrs ago):
And my attempt to circumvent the shortcut:
Set WshShell = WScript.CreateObject("WScript.Shell")
Command = "%WINDIR%\cmd.exe /c start ""schtasks.exe /run /tn ""WD Drive Unlock.exe_-943894699""
WshShell.Run command
WScript.Sleep 1500
WshShell.AppActivate "wd drive"
WshShell.SendKeys "{esc}"
Set WshShell = Nothing:

I care not about the programming; I just want to unlock my drive in one click with no UAC and no dialog remnants.


text:
Q: Microsoft Word: Repeating a figure without renumbering I'm writing a paper for a scientific journal and need to repeat all of my figures at the end of the document for the editor's perusal. My figures are dynamically numbered, and the figures at the end must have the same numbers as those earlier in the document. Copy-pasting the figures to the end of the document gives them new numbers.
Is there a way of doing this without having to manually adjust the numbers? Maybe some way of inserting a figure as a direct duplicate of one earlier in the document?

A: One way:

*

*Save your document, and make a copy of it.

*Open the copy.

*Select all the material and press ctrl-shift-F9 to unlink all the
relevant field codes, i.e. replace the codes by their results.

*Open the original.

*Copy the figures and their captions from the copy to the original.

However, you would either have to make manual changes to reflect any changes to the numbering sequence after that, or you would have to re-do the whole operation. So it's really a pre-publishing step.
Another option you could consider is to do your references using the rather complicated field coding I have suggested here. The main snag with that (other than its complication and lack of real-world testing) is that as it stands, it may not play well with Word's standard cross-referencing and Tables of Figures features.


text:
Q: how do I save all files onto my local computer I have a website up and running.  I have Notepad++ on my local computer.  I can edit my website in real time using Notepad++.  I now would like to save "my website" on my local computer as a backup.  What is the easiest way to save all of the files using Notepad++?

A: You probably have some type of control panel with your web hosting. From within the control panel find the file manager, navigate to your httpdocs directory (or where-ever the public files of your site are located) make a zip of that folder and download it.
Option 2 is

*

*get an FTP client like FileZilla

*get FTP connection details from your hosting provider or via your control panel

*connect and download the httpdocs folder to your local computer

Good luck!


text:
Q: Object Variables vs Class Variables in Java I am in the process of learning Java and I don't understand the difference between Object Variables and Class Variable. All I know is that in order for it to be a Class Variable you must declare it first with the static statement.
Thanks!

A: The difference between a static variable or a class variable and an instance variable or a object variable is pretty simple.  Every object you create has its own copy of its very own instance variables.  Where as if there is a static variable in the class then only one copy of that static variable exists for all the objects.  For example
public class JellyBean{

    // instance variables every jellyBean object will have its own
    // variable for color
    String color;

    // static variable only one copy of this variable exists for
    // all jellyBean objects.
    static int totalNumberOfJellyBeans;

}//end class

If you created 2 jellybean objects you would have two variables for Color because each jellybean has its own variable for color.  And 1 variable for totalNumberOfJellyBeans because both jellyBean objects use this one class variable.

A: An object variable is state dependent on a specific instance of a class, whereas a class variable is globally accessible through the class itself.  That might be a little fuzzy, so here are some examples:
class Muffin {

    private static final int calories = 9320;

    public String flavor;

    public Muffin( String flavor ){
        this.flavor = flavor;
    }

}

In this class, calories is a class variable.  In any other piece of code, you can get the number of calories in any kind of muffin by calling Muffin.calories.  In this case, the final keyword is also used to make the number of calories constant.
In the same class, we have an object variable, flavor.  This is dependent on the instance of the class, and is set in the constructor.
Muffin myMuffin = new Muffin( "blueberry" );

So now you can access this specific muffin's flavor by calling myMuffin.flavor.  Notice how we need to instantiate a Muffin object before we can access its flavor.
Changing static (class) variables
The above example is a bit of a stretch, since different types of muffins would have different calorie counts.  They are useful for constants, but here's a case where the value of the static variable changes:
class Muffin {

    private static int next_id = 1;

    public int id;
    public String flavor;

    public Muffin( String flavor ){
        this.flavor = flavor;
        id = next_id++;
    }

}

In the second example, we need to have a unique ID number for every muffin we create, so we can have a static variable that gets incremented every time a Muffin is instantiated.  The static keyword makes the value of next_id persist through every call to the constructor, so the id will be different and continue to increase for every new muffin.

A: Let's say you have a blueprint of a car called ToyotaYaris, in which you might have a variable called maxSpeed. All the cars made with that blueprint (its instances) will have the same maximum speed, so that variable should belong to the blueprint, and not the individual cars. If the maxSpeed changes in the blueprint, so will it change in all the cars it produces.
However, on each car, you might want to have another variable called speed. This variable can't belong to the blueprint because each car can be driving at different speeds independently of each other, so you need that variable to belong to each specific instance of ToyotaYaris.
Therefore:
class ToyotaYaris {
    static int maxSpeed;
    int speed;
}

A: In Java (and in OOP in general) the objects have two kinds of fields(variable).
Instance variables(or object variable) are fields that belong to a particular instance of an object.
Static variables (or class variable) are common to all the instances of the same class.
Here's an example:
public class Foobar{
    static int counter = 0 ; //static variable..all instances of Foobar will share the same counter and will change if such is done
    public int id; //instance variable. Each instance has its own id
    public Foobar(){
        this.id = counter++;
    }
}

usage:
Foobar obj1 = new Foobar();
Foobar obj2 = new Foobar();
System.out.println("obj1 id : " + obj1.id + " obj2.id "+ obj2.id + " id count " + Foobar.counter);

A: An object variable or instance member belongs to a specific instance of a class. That is to say that every instance has its own copy of that piece of data. A class variable or static member is shared by every instance of the class.  That is to say that there is only one copy of that piece of data no matter how many class instances there are.


text:
Q: Django - Appending dictionary values return empty dictionary I have a list of words, called lyrics_sorted, that looks like this:
lyrics_sorted = ['word1', 'word2', 'word3', ]
Now I want to make a dictionary with this as one of the keys, and another key the normalized form of the word.
So first I declare the key values, like this:
word_original = lyrics_sorted
word_normalized = []

And then the dictionary:
grammar_dict = {'word_original': word_original, 'word_normalized': word_normalized}

And now for every word in word_original (or lyrics_sorted), I want to add the normalized form, so I do as follows:
for word in lyrics_sorted:
    w = morph.parse(word)[0]
    word_normalized.append(w.normal_form)

    context['grammar_dict'] = list(zip(grammar_dict['word_original'],
                                       grammar_dict['word_normalized'],))
return context

But I get just an empty list. I can't figure out what I'm doing wrong; when I test it in the shell it works.

A: I would go with this setup.
class MyView(...):

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        lyrics_sorted = ['word1', 'word2', 'word3', ]
        grammar_list = []
        for word in lyrics_sorted:
            parsed_word = morph.parse(word)[0]
            result = {
                'word_original': word,
                'word_normalized': parsed_word.normal_form
            }
            grammar_list.append(result)

            context['grammar_list'] = grammar_list
        return context
So, the grammar_list will look like
[
    {'word_original': 'word1', 'word_normalized': 'word1_normalized'},
    {'word_original': 'word2', 'word_normalized': 'word2_normalized'},
    {'word_original': 'word3', 'word_normalized': 'word3_normalized'},
]

hence, you can access the grammar_list context variable in your Django template as,
{% for item in grammar_list %}
    {{ item.word_original }} ---- {{ item.word_normalized }}
{% endfor %}


text:
Q: JS Switch Case is not matching the right value I have a switch case, which tracks the key down press events and execute actions. For example, my switch matches the number 37 with 13 and executes the branch for case 13 when the left/ right arrow is pressed. I made sure the data type is parsed to int before, but I still see the issue. My switch-case logic is as below. Am I missing something here?
switch (evt.keyCode) {
                        case 27: // Escape
                            emit('editCanceled');
                            break;
                        case 9: // tab
                        case 37: // left
                        case 38: // up
                        case 39: // right
                        case 40: // down
                        case 13: // Enter
                            self.validateAndComplete();
                            break;
                        default:
                    }

A: The following update to the switch logic ensures that my validateAndComplete is triggered for only enter and tab events. Left/ right/ up/ down key arrow events would not have any effect
  switch (evt.keyCode) {
                            case 27: // Escape
                                emit('editCanceled');
                                break;
                            case 9: // tab
                            case 13: // Enter
                                self.validateAndComplete();
                                break;
                            default:
                        }


text:
Q: Is $P(T>c|T=k) = P(k>c|T=k)$? Is it acceptable to write:
$P(T>c|T=k) = P(k>c|T=k)$?
I think not, because k isn't a random variable, but I have seen this written this way.
If C is a rv, does this change things?
$P(T>C|T=k) = P(k>C|T=k)$?

A: Yes. Option 1 is ok. Random variables are allowed to be degenerate (implicit in this notation is that $k$ is a random variable that for all $\omega$ gives the value $k$). There may be some problems with this notation if the conditioning set has probability 0.
This is not so different from saying that the covariance of a random variable with a (constant) number is zero - even if strictly speaking we can only compute covariances between two random variables. The number is interpreted as a constant random variable,

A: Both of them can be written. The latter is the one you generally see; but the first one is like saying $P(1 < 2)$, which is actually 1, since 1 is always smaller than 2. We're in a limiting case here. Surely, you can define a PMF of the form:
$$
P_X(x)= \begin{cases}
      1 & x =1 \\
      0 & x \neq 1
   \end{cases}
$$
It is not against the definition. But, this is a constant. In your case, $k$ or $c$ are also constants with similar PMFs. You don't violate RV definition.


text:
Q: mkfs.vfat unable create file partition I am trying to create a file system partition using the mkfs.vfat command.
Below is the command I'm using:
mkfs.vfat -F 32 -n program /dev/sdb1
mkfs.vfat -F 32 -n init /dev/sdb2

I'm getting the below warning:
mkfs.fat 3.0.26 (2014-03-07)
mkfs.fat: warning - lowercase labels might not work properly with DOS or Windows
mkfs.vfat: failed whilst writing FAT
mkfs.fat 3.0.26 (2014-03-07)
mkfs.fat: warning - lowercase labels might not work properly with DOS or Windows
mkfs.vfat: failed whilst writing FAT

Why?

A: You can ignore the lowercase label warning.
You need to separate the commands, e.g.
mkfs.vfat -F 32 -n program /dev/sdb1
mkfs.vfat -F 32 -n init /dev/sdb2

If your device have no partitions than you have to create new partition table, here is a good example: http://www.howtogeek.com/106873/how-to-use-fdisk-to-manage-partitions-on-linux/.


text:
Q: SonarQube multi-language module within multi-modules project I have a multi mudule project with lots of modules and most of them are java. therefore i set in the root pom the sonar.language to java.
however, one of my module contains both java and js so in order to disable the sonar.language property i had to add the following to this module pom:
<plugin>
    <groupId>org.codehaus.gmaven</groupId>
    <artifactId>gmaven-plugin</artifactId>
    <executions>
        <execution>
            <phase>validate</phase>
            <goals>
                <goal>execute</goal>
            </goals>
            <configuration>
                <source>
                    project.properties.remove('sonar.language')
                </source>
            </configuration>
        </execution>
    </executions>
</plugin>

is there a cleaner way to have a default language and unset it in one of the modules?


text:
Q: QDS_SHUTDOWN_QUEUE and SOS_SCHEDULER_YIELD Please see below the statistics of our wait events.
Here is how it looks like when the server was slow
WaitType            Wait_S      Resource_S  Signal_S    WaitCount   Percentage  AvgWait_S   AvgRes_S    AvgSig_S
SOS_SCHEDULER_YIELD         25081233.07     5479.80     25075753.27       3861884336      71.85         0.0065      0.0000          0.0065
LCK_M_U                 4266673.43      4089972.80      176700.64       181841311       12.22       0.0235      0.0225      0.0010
QDS_SHUTDOWN_QUEUE              2990777.05      2990575.12      201.93         49843        8.57            60.0040     59.9999     0.0041
WRITELOG                510297.58       361099.16       149198.42       217670297       1.46            0.0023      0.0017      0.0007
LCK_M_IX                315018.33       314945.12       73.21       40190       0.90            7.8382      7.8364      0.0018

Here is how it looked like when the server was fast
SOS_SCHEDULER_YIELD                26677340.27       5587.81 26671752.46       3946140972         72.84     0.0068   0.0000                0.0068   https://www.sqlskills.com/help/waits/SOS_SCHEDULER_YIELD
LCK_M_U            4413555.12          4227846.32          185708.80            188067634           12.05     0.0235   0.0225   0.0010                https://www.sqlskills.com/help/waits/LCK_M_U
TRACEWRITE      3052641.54          3046721.06          5920.48 2456310                8.34        1.2428   1.2404   0.0024                https://www.sqlskills.com/help/waits/TRACEWRITE
WRITELOG          520701.92            368987.94            151713.99            219597994           1.42        0.0024   0.0017   0.0007                https://www.sqlskills.com/help/waits/WRITELOG
LCK_M_IX           317274.13            317197.46            76.68     41936    0.87        7.5657   7.5638   0.0018                https://www.sqlskills.com/help/waits/LCK_M_IX

The CPU is under constant pressure due to a continuously running query.
The CPU is around 50 to 60% and doesn't go higher.
The Database didn't encounter any slowdowns when it was in SQL Server 2008 but started acting up on we migrated to SQL 2014.
Can anyone help shed light on this  ?
scheduler_address   parent_node_id  scheduler_id    cpu_id  status  is_online   is_idle preemptive_switches_count   context_switches_count  idle_switches_count current_tasks_count runnable_tasks_count    current_workers_count   active_workers_count    work_queue_count    pending_disk_io_count   load_factor yield_count last_timer_activity failed_to_create_worker active_worker_address   memory_object_address   task_memory_object_address  quantum_length_us
0x0000000C7F190040  0   0   0   VISIBLE ONLINE  1   1   4201433 265078042   105192749   3   0   6   3   0   0   3   523674903   3017581829  0   0x0000000C7E090160  0x0000000C7F014040  0x0000000C7F016040  4000
0x0000000C7F1A0040  0   1   1   VISIBLE ONLINE  1   0   5334160 314838759   259747024   5   1   6   4   0   0   6   951409528   3017581954  0   0x00000015AD4F0160  0x0000000C7F01E040  0x0000000C7F020040  4000
0x0000000C7F1B0040  0   2   2   VISIBLE ONLINE  1   0   4232445 264243145   106502397   4   0   6   4   0   0   5   534826882   3017581955  0   0x0000002CEFFE2160  0x0000000C7F026040  0x0000000C7F028040  4000
0x0000000C7F1C0040  0   3   3   VISIBLE ONLINE  1   0   6172543 427766854   344998697   3   0   6   3   0   0   4   1199857921  3017581953  0   0x0000001993EE4160  0x0000000C7F02E040  0x0000000C7F030040  4000
0x0000000C7F1D0040  0   4   4   VISIBLE ONLINE  1   0   5195146 318930441   266000445   4   0   7   3   0   0   4   971326640   3017581952  0   0x0000000380B0E160  0x0000000C7F036040  0x0000000C7F038040  4000
0x0000000C7F1E0040  0   5   5   VISIBLE ONLINE  1   0   5276883 319954368   261387691   2   0   5   2   0   0   4   960323343   3017581953  0   0x0000000333D96160  0x0000000C7F03E040  0x0000000C7F040040  4000
0x0000000C7F1F0040  0   6   6   VISIBLE ONLINE  1   0   9467930 336593259   288395855   2   0   5   2   0   0   4   1032632158  3017581951  0   0x00000004CE9C8160  0x0000000C7F046040  0x0000000C7F048040  4000
0x0000000C7F580040  0   7   7   VISIBLE ONLINE  1   1   5783581 331850535   279067751   2   0   5   2   0   0   2   1032376996  3017581389  0   0x0000001BD5E16160  0x0000000C7F04E040  0x0000000C7F050040  4000
0x0000000C7F590040  0   8   8   VISIBLE ONLINE  1   1   4144833 265265702   101585831   2   0   5   2   0   0   3   523265379   3017580639  0   0x0000001BD5D3C160  0x0000000C7F056040  0x0000000C7F058040  4000
0x0000000C7F5A0040  0   9   9   VISIBLE ONLINE  1   1   6418985 323036670   263756664   3   0   5   3   0   0   4   960004710   3017581712  0   0x0000001754B9A160  0x0000000C7F05E040  0x0000000C7F060040  4000
0x0000000C7F5B0040  0   10  10  VISIBLE ONLINE  1   1   4153093 265733808   92616497    3   0   5   3   0   0   3   498959733   3017581933  0   0x0000002CBF4B2160  0x0000000C7F066040  0x0000000C7F068040  4000
0x0000000C7F5C0040  0   11  11  VISIBLE ONLINE  1   1   4386529 264383817   98983641    3   0   6   3   0   0   3   510839760   3017580637  0   0x0000001974E0A160  0x0000000C7F06E040  0x0000000C7F070040  4000
0x0000000C7F5D0040  0   12  12  VISIBLE ONLINE  1   1   3991082 265081140   99554703    2   0   5   2   0   0   3   509176368   3017581771  0   0x0000000C3F316160  0x0000000C7F076040  0x0000000C7F078040  4000
0x0000000C7F5E0040  0   13  13  VISIBLE ONLINE  1   1   4116189 262203107   101069089   2   0   5   2   0   0   3   510118760   3017581915  0   0x0000000A43526160  0x0000000C7F07E040  0x0000000C7F900040  4000
0x0000000C7F5F0040  0   14  14  VISIBLE ONLINE  1   0   5797666 378781420   176936312   2   0   5   2   0   0   3   817116602   3017581953  0   0x0000001DC7DEC160  0x0000000C7F906040  0x0000000C7F908040  4000
0x0000000C7FA80040  0   15  15  VISIBLE ONLINE  1   1   3625843 260929187   96066759    3   0   6   3   0   0   3   496703022   3017581849  0   0x0000000C7FB16160  0x0000000C7F90E040  0x0000000C7F910040  4000

Thanks


text:
Q: How to put some keyboard layout aside from layout switching ring? What I need is to

*

*switch between Russian and English layout with my favorite shortcut (namely Shift-CapsLock)

*switch to Belarusian layout with another shortcut (say, Ctrl-RightShift, but actual binding doesn't matter)

*while Belarusian layout is active, switch back to Russian/English with Shift-CapsLock
Is it possible with xkb at all? If so, how can this be done?

A: Three useful commands:
1. Get the current keyboard layout, from this topic :
setxkbmap -print | grep xkb_symbols | awk -F"+" '{print $2}'

Returns layout(variant) where variant is optional
2. Know if the current keyboard layout is layout(variant):
 setxkbmap -print | grep "layout(variant)"

Or without "(variant)".
Returns nothing is not.
3. Set the keyboard layout to a specified value:
setxkbmap layout variant

Where variant is optional.
(see man setxkbmap for more informations)
What you can do:
1. Create a simple executable (chmod +x file) script that changes the keyboard layout on the fly, depending on the current one. For instance, if we deal with the first point:
#!/bin/bash

if setxkbmap -print | grep "us"
then
  setxkbmap ru
else
  setxkbmap us
fi

2. With your keyboard shortcuts manager, assign the Shift-CapsLock keys to this script.
Good luck!

A: What you exactly want is not possible as it would require statefull process (to know the state previous of switching to by layout).
However, along with the ISO_Prev_Group and ISO_Next_Group symbols allowing to decrement/increment in the layouts ring, there is also those two: ISO_First_Group and ISO_Last_Group.
With this ring: us,by,ru you can always access any of the three layouts in a single toggle.
For example, define Shift-CapsLock to send ISO_Last_Group when in us layout, ISO_First_Group when in ru or by;
define Ctrl-RightShift to send ISO_Next_Group when in us ISO_Prev_Group when in ru and ISO_Next_Group (or Last) when in by.
The difference with what you want is that you have to manually choose (with different shortcuts) the layout you want to go, when in by.
Also, if you need by layout for just a few belarussian specific cyrillic letters; another option would be to use a modified ru layout, with extra symbols in some keys, accessible with an AltGr or similar key, like in most latin keyboards.
As in the by file there are only 3 different keys from ru it seems that would be the right approach.
In such cas I would stack the layouts as: us,ru,by
Use ISO_Next_Group in "us", ISO_Prev_Group in "ru" for Shift-Capslock, and in "ru" define a key with a latching ISO_Next_Group.
To do that:
Create a ~/.xkb/keymap/mykbd where you put the output of setxkbmap, it will be your base keyboard definition; eg:
setxkbmap "us,ru,by" ; setxkbmap -print > ~/.xkb/keymap/mykbd

then create a file ~/.xkb/symbols/mysymbols with:
partial modifier_keys
xkb_symbols "shift_caps_us_ru_by" {
  key <CAPS> {
    symbols[Group1] = [  Caps_Lock, ISO_Next_Group   ],
    symbols[Group2] = [  Caps_Lock, ISO_Prev_Group   ],
    symbols[Group3] = [  Caps_Lock, ISO_First_Group  ]
  };
  key <RALT> {
    symbols[Group2] = [ ISO_Group_Latch ]
  };
};

edit the ~/.xkb/keymap/mykbd file, and change the xkb_symbols line to add +mysymbols(shift_caps_us_ru_by)
finally, you can load it with xkbcomp -I$HOME/.xkb ~/.xkb/keymap/mykbd and now Shift-CapsLock switch between latin (us) and cyrillic (ru) layouts; and while in cyrillic, you can access belarusian-specific letters holding AltGr (right Alt) key.

A: All right, so what I was really wanted was switching layouts in MRU (most recently used) order. And guess what, GNOME's default layout switcher does precisely that (make sure no checkboxes in "Tweaks" → "Keyboard & Mouse" → "Additional Layout Options" → "Keys to change layout" are activated!). So currently I have 4 layouts in a ring (Russian, Belarusian, Ukrainian, English) and switching between most recent ones is one SuperSpace away. So that solves the issue for me and then some.

A: I highly recommend using sxhkd (simple X hotkey daemon).Its configuration should not be challenging at all. Follow the steps presented in the archwiki tutorial and you'll get it up and running in no time.
For the sake of simplicity, sxhkd gives you the power to map/bind input events (like pressing a key down...) to actions (like changing the keyboard layout back and forth...)
I, personally, switch between 3 different layouts on the fly. The mappings I use :
super + k; {u,f,r}
  setxkbmap {us,fr,ru}

super is a special key (called modifier), you can use other modifier keys like Ctrl or Alt etc (it's all documented)
So when I hold press my modifier key (super the windows key in my case) and k then release both and press one of the three keys u f r it runs the command setxkbmap with one of the three arguments supplied depending on the key pressed (order is respected). Let's say I hit superkthenf I get setxkbmap fr the french layout
ps: if you bind, by accident, a combination of keys that is already associated with an action, you might get indesirable/unexpected results (most likely the late bindings will shadow the early ones). But keep in mind that everyting has always a fix. So dont be afraid to experiment.


text:
Q: Zipkin : zipkin2.reporter.AsyncReporter$BoundedAsyncReporter flush Dropped 1 spans due to SocketTimeoutException(connect timed out) Small Zipkin question, how to set the time out please?
I am writing a very simple piece of code, where I am the client, and sending requests to a server.
import brave.Span;
import brave.Tracing;
import zipkin2.reporter.AsyncReporter;
import zipkin2.reporter.okhttp3.OkHttpSender;

public class QuestionApplication {

    public static void main(String[] args) {

        var sender = OkHttpSender.newBuilder().endpoint("http://zipkin-server:9411/api/v2/spans").build();
        var reporter = AsyncReporter.builder(sender).build();

        var tracing = Tracing.newBuilder().localServiceName("component-test").spanReporter(reporter).build();

        // Create parent span and his child --------------------

        // Parent
        tracing.tracer().startScopedSpan("parentSpan");
        Span span =  tracing.tracer().currentSpan();
        span.tag("key", "firstBiz");

        // Child
        tracing.tracer().startScopedSpanWithParent("childSpan", tracing.tracer().currentSpan().context());
        Span childSpan =  tracing.tracer().currentSpan();
        childSpan.tag("key", "secondBiz");
        childSpan.finish();
        System.out.println("id:" + childSpan.context().traceIdString());
      final var response      = webClient.post().uri("http://the-server.com/api/route").header("X-B3-TraceId", childSpan.context().traceIdString()).body(BodyInserters.fromValue(jsonPayload)).retrieve().bodyToMono(String.class).block();
        System.out.println(response);

        // Finish span
        span.finish();

    }

}

Reproducible 100%, I am always getting this error:
zipkin2.reporter.AsyncReporter$BoundedAsyncReporter flush
WARNING: Spans were dropped due to exceptions. All subsequent errors will be logged at FINE level.
zipkin2.reporter.AsyncReporter$BoundedAsyncReporter flush
WARNING: Dropped 1 spans due to SocketTimeoutException(connect timed out)
java.net.SocketTimeoutException: connect timed out
    at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399)
    at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242)
    at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:403)
    at java.base/java.net.Socket.connect(Socket.java:609)
    at okhttp3.internal.platform.Platform.connectSocket(Platform.java:130)
    at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:263)
    at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:183)
    at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.java:224)
    at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.java:108)
    at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.java:88)
    at okhttp3.internal.connection.Transmitter.newExchange(Transmitter.java:169)
    at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:41)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
    at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:94)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
    at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
    at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:88)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
    at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:229)
    at okhttp3.RealCall.execute(RealCall.java:81)
    at zipkin2.reporter.okhttp3.HttpCall.execute(HttpCall.java:34)
    at zipkin2.reporter.okhttp3.HttpCall.execute(HttpCall.java:25)
    at zipkin2.reporter.AsyncReporter$BoundedAsyncReporter.flush(AsyncReporter.java:299)
    at zipkin2.reporter.AsyncReporter$Flusher.run(AsyncReporter.java:378)
    at java.base/java.lang.Thread.run(Thread.java:834)

zipkin2.reporter.AsyncReporter$BoundedAsyncReporter close
WARNING: Timed out waiting for in-flight spans to send

I tried looking at the internal API for a method to set the time out, but no luck.
May I ask what is the proper way to set the time out please?
Thank you


text:
Q: Yaml numeric keys: can't start with zero? Let's say I have this .yml file used for Symfony2 i18n
month:
  01: Jan
  02: Feb
  03: Mar
  04: Apr
  05: May
  06: Jun
  07: Jul
  08: Aug
  09: Sep
  10: Oct
  11: Nov
  12: Dec

In twig, for tanslation, I will use something like
{% set month = my_date|date("m") %}
{{ ('month.'month)|trans }}

In this scenario, all months starting with "0" will not be translated. I've read yaml documentation (not so deep, but I've searched on the internet) and I haven't find any page saying that a key couldn't start with zero (and it seems not to be possible for a key start with zero).
So, my questions are:

*

*Is that a yaml issue?

*If this isn't an issue, why keys could not start with "0"?

A: As @Maerlyn commeted, you should encapsulate your keys with quotes to avoid loosing preceding and following zeros.


text:
Q: Prevent JavaFx Scene from gaining focus - Onscreen Keyboard I'm trying to build an onscreen keyboard in javafx. The only issue I am having is that when you select the javafx scene or click a button on the window, the focus is then redirected to the javafx scene and the button click doesn't actually type a letter on a browser, text document, etc.
Here is my code for the button click. I'm using the robot class.
private void handleButtonAction(ActionEvent event) throws AWTException {

    Robot a = new Robot();
    a.keyPress(KeyEvent.VK_Y);//testing keypress of "Y".

}

I've seen in Swing how you can set a focus property to false, but I'm set on using JavaFx. I've seen quite a few people attempt this same question, but no one has a correct answer.

A: I am afraid there is currently no way to achieve this purely with JavaFx.
Here is an example how you could achieve it by wrapping your JavaFx-App in a Swing-App. An architectural monstrosity ;).
Alternatively, I could imagine that using a native layer like JNI/JNA is possible in this scenario.
However, in this case I would question if Java is technically the right tool for the job. One might argue, that an OSK is by definition tightly coupled to the OS and as such more native toolkits are in order. This of course depends on the scope of your project. As a side project this might be fine, but as a product not.


text:
Q: Add lines to the top of a memo in Delphi The function Memo.Lines.Add('Some text') in Delphi adds the string to the bottom of the memo. Is there any function which adds the text to the top?
For example, if the Lines property of the Memo contains:
string 1
string 2
string 3

I want to add a string string 0 before string 1. How can I do that?

A: The Lines property is a TStrings instance that supports inserting at a specified line number. The method to do so is Insert and is called like this:
Memo.Lines.Insert(0, 'string 0');