text:
Q: ctypes string buffer in scope thank you for your time reading this, this bugs me long time.I'm using Python3.8 and using ctypes to call a DLL. In most of cases ,ctypes works like charm.
One function from C DLL will output a list of names  i.e
int get_date(char* names[]) // each name has length 10, with size of 5

in Python I'm successfully call it like
    string_buffers = [ctypes.create_string_buffer(10) for i in range(5)]
    char_array = (ctypes.c_char_p*5)(*map(ctypes.addressof, string_buffers))
    handler.get_date(char_array)

But I am try to factor out a function to create such case :
def create_char_p_array(length:int, size:int):
    string_buffers = [create_string_buffer(length) for i in range(size)]
    ia = (c_char_p*size)(*map(addressof, string_buffers))
    return ia

char_array = create_char_p_array(10,5)
handler.get_date(char_array) ### failed, or ,crashed, or random value ###

So to narrow down the issue, I move out the map(addressof) out, it magically works! :
def create_char_p_array(length:int, size:int):
    string_buffers = [create_string_buffer(length) for i in range(size)]
    return string_buffers

sbrs = create_char_p_array(10,5)
char_array = (c_char_p*5)(*map(addressof, sbrs ))
handler.get_date(char_array) # Success !

Is it because create_string_buffer created in function scope will be wipe out once the function create_char_p_array return ?
Thank you for your time ,much appreciated.

A: Here's what I came up with.  addressof doesn't create a reference to the object it operates on.  cast will.
test.c:
#include <string.h>

__declspec(dllexport) int get_date(char* names[])
{
    strcpy_s(names[0],10,"One");
    strcpy_s(names[1],10,"Two");
    strcpy_s(names[2],10,"Three");
    strcpy_s(names[3],10,"Four");
    strcpy_s(names[4],10,"Five");
    return 5;
}

test.py:
from ctypes import *

dll = CDLL('./x')
dll.get_date.argtypes = POINTER(c_char_p),
dll.get_date.restype = c_int

def create_char_p_array(length:int, size:int):
    return (c_char_p*size)(*[cast(create_string_buffer(length),c_char_p) for _ in range(size)])

a = create_char_p_array(10,5)
dll.get_date(a)
for s in a:
    print(s)

Output:
b'One'
b'Two'
b'Three'
b'Four'
b'Five'


text:
Q: how to Filter one list based on another lists field I am fetching data from database from separater tables and storing in separate variables.
this is first list
   var res = (from v in context.MasterValues
                       join c in context.MasterCategories on v.Category_Id equals c.Id
                       where c.Model_Key == (int)model && c.Name == tableName && v.Version_Id == version && v.Active == "Y" && c.Name.Equals("FXRates")
                       select new
                       {
                           Id = v.Id,
                           VersionId = v.Version_Id,
                           Text1 = v.Text1,
                       }).ToList();

This is second list
        var fxview = context.MasterFXRates.Select
            (x => new
            {
                Currency_code = x.Currency_code,
                Rate = x.Rate,
                Effective_dt = x.Effective_dt
            }
            ).ToList();

So now How to filter Data from my second list fxview based on data from my first list ?
i.e.
i need to filter data where Currency_code's data of list2 matches with  Text1 of List1 where effective_dt(datetime column) is maximum/Latest date
For Example if second lists data has

*

*ABC , 100 , 2010-10-10

*ABC , 120 , 2014-12-12

*DEF ,700 , 2013-08-02

*DEF ,500 ,2015-06-06

And List 1(res) has following data

*

*1 , 1 , ABC

*2 , 1 , DEF

So after filtering my final list must have following output

*

*ABC ,120 (Since 2014-12-12 is latest date , the corresponding value is fetched and duplicate value (ABC,100) should be filtered.)

2.DEF ,500 (Since 2015-06-06 is latest date , the corresponding value is fetched and duplicate value (DEF,&00) should be filtered.)

A:   fxView = fxView.OrderByDescending(x => x.effectiveDate).ToList();
  var result = new List();
 res.ForEach((x) => result.Add(fxView.First(y => x.text1 == y.currency_code)));

If effectiveDate is already a DateTime this should work otherwise convert it to a DateTime
 var fxview = context.MasterFXRates.Select
        (x => new
        {
            Currency_code = x.Currency_code,
            Rate = x.Rate,
            Effective_dt = Convert.ToDateTime(x.Effective_dt)
        }
        ).ToList();

A:  var result = from masterFxRate in masterFxRates
                     join masterValue in masterValues on masterFxRate.Currency_code equals masterValue.Text1
                     group masterFxRate by
                     new
                     {
                         masterFxRate.Currency_code
                     } into groupedRates
                     select new
                     {
                         groupedRates.Key.Currency_code,
                         Rate = groupedRates.FirstOrDefault(g => g.Effective_dt != null
                                                              && g.Effective_dt == groupedRates.Max(c => c.Effective_dt)).Rate
                     };

        foreach (var item in result)
        {
            Console.WriteLine("{0} : {1} ", item.Currency_code, item.Rate);
        }

redpajama_set_name: RedPajamaStackExchange


text:
Q: AppSettings not getting resolved via constructor injection I have the configuration in appsettings.json as follows:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
  "Default": "Warning"
}
},
 "GatewaySettings": {
 "DBName": "StorageDb.sqlite",
 "DBSize": "100"
 }
}

Here is the class to represent the configuration data
 public class GatewaySettings
 {
    public string DBName { get; set; }
    public string DBSize { get; set; }
 }

Configured service as follows:
  services.AddSingleton(Configuration.GetSection("GatewaySettings").Get<GatewaySettings>());

but I'm getting this error:

Value cannot be null. Parameter name: implementationInstance'

Code:
  public class SqlRepository
  {
        private readonly GatewaySettings _myConfiguration;

        public SqlRepository(GatewaySettings settings)
        {
              _myConfiguration = settings;
        }
  }

Dependency injection code:
var settings = new IOTGatewaySettings();
builder.Register(c => new SqlRepository(settings))

Background
I am hosting ASPNET CORE application as windows service, and .NET Framework is 4.6.1
Note: similar question appears here but there is no solution provided.System.ArgumentNullException: Value cannot be null, Parameter name: implementationInstance

A: Don't add concrete data model classes into DI - use the IOptions<> framework.
In your startup:
services.AddOptions();

// parses the config section into your data model
services.Configure<GatewaySettings>(Configuration.GetSection("GatewaySettings"));

Now, in your class:
public class SqlRepository
{
    private readonly GatewaySettings _myConfiguration;
    public SqlRepository(IOptions<GatewaySettings> gatewayOptions)
    {
        _myConfiguration = gatewayOptions.Value;
        // optional null check here
    }
}

Note: if your project does not include the Microsoft.AspNetCore.All package, you will need to add another package Microsoft.Extensions.Options.ConfigurationExtensions to get this functionality.

A: You should use IOptions of T
services.Configure<GatewaySettings>(Configuration.GetSection("GatewaySettings"));

  public class SqlRepository
  {
    private readonly GatewaySettings _myConfiguration;
    public SqlRepository(IOptions<GatewaySettings> settingsAccessor)
    {
          _myConfiguration = settingsAccessor.Value;
    }
  }

you need these packages
<PackageReference Include="Microsoft.Extensions.Options" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.1.0" />

Reference Options pattern in ASP.NET Core


text:
Q: Cannot read property 'onPageChanged' of undefined sample extension background.js code
chrome.runtime.onInstalled.addListener(function() {
  chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
    chrome.declarativeContent.onPageChanged.addRules([{
      conditions: [
        // When a page contains a <video> tag...
        new chrome.declarativeContent.PageStateMatcher({
          pageUrl: { hostEquals: 'www.youtube.com'}
        })
      ],
      // ... show the page action.
      actions: [new chrome.declarativeContent.ShowPageAction() ]
    }]);
  });

});
and I got Cannot read property 'onPageChanged' of undefined in console. No problem running the code, why is that happening?

A: Check that you have added the declarativeContent permission to your manifest.json file.
This will give your extension access to the chrome.declarativeContent API and should resolve your problem.

A: If you just added delarativeContent permission to the manifest.json, remember to remove the extension and add it back again. Permissions might be added during installation only.


text:
Q: how to create table view who's 1st cell look like as selected? I have created one ipad app where 1st screen is split view. In that master view is table view and detail view holds image view controller. My problem is that when initially application gets loaded the 1st cell of table view should seen as selected and corresponding image view should appear at detail view.

A: It seems like you don't need only the cell to be seen as selected, but you need that cell to be selected (to make corresponding image appear)
You should see this post How do I select a UITableViewCell by default?
Here is sample code
-(void)viewDidLoad:(BOOL)animated {
    [uiTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:0];
}

or if you actually want to make the cell look like selected, you can do something like
-(void)viewDidLoad:(BOOL)animated {
    UITableViewCell *cell= [uiTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    [cell setHighlighted:TRUE animated:TRUE];
}


text:
Q: How to get the size of the decompressed file without extracting? Using the below command, I am writing a pyspark dataframe to S3. My next step is to create a trigger file containing the decompressed file's size. The problem is that the file size is too large (30GB), which after decompression is approximately 700GB. Can I calculate the size of a decompressed file without extracting it?
df.coalesce(1).write \
        .mode("overwrite") \
        .option("compression", "gzip") \
        .csv("s3a://dummy-bucket/data_20221003.tab.gz", sep="\t", header=False, emptyValue='')

output file
data_20221003.tab.gz           30GB

trigger_file.txt example
file_size=13124123


text:
Q: question about pexpect in python I tried both pexpect and subprocess.Popen from python to call an external long term background process (this process use socket to communicate with external applications), with following details.

*

*subprocess.Popen(launchcmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
This works fine. I do not need to do anything else. However, because I have to get the output immediately, I choose pexpect to avoid the pipe file buffer problem.

*obj= pexpect.spawn(launchcmd, timeout=None)
after launching external process, I use a separate thread to do "readline" to read the output of the launched process "obj", and everything is ok.

*obj= pexpect.spawn(launchcmd, timeout=None)
after launching external process, I did nothing further, i.e., just leave it there. Although, by using the "ps -e" command I can find the launched process, but the launched process seems blocked and cannot communicate in sockets with other applications.
OK. To be more specific, I put some sample code to formulate my question.
import subprocess
import pexpect
import os

t=1
while(True):
    if(t==1):
        background_process="./XXX.out"
        launchcmd = [background_process]
        #---option 3--------
        p=pexpect.spawn(launchcmd, timeout=None) # process launced, problem with socket.
        #---option 1--------
        p=subprocess.Popen(launchcmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # process launced, everything fine
        t=0

Could anyone tell me what's wrong with the 3rd option? And if it is due to the fact that I did not use a separate thread to manipulate the output, why 1st option works with subprocess.popen?  I suspect there is something wrong with pexpect to launch a process using socket, but I am not sure, especially considering option 2 works well.

A: I think that you are making this too complicated.
Yes, it is a good idea to use a pty instead of a pipe to communicate with the background process because most applications recognize tty/pty devices and switch to using unbuffered output, (or at least line-buffered).
But why pexpect? Just use Python's pty module. First call openpty to get some filehandles and then use Popen to spawn the process. Example code is found in the following question (the answer with the green checkmark)  Python Run a daemon sub-process & read stdout


text:
Q: ¿Cómo hago para que me imprima el total sumando todos los precios y no asi = $ 031983198? Estoy trabajando con una función en JavaScript lo que quiero hacer es ir sumando en total la variable precio. Mi problema es que me imprime todos los precios, no los va sumando y al final imprime uno solo. Si yo coloco el precio directo si me los suma, pero si uso:
precioo=document.getElementById('dobleentre').value;

me imprime todo.

 function difDias(fechaA, fechaB) {
return Math.round(Math.abs(fechaA.getTime() - fechaB.getTime())/(1000 * 60 * 60 * 24))
}
      function diferencia(){
var intermedios = "";
var dias_semana=[];
var dias="";
var precioo=0;
var total=0;
dias_semana[0]="Domingo";
dias_semana[1]="Lunes";
dias_semana[2]="Martes";
dias_semana[3]="Miercoles";
dias_semana[4]="Jueves";
dias_semana[5]="Viernes";
dias_semana[6]="Sábado";
var f1 = document.getElementById('inicial').value.split("/");
var d1 = new Date(f1[2],f1[1]-1,f1[0]);
var f2 = document.getElementById('final').value.split("/");
var d2 = new Date(f2[2],f2[1]-1,f2[0]);
var dias_entre =difDias(d1,d2)-1;

for (var i=1; i <= dias_entre; i++){
var nd =    new Date(f1[2],f1[1]-1,f1[0]);
nd.setDate(nd.getDate()+ i);
if (dias_semana[nd.getDay()]=="Domingo" || dias_semana[nd.getDay()]=="Lunes" || dias_semana[nd.getDay()]=="Martes" || dias_semana[nd.getDay()]=="Miercoles") {
  precioo=document.getElementById('dobleentre').value;
 }else{
  precioo=document.getElementById('doblef').value;
 }
total=total+precioo;
}
document.getElementById('llegadaa').innerHTML =total;
}
 <body onload="diferencia();">
 <input type="hidden" name="inicial" id="inicial"  value="'.$llegada.'" >
              <input type="hidden" name="final" id="final"  value="'.$salida.'" >

 <input type="hidden" name="dobleentre" id="dobleentre" value="'.$f['preciodobleentre'].'">
              <input type="hidden" name="doblef" id="doblef" value="'.$f['preciodoblef'].'">
              <span id="llegadaa">

A: El problema es que la función document.getelementbyid().value retorna por defecto una variable de tipo texto. Para convertirla en un entero debes agregar un signo más (+) al principio. En tu caso sería algo así:
precioo = +document.getElementById('doblef').value;

Otra alternativa utilizar el método parseInt:
precioo = parseInt(document.getElementById('doblef').value);

Cualquiera de las 2 debería funcionar.


text:
Q: Get text() from Widget in Layout I have created widgets from code for the first time instead of through the creator. It reads in a text file and fills a QScrollArea widget with the material name (checkbox to enable it or not) and the thickness lineEdit, as seen in the picture. The number of widgets made corresponds to the number of entries in the text file.
I create the pushbuttons and checkboxes using the following function:
void overlayers::newField(QString material, bool checked, double thickness)
{
    //Create new checkbox.
    QCheckBox * checkbox = new QCheckBox(material);
    checkbox->setChecked(checked);

    //Create new field.
    QLineEdit * line = new QLineEdit(QString::number(thickness));

    //Create horizontal layout.
    QHBoxLayout * layout = new QHBoxLayout();
    layout->addWidget(checkbox,Qt::AlignLeft);
    layout->addWidget(line,Qt::AlignRight);

    //Add horizontal layout to vertical.
    scrollLayout->addLayout(layout);
}

Where QVBoxLayout scrollLayout is defined in the class header.
I realised after doing the whole dialog box, I have to get the values from the fields and the checkbox flags to save the data but I have no idea how to iterate through all the checkboxes and lineEdits to get the text() and checkedState() variables!
I feel I have programmed this incorrectly and that there is a better way to do it. Is it possible to do this with how I have done it? If not, how would a better programmer do it re: creating the variable number of widgets and being able to access their data? A QVector sort of thing?
Thanks heaps!
http://i.stack.imgur.com/NKJVW.png


text:
Q: how to display json content in li format in phonegap i can get the json in the following format
[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
{"data":{"id":"3","user_name":"StudentB","book":"456","role":"Student"}}]

how can i use the data to present like the image below, where the first line is username and second line is book

<button type="button" id="test">Test 123</button>

var serviceURL = "http://mydomain.com/";
var students;

    $("#test").click(function()
    {
        getStudentList();
    });
function getStudentList() {
    $.getJSON(serviceURL + 'getStudents.php', function(data) {
        $('#studentList li').remove();
        students = data.user_name;
        $.each(students, function(index, student) {
            $('#studentList').append('
' +
                    '
' + student.user_name + ' ' + student.password + '
' +
                    '
' + student.user_name + '
' +
                    '
');
        });
        $('#studentList').listview('refresh');
    });
}

may i ask if the codes above correct?

A: you are naming response as data..since you response is in array [] you have to loop data first.. get its object which is data again  ..
[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
//-^^^^---here

and get the correponding name and password object in the loop...you can get that by . operator.. so inside loop, student.data.user_name gives you username , student.data.book gives you book and similar for others...
try this...
$.getJSON(serviceURL + 'getStudents.php', function(data) {
    $('#studentList li').remove();
  //students = data.user_name;
    $.each(data, function(index, student) {
        $('#studentList').append('
' +
                '
' + student.data.user_name +'
' +  //here get username
                '
' + student.data.book + '
' +   //here get book
                '
');
    });
    $('#studentList').listview('refresh');
});

A: I have done it like that based on your input, you just need to include it into your code. I don't know what you mean by 'second line is book' since there is no book included in your json input + you are trying to access 'student.data.password' which is also not present in input.
Simple  version of jsFiddle http://jsfiddle.net/2KMd9/
var json =[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
    {"data":{"id":"3","user_name":"StudentB","book":"456","role":"Student"}}];

    var students = json;
    $.each(students, function(index, student) {
        $('#studentList').append('
' +
                '
' + student.data.user_name + '
' +
                '
' + student.data.role + '
' +
                '
');
    });

So for your needs:
function getStudentList() {
    $.getJSON(serviceURL + 'getStudents.php', function(data) {
        $('#studentList li').remove();

        $.each(data, function(index, student) {
                $('#studentList').append('
' +
                '
' + student.data.user_name + '
' +
                '
' + student.data.role + '
' +
                '
');
        });
        $('#studentList').listview('refresh');
    });
}


text:
Q: How do I get the list of ids in a particular class using jquery? e.g.

I'd like to end up with array something like ["div_1","div_2"]

A: After selecting $(".myclass"), you can use the .map() method [docs] to take the .id of each element. This will return a jQuery array-like object containing the ids.
var ids = $(".myclass").map(function() { return this.id; });

Add .toArray() [docs] to the end if you need a real array.

A: var IDs = [];

$('.myclass').each(function(){
    IDs.push( this.id );
});

A: Besides .map you need .get() if you want an array in the end:
$('.myclass').map(function() { return this.id; }).get();


text:
Q: Module variable scoping in Scheduled Tasks? I ran across a scoping puzzle while experimenting with ScheduledTasks, and I'd be grateful for an explanation from the sages here.  I found a workaround by intuitive horse sense, but was unable to explain to myself adequately what was wrong with my original attempt.
First, a straightforward, tail-recursive, synchronous Module
Module[{state = 0, doNextIteration},
 doNextIteration = Function[
   state = state + 1;
   If[state < 4,
    (Print[state]; doNextIteration[])]];
 doNextIteration[]]
(* 1 2 3 *)

Next, my first attempt to do the same with asynchronous tasks, which I need to tail-chain as one-shot ScheduledTasks.  If CreateScheduledTask has a second List argument, then it creates a one-shot task delayed by the time in seconds in the list, just what I need for my bigger application.  In this simplified sample, the ScheduledTask tail-chains a new one-shot ScheduledTask by a tail-recursive call -- just like the successful synchronous code -- once every tenth of a second until the condition on state produces False (ignore cleanup of the task objects for simplicity, here).
Module[{state = 0, runNextTask},
 runNextTask = Function[
   StartScheduledTask@
    CreateScheduledTask[
     state = state + 1;
     If[state < 4,
      (Print[state]; runNextTask[])],
     {0.10}]];
 runNextTask[]]

OK, the problem is this only Prints once, not the desired three times.  I had a sickening hunch that the problem has something to do with runNextTask being local to the Module and somehow not being able to refer to itself recursively -- even though there is only one Module -- in the bizzaro-land of asynchrony, so I "fixed" the code as follows:
Module[{state = 0, runNextTask = Unique[]},
 runNextTask[] :=
  If[state < 3,
   StartScheduledTask@
    CreateScheduledTask[
     Module[{},
      state = state + 1;
      Print[state];
      runNextTask[]],
     {0.10}]];
 runNextTask[]]

I made runNextTask refer to a Unique global symbol, and made my function into a rewrite rule attached to runNextTask[].  This works great, but I don't understand well why it does.  I hate being as dumb as a horse, even if I can jump the fences.
Clues, advice, explanations: all appreciated.

A: You hit a rather subtle behavior, related to the garbage-collection and the Temporary attribute, and the semantics of Module regarding returning expressions. The thing is, to achieve your goal, you need the Module-generated variable (function)'s definition(s) to be exported outside Module (to be persistent). But, since you return not the symbol itself, but its r.h.s. (which is a chunk of code with delayed evaluation, either Function or ScheduledTaskObject in this case), the definitions of runNextTask are destroyed because it has a Temporary attribute, despite the fact that code containing this variable has been exported outside Module.
To illustrate my point, here are two work-arounds which both will lead to your desired effect:

*

*Instead of assigning runNextTask to Unique[], insert a line ClearAll[runNextTask] right after the Module declarations. This will remove the Temporary attribute and the definition of runNextTask will persist.

*Wrap your final call in Hold (so, return Hold[runNextTask[]]), and then use ReleaseHold outside Module.
This is your code for this option:
res =
 Module[{state = 0, runNextTask},
   runNextTask[] :=
     StartScheduledTask@
       CreateScheduledTask[
         state = state + 1;
         If[state < 4,
           (Print[state]; runNextTask[])
         ],
         {0.10}];
   Hold@runNextTask[]]

ReleaseHold[res]

In this case, the definition also persists.
Note that this problem is not seen in examples where all evaluation happens at the time when Module is left: the following code will execute promptly
Module[{f, n = 0},
  f[] := (n++; If[n < 10, Print["*"]; f[]]);
  f[]]

even though all definitions for f are destroyed at the end - because the execution here is immediate (the same evaluation process, so that f still has all definitions during this evaluation), while delayed and asynchronous code induces a separate evauation process.


text:
Q: Same pubkey allows access on one user, but not another So I have a centos 7 server with 2 users.
User1 has the ~/.ssh/authorized_keys file with proper permissions and with externaluser's public key in it.
User2 has the ~/.ssh/authorized_keys file with proper permissions and with the same externaluser's public key in it.
Externaluser can ssh to User1 with no problems, however, he gets Permission denied (publickey,gssapi-keyex,gssapi-with-mic) error when trying to ssh to User2.
Why does this happen? It's literally the same public key, properly pasted into the authorized_keys file of each user, using the same method.

A: Thank you RalfFriedl for your useful comment, the problem was the .ssh folder permissions.

Check the owner and permissions on .ssh and on authorized_keys.


text:
Q: Workaround for Chrome 53 printing table header twice on 2nd and later pages? Users of my website need to be able to print web pages consisting of content on the first printed page followed by a table on the second page.  A stripped down version is (jsFiddle at https://jsfiddle.net/jaydeedub/n3qhvtvx/25/ ):
HTML:

  <button class="button" onclick="window.print()">Print Me</button>

    This is the page 1 content. Blah, blah, blah.

        Page 2 table header prints twice

        Page 2 table body

        Page 2 table footer

CSS:
@media print {
  div.page1 {
    page-break-after: always;
  }
}

.table {
  border-collapse: collapse;
  margin: 16px;
}

.table>thead>tr>td,
.table>tbody>tr>td,
.table>tfoot>tr>td {
  border: 1px solid black;
}

.button {
  width: 6em;
  height: 2em;
  margin: 10px 0px;
}

This prints as expected in Chrome 52 on Chrome OS, but in Chrome 53 on Windows 7 Home and Chrome 53 on Chrome OS, the table header prints twice on the second page: once by itself without the top margin, and once with the top margin, followed by the rest of the table.  It used to print normally in Windows in an earlier version of Chrome, but I do not know if that was Chrome 52 (definitely within the last few versions).  It also prints as expected in Firefox.
I found one workaround, which is to put an empty 'thead' element before the real 'thead' element, but this solution is very kludgy and makes me uncomfortable.
Is there a more robust workaround that would be likely not to have side-effects across browsers?

A: My temporary solution:
thead {
    display: table-row-group;
}

A: I posted the same issue to the Chrome feedback channels.  My workaround for now was to simply remove my thead elements for a standard table row within the tbody.  It's certainly not as semantically pure, but you can pretty simply restyle them with a touch of css.
Table:

Scss:
tr.thead {
  td {
    font-weight:bold;
    border-bottom: solid 1px #333;
  }
}

A: I was getting the double header on the second page in chrome when printing
Adding the following CSS made it appear properly (once)
thead {
    display:table-header-group;
    break-inside: auto;
}

Source: https://stackoverflow.com/a/50987624/175071

A: This fix worked for me

thead {
  display: table-row-group;
}


text:
Q: Couldn't convert Object to Base64 I am unable to convert one object to base64. It throws an error

The first argument must be of type string or an instance of Buffer,
ArrayBuffer, or Array or an Array-like Object. Received an instance of
Client in js

   Client {
      _events: [Object: null prototype] {
    qr: [AsyncFunction (anonymous)],
    ready: [AsyncFunction (anonymous)],
    disconnected: [AsyncFunction (anonymous)],
    message_ack: [AsyncFunction (anonymous)],
    message: [AsyncFunction (anonymous)]
  }
}

A:
"The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.

You can stringify it before trying to set to b64.
const stringifiedObject = JSON.stringify(<your client object>)
Then pass convert it to b64


text:
Q: Can I disappoint people? It seems like the villagers like every house I design so far. Is that because they love me no matter what, or because I am actually skilled at putting houses together?
Is it possible to disappoint someone and design a house that they aren't happy with?

A: Pretty much no, there are bare minimum requirements for many homes (the stuff they have in cardboard boxes) and facilities (general requirements that Isabelle won't let you fail to satisfy). I made a couple joke homes that are impossible to navigate or contain a single item copied over and over and they treat it just as gleefully as any other home.
There ARE certain items that will make a heart appear over a villager's head or make them clap, but this is just an indication that you're matching the theme. They'll react in horror if you dispose of one of their "prised possessions" (even if you clone dozens of them and only toss one). But the actual reaction once you finish the home is always positive best I can tell after a couple dozen trials.


text:
Q: Nuvoton USB Isochronous communication I have Nuvoton M032SG8AE. It has USB peripheral so it supports USB communication. Nuvoton has sample project which is called HID_Transfer. However, it is quite confusing. I could not follow everything in the code. Nevertheless, I could communicate my microproccessor with my laptop using interrupt data transfer type.
I need to change the data transfer type from interrupt to isochronous for OUT operation.
I changed EP3's configuration from interrupt to isochronous.
    /*****************************************************/
    /* EP3 ==> Isochronous OUT endpoint, address 2 */
    USBD_CONFIG_EP(EP3, USBD_CFG_EPMODE_OUT | USBD_CFG_TYPE_ISO | 0x02);
    /* Buffer offset for EP3 */
    USBD_SET_EP_BUF_ADDR(EP3, EP3_BUF_BASE);
    /* trigger receive OUT data */
    USBD_SET_PAYLOAD_LEN(EP3, EP3_MAX_PKT_SIZE);

I also changed the device descriptor settings from interrupt to isochronous.
This is the full code:
/******************************************************************************
 * @file     hid_mouse.c
 * @version  V1.00
 * $Revision: 11 $
 * $Date: 18/07/18 4:54p $
 * @brief    M031 series USBD driver Sample file
 *
 * @note
 * SPDX-License-Identifier: Apache-2.0
 * Copyright (C) 2018 Nuvoton Technology Corp. All rights reserved.
 *****************************************************************************/
/*!<Includes */
#include <stdio.h>
#include <string.h>
#include "NuMicro.h"
#include "hid_transfer.h"

uint8_t volatile g_u8EP2Ready = 0;
uint8_t volatile g_u8Suspend = 0;
uint8_t g_u8Idle = 0, g_u8Protocol = 0;
void taken_data(uint8_t* pu8EpBuf, uint32_t u32Size);

void USBD_IRQHandler(void)
{
    uint32_t volatile u32IntSts = USBD_GET_INT_FLAG();
    uint32_t volatile u32State = USBD_GET_BUS_STATE();

    if (u32IntSts & USBD_INTSTS_FLDET)
    {
        /* Floating detect */
        USBD_CLR_INT_FLAG(USBD_INTSTS_FLDET);

        if (USBD_IS_ATTACHED())
        {
            /* USB Plug In */
            USBD_ENABLE_USB();
        }
        else
        {
            /* USB Un-plug */
            USBD_DISABLE_USB();
        }
    }

    if (u32IntSts & USBD_INTSTS_BUS)
    {
        /* Clear event flag */
        USBD_CLR_INT_FLAG(USBD_INTSTS_BUS);

        if (u32State & USBD_STATE_USBRST)
        {
            /* Bus reset */
            USBD_ENABLE_USB();
            USBD_SwReset();
            g_u8Suspend = 0;
        }
        if (u32State & USBD_STATE_SUSPEND)
        {
            /* Enter power down to wait USB attached */
            g_u8Suspend = 1;

            /* Enable USB but disable PHY */
            USBD_DISABLE_PHY();
        }
        if (u32State & USBD_STATE_RESUME)
        {
            /* Enable USB and enable PHY */
            USBD_ENABLE_USB();
            g_u8Suspend = 0;
        }
    }

    if(u32IntSts & USBD_INTSTS_SOF)
    {
        /* Clear SOF flag */
        USBD_CLR_INT_FLAG(USBD_INTSTS_SOF);
    }

    if(u32IntSts & USBD_INTSTS_WAKEUP)
    {
        /* Clear event flag */
        USBD_CLR_INT_FLAG(USBD_INTSTS_WAKEUP);
    }

    if (u32IntSts & USBD_INTSTS_USB)
    {
        /* USB event */
        if (u32IntSts & USBD_INTSTS_SETUP)
        {
            /* Setup packet */
            /* Clear event flag */
            USBD_CLR_INT_FLAG(USBD_INTSTS_SETUP);

            /* Clear the data IN/OUT ready flag of control end-points */
            USBD_STOP_TRANSACTION(EP0);
            USBD_STOP_TRANSACTION(EP1);

            USBD_ProcessSetupPacket();
        }

        /* EP events */
        if (u32IntSts & USBD_INTSTS_EP0)
        {
            /* Clear event flag */
            USBD_CLR_INT_FLAG(USBD_INTSTS_EP0);
            /* control IN */
            USBD_CtrlIn();
        }

        if (u32IntSts & USBD_INTSTS_EP1)
        {
            /* Clear event flag */
            USBD_CLR_INT_FLAG(USBD_INTSTS_EP1);
            /* control OUT */
            USBD_CtrlOut();
        }

        if (u32IntSts & USBD_INTSTS_EP2)
        {
            /* Clear event flag */
            USBD_CLR_INT_FLAG(USBD_INTSTS_EP2);
            /* Interrupt IN */
            EP2_Handler();
        }

        if (u32IntSts & USBD_INTSTS_EP3)
        {
            /* Clear event flag */
            USBD_CLR_INT_FLAG(USBD_INTSTS_EP3);
            /* Isochronous OUT */
            EP3_Handler();
        }

        if (u32IntSts & USBD_INTSTS_EP4)
        {
            /* Clear event flag */
            USBD_CLR_INT_FLAG(USBD_INTSTS_EP4);
        }

        if (u32IntSts & USBD_INTSTS_EP5)
        {
            /* Clear event flag */
            USBD_CLR_INT_FLAG(USBD_INTSTS_EP5);
        }

        if (u32IntSts & USBD_INTSTS_EP6)
        {
            /* Clear event flag */
            USBD_CLR_INT_FLAG(USBD_INTSTS_EP6);
        }

        if (u32IntSts & USBD_INTSTS_EP7)
        {
            /* Clear event flag */
            USBD_CLR_INT_FLAG(USBD_INTSTS_EP7);
        }
    }
}

void EP2_Handler(void)  /* Interrupt IN handler */
{
    //HID_SetInReport();
}

void EP3_Handler(void)  /* Interrupt OUT handler */
{
    uint8_t *ptr;
    /* Interrupt OUT */
    ptr = (uint8_t *)(USBD_BUF_BASE + USBD_GET_EP_BUF_ADDR(EP3));
    taken_data(ptr, USBD_GET_PAYLOAD_LEN(EP3));
    USBD_SET_PAYLOAD_LEN(EP3, EP3_MAX_PKT_SIZE);
}

/*--------------------------------------------------------------------------*/
/**
  * @brief  USBD Endpoint Config.
  * @param  None.
  * @retval None.
  */

void HID_Init(void)
{
    /* Init setup packet buffer */
    /* Buffer range for setup packet -> [0 ~ 0x7] */
    USBD->STBUFSEG = SETUP_BUF_BASE;

    /*****************************************************/
    /* EP0 ==> control IN endpoint, address 0 */
    USBD_CONFIG_EP(EP0, USBD_CFG_CSTALL | USBD_CFG_EPMODE_IN | 0);
    /* Buffer range for EP0 */
    USBD_SET_EP_BUF_ADDR(EP0, EP0_BUF_BASE);

    /* EP1 ==> control OUT endpoint, address 0 */
    USBD_CONFIG_EP(EP1, USBD_CFG_CSTALL | USBD_CFG_EPMODE_OUT | 0);
    /* Buffer range for EP1 */
    USBD_SET_EP_BUF_ADDR(EP1, EP1_BUF_BASE);

    /*****************************************************/
    /* EP2 ==> Interrupt IN endpoint, address 1 */
    USBD_CONFIG_EP(EP2, USBD_CFG_EPMODE_IN | INT_IN_EP_NUM);
    //USBD_CONFIG_EP(EP2, USBD_CFG_TYPE_ISO | USBD_CFG_EPMODE_OUT | 0);
     /* Buffer range for EP2 */
    USBD_SET_EP_BUF_ADDR(EP2, EP2_BUF_BASE);

    /*****************************************************/
    /* EP3 ==> Isochronous OUT endpoint, address 2 */
    USBD_CONFIG_EP(EP3, USBD_CFG_EPMODE_OUT | USBD_CFG_TYPE_ISO | 0x02);
    /* Buffer offset for EP3 */
    USBD_SET_EP_BUF_ADDR(EP3, EP3_BUF_BASE);
    /* trigger receive OUT data */
    USBD_SET_PAYLOAD_LEN(EP3, EP3_MAX_PKT_SIZE);
}

void HID_ClassRequest(void)
{
    uint8_t buf[8];
     int i;
    USBD_GetSetupPacket(buf);

    if(buf[0] & 0x80)    /* request data transfer direction */
    {
        /* Device to host */
        switch(buf[1])
        {
            case GET_IDLE:
            {
                USBD_SET_PAYLOAD_LEN(EP1, buf[6]);
                /* Data stage */
                USBD_PrepareCtrlIn(&g_u8Idle, buf[6]);
                /* Status stage */
                USBD_PrepareCtrlOut(0, 0);
                break;
            }
            case GET_PROTOCOL:
            {
                USBD_SET_PAYLOAD_LEN(EP1, buf[6]);
                /* Data stage */
                USBD_PrepareCtrlIn(&g_u8Protocol, buf[6]);
                /* Status stage */
                USBD_PrepareCtrlOut(0, 0);
                break;
            }
            case GET_REPORT:
//             {
//                 break;
//             }
            default:
            {
                /* Setup error, stall the device */
                USBD_SetStall(EP0);
                USBD_SetStall(EP1);
                break;
            }
        }
    }
    else
    {
        /* Host to device */
        switch(buf[1])
        {
            case SET_REPORT:
            {
                if(buf[3] == 3)
                {
                    /* Request Type = Feature */
                    USBD_SET_DATA1(EP1);
                    USBD_SET_PAYLOAD_LEN(EP1, 0);
                }
                break;
            }
            case SET_IDLE:
            {
                g_u8Idle = buf[3];
                /* Status stage */
                USBD_SET_DATA1(EP0);
                USBD_SET_PAYLOAD_LEN(EP0, 0);
                break;
            }
            case SET_PROTOCOL:
            {
                g_u8Protocol = buf[2];
                /* Status stage */
                USBD_SET_DATA1(EP0);
                USBD_SET_PAYLOAD_LEN(EP0, 0);
                break;
            }
            default:
            {
                /* Stall */
                /* Setup error, stall the device */
                USBD_SetStall(EP0);
                USBD_SetStall(EP1);
                break;
            }
        }
    }
}

/***************************************************************/
#define HID_CMD_SIGNATURE   0x43444948

/* HID Transfer Commands */
#define HID_CMD_NONE     0x00
#define HID_CMD_ERASE    0x71
#define HID_CMD_READ     0xD2
#define HID_CMD_WRITE    0xC3
#define HID_CMD_TEST     0xB4

#define PAGE_SIZE        2048
#define TEST_PAGES       4
#define SECTOR_SIZE      4096
#define START_SECTOR     0x10

#ifdef __ICCARM__
typedef __packed struct
{
    uint8_t u8Cmd;
    uint8_t u8Size;
    uint32_t u32Arg1;
    uint32_t u32Arg2;
    uint32_t u32Signature;
    uint32_t u32Checksum;
} CMD_T;

#else
typedef struct __attribute__((__packed__))
{
    uint8_t u8Cmd;
    uint8_t u8Size;
    uint32_t u32Arg1;
    uint32_t u32Arg2;
    uint32_t u32Signature;
    uint32_t u32Checksum;
}
CMD_T;
#endif

CMD_T gCmd;

static uint8_t  g_u8PageBuff[PAGE_SIZE] = {0};    /* Page buffer to upload/download through HID report */
static uint32_t g_u32BytesInPageBuf = 0;          /* The bytes of data in g_u8PageBuff */
static uint8_t  g_u8TestPages[TEST_PAGES * PAGE_SIZE] = {0};    /* Test pages to upload/download through HID report */

int32_t HID_CmdEraseSectors(CMD_T *pCmd)
{
    uint32_t u32StartSector;
    uint32_t u32Sectors;

    u32StartSector = pCmd->u32Arg1 - START_SECTOR;
    u32Sectors = pCmd->u32Arg2;

    printf("Erase command - Sector: %d   Sector Cnt: %d\n", u32StartSector, u32Sectors);

    /* TODO: To erase the sector of storage */
    memset(g_u8TestPages + u32StartSector * SECTOR_SIZE, 0xFF, sizeof(uint8_t) * u32Sectors * SECTOR_SIZE);

    /* To note the command has been done */
    pCmd->u8Cmd = HID_CMD_NONE;

    return 0;
}

int32_t HID_CmdReadPages(CMD_T *pCmd)
{
    uint32_t u32StartPage;
    uint32_t u32Pages;

    u32StartPage = pCmd->u32Arg1;
    u32Pages     = pCmd->u32Arg2;

    printf("Read command - Start page: %d    Pages Numbers: %d\n", u32StartPage, u32Pages);

    if(u32Pages)
    {
        /* Update data to page buffer to upload */
        /* TODO: We need to update the page data if got a page read command. (0xFF is used in this sample code) */
        memcpy(g_u8PageBuff, g_u8TestPages, sizeof(g_u8PageBuff));
        g_u32BytesInPageBuf = PAGE_SIZE;

        /* The signature word is used as page counter */
        pCmd->u32Signature = 1;

        /* Trigger HID IN */
        USBD_MemCopy((uint8_t *)(USBD_BUF_BASE + USBD_GET_EP_BUF_ADDR(EP2)), (void *)g_u8PageBuff, EP2_MAX_PKT_SIZE);
        USBD_SET_PAYLOAD_LEN(EP2, EP2_MAX_PKT_SIZE);
        g_u32BytesInPageBuf -= EP2_MAX_PKT_SIZE;
    }

    return 0;
}

int32_t HID_CmdWritePages(CMD_T *pCmd)
{
    uint32_t u32StartPage;
    uint32_t u32Pages;

    u32StartPage = pCmd->u32Arg1;
    u32Pages     = pCmd->u32Arg2;

    printf("Write command - Start page: %d    Pages Numbers: %d\n", u32StartPage, u32Pages);
    g_u32BytesInPageBuf = 0;

    /* The signature is used to page counter */
    pCmd->u32Signature = 0;

    return 0;
}

int32_t gi32CmdTestCnt = 0;
int32_t HID_CmdTest(CMD_T *pCmd)
{
    int32_t i;
    uint8_t *pu8;

    pu8 = (uint8_t *)pCmd;
    printf("Get test command #%d (%d bytes)\n", gi32CmdTestCnt++, pCmd->u8Size);
    for(i=0; i<pCmd->u8Size; i++)
    {
        if((i&0xF) == 0)
        {
            printf("\n");
        }
        printf(" %02x", pu8[i]);
    }

    printf("\n");

    /* To note the command has been done */
    pCmd->u8Cmd = HID_CMD_NONE;

    return 0;
}

uint32_t CalCheckSum(uint8_t *buf, uint32_t size)
{
    uint32_t sum;
    int32_t i;

    i = 0;
    sum = 0;
    while(size--)
    {
        sum+=buf[i++];
    }

    return sum;

}

int32_t ProcessCommand(uint8_t *pu8Buffer, uint32_t u32BufferLen)
{
    uint32_t u32sum;

    USBD_MemCopy((uint8_t *)&gCmd, pu8Buffer, u32BufferLen);

    /* Check size */
    if((gCmd.u8Size > sizeof(gCmd)) || (gCmd.u8Size > u32BufferLen))
        return -1;

    /* Check signature */
    if(gCmd.u32Signature != HID_CMD_SIGNATURE)
        return -1;

    /* Calculate checksum & check it*/
    u32sum = CalCheckSum((uint8_t *)&gCmd, gCmd.u8Size);
    if(u32sum != gCmd.u32Checksum)
        return -1;

    switch(gCmd.u8Cmd)
    {
        case HID_CMD_ERASE:
        {
            HID_CmdEraseSectors(&gCmd);
            break;
        }
        case HID_CMD_READ:
        {
            HID_CmdReadPages(&gCmd);
            break;
        }
        case HID_CMD_WRITE:
        {
            HID_CmdWritePages(&gCmd);
            break;
        }
        case HID_CMD_TEST:
        {
            HID_CmdTest(&gCmd);
            break;
        }
        default:
            return -1;
    }

    return 0;
}

void HID_GetOutReport(uint8_t *pu8EpBuf, uint32_t u32Size)
{
    uint8_t  u8Cmd;
    uint32_t u32StartPage;
    uint32_t u32Pages;
    uint32_t u32PageCnt;

    /* Get command information */
    u8Cmd        = gCmd.u8Cmd;
    u32StartPage = gCmd.u32Arg1;
    u32Pages     = gCmd.u32Arg2;
    u32PageCnt   = gCmd.u32Signature; /* The signature word is used to count pages */

    /* Check if it is in the data phase of write command */
    if((u8Cmd == HID_CMD_WRITE) &&  (u32PageCnt < u32Pages))
    {
        /* Process the data phase of write command */

        /* Get data from HID OUT */
        USBD_MemCopy(&g_u8PageBuff[g_u32BytesInPageBuf], pu8EpBuf, EP3_MAX_PKT_SIZE);
        g_u32BytesInPageBuf += EP3_MAX_PKT_SIZE;

        /* The HOST must make sure the data is PAGE_SIZE alignment */
        if(g_u32BytesInPageBuf >= PAGE_SIZE)
        {
            printf("Writing page %d\n", u32StartPage + u32PageCnt);
            /* TODO: We should program received data to storage here */
            memcpy(g_u8TestPages + u32PageCnt * PAGE_SIZE, g_u8PageBuff, sizeof(g_u8PageBuff));
            u32PageCnt++;

            /* Write command complete! */
            if(u32PageCnt >= u32Pages)
            {
                u8Cmd = HID_CMD_NONE;

                printf("Write command complete.\n");
            }

            g_u32BytesInPageBuf = 0;

        }

        /* Update command status */
        gCmd.u8Cmd        = u8Cmd;
        gCmd.u32Signature = u32PageCnt;
    }
    else
    {
        /* Check and process the command packet */
        if(ProcessCommand(pu8EpBuf, u32Size))
        {
            printf("Unknown HID command!\n");
        }
    }
}

void HID_SetInReport(void)
{
    uint32_t u32StartPage;
    uint32_t u32TotalPages;
    uint32_t u32PageCnt;
    uint8_t *ptr;
    uint8_t u8Cmd;

    u8Cmd        = gCmd.u8Cmd;
    u32StartPage = gCmd.u32Arg1;
    u32TotalPages= gCmd.u32Arg2;
    u32PageCnt   = gCmd.u32Signature;

    /* Check if it is in data phase of read command */
    if(u8Cmd == HID_CMD_READ)
    {
        /* Process the data phase of read command */
        if((u32PageCnt >= u32TotalPages) && (g_u32BytesInPageBuf == 0))
        {
            /* The data transfer is complete. */
            u8Cmd = HID_CMD_NONE;
            printf("Read command complete!\n");
        }
        else
        {
            if(g_u32BytesInPageBuf == 0)
            {
                /* The previous page has sent out. Read new page to page buffer */
                /* TODO: We should update new page data here. (0xFF is used in this sample code) */
                printf("Reading page %d\n", u32StartPage + u32PageCnt);
                memcpy(g_u8PageBuff, g_u8TestPages + u32PageCnt * PAGE_SIZE, sizeof(g_u8PageBuff));

                g_u32BytesInPageBuf = PAGE_SIZE;

                /* Update the page counter */
                u32PageCnt++;
            }

            /* Prepare the data for next HID IN transfer */
            ptr = (uint8_t *)(USBD_BUF_BASE + USBD_GET_EP_BUF_ADDR(EP2));
            USBD_MemCopy(ptr, (void *)&g_u8PageBuff[PAGE_SIZE - g_u32BytesInPageBuf], EP2_MAX_PKT_SIZE);
            USBD_SET_PAYLOAD_LEN(EP2, EP2_MAX_PKT_SIZE);
            g_u32BytesInPageBuf -= EP2_MAX_PKT_SIZE;
        }
    }

    gCmd.u8Cmd        = u8Cmd;
    gCmd.u32Signature = u32PageCnt;

}

void send_data(void)
{
    uint8_t testData[64];
    uint8_t i;

    testData[0] = 1;

    for(i= 1; i < 64; i++)
    {
        testData[i] = i;
    }

    USBD_MemCopy((uint8_t*)(USBD_BUF_BASE + USBD_GET_EP_BUF_ADDR(EP3)),(void*)testData,64);
    USBD_SET_PAYLOAD_LEN(EP3,64);
}

void taken_data(uint8_t* pu8EpBuf, uint32_t u32Size)
{
    send_data();
}

I downloaded USB Trace application to see the data that I am sending from MCU to my laptop. There is nothing wrong when I am doing it with interrupt type data transfer. However, when I changed the setting from interrupt to isochronous I can't even see the USB port that is connected to the microprocessor's USB peripheral in USB Trace.
How can I solve this problem ?

A: I figured out that HID can't be used for isochronous data transfer type.That's why my program does not work.


text:
Q: Subprocess not returning meaningful error messages What specific syntax must be changed in the Python code below in order for the python function to return the same correct error
message that the CLI command below is returning?
THE CORRECT ERROR MESSAGE:
The following CLI command returns a useful error message correctly as intended:
$ az repos import create --git-source-url https://github.com/SomeAccount/some-repo.git --repository SomeTargetRepo --git-service-endpoint-id  long-alpha-numeric-guid --organization https://dev.azure.com/SomeOrgName --project SomeProjectName --requires-authorization
Can only import into an empty repository.

WRONG USELESS ERROR RESPONSE:
But when the same CLI command gets run by the Python 3 function at bottom below, it
returns the following useless response which does not allow us to debug the cause of the error:
data string is:
err is: None
process.returncode is: 1
Error: None
Error: Return Code is: 1

CODE THAT RETURNS USELESS ERROR RESPONSE:
The following Python 3 function is what is causing the useless error response to be returned:
def getShellJsonResponse(cmd,counter=0):
  process = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, text=True)
  data = process.stdout
  err = process.stderr
  logString = "data string is: " + data
  print(logString)
  logString = "err is: " + str(err)
  print(logString)
  logString = "process.returncode is: " + str(process.returncode)
  print(logString)
  if process.returncode == 0:
    logString = str(data)
    print(logString)
    decodedData = data #.decode('utf-8')
    return decodedData
  else:
    logString = "Error: " + str(err)
    print(logString)
    logString = "Error: Return Code is: " + str(process.returncode)
    print(logString)
    sys.exit(1)

What specific syntax must be changed in the Python code above in order to return the meaningful error message which can be used to resolve the root cause of the error?

A: If you try something like this:
# powershell command
getShellJsonResponse(['powershell', '-Command', 'Write-Host', '"Hello world"'])
# cmd command
getShellJsonResponse('echo "Hello world"')

You'll see that your routine is showing the standard out just fine. So, the problem must be with the command you are passing, or how you're passing it.
Since your code doesn't show how you're calling it, it's hard to say, but I did notice that I couldn't just run az directly. Something like this does produce the expected output though:
getShellJsonResponse([r'C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd', 'account', 'list'])

Or, if you prefer passing a string:
getShellJsonResponse(r'"C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd" account list')

Note: do future you and everyone that has to work with you and your code a favour and start using a default indentation of 4 instead of 2 - this is Python, after all. If that means your code starts running off screen on the right, the problem is generally the structure of your code, not the indentation.


text:
Q: Django Access Data in "through" table given both entities I have browsed through lots of "through table access" in SO so if I missed something, feel free to close this.
I have a table A, a table B, in an n-n relationship and a through table C. C contains the "in_stock"property. Obviously, a pairing of object A1 and B1 will always be unique. So if I am given A1, and B1, how do I access in a template, the "in_stock" property in the "through table" C?
Additional INfo:
I am looping over the Bs A1 has in the template, so in an iteration I can have A1-B1, on another A1-B2, etc.

A: I use a custom tag to do so :
(assuming you have A1 in the template)
{% load custom_tag %}

{% for b in Bs %}
    {% autoescape off %}

in_stock for {{ A1 }} and {{ b }} : {{ A1|through:b }}

    {% endautoescape %}

{% endfor %}

custom_tag.py
register = template.Library()

def through(A1, b):
    t = "%s" % (C.objects.get(b=b, a=A1).in_stock)
    return t

register.filter(through)


text:
Q: product of vectors is zero then products of basis is. Let $V$ be a vector space over a finite field $F_q$ and let $\{v_1, v_2, . . . , v_k\}$ be
a basis of $V$. Show that the following two statements are equivalent:
(i) $v\cdot v^\prime = 0$ for all $v, v^\prime\in V$,
(ii) $v_i\cdot v_j = 0$ for all $i, j \in \{1, 2, . . . , k\}$.
(Note: this shows that it suffices to check (ii) when we need to determine
whether a given linear code is self-orthogonal.)
(u.v is inner product)
(i)$\Rightarrow$(ii) is obvious as product of basis are $0$ then product of vector is.
{{
Let $v = (v_1, v_2, . . . , v_n),w = (w_1,w_2, . . . , w_n) \in F_q^n$.
The scalar product (also known as the dot product or the Euclidean inner
product) of $v$ and $w$ is defined as
$$v \cdot w = v_1w_1 + ·· ·+v_nw_n \in F_q .$$
The two vectors $v$ and $w$ are said to be orthogonal if $v \cdot w = 0.$}}
but the other side is confusing.
Thanks for help

A: Every vector's a linear combination of basis vectors, and the standard properties of the dot product (ditributivity and the like) show that if the basis vectors are orthogonal (including each being orthogonal to itself) then all pairs of vectors are orthogonal.
Just to give a small example, if $v\cdot v=v\cdot w=w\cdot w=0$, then $$(av+bw)\cdot(cv+dw)=(ac)v\cdot v+(ad)v\cdot w+(bc)w\cdot v+(bd)w\cdot w=0+0+0+0=0$$


text:
Q: Can I use Visual Studio 2010 Architectural features to enforce design on code, without feature packs? I am studying Visual Studio 2010's architectural tools for application lifecycle management.
After we have sketched some modeling diagrams, we wonder now how should be the natural workflow to convert that to architecture-compliant code.
We noticed that UML Explorer tab keeps track of entities created in class diagrams, sequence diagrams and component diagrams, but not so with layer diagrams and activity diagrams.
The main problem is: when the modeling is ready, how would be the expected way to convert it to a compliant code? Possible paths could be:

*

*"you have to manually keep track of everything";

*"you can use feature X and/or technique Y";

*"There's no way to do that without the Modeling Feature Pack";

As far as I have researched until now, everything suggests that the Feature Pack is needed, but I wonder what would be the point to have those standard modeling projects if the greatest advantages of modeling (tracking and validating development code) cannot be performed...
UPDATE: This blog post shows how to use Layers Diagram of a modeling project (via Validation flag on modeling project's properties tab) to RAISE BUILD ERRORS in case a layer dependency (which can be manually created) is violated. That seems promising, and I wonder which more of these hidden features the "non-feature-packed" Visual Studio 2010 might have.
Thanks for any help

A: As you have discovered, the layer validation, for C# at least, was present out of the box with Visual Studio Premium and Ultimate.
You also get the ability to generate Dependency Graphs, and Sequence Diagrams from your code, as well as the old-school class diagram view that has been around since VS2005 (possibly 2008, I'm not sure). I don't believe there is any code generation from models, though.
Whilst you can draw UML static structure diagrams, you can't generate them from code without the feature pack.
With the feature pack you can do Code-to-UML, and UML-to-Code (for C#, at least). The feature pack also extends the visualisation features that were out-of-the-box for C# so that they can handle C/C++, and also extends the layer diagram features to C++.
In answer to your question about what the point would be:
Microsoft often ship to fairly hard (as in, must not be missed) deadlines, and so sometimes features don't make the cut for quality reasons. These are often shipped as feature packs, service packs, etc. I believe they always intended the functionality to work the way it does with the feature pack, it just wasn't ready for the target ship-date.
The links to the documentation for the out-of the box features is:
http://msdn.microsoft.com/en-us/library/57b85fsc(v=vs.100).aspx
I presume you have the link to the feature pack docs, but for future readers:
http://msdn.microsoft.com/en-us/library/dd460723(v=vs.100).aspx


text:
Q: Oracle: Error ORA-00932: inconsistent Datatypes number assumed, but got ARRAY We are trying to select an array/varray type with embedded SQL.
Type/Table:
create type int55 is array(4) of integer;
create table rtable (a int, b int55);

Code for SQL Precompiler in C++ with Oracle 11g Client:
BOOL static_TestIt(void) {
  EXEC SQL BEGIN DECLARE SECTION;
    int a;
    long b[4];
    short i[4];
  EXEC SQL END DECLARE SECTION;

  EXEC SQL DECLARE cdtest_cursor CURSOR FOR select a,b from rtable;
  EXEC SQL open cdtest_cursor;
  EXEC SQL FETCH cdtest_cursor INTO  :a, :b:i;
  EXEC SQL close cdtest_cursor;

  return TRUE;
}

The precompiler shows warning:
PCC-W-02344 invalid size of host array
During runtime i get error: ORA-00932
Does anybody know a solution to this problem?

A: You need to do a few more steps, based on the documentation on collection handling in Pro*C.
First, create a file called int55_in.typ containing the name of your collection type:
case=lower
type int55

Then run the object type translator tool:
$ORACLE_HOME/bin/ott intype=int55_in.typ outtype=int55_out.typ hfile=int55.h user=usr/pwd code=c

which will generate two files. In your .pc file add:
#include "int55.h"

and your code needs to use that declared collection type:
  EXEC SQL BEGIN DECLARE SECTION;
    int a;
    int55 *b;   /* collection type */
    int c;      /* single instance from collection */
    OCIInd i;   /* indicator */
  EXEC SQL END DECLARE SECTION;

  EXEC SQL ALLOCATE :b;

  EXEC SQL DECLARE cdtest_cursor CURSOR FOR select a, b from rtable;
  EXEC SQL open cdtest_cursor;
  EXEC SQL FETCH cdtest_cursor INTO :a, :b:i;

Then you can use COLLECTION GET to get the individual elements; as it's a varray you can loop over the four entries, e.g. as a simple demo:
  int j;
  for (j = 0; j < 4; j++)
  {
    EXEC SQL COLLECTION GET :b INTO :c;
    printf("%d %d %d\n", j, a, c);
  }

  EXEC SQL close cdtest_cursor;

When you compile you need tomake sure the location for oci.h (included from the generated int55.h) if it isn't already referred to; and you need to specify the generated type file:
$ORACLE_HOME/bin/proc include=$ORACLE_HOME/rdbms/public intyp=int55_out.typ ...

With a single row in your table:
insert into rtable values (1, int55(2, 3, 4, 5));

running that then gets:
0 1 2
1 1 3
2 1 4
3 1 5

Obviously you should pick your own file names, I've just used your type name as an example to hopefully make it clearer. And if you have to handle mutlipel types they can all go in a single _in.typ to generate a single _out.typand.h` file.


text:
Q: Wiring CDI beans and business logic I am building a JSF (2.2.13) application wired with CDI 2.0 (Weld 3.0.4).
The app contains some real beans (frontend) and some business logic (backend).
Now the question is up to what part of the application CDI should be used?

*

*Obviously the frontend beans shall be managed by CDI

*My first guess was to inject the backend services (somehow wrapping them in an @ApplicationScoped scope) to those CDI-managed frontend beans

*The backend then would be good old plain Java

I am a little bothered to use CDI in some parts of the application in in some not...


text:
Q: Book (maybe series) about someone going to a magic academy, who has no magic of his own, but can act as a conduit/amplifier for the magic of others The main character is seemingly a magical dude. He, I think the character was a he, and has no magic of his own at an academy of magic. Turns out he's a conduit. If he touches another magic user he can use and amplify their power and even combine multiple people's magic into one if they are all touching. I'm pretty sure this was a series.
I read this somewhere between 2000 and 2010, but probably closer to 2000, I believe. It is a kids book. For some reason I want to say the kid was albino and/or had glasses... but there's no real remembrance. I don't remember if they used witch, wizard, sorcerer, or some other word for a magic user.

A: Wizard's Hall, by Jane Yolen
Wizard's Hall is about Henry (aka Thornmallow), a young boy who goes to the Wizarding school to become a wizard.  He turns out to be unable to do magic on his own, but his ability to enhance the magic of others and his willingness to really try ends up saving the day when the dark wizard Nettle attacks the school.
Thornmallow is depicted with white hair on the cover, probably why you remember him as albino.

"Thornpower asks if he has a talent for magic." She smiled slowly and shook her head. "He does not. At least, he does not have a talent for enchantment. His talent is far greater. He has a talent for enhancement. He can make any spell someone else works even greater simply by trying."


text:
Q: Soap update error Sharepointapi.php Using sharepointapi.php in order to update some value into a sharepoint list. I get the next request XML, generated by sharepointapi.php:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://schemas.microsoft.com/sharepoint/soap/">
  <SOAP-ENV:Body>
    <UpdateListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
    <listName>CONTRACTS</listName>
    <updates>
      <Batch ListVersion="1" OnError="Continue">
      <Method Cmd="Update" ID="1">
        <Field Name="state">Awaiting F</Field>
                 <Field Name="ID">10</Field>
               </Method>
      </Batch>
      </updates>
    </UpdateListItems>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

And I got this from the server:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body><soap:Fault>
    <faultcode>soap:Server</faultcode>
    <faultstring>Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown.</faultstring>
    <detail>
      <errorstring xmlns="http://schemas.microsoft.com/sharepoint/soap/">Cannot access a closed Stream.
      </errorstring>
    </detail>
    </soap:Fault>
  </soap:Body>
</soap:Envelope>

Note. I am actually able to get all the rows from the list.
Is my query bad formatted?
Thankyou.

A: Looks like your trying to update the ID of a listitem. The ID is generated by SharePoint and cannot be changed.


text:
Q: remove method of doublylinkedlist throwing exception java so i have a doublylinkedlist in java and i'm testing it but when i decided to remove two elements at the same index it throwed a null pointer exception
this is my list [ A, B, C, D, E]
and this is my test
System.out.println("Item removed at index 3: " + list.removeAtIndex(3));
System.out.println(list);
//throws exception at following line
System.out.println("Item removed at index 3: " + list.removeAtIndex(3));
System.out.println(list);

list should be [ A, B, C]
but it throws an exception
here is my implementation of the removeAtIndex method
public E removeAtIndex(int index) {
    DoublyLinkedNode<E> node = firstNode;
    for(int i = 0; i < index; i++)
    {
        node = node.getNext();
    }
    E item = node.getItem();
    node.getPrevious().setNext(node.getNext());
    node.getNext().setPrevious(node.getPrevious());
    return item;
 }

how can i work this out?
Edit: i forgot to say, that when i delete at one index and then again but at a different index it works just fine

A: I suspect one issue:
You are not using sentinel (dummy) header and tail nodes. So when you remove from the end and call
node.getNext().setPrevious(node.getPrevious());
node.getNext();//actually returns null at the end of a list

You will need to check for null after you call the getNext and getPrevious methods


text:
Q: Discord.py (table user has 1 columns but 6 values were supplied) Вылазит ошибка во время запуска кода. Пытался поставить (?,?,?,?,?,?), ({member.id}', '{member}', 0, 0, 1, 0) - Не помогло. Убирал ссылку на файл подключения - Не помогло.
Перепробывал уже много способ, всё напрасно, может кто нибудь сталкивался, и сможет помочь?
connect=sqlite3.connect('discord.db')
cursor=connect.cursor()

@bot.event
async def on_ready():
    cursor.execute("""CREATE TABLE IF NOT EXISTS user (
        "id" INT,
        "name" TEXT,
        "cash" BIGINT,
        "lvl" INT,
        "rank" INT,
        "runes" INT
    )""")
    connect.commit()
    print('Bot Ready')

    for guild in bot.guilds:
        for member in guild.members:
            if cursor.execute(f"SELECT id FROM user WHERE id={member.id}").fetchone() == None:
                cursor.execute(f"INSERT INTO user VALUES('{member.id}', '{member}', 0, 0, 1, 0)")
                connect.commit()
            else:
                pass
            connect.commit()

Сама ошибка:
Traceback (most recent call last):
  File "D:\APython\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "D:\APython\Code\DforriaMG\main.py", line 28, in on_ready
    cursor.execute(f"INSERT INTO user VALUES('{member.id}', '{member}', 0, 0, 1, 0)")
sqlite3.OperationalError: table user has 1 columns but 6 values were supplied

A: В строке:
cursor.execute(f"INSERT INTO user VALUES('{member.id}', '{member}', 0, 0, 1, 0)")

 Колонка id у вас типа int, значит вводить нужно int, а вы ставите скобки, тем самым вставляете значение как строку.

cursor.execute(f"INSERT INTO user VALUES({member.id}, '{member}', 0, 0, 1, 0)")


text:
Q: How to enable a submit button on a registration form if all the fields are filled out and are valid i'm new in jquery and i'm having trouble with the submit button on the form i'm trying to create. When the button gets disabled and i want to enabled it again if all the validations return true, it stays disabled. Can somebody please help me figure this out. This is part of my jQuery code:
      //some code...

    $('form>input').blur(function () {
       if (firstName == false || lastName==false || email==false || password1==false || password2==false)
           $('#submitButton').prop('disabled',true);
       if (firstName == true && lastName == true && email == true && password1 == true && password2 == true) //{ //$('#submitButton').prop('disabled',false);
               $('#submitButton').removeAttr('disabled');
       });

  });

this is part of my HTML code:

    <form>
        first name:<input type="text" class="firstName" name="firstName" />
        last name:<input type="text" class="lastName" name="lastName" />
        email address:<input type="text" class="email" name="email" />
        create password:<input type="password" class="password1" name="password" />
        confirm password:<input type="password" class="password2"/>
        <input type="submit" id="submitButton" value="register" />
    </form>

A: You can use removeAttr() function to remove disabled attribute:

$('#enable').on('click', function() {
  $('#submit').removeAttr('disabled');
});

<button id="submit" type="button" disabled>Submit</button>
<button id="enable" type="button">Enable</button>

A: The context here is form>input .Give an id to the submit button and then disable the button using the same command you are using now

A: Please check following code:

                    <form>
                firstName

                <input type="text" id="firstName" name="firstName" />

                lastName

                <input type="text" id="lastName" name="lastName" />

                Email

                <input type="text" id="email" name="email" />

                password1

                <input type="password" id="password1" name="password1" />

                <input type="submit" id="register" value="Register" disabled="disabled" />
            </form>


text:
Q: How to save previous interaction using reactiveValues I am developing a table which does some calculations each time that an action button is used. One column of my table depends on its previous value,
C_new <- C_old + B_new - A_new

For instance, if A=4, B=A+2 and C= C(-1) + B - A my expected results are
A   B  C
1   2  3
4   6  5

I have tried to save the previous value of column C using reactiveValue, as mentioned in  How to "remember" information from the previous iteration when using reactiveTimer in Shiny?,  but it doesn't work. I don't know where I am getting wrong.
Here is my code
library(shiny)
ui <- fluidPage(
  sidebarPanel(textInput("c1","Example"),
           actionButton("update", "Update Table")),
  mainPanel(tableOutput("example"))
)

server <- function(input, output) {

  C_old <- reactive(x=3)

  values <- reactiveValues(df = data.frame(A=1, B=2, C=3))

  newEntry <- observeEvent(input$update,{

    A_new <- as.numeric(input$c1)
    B_new <- A_new + 2
    C_new <- isolate (C_old$x + B_new - A_new)
    C_old$x <<- C_new

  new <- data.frame(A=A_new,B=B_new, C=C_new)

   # attach the new line to the old data frame here:
   values$df <- rbind(values$df, new)

  })

  # Print the content of values$df
  output$example <- renderTable({
   return(values$df)
  })

}

shinyApp(ui = ui, server = server)

A: Important to know, observeEvents (similar to observes) don't have outputs. You just observe a change and do something in their body, but nothing is supposed to be returned (this is different to reactive({ }), which also observes changes but has return values), useful link.
Isolate is not needed in observeEvent , because nothing triggers an update except for input$update (this is different to observe and reactive, where all changeable items in the body trigger an update).
Below is the solution to your problem. I used reactiveVal which stores one single updateable value (see ?reactiveVal for help). After clicking the action button, I retrieve the old table by calling values(), calculate all new values (beware, I need to use tail to get only the last C value) and attach the result to the old value before storing the extended table into values by calling values(new_df):
library(shiny)
ui <- fluidPage(
  sidebarPanel(numericInput("c1","Example", 0),
               actionButton("update", "Update Table")),
  mainPanel(tableOutput("example"))
)

server <- function(input, output) {

  # stores the current data frame, called by values() and set by values(new_data_table)
  values <- reactiveVal(data.frame(A=1, B=2, C=3))

  # update values table on button click
  observeEvent(input$update,{

    old_values <- values()

    A_new <- input$c1
    B_new <- A_new + 2
    C_new <- tail(old_values$C, 1) + B_new - A_new  # tail to get the last C value

    new_values <- data.frame(A=A_new, B=B_new, C=C_new)

    # attach the new line to the old data frame here:
    new_df <- rbind(old_values, new_values)

    #store the result in values variable
    values(new_df)

  })

  # Print the content of values$df
  output$example <- renderTable({
    return(values())
  })

}

shinyApp(ui = ui, server = server)


text:
Q: cocoa read text to custom data format, porting from sgi I'm trying to port an academic research application that I wrote for SGI IRIX 10 years ago, to native Mac OS X, because of Apple's disconcern about X11 and glx, which never gave satisfying results for the program to properly run.
On the other hand, using Apple's port of GLUT introduces threading problems between visualization and sonification callbacks which I find almost impossible to debug. So rewriting in Cocoa should be the obvious solution.
However, when trying to read a data text file I already encounter a wall of problems, because of a custom file scanning and data retrieving routine I need. Once opened by means of
- (IBAction)openExistingDocument:(id)sender
and
NSOpenPanel*
file gets "flockfile'd" for all reading methods and access other than
dataString = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:nil];
which would be in itself ok, if I only knew where and how to declare and return the variable
dataString, so it can be passed to my custom data extraction and modification routines, and mapped to a three-dimensional array of seven-member program-defined int/float/double structs (whose dimensions can't be assumed before the entire string/file gets analyzed.
On the other hand NSOpenGLPixelFormat forces into using pre-defined data types, which make recalculations somewhat inpractical.
Since I have to deal with about 20000+ lines of code to port, I prefer to understand the mechanisms of Cocoa better then the on level of pre-defined data types and built-in callbacks, which are being covered in the technical documentation, tutorials and sample code of Cocoa and Xcode.
If someone could point me at a relevant source, where I could learn more about real possibilities and bottlenecks of Cocoa, it would help me make a better decision in assuming porting strategies.
Thanks in advance!

A: Have you tried using class methods? Do you need to use NSData instead of NSString? One way you can get the contents of an NSString as a C string is using [theStr UTF8String].

A: Here's a working answer to my question - hope it can contribute to someone with similar questions. This is my specific case, else actual read and data formatting function will look differently. It's not meant to serve as case example of OSX coding, just as a simple practical code solving the question.
There are two important parts in the code:

*

*The part which belongs to the NSOpenPanel code, invoking a plain-C file reading function:
//code inside OpenDialog IBAction's completion handler
//...   ...   ...
fileName = [[files objectAtIndex:i] path];//*NOT* absoluteString - no URLs in Unix!
//...   ...   ...
str = [NSString stringWithFormat:@"Raw data file: %s", openFile([fileName UTF8String],self->swapRaw)];

*The actual, plain-C, Unix-style file reading function:
char *openFile(const char file[1024], BOOL swap)
{
FILE *f = fopen(file, "r");
char *d;
UInt32 size;

//assuming fBuffer and fBuffersize are global variables
if(fBuffersize > 0){
free(fBuffer);
fBuffersize = 0;
}

if (f != NULL){
if((size = getSize(f, file)) == 0)
{
    d = "size_error";
    fclose(f);
    return d;
}

fBuffer  = calloc(size, sizeof(Float32));
fBuffersize = size;
fread(fBuffer,sizeof(Float32),size, f);
fclose(f);

//local swap function if format not native-endian
if(swap) swapFloat32Buffer(fBuffer, fBuffersize);
d = "Success";
}
return d;
}


text:
Q: Spark Sql OR command not returning results I'm trying to run the following command in Zeppelin:
SELECT duration FROM voip where duration = 17 or  duration = 1

This doesn't return any results but while running them on there own the query returns results. I'm trying to run similar code in Scala as well but it doesn't work.
df.where(df("duration").===(1) || df("duration").===(2)).limit(10)

I can write something which just does each query and union all the data frames but I'm worried about performance. Any ideas?

A: Can you try with isin function:
df.where(df("duration").isin("1","2")).limit(10)
 val df = Seq(30,1,2,3,4,5,6).toDF("duration")

 val df1 = df.where(df("duration").isin("1","2"))
 df1.show()

-----------------+
|duration         |
+-----------------+
|                1|
|                2|
+-----------------+


text:
Q: Why does ToPagedList take half a minute on an empty IQueryable while the underlying SQL runs in just one second? I have a piece of Entity-to-SQL code that composes an IQueryable, runs ToPagedList() on it and then passes the result into an MVC view.
ToPagedList() fails with a timeout running the SQL query. I extracted the generated SQL query (using IQueryable.ToString()) and ran it on the server - it runs in less than one second and the output is empty (which is correct).
So I have ToPagedList() running the query that would produce an empty result that runs half a minute and times out and I have the underlying SQL that runs in less than one second on the same server.
Since the SQL query output is empty I can't blame the delay on filtering, retrieval or whatever else in the EF.
What can cause a fast SQL query producing an empty output to run extremely slow from inside ToPagedList()?
UPD
This problem seems to have resolved on its own, so it looks like it was some temporary problem between the machine running the code and the SQL Server machine.

A: Make sure to run a TRACE on your SQL Server and look at the query that Entity is generating and then check its execution plan.
Most of the time the latest version of Entity does a pretty good job of creating a robust query but that doesn't mean that a well placed INDEX on the tables you are hitting would speed things up significantly.
Enjoy!


text:
Q: How can I spread an object's properties in jq? If I need to access the properties of an object, I'm currently accessing each property manually:
echo '{"a": {"a1":1, "a2": 2}, "b": 3}' | jq '{a1:.a.a1, a2: .a.a2,b}'
{
  "a1": 1,
  "a2": 2,
  "b": 3
}

I'd like to avoid specifying every property. Is there an equivalent to the Object spread operator in JS, something like jq '{...a, b}'?

A: You can add objects together to combine their contents. If a key exists in both the left and right objects the value from the right object will remain.
echo '{"a": {"a1":1, "a2": 2}, "b": 3}' | jq '.a+{b}'
{
  "a1": 1,
  "a2": 2,
  "b": 3
}

A: If you want a completely generic solution:
[..|objects|with_entries(select(.value|type!="object"))]|add

Or if you want a depth-first approach, replace add by reverse|add.
The above of course comes with the understanding that add resolves conflicts in a lossy way. If you don't want any lossiness, choose a different method for combining objects, or maybe don't combine them at all.

A: Here is a solution that only examines the top-level values, without referring to any key by name:
with_entries(if .value|type=="object" then .value|to_entries[] else . end)

For the example, this produces:
{
  "a1": 1,
  "a2": 2,
  "b": 3
}

Note that even though this solution doesn't use add explicitly, it comes with a similar caveat about key collisions.


text:
Q: Upload Excel file to Python I'm simply trying to upload excel.xlsx file with Python panda package so i can tokenize the text. I tried for hours but nothing works. Any help will be great:
import pandas as pd

excel_file = open(r'''C:\Users\farid-PC\Desktop\Tester.xlsx''', errors
='ignore')
movies = pd.read_excel(excel_file)
movies.head()

Errors:
Traceback (most recent call last):
  File "C:/Users/farid-PC/PycharmProjects/fake_news/fault.py", line 4, in <module>
    movies = pd.read_excel(excel_file)
  File "C:\Users\farid-PC\PycharmProjects\fake_news\venv\lib\site-packages\pandas\util\_decorators.py", line 178, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\farid-PC\PycharmProjects\fake_news\venv\lib\site-packages\pandas\util\_decorators.py", line 178, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\farid-PC\PycharmProjects\fake_news\venv\lib\site-packages\pandas\io\excel.py", line 307, in read_excel
    io = ExcelFile(io, engine=engine)
  File "C:\Users\farid-PC\PycharmProjects\fake_news\venv\lib\site-packages\pandas\io\excel.py", line 392, in __init__
    self.book = xlrd.open_workbook(file_contents=data)
  File "C:\Users\farid-PC\PycharmProjects\fake_news\venv\lib\site-packages\xlrd\__init__.py", line 162, in open_workbook
    ragged_rows=ragged_rows,
  File "C:\Users\farid-PC\PycharmProjects\fake_news\venv\lib\site-packages\xlrd\book.py", line 91, in open_workbook_xls
    biff_version = bk.getbof(XL_WORKBOOK_GLOBALS)
  File "C:\Users\farid-PC\PycharmProjects\fake_news\venv\lib\site-packages\xlrd\book.py", line 1267, in getbof
    opcode = self.get2bytes()
  File "C:\Users\farid-PC\PycharmProjects\fake_news\venv\lib\site-packages\xlrd\book.py", line 672, in get2bytes
    return (BYTES_ORD(hi) << 8) | BYTES_ORD(lo)
TypeError: unsupported operand type(s) for <<: 'str' and 'int'


text:
Q: What does "along the handle of the cart" mean? And how does one calculate weight?
A horizontal force is used to pull a $5.0\text{ kg}$ cart at a constant speed of $5.0\text{ m/s}$ across the floor. The force of friction between the cart and the floor is $10\text{ N}$.

*

*What is the magnitude of the horizontal force along the handle of the cart?

*Calculate the weight of the cart?

*Calculate the coefficient of kinetic friction between the cart and the floor.

I'm not sure what they mean by "along the handle of the cart". Is that still the same as $F_{net}$? Also, I have no idea how I would calculate the weight.Is the weight just the normal Force? Because in order to do anything with $F_N$, I need $F_f$ and $\mu$ which I do not have.

A:
A horizontal force is used to pull a 5.0 kg cart at a constant speed of 5.0 m/s accross the floor. The force of friction between the cart and the floor is 10N.
What is the magnitude of the horizontal force along the handle of the cart? Calculate the weight of the cart? Calculate the coefficient of kinetic friction between the cart and the floor.
I'm not sure what they mean by "along the handle of the cart".

I presume this is the force in the horizontal direction.

Is that still the same as $F_{net}$?

It is the horizontal component of ${\vec F}_{net}$

Also, I have no idea how I would calculate the weight...is the weight just normal Force?

The weight of an object of mass $m$ is simply equal to $m g$ where $g$ is the acceleration due to gravity.

Because in order to do anything with $F_N$, I need $F_f$ and $\mu$ which i do not have. So, i have no idea what to do.

$F_f$ is given to you. You can find $F_N$ by balancing forces along the vertical direction. This should allow you to compute $\mu$.

A: Question 1.
Because the cart is travelling at a constant velocity, the net force on the cart must be 0.  This means the force at which the cart is pulled must balance the force of friction.
Therefore, the magnitude of the horizontal force along the handle is also 10N.
Question 2
Weight = mg = 5*10 = 50 N (assuming g = 10)
Question 3
Force of friction = Normal Force * Coefficient
The Normal Force in this case is simply the weight, so,
Force of friction = Weight*Coefficient
Substituting in numbers gives,
10 = 50*Coefficient
Therefore,
Coefficient = 0.2


text:
Q: java: weird NullPointerException in ternary operator (? : ) Please consider this code snippet:
private static void doSomething(Double avg, Double min, Double sd) {
    final Double testMin;
    if (avg != null) {
        testMin = Math.max(min, avg - 3 * sd);
    } else {
        testMin = min;
    }
    System.out.println("testMin=" + testMin);

    final Double verwachtMin = avg != null ? Math.max(min, avg - 3 * sd) : min;
    System.out.println("verwachtMin=" + verwachtMin);
}

As far as I know (and for what my IDE can tell me), the variables testMin and verwachtMin should be equivalent.
As you might expect, I'd rather write the last 2 lines than the first 7. However, when I pass 3 null values to this method, I get an NPE on the calculation of the verwachtMin variable.
Does anyone know how this can happen? Does the ternary operator evaluate the 2nd part, even when the condition is not true?
(Java version 1.6.0_21)

A:
Does the ternary operator evaluate the 2nd part, even when the condition
  is not true

No - but it evaluates the 3rd part and I think in this case it tries to autounbox min (leading to the NPE) because the return type of Math.max() is primitive double and determines the return type of the entire expression.
Autoboxing/-unboxing is of the devil.

A: Try:
final Double verwachtMin = avg != null ? new Double(Math.max(min, avg - 3 * sd)) : min;

or
final Double verwachtMin = avg != null ? Double.valueOf(Math.max(min, avg - 3 * sd)) : min;

The types of the alternate sides of the ternary operator were double and Double, which means that the Double gets unboxed to double, and then on assignment we have a boxing from double to Double. If the value of min is null then the unboxing NPEs.

A: The problem is caused by autoboxing*, not by the ternary operator. You are using the Double wrapper type rather than the double primitive type. Because Math.max() expects double parameters, not Doubles, there is an invisible call to Double#doubleValue() before the values are passed to Math.max(). However, you can't call a method on a null object - hence the NullPointerException.
Why are you using Double instead of double in the first place? A primitive-type variable  (such as a double) simply cannot be null.

*Well, autounboxing, in this case

A: Auto-unboxing causes the problem. Similar question has been asked before .. You sould use double instead of Double to solve your problem..

A: Math.max(min, avg - 3 * sd) here min, avg and sd are autounboxed from Double to double which when one of them is null causes an NPE.


text:
Q: Log4J - disable logging for specific class - multiple appenders I setup Log4J to use multiple appenders.  This is working fine.  However, I want to set the default log level to one appender to DEBUG, and restrict logging for a specific class to INFO and above.  What I came up with works for the FA appender, but not the DCSLOAD and DCSPROC appenders.  What am I doing wrong?
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger = CA, FA

# CA is set to be a ConsoleAppender.
log4j.appender.CA=org.apache.log4j.ConsoleAppender

# CA uses PatternLayout.
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5p %c{3} %x - %m%n

# FA uses PatternLayout.
log4j.appender.FA=org.apache.log4j.RollingFileAppender
log4j.appender.FA.File=${catalina.base}/logs/dcs.log
log4j.appender.FA.layout=org.apache.log4j.PatternLayout
log4j.appender.FA.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5p %c{3} %x - %m%n
log4j.appender.FA.MaxFileSize=1024KB
log4j.appender.FA.MaxBackupIndex=100

# DCSPROC, DCSLOAD and DCSDB are all File Appenders to different targets
log4j.appender.DCSPROC=org.apache.log4j.RollingFileAppender
log4j.appender.DCSPROC.File=${catalina.base}/logs/dcs_process.log
log4j.appender.DCSPROC.layout=org.apache.log4j.PatternLayout
log4j.appender.DCSPROC.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5p %c{3} %x - %m%n
log4j.appender.DCSPROC.MaxFileSize=1024KB
log4j.appender.DCSPROC.MaxBackupIndex=100

log4j.appender.DCSLOAD=org.apache.log4j.RollingFileAppender
log4j.appender.DCSLOAD.File=${catalina.base}/logs/dcs_business.log
log4j.appender.DCSLOAD.layout=org.apache.log4j.PatternLayout
log4j.appender.DCSLOAD.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5p %c{3} %x - %m%n
log4j.appender.DCSLOAD.MaxFileSize=1024KB
log4j.appender.DCSLOAD.MaxBackupIndex=100

log4j.appender.DCSDB=org.apache.log4j.RollingFileAppender
log4j.appender.DCSDB.File=${catalina.base}/logs/dcs_database.log
log4j.appender.DCSDB.layout=org.apache.log4j.PatternLayout
log4j.appender.DCSDB.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5p %c{3} %x - %m%n
log4j.appender.DCSDB.MaxFileSize=1024KB
log4j.appender.DCSDB.MaxBackupIndex=100

# set default logging level for outputs
log4j.logger.CA = DEBUG
log4j.logger.FA = DEBUG

log4j.logger.DCSDB = DEBUG, DCSDB
log4j.logger.DCSPROC = DEBUG, DCSPROC
log4j.logger.DCSLOAD = DEBUG, DCSLOAD

log4j.additivity.DCSDB=false
log4j.additivity.DCSPROC=false
log4j.additivity.DCSLOAD=false

#This works
log4j.logger.LoginServlet=INFO, FA

#These two do not
log4j.logger.LoginServlet=INFO, DCSLOAD
log4j.logger.LoginServlet=INFO, DCSPROC

A: change these:
    log4j.logger.DCSDB = DEBUG, DCSDB
    log4j.logger.DCSPROC = DEBUG, DCSPROC
    log4j.logger.DCSLOAD = DEBUG, DCSLOAD

to
    log4j.logger.DCSDB = DEBUG
    log4j.logger.DCSPROC = DEBUG
    log4j.logger.DCSLOAD = DEBUG


text:
Q: how to get records from a result of a subquery which matches a value of a column in SQL? In my Android app, I am using the Room persistence library. In one of the Tables (Room Entity).
Consider the following table.

S_ID
STATUS

1
Pending

1
Rejected

3
Approved

4
Approved

5
Pending

6
Rejected

7
Rejected

8
Approved

9
Rejected

the expected result of the SQL sub-query where I want a record with 'Rejected' status to be removed from results if its S_ID collides with another 'Pending' status record. This was sorted in my previous question:
link here

S_ID
STATUS

1
Pending

3
Approved

4
Approved

5
Pending

6
Rejected

7
Rejected

8
Approved

9
Rejected

Now, the outer query should give the following result with records only with 'Rejected' status.

S_ID
STATUS

6
Rejected

7
Rejected

9
Rejected

This result is required to satisfy a use case where I need to show the records based on a selected 'Status' by the user. for example, if user selects 'Approved', then the app will show all 'Apprvoed' records. But in case of 'Rejected', I need to show all rejected records except those whose s_id conflict with that of 'Pending'. I also want a count of such records additionlally.

A: If I understand your question correctly, you want the rows after the last 'Pending' status:
select t.*
from t
where t.s_id > (select max(t2.s_id) from t t2 where t2.status = 'Pending');

I don't even think you need to remove the "conflicts" if this is the logic you want.


text:
Q: Remove element from ArrayCollection on OneToMany wont delete it on persist()? In a Zend Framework 2 project, we got two Doctrine 2 entities and we would like to remove an element from a collection allready saved in the database...
So we have a first entity named FormGroupConstraint :
/**
 * FormGroupConstraint
 *
 * @ORM\Table(name="form_group_constraint")
 * @ORM\Entity(repositoryClass="Application\Dao\FormGroupConstraintDao")
 */
class FormGroupConstraint {

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
     protected $id;

    /**
     * @param \Doctrine\Common\Collections\ArrayCollection
     * @ORM\OneToMany(targetEntity="Application\Entity\FormQuestionConstraint", mappedBy="groupConstraint", fetch="EAGER", cascade={"persist", "merge", "refresh", "remove"})
     */
     protected $constraints;

     public function __construct()
          $this->constraints = new \Doctrine\Common\Collections\ArrayCollection();
     }

     /**
     * @param \Doctrine\Common\Collections\ArrayCollection $constraints
     */
     public function addConstraints($constraints) {
        foreach ($constraints as $constraint) {
            $this->constraints->add($constraint);
        }
        return $this->constraints;
    }
    /**
     * @param \Doctrine\Common\Collections\ArrayCollection $constraints
     */
     public function removeConstraints($constraintsToRemove) {
            foreach ($constraintsToRemove as $key => $constraintToRemove) {
                $this->constraints->removeElement($constraintToRemove);
            }
            return $this->constraints;
     }
}

And the sub entity named FormQuestionConstraint :
/**
 * FormQuestionConstraint
 *
 * @ORM\Table(name="form_question_constraint")
 * @ORM\Entity(repositoryClass="Application\Dao\FormQuestionConstraintDao")
 */
class FormQuestionConstraint
{
    /**
    * @var integer
    *
    * @ORM\Column(name="id", type="integer", nullable=false)
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="IDENTITY")
    */
    protected $id;

    /**
    * @var \Application\Entity\FormGroupConstraint
    *
    * @ORM\ManyToOne(targetEntity="Application\Entity\FormGroupConstraint", cascade=   {"persist", "merge", "refresh", "remove"})
    * @ORM\JoinColumns({
    *   @ORM\JoinColumn(name="form_group_constraint_id", referencedColumnName="id")
    * })
    */
    protected $groupConstraint;
}

So if we try to create, persist, flush a FormGroupConstraint entity, no problem,
but when we want to remove an element of $constraints ArrayCollection, nothing happens...
We are using doctrine-orm-module for zend 2 installed with composer.phar in dev-master...
Here is an example of what we are trying to do :
$constraint = $this->findConstraintByGroup(1);

$formGroupConstraint = $this->_em->findOneById(1);

$formGroupConstraint->getConstraints()->removeElement($constraint);
$this->_em->persist($formGroupConstraint);
$this->_em->flush();

No error, but no delete or remove...
And if we var_dump() the getConstraints() before persist(), actually the element is still in the ArrayCollection...
Could anyone explain us how we could do that or why the element is not removed ?

A: You could add orphanRemoval=true on the OneToMany side of the relation, for instance like this:
@ORM\OneToMany(
    targetEntity="Application\Entity\FormQuestionConstraint",
    mappedBy="groupConstraint",
    cascade={"all"},
    orphanRemoval=true
)

The reason for this behaviour is that the entity is removed from the ArrayCollection, but the collection's contents are only determined by the child entity's foreign key pointing to the parent entity.
When doctrine looks up the parent entity's children for the next time, it's still there and will be shown in the next request again, when the ArrayCollection is fetched from the database again.
If orphanRemoval is set to true, such child entities will be removed upon persist().

A: Maybe a bit late but try adding orphanRemoval=true to the inverse side (OneToMany) of relationship
@ORM\OneToMany(
    targetEntity="Application\Entity\FormQuestionConstraint",
    mappedBy="groupConstraint",
    cascade={"persist", "remove"},
    orphanRemoval=true
)

A: Because the reference is held on FormQuestionConstraint you need to do:
$this->_em->remove($constraint);
$this->_em->flush();


text:
Q: Android push message without gcm possible? Is there any possibility to implement push-messages to android without google cloud messaging?
I already took a view on openmobster but it does not satisfy my needs.
I need to:

*

*create push-messages to an android device

*self-hosted

A complete sync-framework (with REST) for android would even be better :)
Thank you

A: Rabbitmq works perfectly fine, but I dont know about effectiveness. Roaring Rabbit of CloudAMQP.com is supporting only 100 concurrent connections and 229$ per month. What if you have more than 100 mobiles that are currently connected to rabbit. I made the push with cloudamqp.com' little lemure. May be you need to have a rabbitmq server in ec2.

A: You can check with Parse library
https://www.parse.com/docs/android_guide
You can also see userban airship.
https://docs.urbanairship.com/display/DOCS/Home


text:
Q: D3JS force layout center image I'm using force layout with d3js to draw a network graph
the problem is that my SVG is truncated (see the image bellow)

how to get the whole image ?
i'm using this to initialise the chart :
var width = 1200,
        height = 1000,
        root;

    var force = d3.layout.force()
        .size([width, height])
        .on("tick", tick)
        .start();

    var svg = d3.select("body").append("svg")
        .attr("width", width)
        .attr("height", height);

    var link = svg.selectAll(".link"),
        node = svg.selectAll(".node");

A: At first simple step i suggest simply to scale the viewport...
var svg = d3.select("body").append("svg")
        .attr("width", width)
        .attr("height", height);
        .attr("viewBox", `${-width/2} ${-height/2} ${width*2} ${height*2}`)

Or you can compute bbox of all nodes and set viewbox more percise


text:
Q: Possible to use interaction between continuous variable and the same dichotomized var in model? We are wondering whether it would be possible to use the same variable twice in a model: Once dichotomized, once continuous. The variable are questionnaire scores and participants are pre-screened to fall into extreme groups (so the middle is missing). The idea is that the two groups are qualitatively different from each other and do not represent a linear trend. To be precise, we expect a negative relationship with the DV in one group, but not in the other.
So we could model it using some non-linear model, but it might be difficult to interpret. If we use only the categorical variables we could compare these different groups well, but we lose all the variance in the predictor/questionnaire. So we were wondering if it is possible to get separate regression lines for each group by simply including the interaction of the two? It does feel very wrong to use the same variable twice. Also, it might be the same as using a quadratic predictor, maybe?
So the model would be
DV = IVgrouped * IVcont.
Any thoughts?
Thanks!

A: Of course, your software will let you do this. And as long as there are (approximately) linear trends within each of these groups, you would also get reasonable predictions from the model (at least within the range where you have a decent number of observed values). However, you would have some serious problems to interpret the coefficients without looking at the predicted values for different values, because the coefficients for the linear variable in the interaction would be relative to the zero value of the variable and the coefficients of the main and interaction effects are correlated (which particularly matters for confidence/prediction intervals). You may also get funny discontinuities in the piece-wise linear "curve" you use at the ends of each group.
If you need to look at the predicted values anyway, perhaps it becomes preferrable to use e.g. splines. Almost all standard statistical software will quite easily do this for you (and often also give you useful plots of the non-linear relationship between expected response and continuous covariate). I only specifically mention splines, because they are a commonly used approach and because, If you want, you could then force the knots to be on the boundaries of the groups you have a-priori identified (similar to the idea you had).


text:
Q: DrawerNavigator redirects to first route at opening // AppContainer.js
const AuthNavigator = createStackNavigator(...code);

const DrawerNavigator = createDrawerNavigator(
  {
    MyAccount: MyAccountScreen,
    Home: HomeScreen,
  }
);

const AppNavigator = createStackNavigator(
  {
    Home: HomeScreen,
    MyAccount: MyAccountScreen,
  }
);

const AppContainer = createAppContainer(
  createSwitchNavigator(
    {
      AuthNavigator,
      AppNavigator,
      DrawerNavigator,
    },
    {
      initialRouteName: AuthNavigator,
    }
  )
);

// HomeScreen.js I call:
onPress={() =>
  this.props.navigation.dispatch(DrawerActions.openDrawer())
}

It opens the modal, but always goes automatically to MyAccountScreen without touch anything. The expected behaviour it's only open the modal.

A: Yes, which is actually correct. But you have some flows in understanding how a DrawerNavigator should work. You cannot open the drawer if you're not on the Drawer.
I see that you have HomeScreen defined in 2 Navigators. And I have a feeling that you want to be able to navigate from Home to/from MyAccount using the DrawerNavigator, which means that both those routes have to be inside the DrawerNavigator and you want the HomeScreen to be the first screen that is visible by default.
const DrawerNavigator = createDrawerNavigator(
  {
    Home: HomeScreen,
    MyAccount: MyAccountScreen,
  }
);

Which you kind of already have. The misconception that you have is that for your current routes, you don't need the AppNavigator, you could simply rename the above one as AppNavigator and your navigation configuration should look something like this:
const AppNavigator = createDrawerNavigator(
  {
    Home: HomeScreen,
    MyAccount: MyAccountScreen,

  }
);

const AppContainer = createAppContainer(
  createSwitchNavigator(
    {
      AuthNavigator,
      AppNavigator,
      DrawerNavigator,
    },
    {
      initialRouteName: AuthNavigator,
    }
  )
);

And that's it. Now when you navigate to AppNavigator, the first displayed route will be Home and opening the Drawer will just display the Drawer and won't automatically navigate you to MyAccountScreen.