text:
Q: Specifying Values in D3 Graph from JSON I am trying to get values from the "links" instead of "nodes. I guess a more helpful way of asking this is how to specify where I am requesting getting the values from my JSON.
JSON for reference:
{
"nodes": [
{"fixed":true,"data": {"id": "foo","idType":"USERNAME","color":"red"},"selected":false},
{"fixed":true,"data": {"id": "bar","idType":"USERNAME","color":"yellow"},"selected": false}
],
"links": [
{"classes":null,"data":{"color":"blue","source":"foo","target":"bar","visible":true},"grabbable":false},
{"classes":null,"data":{"color":"green","source":"bar","target":"foo","visible":true},"grabbable":false}
]}

So an example is I can get this to work
node.style("fill", function(d) { return d.data['color'] });

but not
link.style("stroke", function(d) { return d.data['color'] });

However, this works...
link.style("stroke", "red"});

In the console it says d.data['color'] is undefined. I guess I do not understand how it is being called exactly. I have seen some examples of code that has
function(d, i) { return bla bla }

and I assumed that if d is always node, maybe i might be edges but adding that to my code didn't do much. If someone could explain what the i is touching that would be good also.
Code snippet of actual code below:
// Define the dimensions of the visualization.
var width = innerWidth,
    height = innerHeight,
    color = d3.scale.category20(),
    root;

// Create an array logging what is connected to what
var linkedByIndex = { };

// Create the SVG container for the visualization and define its dimensions
var svg = d3.select('body').append('svg')
    .attr('width', width)
    .attr('height', height);

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

// Create the force layout
var force = d3.layout.force()
    .size([width, height])
    .charge(-400)
    .linkDistance(50);

//Read in the JSON data.
d3.json("../test/resources/full.json", function(error, json) {
    // expands scope of json
    root = json
    alert(root)
    update();
});

function update() {

// sets the source and target to use id instead of index
var edges = [];
root.links.forEach(function(e) {
    var sourceNode = root.nodes.filter(function(n) {
                return n.data.id === e.data.source;
            })[0],
            targetNode = root.nodes.filter(function(n) {
                return n.data.id === e.data.target;
            })[0];

    edges.push({
        source: sourceNode,
        target: targetNode
    });
});

force
        .nodes(root.nodes)
        .links(edges)
        .start();

link = link
        .data(edges)
        .enter().append("line")
        .attr("class", "link");

node = node
        .data(root.nodes)
        .enter().append("g")
        .attr("class", "node")
    //.attr("fixed", function(d) { return d.fixed=true })
        .call(force.drag)
        .on('mouseover', connectedNodes)
        .on('mouseleave', restore)
        .on('click', highlight);

// Checks for the shape and color to be made for the node.
node.append("circle")
        .attr("r", 10);

node.style("fill", function(d) { return d.data['color'] });
link.style("stroke", function(d) { return d.data['color'] });

node.append("text")
        .attr("dx", 12)
        .attr("dy", ".35em")
        .style("fill", "black")
    // Checks what to return as the node label based on idType.
        .text(function (d) {
            if (d.data['idType']==="Comment") {
                return d.data.attrs[1].val;
            }
            else if(d.data['idType']==="MEDIA") {
                return "MEDIA " + d.data['id'];
            }
            else
                return d.data['id'];
        });

root.links.forEach(function (d) {
    linkedByIndex[d.data.source + "," + d.data.target] = 1;
});

resize();
window.addEventListener('resize', resize);

}

A: Per Lars' comment, edges does not contain the original link data. So it was currently pushing only
edges.push({
    source: sourceNode,
    target: targetNode
});

so to add any information that isn't in my edges I would have to add it. An example is if I were to push the color attribute from JSON my code would look like
edges.push({
    source: sourceNode,
    target: targetNode,
    color: e.data['color']
});


text:
Q: Recursive variable expansion in Perl I have a need to expand ASA access-lists for reference after a migration.
The ASA is gone now and I want to expand the object-group references to validate we captured all expected access.
I have a working idea for an ACL line with 4 object-groups.
My rub is ACLs could have 0-4 object-group references and I need a loop to run through and handle each possible combination.
I can write a loop for each possible combination but I know there has to be a more elegant way.
I already have code to expand and store the object groups individually, but substituting them in-line is the challenge.
Thank you for your time and consideration.
@line = ('access-list','vlan_in','extended','permit','object-group','ob1','object-group','ob2','object-group','ob3','object-group','ob4');
# @line = ('access-list','vlan_in','extended','permit','object-group','ob1','object-group','ob2','object-group','ob3','eq','53');
# @line = ('access-list','vlan_in','extended','permit','object-group','ob1','host','30.0.0.30','object-group','ob2','eq','23');
# @line = ('access-list','vlan_in','extended','permit','tcp','host','40.0.0.10','object-group','ob1','eq 80');

$OG{'ob1'} = ['tcp','udp'];
$OG{'ob2'} = ['10.0.0.10', '10.0.0.20'];
$OG{'ob3'} = ['20.0.0.15', '20.0.0.25'];
$OG{'ob4'} = ['eq 22', 'eq 443'];

foreach $ins4 (@{$OG{ob4}}) {
  foreach $ins1 (@{$OG{ob1}}) {
    foreach $ins2 (@{$OG{ob2}}) {
      foreach $ins3(@{$OG{ob3}}) {
        $buffer = "";
        foreach $element (@line) {
          if($element =~ /object-group/) { next; }
          $buffer = $buffer . ' ' . $element;
        }
        $buffer =~ s/ob1/$ins1/;
        $buffer =~ s/ob2/$ins2/;
        $buffer =~ s/ob3/$ins3/;
        $buffer =~ s/ob4/$ins4/;
        print "$buffer\n";
      }
    }
  }
}

(Current Output)
access-list vlan_in extended permit tcp 10.0.0.10 20.0.0.15 eq 22
access-list vlan_in extended permit tcp 10.0.0.10 20.0.0.25 eq 22
access-list vlan_in extended permit tcp 10.0.0.20 20.0.0.15 eq 22
access-list vlan_in extended permit tcp 10.0.0.20 20.0.0.25 eq 22
access-list vlan_in extended permit udp 10.0.0.10 20.0.0.15 eq 22
access-list vlan_in extended permit udp 10.0.0.10 20.0.0.25 eq 22
access-list vlan_in extended permit udp 10.0.0.20 20.0.0.15 eq 22
access-list vlan_in extended permit udp 10.0.0.20 20.0.0.25 eq 22
access-list vlan_in extended permit tcp 10.0.0.10 20.0.0.15 eq 443
access-list vlan_in extended permit tcp 10.0.0.10 20.0.0.25 eq 443
access-list vlan_in extended permit tcp 10.0.0.20 20.0.0.15 eq 443
access-list vlan_in extended permit tcp 10.0.0.20 20.0.0.25 eq 443
access-list vlan_in extended permit udp 10.0.0.10 20.0.0.15 eq 443
access-list vlan_in extended permit udp 10.0.0.10 20.0.0.25 eq 443
access-list vlan_in extended permit udp 10.0.0.20 20.0.0.15 eq 443
access-list vlan_in extended permit udp 10.0.0.20 20.0.0.25 eq 443

I can brute force this but was hoping for some inspiration rather than repeating code excessively. I can write separate loops for each scenario, but was hoping for some inspiration on a more elegant way.
(if 3 occurrences of ob#)
# @line = ('access-list','vlan_in','extended','permit','object-group','ob1','object-group','ob2','object-group','ob3','eq','53');

foreach $ins1 (@{$OG{ob1}}) {
  foreach $ins2 (@{$OG{ob2}}) {
    foreach $ins3(@{$OG{ob3}}) {
      $buffer = "";
      foreach $element (@line) {
        if($element =~ /object-group/) { next; }
        $buffer = $buffer . ' ' . $element;
      }
      $buffer =~ s/ob1/$ins1/;
      $buffer =~ s/ob2/$ins2/;
      $buffer =~ s/ob3/$ins3/;
      print "$buffer\n";
    }
  }
}

(if 2 occurrences of ob#)
# @line = ('access-list','vlan_in','extended','permit','object-group','ob1','host','30.0.0.30','object-group','ob2','eq','23');

foreach $ins1 (@{$OG{ob1}}) {
  foreach $ins2 (@{$OG{ob2}}) {
    $buffer = "";
    foreach $element (@line) {
      if($element =~ /object-group/) { next; }
      $buffer = $buffer . ' ' . $element;
    }
    $buffer =~ s/ob1/$ins1/;
    $buffer =~ s/ob2/$ins2/;
    print "$buffer\n";
  }
}

(if 1 occurrence of ob#)
# @line = ('access-list','vlan_in','extended','permit','tcp','host','40.0.0.10','object-group','ob1','eq 80');

foreach $ins1 (@{$OG{ob1}}) {
  $buffer = "";
  foreach $element (@line) {
    if($element =~ /object-group/) { next; }
    $buffer = $buffer . ' ' . $element;
  }
  $buffer =~ s/ob1/$ins1/;
  print "$buffer\n";
}

A: What you're looking for is a cross-product of the values in %OG.  CPAN to the rescue.  The following code uses  Set::Product to create the cross-products.
use Set::Product qw[ product ];

my @line = (
    'access-list',  'vlan_in', 'extended',     'permit',
    'object-group', 'ob1',     'object-group', 'ob2',
    'object-group', 'ob3',     'object-group', 'ob4'
);

# same order as things fed to product
my @placeholders = qw[ ob1 ob2 ob3 ob4 ];

product {
    # for efficiency, this should be done outside of this loop
    my $buffer = join( ' ', grep { !/object-group/ } @line );

    # product places the values in @_; shift them off in order
    $buffer =~ s/$_/shift()/ge for @placeholders;

    print $buffer . "\n";
}
  [ 'tcp',         'udp' ],
  [ '10.0.0.10', '10.0.0.20' ],
  [ '20.0.0.15', '20.0.0.25' ],
  [ 'eq 22',     'eq 443' ]
;

which results in
access-list vlan_in extended permit tcp 10.0.0.10 20.0.0.15 eq 22
access-list vlan_in extended permit tcp 10.0.0.10 20.0.0.15 eq 443
access-list vlan_in extended permit tcp 10.0.0.10 20.0.0.25 eq 22
access-list vlan_in extended permit tcp 10.0.0.10 20.0.0.25 eq 443
access-list vlan_in extended permit tcp 10.0.0.20 20.0.0.15 eq 22
access-list vlan_in extended permit tcp 10.0.0.20 20.0.0.15 eq 443
access-list vlan_in extended permit tcp 10.0.0.20 20.0.0.25 eq 22
access-list vlan_in extended permit tcp 10.0.0.20 20.0.0.25 eq 443
access-list vlan_in extended permit udp 10.0.0.10 20.0.0.15 eq 22
access-list vlan_in extended permit udp 10.0.0.10 20.0.0.15 eq 443
access-list vlan_in extended permit udp 10.0.0.10 20.0.0.25 eq 22
access-list vlan_in extended permit udp 10.0.0.10 20.0.0.25 eq 443
access-list vlan_in extended permit udp 10.0.0.20 20.0.0.15 eq 22
access-list vlan_in extended permit udp 10.0.0.20 20.0.0.15 eq 443
access-list vlan_in extended permit udp 10.0.0.20 20.0.0.25 eq 22
access-list vlan_in extended permit udp 10.0.0.20 20.0.0.25 eq 443

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to call a C function from Assembly? Here's the entire assembly program:
.model small
.stack 256

.code
start:
    call printer
    mov ax, 3       ; store 3 into ax

    mov ah, 76      ; back to DOS
    mov al, 0       ; no errors
    int 21h         ; interupt -> DOS
end start

And this is where I define the C function printer
#include <stdio.h>

void printer()
{
    printf("Hello!\n");
}

When compiling the assembly code, I get an error: undefined symbol: printer. In C I would do an #include "file.h", how do I achieve the same result here?

A: The problem is not compilation, it's linking.  You must link (using ld if on Unix/Linux) your executable including the object file with the assembly code and the object file with the C code.
Or put your assembly code into your C file using an "asm" block.

A: You should add something like
extern  _printer

on the top of your assembly and use call with this name
call _printer

Correct name of function depends on naming convention of your C compiler. Compiler may add some characters to the C name of the function.
Correct "extern" keyword depends on your assembler and it could be ".extern" or so.
Edit 1:
In Turbo Assembler and for that case with function without parameter, it should be just
extrn printer

or
extrn printer:NEAR

I am not familiar with TASM.


text:
Q: Serial Port Synchronization in Delphi I am still having issues with the TComPort component but this time is not the component itself is the logic behind it. I have a device witch sends some ascii strings via serial port i need to prase those strings the problem is the computer reacts very fast so in the event char it captures only a part of the string the rest of the string comes back later... so parsing it when it is recived makes it impossible.
I was thinking in writing a timer witch verify if there was no serial activity 10 secons or more and then prase the string that i am saving into a buffer. But this method is unprofessional isn't there a idle event witch i can listen...Waiting for the best solution for my problem. Thanks.

A: After using a number of serial-port-components, I've got the best results until now, by using CreateFile('\\?\COM1',GENERIC_READ or GENERIC_WRITE,0,nil,OPEN_EXISTING,     FILE_ATTRIBUTE_NORMAL,0), passing that handle to a THandleStream instance, and starting a dedicated thread to read from it. I know threads take a little more work than writing an event handler, but it still is the best way to handle any synchronization issues that arise from using serial ports.

A: Typical handler for OnRXChar event:
procedure XXX.RXChar(Sender: TObject; Count: Integer);
begin
  ComPort.ReadStr(s, Count);
  Accumulator := Accumulator + s;
  if not AccumContainsPacketStart then
    Accumulator := ''
  else if AccumContainsPacketEndAfterStart then begin
    ExtractFullStringFromAccum;
    ParseIt;
  end;
end;

A: Note.
Most com-port components do not have a clue when to report back to the owner. Normally the thread that is responsible to gather the bytes from the port is informed by the OS that one or more bytes are ready to be processed. This information is then simply popped up to your level. So when you expect the message to be transferred, you get what the OS is giving you.
You have to buffer all incoming characters in a global buffer. When you get the final character in your message string, handle the message.
Here is an example where the message start is identified with a special character and the end of the message is identified with another character.
If your message is constructed in another way, I'm sure you can figure out how to adapt the code.
var
  finalBuf: AnsiString;

{- Checking message }
Function ParseAndCheckMessage(const parseS: AnsiString) : Integer;
begin
  Result := 0; // Assume ok
  {- Make tests to confirm a valid message }
  ...
end;

procedure TMainForm.ComPortRxChar(Sender: TObject; Count: Integer);
var
  i,err: Integer;
  strBuf: AnsiString;
begin
  ComPort.ReadStr(strBuf, Count);
  for i := 1 to Length(strBuf) do
    case strBuf[i] of
      '$' :
        finalBuf := '$';  // Start of package
      #10 :
        begin
          if (finalBuf <> '') and (finalBuf[1] = '$') then  // Simple validate check
            begin
              SetLength( finalBuf, Length(finalBuf) - 1); // Strips CR
              err := ParseAndCheckMessage(finalBuf);
              if (err = 0) then
                {- Handle validated string }
              else
                {- Handle error }
            end;
          finalBuf := '';
        end;
    else
      finalBuf := finalBuf + strBuf[i];
    end;
end;

A: If your protocol has begin/end markers, you can use TComDataPacket to provide you full packets, when they are available.

A: For certain amount of character we can use delay some miliseconds before ReadStr to make sure the data is completely sent. Example for 4 amount of character:
procedure TForm1.ComPort1RxChar(Sender: TObject; Count: Integer);
var
  Str: String;
  tegangan : real;
begin
  sleep(100); //delay for 100ms
  ComPort1.ReadStr(Str, 4);

...


text:
Q: Mathematica and gaps in continuous plot I have a bit of trouble with Mathematica and it's plotting stuff. I tried to plot Jacobi amplitude function:
JacobiAmplitude[Sqrt[0.1]*x, 10], {x, 0, 50}]

but the result leaves gaps where the roots of the function should be (particularly for this function around x = 3, 6, 10, ...). I've done a bit of googling and found that either Exclusions set to None or raising PlotPoints should help. Well, it didn't. I even tried to set MaxRecursion to 8, PlotPoints to one million, waited several hours for the plot and it didn't change. Funny thing is, that when I added Mesh -> None, I've found out, that mathematica added plot points even at the gaps, but it didn't join them with lines! This is something like bug, or how should I deal with that? Any help'd be appreciated.
P.S.: I'm using Mathematica 9.0

A: Graphics[{Blue,
          Line[Sort @@  Cases[Plot[JacobiAmplitude[Sqrt[0.1]*x, 10], {x, 0, 50}, Mesh -> All],
                              GraphicsComplex[a_, ___] :> a]]},
 AspectRatio -> 1/GoldenRatio, Axes -> True]

A: There's a small but nontrivial complex part to the value being plotted that arises from using MachinePrecision numbers for plotting.  Use arbitrary precision numbers by setting the WorkingPrecision to a suitable value.
Plot[JacobiAmplitude[Sqrt[0.1]*x, 10], {x, 0, 50}, WorkingPrecision -> 10]

Or, Szbolcs' points out, one can apply Chop orRe to your function, which will be faster, if you are certain your function is real-valued.


text:
Q: which VR SDK is best for unity application? I need some help about VR camera which VR SDK is best and support all Device like(Mixed Reality, Oculus Rift and HTC Vive).any idea quick..

A: You can use Google VR SDK.
Download link

A: If you want to build an VR-Application for Desktop-VR (like Oculus, WMR, Vive), you can just roll with SteamVR which supports them all.


text:
Q: With CMake, how can I set environment properties on the gtest_discover_tests --gtest_list_tests call? I'm currently working on migrating our current build environment from MSBuild to CMake.  I have a situation where I need to update the PATH variable in order for the units tests executable to run.  This is not a issue for gtest_add_tests, as it uses the source to identify tests.  But gtest_discover_tests, which executes the unit tests with the --gtest_list_tests flag, fails to identify any tests because a STATUS_DLL_NOT_FOUND error is encountered during the build.
For example:
add_executable(gTestExe ...)
target_include_directories(gTestExe ...)
target_compile_definitions(gTestExe ...)
target_link_libraries(gTestExe ...)
set (NEWPATH "/path/to/bin;$ENV{PATH}")
STRING(REPLACE ";" "\\;" NEWPATH "${NEWPATH}")

This works:
gtest_add_tests(TARGET gTestExe TEST_LIST allTests)
set_tests_properties(${all_tests} PROPERTIES ENVIRONMENT "PATH=${NEWPATH}")

But this does not:
#set_target_properties(gTestExe  PROPERTIES ENVIRONMENT "PATH=${NEWPATH}")
#set_property(DIRECTORY PROPERTY ENVIRONMENT "PATH=${NEWPATH}")
gtest_discover_tests(gTestExe  PROPERTIES ENVIRONMENT "PATH=${NEWPATH}")

Edit:
The tests themselves work when added using gtest_add_tests.  The issue is the call to discover the tests, during the post build step that gtest_discover_tests registers, fails because the required libraries are not in the PATH.

A: I came across the same issue this morning and I found a (dirty ?) workaround. The reason why it won't work is a bit complicated, but the workaround is quite simple.
Why it won't work
gtest_discover_tests(gTestExe  PROPERTIES ENVIRONMENT "PATH=${NEWPATH}")

Will not work is because the PATH contents are separated by semicolons and therefore are treated by CMake as a list value.
If you look a the GoogleTestAddTests.cmake file (located in C:\Program Files\CMake\share\cmake-3.17\Modules), it treats the PROPERTIES argument with a foreach.
The PROPERTIES value look like this for CMake at this point in the script : ENVIRONMENT;PATH=mypath;mypath2 and will treat mypath2 as a third argument instead of a value for the PATH environment variable.
CMake will then generate the following line :
set_tests_properties( mytest PROPERTIES ENVIRONMENT PATH=mypath mypath2)

Escaping the ; won't work because the list is automatically expended in add_custom_command() in GoogleTest.cmake (l. 420 in cmake 3.17.1) ignoring any form of escaping.
To prevent the cmake foreach to treat each value in the path as a list you can use a bracket argument like :
gtest_discover_tests(gTestExe PROPERTIES ENVIRONMENT "[==[PATH=${NEWPATH}]==]")

The cmake foreach will then treat your argument as one entity. Unfortunately CMake will also put a bracket in the generated code as it contains [ = and maybe spaces :
# This line
if(_arg MATCHES "[^-./:a-zA-Z0-9_]")
  set(_args "${_args} [==[${_arg}]==]")
else()
  set(_args "${_args} ${_arg}")
endif()

resulting in the following generated script :
set_tests_properties( mytest PROPERTIES ENVIRONMENT [==[ [==[PATH=mypath;mypath2] ]==])

And when executing the test cmake will attempt to read the value only removing the first bracket argument as they don't nest.
Possible workaround
So to do this we need CMake to not use bracket argument on our own bracket argument.
First make a local copy of GoogleTestAddTests.cmake file in your own repository (located in C:\Program Files\CMake\share\cmake-3.17\Modules).
At the beginning of your local copy of GoogleTestAddTests.cmake (l. 12) replace the function add_command by this one :
function(add_command NAME)
  set(_args "")
  foreach(_arg ${ARGN})
    # Patch : allow us to pass a bracket arguments and escape the containing list.
    if (_arg MATCHES "^\\[==\\[.*\\]==\\]$")
        string(REPLACE ";" "\;" _arg "${_arg}")
        set(_args "${_args} ${_arg}")
    # end of patch
    elseif(_arg MATCHES "[^-./:a-zA-Z0-9_]")
        set(_args "${_args} [==[${_arg}]==]")
    else()
        set(_args "${_args} ${_arg}")
    endif()
  endforeach()
  set(script "${script}${NAME}(${_args})\n" PARENT_SCOPE)
endfunction()

This will make cmake don't use bracket list on our bracket list and automatically escape the ; as set_tests_properties also treat the ; as a list.
Finally we need CMake to use our custom GoogleTestAddTests.cmake instead of the one in CMake.
After your call to include(GoogleTest) set the variable _GOOGLETEST_DISCOVER_TESTS_SCRIPT to the path to your local GoogleTestAddTests.cmake :
# Need google test
include(GoogleTest)

# Use our own version of GoogleTestAddTests.cmake
set(_GOOGLETEST_DISCOVER_TESTS_SCRIPT
  ${CMAKE_CURRENT_LIST_DIR}/GoogleTestAddTests.cmake
)

Note : In my example the GoogleTestAddTests.cmake is right next to the processing cmake file.
Then a simple call to
 gtest_discover_tests(my_target
   PROPERTIES ENVIRONMENT "[==[PATH=${my_path};$ENV{PATH}]==]"
 )

should work.


text:
Q: Is there a way to change the return value of fn:path()? Given a relatively simple snippet like:
<?xml version="1.0" encoding="UTF-8"?>
<doc>

Irrelevant

   <item>

         something

Not a target

   </item>
   <item>

Relevant.

         Location of relevant content

The target.

   </item>
</doc>

I'm interested in finding the path to the target node.  I can do this, for example:
//div[contains(.,"content")]/p/path()

The output is:
/Q{}doc[1]/Q{}item[2]/Q{}div[1]/Q{}p[1]

While it's probably helpful in other cases, in this particular case, the inclusion of the namespace uri of the target node name is not very informative.
I know I can forcibly strip Q{uri} by using replace():
replace(//div[contains(.,"content")]/p/path(),"Q\{}","")

which outputs the path I want to see:
/doc[1]/item[2]/div[1]/p[1]

But it becomes cumbersome with multiple expressions.
Is there a way to suppress the inclusion of the namespace uri and receive only the local part of the node name? Absent that, is there another way/function (any version of xpath/xquery) to achieve the same result?

A: To roll your own function, in this example ignoring the namespaces, for instance, contrast
declare function local:step($node as node()) as xs:string {
  typeswitch($node)
    case element() return local-name($node) || '[' || (1 + count($node/preceding-sibling::*[node-name() = node-name($node)])) || ']'
    case text() return 'text()' || '[' || (1 + count($node/preceding-sibling::text())) || ']'
    case comment() return 'comment()' || '[' ||  (1 + count($node/preceding-sibling::comment())) || ']'
    case processing-instruction() return 'processing-instruction(' || node-name($node) || ')' || '[' || (1 + count($node/preceding-sibling::processing-instruction()[node-name() = node-name($node)]))|| ']'
    default return ''
};

declare function local:path($node as node()) as xs:string {
    string-join($node/ancestor-or-self::node()!local:step(.), '/')
};

//div[contains(.,"content")]/p/(path(), local:path(.))

https://xqueryfiddle.liberty-development.net/bdxZ8T


text:
Q: Set up kubernetes cluster with multiple pods automatically Sorry if the question is a bit abstract but I am currently getting into GCP.
First of all my goal - I want to set up automatic creation of kubernetes cluster with a number of pods.
What I have so far - I have past few days looking in the GCP and Kubernetes documentation as well as some examples. I have two working bits:

*

*I have created a cluster config with yaml and jinja files and I
can use deployment manager to set them up.
gcloud deployment-manager deployments create my-config --config my-config.yaml

*I have created another configuration yaml file which uses a docker image stored in the GCP Container Registry to start some pods on the cluster above (which again works fine)
kubectl apply -f image-config.yaml --record
My question is is it possible to combine somehow the above into a single config file and start everything up with a single command?
Or if you can point me in the direction of some appropriate example.

A: The Agones project accomplishes this task using a combination of Terraform and Helm as described in the Install with Terraform documentation. There is a single command which builds a GKE cluster and also installs an application into the cluster (e.g. runs some pods).
If you don't want to use Helm and build a full installer for your pods, you can also look at using the Kubernetes Provider to run some simple applications once the cluster has been deployed (check out the google_container_cluster configuration in the GCP provider).

A: Yes that is entirely possible. You should combine the two config files in a multi-document YAML file, the first of which contains a sequence of commands to be executed on document two and following.
---
- gcloud deployment-manager deployments create my-config --config $doc2:my-config.yaml
- kubectl apply -f $doc3:image-config.yaml --record
---
<insert contents of my-config.yaml here>
---
<insert contents of image-config.yaml here>

A small program can load the documents, parse the sequence in the first doc, extract the name of the temporary file to write, dump the appropriate doc to that file, execute the command (removing $docN:), remove the temporary file. My guess is that should be doable in about 15 lines of code.


text:
Q: div inside div is not obeying margin and hiding the child I have a page where I display a series of jobs inside divs. One parent div contain two sub divs. One for text description which occupies 80% of the container and the other one occupies 20% of the container. The right one has the company's picture and two buttons in-line at the bottom for save and view more. However, in one div the buttons are touching the line of the container and in the 2nd one it is moving higher. Also, for the first sub div containing description, I want to have a fixed size text and any other overflow should be like .....
However, it is not happening and in one  div, the text covers the buttons which do not show up.
Also, whenever I click on the save, it scrolls to the top :((
How do I properly format it please? Thank you
Here is my code snippet

.internship_posting {
  margin-top: 20px;
  border-radius: 5px;
  border: 1px solid #00468c;
  margin-bottom: 20px;
  padding: 20px;
  max-height: 250px;
  overflow: hidden;
  position: relative;
}

.internship_desc p {
  white-space: nowrap;
  width: calc(70%);
  overflow: hidden;
  text-overflow: ellipsis;
}

.content_for_right {
  float: right;
  list-style: none;
  align-items: center;
  display: flex;
  justify-content: center;
  width: 20%;
}

.content_for_right a.save {
  color: #00000030;
  font-size: 2.5em;
  margin: auto;
  margin-right: 10px;
}

.heart i.fa-heart {
  color: #f44336;
}

.heart {
  animation: heart 0.5s linear;
}

div a.btn:hover {
  color: rgb(93, 129, 177)
}

div a.btn:active {
  background-color: rgb(99, 175, 226);
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}

@keyframes heart {
  0% {
    transform: rotate(0deg) scale(1.7);
  }
  40% {
    transform: rotate(0deg) scale(1);
  }
  41% {
    transform: rotate(360deg) scale(1);
  }
  100% {
    transform: rotate(0deg) scale(1);
  }
}

Showing internships for {{ industry_type.industry_name }}

          {% for internship, recruiter in posts %}

{{internship.internship_title
              }}

Start Date: {{
              internship.start_date }}   End Date: {{ internship.end_date }

{{ internship.internship_desc | safe}}

                View More>>

      {% endfor %}


text:
Q: Azure SQL as a service linked services to an on-premise SQL Server It would appear that there is no way to make use of linked serveries when running SQL as a services and then try and connect to a on premises SQL server. There is only a way to make use of linked services if both db's are in the cloud. Is there a work around other than moving on prem db to Azure and making use of data-factory
Arthur

A: If your goal is to connect on-prem SQL with an IaaS SQL, you need to install Data Management Gateway. For both on-prem and IaaS SQL, use OnPremisesSqlServer as the linked service type, then you can specify gatewayName. Refer to the document at https://learn.microsoft.com/en-us/azure/data-factory/data-factory-sqlserver-connector


text:
Q: Why does ((unsigned char)0x80) << 24 get sign extended to 0xFFFFFFFF80000000 (64-bit)? The following program
#include <inttypes.h> /*  printf(" %" PRIu32 "\n"), my_uint32_t) */
#include <stdio.h> /* printf(), perror() */

int main(int argc, char *argv[])
{
  uint64_t u64 = ((unsigned char)0x80) << 24;
  printf("%"  PRIX64 "\n", u64);

  /* uint64_t */ u64 = ((unsigned int)0x80)  << 24;
  printf("%016"  PRIX64 "\n", u64);
}

produces
FFFFFFFF80000000
0000000080000000

What is the difference between ((unsigned char)0x80) and ((unsigned int)0x80) in this context?
I guess that (unsigned char)0x80 gets promoted to (unsigned char)0xFFFFFFFFFFFFFF80 and then is bit shifted, but why does this conversion think that unsigned char is signed?
It's also interesting to note that 0x80 << 16 produces the expected result, 0x0000000000800000.

A: The strange part of the conversion happens when converting result of << from int32 to uint64. You are working on a 32 bit system, so the size of integer type is 32 bits. The following code:
 u64 = ((int) 0x80) << 24;
 printf("%llx\n", u64);

prints:
 FFFFFFFF80000000

because (0x80 << 24) gives 0x8000000 which is a 32 bit representation of -2147483648. This number is converted to 64 bits by multiplying sign bit and it gives 0xFFFFFFFF80000000.

A: What you're witnessing is undefined behavior. C99 §6.5.7/4 describes shifting left like this:

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

In your case, E1 has the value 128, and its type is int, not unsigned char. As other answers have mentioned, the value gets promoted to int prior to evaluation. The operands involved are signed int, and the value of 128 shifted left 24 places is 2147483648, which is one more than the maximum value representable by int on your system. Therefore, the behavior of your program is undefined.
To avoid this, you could make sure the type of E1 is unsigned int by type-casting to that instead of to unsigned char.

A: One major difficulty with the evolution of the C standard is that by the time efforts were made to standardize the language, there were not only implementations that did certain things differently from each other, but there was a significant body of code written for those implementations which relied upon those behavioral differences.  Because the creators of the C standard wanted to avoid forbidding implementations from behaving in ways which users of those implementations might rely upon, certain parts of the C standard are a real mess.  Some of the worst aspects concern aspects of integer promotion such as the one you've observed.
Conceptually, it would seem that it would make more sense to have unsigned char should promote to unsigned int than to signed int, at least when used as anything other than the right-hand operand of the - operator.  Combinations of other operators may yield large results, but there's no way any operator other than - could yield a negative result.  To see why signed int was chosen despite the fact that the result can't be negative, consider the following:
int i1; unsigned char b1,b2; unsigned int u1; long l1,l2,l3;

l1 = i1+u1;
l2 = i1+b1;
l3 = i1+(b1+b2);

There's no mechanism in C by which an operation between two different types could yield a type which isn't one of the originals, so the first statement must perform the addition as signed or unsigned; unsigned generally yields slightly less surprising results, especially given that integer literals are by default signed (it would be very weird if adding 1 rather than 1u to an unsigned value could make it negative).  It would be surprising, however, to have the third statement could turn a negative value of i1 into a large unsigned number.  Having the first statement above yield an unsigned result but the third statement yield a signed result implies that (b1+b2) must be signed.
IMHO, the "right" way to resolve signedness-related issues would be to define separate numeric types which had documented "wrapping" behavior (like present unsigned types do), and versus those that should behave as whole numbers, and have the two kinds of types exhibit different promotion rules.  Implementations would have to keep supporting existing behavior for code using existing types, but new types could implement rules which were designed to favor usability over compatibility.

A: C compiler performs integer promotions before executing the shift.
Rule 6.3.1.1 of the standard says:

If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.

Since all values of unsigned char can be represented by int, 0x80 gets converted to a signed int. The same is not true about unsigned int: some of its values cannot be represented as an int, so it remains unsigned int after applying integer promotions.

A: The left operand of the << operator undergoes integer promotion.

(C99, 6.5.7p3) "The integer promotions are performed on each of the operands."

It means this expression:
 ((unsigned char)0x80) << 24

is equivalent to:
 ((int) (unsigned char)0x80) << 24

equivalent to:
  0x80 << 24

which set the sign bit of an int in a 32-bit int system. Then when 0x80 <<  24 is converted to uint64_t in the u64 declaration the sign extension occurs to yield the value 0xFFFFFFFF80000000.
EDIT:
Note that as Matt McNabb correctly added in the comments, technically 0x80 << 24 invokes undefined behavior in C as the result is not representable in the type of the << left operand. If you are using gcc, the current compiler version guarantees that it does not currently make this operation undefined.


text:
Q: How Can I Fix my Method to Update the Derivative Sum of Squares -- Linear Model? I have been trying to solve this problem for a few days right now, but with no success. I showered over stack overflow but have not yet found the answer to my problem. In essence, we have our derivative sum of squares function (drss) which should update the betas, but it is not currently achieving that goal. calcError and y_pred are helper functions for drss. For the parameters betas = np.array(0.0, 0.0) (betas[0] is the intercept), x is the input column of a pandas dataframe, and y is the output column of a pandas dataframe. I feel this code is very close, but I would appreciate help just tweeking this. Thanks in advance for your help. You are really helping not just one but two struggling students.
def calcError(betas, x, y):
    return np.sum((betas[0] + betas[1]*x - y)**2)

def y_pred(betas, x):
    return betas[0] + betas[1]*x

def dRSS(betas, x, y, learning_rate):
    n = float(len(x))
    new_betas = np.array([0.0,0.0])
    db0 = betas[0] - learning_rate*(2.0/n)*np.sum(y_pred(betas,x)-y)
    db1 = betas[1] - learning_rate*(2.0/n)*np.sum(x*(y_pred(betas,x)-y))

    new_betas[0] = db0
    new_betas[1] = db1
    return new_betas

A: If you are calculating sum((betas[0] + betas[1]*x - y)**2) you will calculate the sum of several terms of the form (beta[0] + beta[1]*x - y)**2
You must be aware that the derivative of (f)**2 is 2 * df * f
the derivative of (beta[0] + beta[1] - y w.r.t beta[0] is 1, and w.r.t beta[1] is x.
so your derivatives of with respect to beta[0] and beta[1] can be calculated as follow
def calcGrad(betas, x, y):
    f = (betas[0] + betas[1] * x - y)
    dbeta0 = 2 * np.sum(1 * f);
    dbeta1 = 2 * np.sum(x * f);
    return [dbeta0, dbeta1]

Then if you want to update beta using gradient descent you simply do
dbeta = calcGrad(betas, x, y)
beta[0] -= learning_rate * dbeta[0];
beta[0] -= learning_rate * dbeta[1];


text:
Q: Share a custom made Visual Studio 2010 toolbar I've created a new Toolbar in Visual Studio 2010 and added some custom buttons to it (mainly utilising the External commands).
I'd now like to share that toolbar with others, or be able to "save" it so that I could re-import at a later date.
I know that you can use the Import and Export Settings Wizard to back-up all your settings and re-import them elsewhere, but it does not allow you to Export a single toolbar instance.
Can anyone point me in the right direction of how I might be able to do this?  I don't mind if it's just a settings file I have to save, a VS Extension I have to write, or an installer package I have to create - I'd just like to be able to share my toolbar!

A: I'm working in 2008, but in the Import Export Settings Wizard, limiting it to
General Settings > Menu and Command Bar Customizations
will narrow it down to just your toolbars.
The settings file is all just XML so you can look at stripping out your personal preferences and leaving just the elements of your custom toolbar.


text:
Q: Python issue with appending JSON file I am having an issue, when I want to append the json file to change the state of the device connected to the server socket from connected to disconnected it will add extra }} in my json file which then will break the json file and give me the following error.
json.decoder.JSONDecodeError: Extra data: line 17 column 2 (char 406).
It works normally on the first connect an disconnect no issues but when the devices reconnects to change the state to Connected for some reason it adds the }} at the end.
python code:
def updatedevices(mac, devicename, state, contactone, filename='devices.json'):
 data = """[{mac: {"devicename": devicename,"state": state,"contactone": contactone}}]"""
 with open(filename,'r+') as file:
    file_data = json.load(file)
    if mac not in file_data:
        file_data.update(data)
        file.seek(0)
        json.dump(file_data, file, indent = 4)
    else:
        pass
    if mac in file_data and state == 'disconnected':
        file_data[mac]['state'] = 'disconnected'
        file.seek(0)
        json.dump(file_data, file, indent = 4)
    elif mac in file_data and state == 'connected':
        file_data[mac]['state'] = 'connected'
        file.seek(0)
        json.dump(file_data, file, indent = 4)
    else:
        pass

this is what it does to the json file.
{
"00001": {
    "devicename": "Device Name 1",
    "state": "connected",
    "contactone": "5555558987"
},
"00002": {
    "devicename": "Device Name 2",
    "state": "connected",
    "contactone": "5555558987"
},
"00003": {
    "devicename": "Device Name 3",
    "state": "connected",
    "contactone": "5555558987"
}}
}

At the end it will add
}
}


text:
Q: .NET: TextChanged event for TextBox not always firing, even though KeyUp and KeyDown are firing I'm running into a very peculiar issue.  I noticed that occasionally while typing into my TextBox, I'll lose some keystrokes.  I added a bunch of trace statements in events hooked by this TextBox, and I found that when I lost keystrokes, the KeyUp, KeyDown, and KeyPress events all correctly fired, but the TextChanged event never fired.
Does anybody have any idea why this would happen?  I could write this off as a ".NET bug", but I'd rather figure out if there is a solution here.
In case there is a suggestion that I use the KeyUp/KeyDown events to determine if the text has changed, there is an issue there as well.  KeyUp/KeyDown are called multiple times for each key press, so it would be very difficult to determine if someone was typing the same letter multiple times.

A: Hmmm....
This is going to be a shot, but, you did say you have the KeyUp, KeyDown and KeyPress event handlers right? Have you set the flag e.Handled to true in the event handlers, have a look here:

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            e.Handled = true;
        }

        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            e.Handled = true;
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
        }

Have a look here in the MSDN about this Handled property. (If you have MSDN 2008 SP 1 installed locally, the link is ms-help://MS.MSDNQTR.v90.en/fxref_system.windows.forms/html/dfc80b44-1d79-6315-cbea-1388a048c018.htm)
To quote:

Handled is implemented differently by different controls within Windows Forms.
For controls like TextBox which subclass native Win32 controls, it is
interpreted to mean that the key message should not be passed to the underlying
native control.

If you set Handled to true on a TextBox, that control will not pass the key
press events to the underlying Win32 text box control, but it will still
display the characters that the user typed.

Maybe it is not set i.e. e.Handled = false; thereby preventing the TextChanged Event from firing?
Can you check and confirm this?
Edit: After dreadprivateryan's response, I can suspect (due to lack of code posted), based on his response, e.Handled is true for when Enter key is pressed and false for everything else which in my mind, thinks that is the reason why no further keystrokes are being accepted as a result of this.

*

*Are you trying to set focus to another control upon the Enter key being pressed? It could be that both KeyUp and KeyDown are conflicting...

*Remove the keyboard hook and disable it...

*My suggestion is to change the code completely in this manner as shown, take out either KeyDown or KeyUp Event Handler as they, simplistically put it, are the same, ok, technically, it is designated respectively for when a key is pressed down, and likewise when a key is released. Have a look at this link here. There was a similar question posted here on SO.

In the example below, I used the keyUp event handler to switch focus to the next available control upon enter key being pressed. In the KeyPress event handler, this simply filters the input and only allows numbers 0-9 respectively, anything else gets discarded. Included in that event handler, is the allowance for the backspace key to provide editing.

        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) SendKeys.Send("{TAB}");
        }
        private const string VALID_KEYS = "0123456789";
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (VALID_KEYS.IndexOf(char.ToUpper(e.KeyChar)) != -1 || e.KeyChar == (char)8)
                 e.Handled = false;
            else
                 e.Handled = true;
}

Hope this helps,
Best regards,
Tom.

A: I don't actually know, but I have a random guess: You running in a VM?
One hack you could use is make a timer that reads the text and compares to the previously entered value.  Call the event handler code when it isn't equal to the previously checked value.  When you need to use the final entered value, do one additional check, in case the timer hasn't fired yet.

A: Do you mean the keypress is actually lost and never shows up in the box? Or do you mean you don't get a TextChanged event for every keypress?
I believe the TextChanged event is driven by the operating system's EN_CHANGE notification which is sent via a WM_COMMAND message. I know that certain kinds of messages in Windows are "coalesced" to avoid redundant notifications. For example this can happen with WM_MOUSEMOVE messages and is why you don't receive a mouse move event for every pixel that the mouse moves across the screen.
I can't say for sure but I suspect that the TextChanged event behaves this way as well. I can say though that alternate input methods have this side effect too. When using a Tablet PC input panel, the textbox will not get a TextChanged notification for every character.


text:
Q: Draw multiple rectangle in single image in reactjs I'm trying to draw rectangles on image using x,y,height and width but i can only able to draw one rectangle at a time can't able to draw multiple rectangle in single image.
JSX code:
          {this.state.books.map((object) => (

              <img  src={`data:image/png;base64,${object.image_id}`} style={{ height:`${object.hw[0]}` , width:`${object.hw[1]}`}} alt="" />

              <svg  width={object.hw[1]} height={object.hw[0]} >

             <g >
               <rect  x={object.bbox[0]} y={object.bbox[1] - object.bbox[3]}  width={object.bbox[2]} height={object.bbox[3] }
             style={{stroke:"red",}} fill-opacity="0.0" />
                         <text x={object.bbox[0]} y={object.bbox[1]} font-family="Verdana" font-size="35" fill="red">{object.category_id}</text>
             </g>

               Sorry, your browser does not support inline SVG.
                  </svg>

Confidence:{object.score}

Category Id:{object.category_id}

{object.bbox[0]},{object.bbox[1]},{object.bbox[3]},{object.bbox[2]}

            ))}

i am using map function to iterate through the array but i couldn't able to draw all the rectangles in single image please help me

A: I've done This, and it worked for me, maybe it is useful for you:
const rectInfos = [
       [{top:"0px",left:"0px",color:"green"},{top:"0px",left:"500px",color:"yellow"}],
       [{top:"150px",left:"0px",color:"blue"},{top:"150px",left:"500px",color:"black"}],
    ]
    const rects = rectInfos.map((row,i)=>
        row.map((svgElement,j)=>
            <svg key={`i+${i}+${j}+j`} style={{width:"500px", height:"150px",position: "absolute", top:svgElement.top, left:svgElement.left}}>
                <rect style={{fill:svgElement.color, width:"500px", height:"150px"}} />
            </svg>
        )
    )

    return (

            {rects}

    )
}

This case is for 4 rectangles with the same width and height in a parent div.


text:
Q: IOS Webkit Debug proxy issue - Unable to bind device I am trying to start ios webkit debug proxy by passing the udid and the port number.
Command: ios_webkit_debug_proxy -c 4ea8dd11e8c4fbc1a2deadbeefa0fd3bbbb268c7:27753 -d.
Facing issue while binding the device on port number 27753. Error message,'Unable to bind udid on port 27753-27753'

A: Check this web link https://github.com/appium/appium/blob/master/docs/en/advanced-concepts/ios-webkit-debug-proxy.md, if it helps.

A: Most likely it cannot be bind to the port since it's already taken.
Check if the port is taken by another process (or same type of process that is hanged by some reason) by running sof -t -i tcp:27753 command in terminal.
To find and kill process run sof -t -i tcp:27753 | xargs kill command in terminal, but it's not safe to do in case if you have parallel execution and/or not only ios_webkit_debug_proxy is using port 27753.


text:
Q: Positioned child won't display due to parent's overflow setting Since the parent has overflow-y (which is a must in my real project) the menu-item will not display when hovering.
Is there any workaround so that the parent still has overflow settings and the menu-item will display when hovering as in my code?

#parent {
  height: 100px;
  width: 100px;
  margin: 10px auto;
  background-color: antiquewhite;
  right: 0;
  top: 0;
  overflow-y: auto;
  list-style: none;
  padding: 0;
}
.menu-item {
  position: relative;
}
.menu-item:hover #popup {
  display: block;
}
#popup {
  position: absolute;
  top: 0;
  right: 108%;
  border: 1px solid red;
  background: red;
  color: #fff;
  display: none;
}

    Menu Title 1

Popup data

Menu 2

Menu 3

Menu 4

http://codepen.io/anon/pen/BLRBLk

A: The absolutely positioned pop-up is confined to the bounds of the nearest positioned ancestor. In this case, that's the .menu-item list item, which has position: relative.
This list item is a child of the ul with id parent, which has the overflow-y: auto rule that hides the pop-up.
One workaround is to remove position: relative from .menu-item.
This releases the pop-up from the confines of the ul and, with no other positioned ancestors, makes it relative to the initial containing block (and no longer subject to the parent's overflow rule).

#parent {
  height: 100px;
  width: 100px;
  margin: 10px auto;
  background-color: antiquewhite;
  right: 0;
  top: 0;
  overflow-y: auto;
  list-style: none;
  padding: 0;
}
.menu-item {
  /* position: relative; */
}
.menu-item:hover #popup {
  display: block;
}
#popup {
  position: absolute;
  /* right: 108%; */
  border: 1px solid red;
  background: red;
  color: #fff;
  display: none;
  top: 10px;
  left: 50%;
  transform: translateX(-200%);
}

    Menu Title 1

Popup data

Menu 2

Menu 3

Menu 4


text:
Q: importing my own python modules I have written a small python module called phpcs. I
folder structure
    cs_qa_support
        phpcs
            init.py
            config_file.py
        setup.py
contents of setup.py
from setuptools import setup

setup(name='cs_qa_support',
      version='0.1',
      description='QA Support',
      packages=['phpcs'],
      zip_safe=False)

I installed this using the command
pip install -e .

the file phpcs/init.py is empty
the content of phpcs/confif_file is
class PhpcsConfigFile:
    def __init__(self,configFileName):
        self.__config_file_name = configFileName
    def dump(self):
        print self.__config_file_name

given all of that I want to start using the module
my first attempt
>>> import phpcs
>>> config_file.PhpcsConfigFile
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'config_file' is not defined

second attempt
>>> from phpcs import config_file
>>> config_file.PhpcsConfigFile
<class phpcs.config_file.PhpcsConfigFile at 0x7fe5ef4b7738>

My question is can I avoid typing config_file.PhpcsConfigFile and just use PhpcsConfigFile?
Thanks

A: you can do it like this
from phpcs import config file as con
then do this
con.phpcsConfifFile


text:
Q: Determining the PMF of an internet service provider using 50 modems to serve 1000 customers. I have the exact same question as the person who asked this question: Determining the probability mass function of an internet service provider using 50 modems to serve 1000 customers.
but I couldn't comment on the provided answer (low reputation). But I don't think the one single answer to the post answers why we need to sum over all the possibilities, if there are $\geq$ 50 customers who needs a connection we need to sum from $50, ..., 1000$:
$$
P(X = 50) = \sum_{k=50}^{1000} {1000 \choose k} 0.01^k (0.99)^{1000 - k}
$$
Could somebody elaborate more on as to why we need to do the summation?
Because for when $k < 50$, this is not the case:
$$
P(X = k) = {1000 \choose k} 0.01^k (0.99)^{1000 - k}, \hspace{2 cm} k = 0..49
$$
which I don't fully understand why.

A: The problem is ambiguously stated. The assumption there is "customer in need of a connection is assigned to an unused device if available". With that clarification the first customer uses any 1 modem, second any other modem (and two are used) and with $k\leq 49$ it's a matter of k successes in a Binomial distrubution with probability p and 1000 trials.
With 50 or more customers there are no unused modems, X=50 for 50 successes (50 customers), 51 successes (51 customers) and so on, the probabilities need to be summed. We can also say $P(X=50)=1-\sum_{c=0}^{49}P(c\ customers\ need\ a\ connection)$, but with these values the sum will round up to 1 with low precision.
If customers could be assigned to the same modem with unused modems available, the problem is more interesting.


text:
Q: open cygwin.bat using Excel VBA's `Shell` and execute command Is there a way to open cygwin.bat using Excel VBA's Shell command and execute commands?
For ex;
How do I execute head data.csv through Excel VBA's Shell?
The following doesn't work;
Private Sub CommandButton1_Click()
    Dim out, cmd As Variant
    cmd = "C:\cygwin\Cygwin.bat" & "head data.csv"
    out = Shell(cmd, vbNormalFocus)
End Sub

A: You can call head.exe directly in your call to Shell. It is in the cygwin/bin directory.


text:
Q: FCM: Sending notification via Firebase Console vs Postman/curl Does anyone know the difference between sending notification by firebase console and by postman using POST request: https://fcm.googleapis.com/fcm/send
As I have observed, when we send notification via Firebase console, the onMessageReceived callback is executed when user clicks on notification whereas when we send notification by Postman, The onMessageReceived is executed as soon as notification is received.
What is the difference between both ways?
Thanks!


text:
Q: 0 current in a circuit using tunnel diode Suppose we have a diode with negative differential resistance of -40 ohm in the region of 0.3-0.5 V and we put it in parallel with a 40 ohm resistor:

simulate this circuit – Schematic created using CircuitLab
Now Rt = R1*R2/R1+R2 = -1600/0 = infinity. So no current should flow. Is that correct?

A: Current will flow, but small changes in V1 will not change that current by much.
Differential resistance \$\ne\$ resistance.
Edit: See below for a representation of the tunnel diode transfer function (from here):

The negative differential resistance is the negative slope between Ip and Iv. But you may notice that I is always positive. In addition to that positive current through the tunnel diode we also have the 10mA going into the 40\$\Omega\$ resistor.

A:
So no current should flow.Is that correct?

No, this is not correct.
You are over-simplifying things.
Take a look at this picture from Wikipedia

You see that from 0 to 13mV the
resistance of this tunnel diode is about (delta 0.013V/0.084A= 1.5 )  +1.5 ohms.
Then, from 13mV up to 54mV it becomes (delta 0.051V/0.0067A= 7.6 ) -7.6 ohms.
Then from 67mV and up it becomes (delta 0.020V/0.0031A= +6.5) +6.5 ohms.
So if you were to put a 7.6 ohms resistance in parallel with the diode you would
end up with a Voltage .vs. Current curve that would look like this.

Explanation:  When the tunnel diode negative resistance involves a decrease in current (from 13mV up to 64mV) then an equivalent increase in current from the parallel resistor of +7.6 ohms will compensate and the sum of both device current will create a zero increase current for this region. Beyond 64mV both device exhibit a positive resistance hence the current shows a steady increase.
So, when you mention that "infinite" resistance you are half correct. Only in the region of negative resistance of the tunnel diode will an equivalent impedance equate to infinity. The sum of current could never be zero because some finite quantity of current is necessary for the tunnel diode to enter the negative resistance region, but infinite impedance is possible, only within the tunnel region of the diode.

A: To complement the other answers, and since you ask about it in a comment, let me recall that for a two-terminal, possibly nonlinear resistance the differential resistance is defined as
$$r = \frac{\mathrm{d}v}{\mathrm{d}i}$$
where \$v\$ is the voltage across the element and \$i\$ is the current crossing it, and the derivative is calculated around the operating point. Likewise, we can define the differential conductance as
$$g = \frac{\mathrm{d}i}{\mathrm{d}v}.$$
For a linear resistor, for which the consitutive relationship is given by \$v = Ri\$ or \$i = Gv\$, the differential resistance and the differential conductance are constant, equal to \$R\$ and \$G\$, respectively, independent of the operating point. For a nonlinear resistor, like a tunnel diode, it is \$i=f(v)\$ and the differential parameters change, instead, with the operating point, that is, \$r = r(i)\$ and \$g = g(v)\$.
Now what happens when you connect a nonlinear element such as a tunnel diode in parallel to a linear resistance?
Label as 1 the nonlinear element and as 2 the linear one. Since the two elements are driven by the same voltage, it's better to use conductances. The total current is
$$i = i_1+i_2 = f(v)+Gv.\tag{1}$$
For the tunnel diode \$f(v)>0\$ when \$v>0\$, and thus the current is never zero for positive \$v\$. Now, let's differentiate (1) with respect to the common applied voltage \$v\$,
$$\frac{\mathrm{d}i}{\mathrm{d}v} = \frac{\mathrm{d}i_1}{\mathrm{d}v}+\frac{\mathrm{d}i_2}{\mathrm{d}v} = g(v)+G.$$
Thus, if for a certain applied voltage \$g(v) = -G\$, we get
$$\frac{\mathrm{d}i}{\mathrm{d}v} = 0,$$
that is, the slope of the tangent line to the \$i\$-\$v\$ curve of the compound element is horizontal, as shown in the answer by Fred Cailloux. This, however, does not imply a total current of zero, as explained in the above.

A: The "mystic" phenomenon of negative differential resistance (NDR), particularly the OP's N-shaped NDR, can be easily understood by the extremely simple and intuitive concept of dynamic resistance. It can be easily demonstrated by a simple electrical experiment where a variable voltage source V drives a variable resistor R (rheostat). If you don't mind, let you control the source and I will control the rheostat.

(The picture is from my Wikibooks story about NDR).
Now imagine that you are increasing the voltage across the rheostat and, at the same time, I start to increase its resistance. Depending on the rate of change, the current will increase more slowly, will not change or even will decrease. This will create the illusion of increased, infinite or "negative" resistance.
So this type of negative resistance is just a vigorously changing dynamic resistance (in the same direction as the input voltage source). If we connect such a "super dynamic resistor" in parallel with an ordinary resistor with equivalent "positive" resistance (OP's circuit), we will get a "super dynamic current divider" that maintains a constant (not zero) total current in such a simple way. In terms of resistance, this means the total differential resistance is infinite... but it is hard to imagine.
See more in my Wikibooks story about NDR.


text:
Q: Export Data from GraphenDB to import locally Does anybody know how to import the data from GraphenDB into a local DB? The export from graphendb.com gives a zip file with a lot of files. I am not sure how to import those into a local instance of neo4j. Below are some of the contents from the zip folder:

A: Copy the contents of that zip file into path/to/neo4j/data/graph.db in a local instance of Neo4j. Then restart the Neo4j server.
Or, if you are using the desktop Neo4j application, just click "Choose" and point it to the extracted archive.


text:
Q: retrieving rows asynchronously with html selectbox jquery and php So I am currently working with a list of stores that are organized by state. instead of just having them all listed on the page i wanted to use a Select Box where you obviously select a state and then the stores in that state appear asynchronously without hitting a submit button...I feel like i know the theory behind it, I am just looking for a good example/tutorial to work from
thanks for any help
skv

A: You can try to make a search for ajax php dropdown tutorial, as a quick guidance all you need to do is , run a ajax request to your server with the selected state, and fill the next dropdown with the store names, i will paste sample code here but still you need to modify it depending upon your needs.
HTML STRUCTURE
<select name="state" id="state">
<option value="State1"> State 1 </option>
<option value="State2"> State 2 </option>
<option value="State3"> State 3 </option>
</select>

<div id="store_dropdown">
</div>

Jquery Ajax Request
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">
    $(function(){
        function getStores(){
            data = 'state=' + $('#state').val();
            $.post('getStores.php',data,function(response){
                $('#store_dropdown').val(response);
            })
        }

        $('#state').keyup(getStores);
        $('#state').keydown(getStores);
        $('#state').mouseup(getStores);
        $('#state').mousedown(getStores);
    })
</script>

Php Code
    $state = $_POST['state'];
// here goes your sql query to the database

// run a while loop with the fetched data

$output = '<select name="store_name">';
while($row = mysql_fetch_array($sql))
{
    $output .= '<option value="'.$row['store_name'].'">'.$row['state_name'].'</option>';
}
$output .= '</select>';
echo $output;

A: I would create your select box of states and a select container for your stores;
<select id="state">
    <option value="">Select State</option>
    <option value="AL">Alabama</option>
    ...
</select>
<select id="stores"></select>

then set a change event in jquery to listen for your state select box to change
$('#state').change(function(){
    if($(this).val()==''){
        $('#stores').html('<option value=""></option>');
        return;
    }
    $.ajax({
        type:"POST",
        url:"PATH_TO_PHP",
        data:"state="+$(this).val(),
        success:function(x){
            $('#stores').html(x);
        }
    });
});

then on your php side retrieve the state, find the stores and return the options
$state = $_POST['state'];

// $stores = SQL QUERY TO GET STORES

echo '<option value="">Choose a Store</option>';
foreach($stores as $s){
    echo '<option value="'.$s.'">'.$s.'</option>';
}


text:
Q: C# anonymous function inside lambda I'm trying to work out the syntax for using an anonymous function inside the lambda of a linq .Where() call.
I'm using the Where to filter certain items from a list.
I want each part of the filter logic inside the Where.  The logic is only useful inside the filter so I don't want to have to define any functions outside.
Here's a simplified & generalised example:
var filtered = myEnumerable.Where(item =>
    item.PropertyA == 1 ||
    item.PropertyB == 2 ||
    item =>
    {
        var heavyResult = GetStuff(item); // Some heavyweight processing
        return heavyResult.IsSomethingTrue() && heavyResult.IsSomethingElseTrue();
    });

So I want the third line in the Where() to be an anonymous function taking item and returning a boolean.
Also, the function being called after the checks on PropertyA and PropertyB is intended to limit having to call GetStuff() if either of those lightweight comparisons already evaluated as true.
I can't do it all inline because I need to evaluate two properties from heavyResult.
This seems like it should be simple, but I don't seem to be able to find the right syntax, either by experimenting or Googling.

A:
I can't do it all inline because I need to evaluate two properties from heavyResult.

You can do it inline, its just you need to wrap the entire thing in {} and use the return keyword.
var filtered = myEnumerable.Where(item =>
    {
        var test = item.PropertyA == 1 || item.PropertyB == 2;
        if(test)
          return true;
        var heavyResult = GetStuff(item); // Some heavyweight processing
        return heavyResult.IsSomethingTrue() && heavyResult.IsSomethingElseTrue();
    });

To be honest though - doing something that even that simple inline is probably the wrong choice. Extract it into a function, with a meaningful name, and your code is self documenting
var filtered = myEnumerable.Where(ADescriptiveNamedFunctionSelfDocumentsYourCode);

A: Firstly, multiline lambdas are a really bad idea.
They were intended as simple functional representations f(x)= ... stuff.
You can't do this the way you're thinking because you first want to call a function, capture its result, & then call 2 different methods on that object.
You can do this more simply by moving the delegate out of the lambda.
The latest version of C# supports local functions, which may be what you want. But you can still do this with anonymous functions in C# 6.
I've also shown how you can do this with another method in HeavyResult or an extension method it's not feasible to change HeavyResult.
In the code below, you would use only one of the options from
validator(item) ||
GetStuff(item).IsAllTrue() ||
GetStuff(item).IsAllTrueExt()

Here's the full code:
public static class Program
{
    static void Main(string[] args)
    {
        var myEnumerable = new List<int>() { 1, 2, 3, 4, 5 };

        Predicate<int> validator;
        validator = delegate (int item)
        {
            var heavyResult = GetStuff(item);
            return heavyResult.IsSomethingTrue() && heavyResult.IsSomethingElseTrue();
        };

        var filtered = myEnumerable.Where(item =>
        item >= 1 ||
        item <= 200 ||
        validator(item) ||
        GetStuff(item).IsAllTrue() ||
        GetStuff(item).IsAllTrueExt()
        );
    }

    public static bool IsAllTrueExt(this HeavyResult hr)
    {
        { return hr.IsSomethingTrue() && hr.IsSomethingElseTrue(); }
    }

    public static HeavyResult GetStuff(int item)
    {
        return new HeavyResult(item);
    }

    public class HeavyResult
    {
        public HeavyResult(int value)
        {
            Value = value;
        }

        int Value { get; }

        public bool IsSomethingTrue()
        {
            { return Value >= 5; }
        }

        public bool IsSomethingElseTrue()
        {
            { return Value <= 50; }
        }

        public bool IsAllTrue()
        {
            { return IsSomethingTrue() && IsSomethingElseTrue(); }
        }

    }
}


text:
Q: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required. C# I've tried with Gmail (tried activating less secure apps, 2 steps verification and apps password, zone time, etc..).
Also, I tried sending emails with outlook and I'm having the same error.
In the console, I get the followed error: POST 500
Notes:

*

*I don't have access to the Server.

*This is working on my Local.

*The website uses Plesk.

*The Gmail code was working before, but after changing the password is not working (we activated less security apps).

*In Gmail code, I've tried different ports.

Code:
MailMessage message = new MailMessage();
message.From = new MailAddress(model.EmailAddress);
message.To.Add("email@gmail.com");
message.Subject = string.Format("Mensaje de {0} ({1}) - {2}", model.FirstName, model.EmailAddress, model.Subject);
message.Body = model.Message;

SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("email@gmail.com", "password");
client.Send(message);

/*
MailMessage mc = new MailMessage(System.Configuration.ConfigurationManager.AppSettings["Email"].ToString(), "email@hotmail.com");
mc.Subject = string.Format("Mensaje de {0} ({1}) - {2}", model.FirstName, model.EmailAddress, model.Subject);
mc.Body = model.Message;
mc.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient("smtp.office365.com", 587);
smtp.Timeout = 1000000;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
NetworkCredential nc = new NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["Email"].ToString(), System.Configuration.ConfigurationManager.AppSettings["Password"].ToString());
smtp.UseDefaultCredentials = false;
smtp.Credentials = nc;
smtp.Send(mc);
        */


text:
Q: Switch Like Interface using JRadioButtons Can anyone please tell me how to make an interface like that which is been shown below.
Right now i'm using two JRadioButton for implementing that task.
My code which i've done is shown below
JRadioButton but1 = new JRadioButton("Option 1");
JRadioButton but2 = new JRadioButton("Option 2");

ButtonGroup db=new ButtonGroup();
db.add(but1);
db.add(but2);

But how can we make the interface shown in the picture which does the same task that i've done through JRadioButtons.

A: *

*required custom Icons and two JToggleButtons chained by ItemListener

*create JSlider with two ranges (required custom painting)

*great idea by @oliholz


text:
Q: Color of polyline in Aladin lite I am using Aladin lite library in my web app. I would like to create interactive map of sky with all constellations. However, when I add new overlay layer and draw lines of any constellation, some lines are brighter and wider then others. Here is fiddle. I would like to have all lines with lineWidth: 1 and color: '#FFF'. Is there any way fix it?

const aladin = A.aladin('#aladin-lite-div',  {survey: "P/DSS2/color", fov: 30, target: "Betelgeuse" })

const constellations = A.graphicOverlay({ color: '#FFF', lineWidth: 0.5 })
aladin.addOverlay(constellations)

// Each array item is [[startX, startY], [endX, endY]] of single line.
const lines = [[[72.46, 6.961], [72.653, 8.9]], [[72.46, 6.961], [72.802, 5.61]], [[72.46, 6.961], [81.283, 6.35]], [[72.653, 8.9], [73.724, 10.15]], [[72.802, 5.605], [73.563, 2.44]], [[73.563, 2.441], [74.637, 1.71]], [[73.724, 10.151], [74.093, 13.51]], [[74.093, 13.514], [76.142, 15.4]], [[76.142, 15.404], [77.425, 15.6]], [[78.635, -8.202], [81.119, -2.4]], [[81.119, -2.397], [83.002, -0.3]], [[81.283, 6.35], [83.002, -0.3]], [[81.283, 6.35], [83.785, 9.93]], [[81.283, 6.35], [88.793, 7.41]], [[83.002, -0.299], [84.053, -1.2]], [[83.785, 9.934], [88.793, 7.41]], [[84.053, -1.202], [85.19, -1.94]], [[85.19, -1.943], [86.939, -9.67]], [[85.19, -1.943], [88.793, 7.41]], [[88.595, 20.276], [90.98, 20.14]], [[88.595, 20.276], [91.893, 14.77]], [[88.793, 7.407], [90.596, 9.65]], [[90.596, 9.648], [92.985, 14.21]], [[90.98, 20.138], [92.985, 14.21]], [[91.893, 14.768], [92.985, 14.21]]]

for (const line of lines) {
        const polyline = A.polyline(line)
    constellations.add(polyline)
}

<link rel="stylesheet" href="https://aladin.u-strasbg.fr/AladinLite/api/v2/latest/aladin.min.css" />

A: What you are seeing is caused by the spherical projection...
If you individually zoom in the lines they look the same
See my example below, it should be a bunch of identical parallel lines, but they do not quite look the same

const aladin = A.aladin('#aladin-lite-div',  {survey: "P/DSS2/color", fov: 100, target: "Betelgeuse" })
const constellations = A.graphicOverlay({ color: '#FFF', lineWidth: 0.5 })
aladin.addOverlay(constellations)

for (i = -10; i < 20; i++) {
    const polyline = A.polyline([[70, i], [105, i]])
    constellations.add(polyline)
}
<link rel="stylesheet" href="https://aladin.u-strasbg.fr/AladinLite/api/v2/latest/aladin.min.css" />

What can we do?

*

*If we increase the lineWidth they look a bit more uniform

*Not use Aladin, get the image you need and draw directly to a canvas


text:
Q: Deriving the Cauchy-Riemann from the derivative of the complex conjugate. I am trying to prove the Cauchy-Riemann conditions naturally arise from the condition that:
$$\frac{\partial f(z,z^{*})}{\partial z^{*}} = 0$$
But I'm having trouble starting from the definition of a derivative and get stuck:
$$\frac{\partial f(z,z^{*})}{\partial z^{*}} = \lim_{\Delta z\to 0}\frac{f(z,z^{*}_{0}+\Delta z)-f(z,z^{*}_{0})}{\Delta z}$$
Am I going about this the right way? Is there a better way to do this?
Thanks!

A: HINT:
You've written the correct definition of the derivative.  But instead, note that
$$  \frac{\partial f}{\partial z^*}=\frac12\left(\frac{\partial f}{\partial x}+i\frac{\partial f}{\partial y} \right)\tag1 $$
Let $f=u+iv$ and set the right-hand of $(1)$ to $0$ .  Can you finish now?


text:
Q: Writing a queue to a properties file in Java Is there an easy way to write a queue to a file in Java so it can be read back?
My programme currently saves arrays to a properties file in comma delimited format. This is easy, as the array can be iterated over.
My programme also features queues. Is my only option with a queue, to remove every item from the queue and re-add them whenever I want to write all the elements of the queue to file?
What is the easiest way of implementing this?
I ideally want to save the information in the same properties file my other arrays are written to.

A: You could try something like this:
FileOutputStream fos = null;
ObjectOutputStream os = null;

try {
    fos = new FileOutputStream(YOUR_FILE_NAME);
    os = new ObjectOutputStream(fos);

    for(YourObjectType current : YourQueue){
        os.writeXXX(current);  //Where XXX is the appropriate write method depending on your data type
        os.writeChars(",");  //Since you mentioned wanting a comma delimiter..
    }
} catch(IOException e){
   e.printStackTrace();
} finally {
    if(fos != null) fos.close();
    if(os != null) os.close();
}

A: The simplest solution is to write the queue as a single collection.
public static void write(String filename, Collection queue) throws IOException {
    try(ObjectOutputStream oos = new ObjectObjectStream(new FileOutputStream(filename))) {
        oos.writeObject(queue);
    }
}

to read this
public static void read(String filename, Collection toAddTo) throws IOException, ClassNotFoundException {
    try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
        toAddTo.addAll((Collection) ois.readObject());
    }
}


text:
Q: Can't able to start CKAN Redis service using docker. It's always in queued I have an application with 2 user roles, Admin and Customer, With 3 states, Open, In Progress & Closed.
When the Customer adds a question on the forum, the state is Open, and I want to notify Admin and Customer using Email.
Admin can change the state to In Progress or Closed and any state change should notify all the Admins and the Customer who has posted the question.
The application is on Docker, and Redis is being used for Emails.
Problem: I am facing an issue while sending an email to any user using CKAN from docker deployment. I changed the email credentials using the docker paster command. Also, uncomment the Redis URL in the .ini file. But can't able to send mail the Redis worker always in queue state.
RUN paster --plugin=ckan config-tool ${APP_DIR}/production.ini "ckan.site_url = ${CKAN_SITE_URL}"
RUN paster --plugin=ckan config-tool ${APP_DIR}/production.ini "ckan.activity_streams_email_notifications = ${CKAN_ACTIVITY_STREAMS_EMAIL_NOTIFICATION}"
RUN paster --plugin=ckan config-tool ${APP_DIR}/production.ini "smtp.server = ${CKAN_SMTP_SERVER}"
RUN paster --plugin=ckan config-tool ${APP_DIR}/production.ini "smtp.starttls = ${CKAN_SMTP_STARTTLS}"
RUN paster --plugin=ckan config-tool ${APP_DIR}/production.ini "smtp.user = ${CKAN_SMTP_USER}"
RUN paster --plugin=ckan config-tool ${APP_DIR}/production.ini "smtp.password = ${CKAN_SMTP_PASSWORD}"
RUN paster --plugin=ckan config-tool ${APP_DIR}/production.ini "smtp.mail_from = ${CKAN_SMTP_MAIL_FROM}"
RUN paster --plugin=ckan config-tool ${APP_DIR}/production.ini "CKAN_SMTP_SERVER = ${CKAN_SMTP_SERVER}"

Any reference and guide would be a great help for me.
Thanks

A: Few things to note here:

*

*It looks like you have set the activity_streams_email_notifications to True and smtp.mail_from, if not make sure they are set?

*Did you correctly set site_url because CKAN will use it to generate links?

*You need cron job to call send_email_notifications so in your Dockerfile add CMD for doing that.


text: Q: Failed to Install PyQt5 in Jetson Ubuntu Env with Python 3.8.16 I am having Jetson with Ubuntu Environment and using Python 3.8.16. I need to install PyQt5 and I have follow many suggestions from the open source to install pyqt5, including upgrade my pip to the latest version. However, I am still failed to install as it prompt out failed to build wheel for sip during the installation. Any suggestion to solve this?


text:
Q: How to draw a ring with CustomPainter in flutter? I'm trying to draw a half ring with CustomPainter class, which you can see in the below image (which is in light purple & light orange colours)  but unable to drawn it.
I can just only draw circle, square and line.
Code:
class MakeCircle extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint();
    paint.color = Colors.white12;
    var position = Offset(size.width /10, size.height / 10);
    canvas.drawCircle(position, 40.0, paint);
  }
  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}

this can only draw circle.

A: you must use PaintingStyle.stroke for your Paint object and also use the Path class to draw your arc
I create an example for you, please test it:
import 'dart:math' as math;

import 'package:flutter/material.dart';

main() {
  runApp(MaterialApp(
    home: Home(),
  ));
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SizedBox(
          width: 300,
          height: 300,
          child: CustomPaint(
            painter: MakeCircle(strokeWidth: 50,strokeCap: StrokeCap.round),
          ),
        ),
      ),
    );
  }
}

class MakeCircle extends CustomPainter {
  final double strokeWidth;
  final StrokeCap strokeCap;

  MakeCircle({this.strokeCap = StrokeCap.square, this.strokeWidth = 10.0});

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.blue
      ..strokeCap = StrokeCap.round
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.stroke; //important set stroke style

    final path = Path()
      ..moveTo(strokeWidth, strokeWidth)
      ..arcToPoint(Offset(size.width - strokeWidth, size.height - strokeWidth),
          radius: Radius.circular(math.max(size.width, size.height)));

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}


text:
Q: Among, in, of, out of for choices Do all of these make sense?

*

*He was the only chosen person out of a hundred others.

*He was the only chosen person of a hundred others.

*He was the only chosen person among a hundred others.

*He was the only chosen person in a hundred others.

It's just that I've seen all four in, among, out of and of used with choosing and selecting:

*

*Two shots in ten tries hit the target.

*The house was among the trees.

*Only three of five songs were recorded today.

*They were out of a bigger group of animals.

Are they all correct?

A: Of your sentences

He was the only chosen person out of a hundred others.

Your self-made sentences are not really analogous to your examples.
More similar examples might be

He was the only one out of a hundred others chosen.
  He was the only chosen person from among a hundred others.
  He was the only chosen person, one in a hundred.

A: You can choose something from a pool of options. Out of your self-written sentences, only the first one,

He was the only chosen person out of a hundred others,

is correct as it makes use of "out of", which is analogous to "from".
Even in the example sentences, you gave, only the last one,

They were out of a bigger group of animals,

which uses "out of", conveys the sense of a particular thing being chosen from a pool of options.


text:
Q: Django set last_online middleware not working I want to log the last time my user has accessed the website and have implemented this middleware. It however does not store the most updated time.
middleware.py
class LastOnlineMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        return self.get_response(request)

    def process_request(self, request):
        if request.user.is_authenticated():
            request.user.profile.last_online = timezone.now()
            request.user.profile.save()

models.py
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    last_online = models.DateTimeField(default=timezone.now)

A: It dose not work because process_request is not called in __call__ function.
You should change __call__ function like below.
def __call__(self, request):
    self.process_request(request)
    return self.get_response(request)

or to make LastOnlineMiddleware subclass of django.utils.deprecation.MiddlewareMixin.
If you use MiddlewareMixin, there is no need to define __init__ and __call__ function. You just needed to define process_request function written in the question.


text:
Q: Controlling the keyboard and mouse of a VM with Python I am currently working on a project that involves simulating keystrokes and mouse moves in a virtual machine, if possible in Python. That is, a Linux distro would be running in a VM and my Python script running on the host (MacOS) would be able to move the mouse pointer and simulate keystrokes inside that Linux VM. Additionally, I would like to be able to get the display output of the VM in my Python script running on the host (there might be some conversion needed to get the image in the right format but this is not an issue).
I have done some research and it seems that VirtualBox has an SDK that allows for such things (see for example Sending mouse or touch events to VirtualBox VM from host shell?). However, it seems that the Python bindings are old and I can't seem to get them to work on a recent version of MacOS.
Does anyone have experience with this (I hardly found any mention of controlling a VM from the host online, but I might be searching for the wrong keywords)? If so, is there another way to achieve this? It seems that most VM software does not even have an API that allows external programs to interface with the VMs.
Thanks!


text:
Q: symfony 1.4 forms: Using  rather than
* When calling a form using
print $widget->render()

rather than printing

       <input ...>

How can I have it print

    <input ...>

PS:  in my form:
public function configure()
{
    $this->widgetSchema->setFormFormatterName('list');
}

A: You will have to create your own form schema formatter class as explained here. For example, to use a paragraph you can just redeclare the $rowFormat variable:
#lib/widget/sfWidgetFormSchemaFormatterParagraph.class.php

class sfWidgetFormSchemaFormatterParagraph extends sfWidgetFormSchemaFormatter
{
    protected $rowFormat = "

                         %label% \n %error%
 %field%
                         %help% %hidden_fields%\n
\n";
}

If you want to use this format for all forms of your project add it to your ProjectConfiguration class (and remove the $this->widgetSchema->setFormFormatterName('list') from your form):
class ProjectConfiguration extends sfProjectConfiguration
{
    public function setup()
    {
      // ...

      sfWidgetFormSchema::setDefaultFormFormatterName('paragraph');
    }
 }

If you want to use it only for one form, add this your form class:
    public function setup()
    {
         $this->widgetSchema->addFormFormatter('paragraph', new sfWidgetFormSchemaFormatterParagraph($this->widgetSchema));
         $this->widgetSchema->setFormFormatterName('paragraph');
         parent::setup();
    }

A: Just look at sfWidgetFormSchemaFormatterListand sfWidgetFormSchemaFormatter.class.php. You can make your own schema from that, let's say sfWidgetFormSchemaFormatterParagraph, and change the properties of the class to match your needs. (you probably need to change only $decoratorFormat and $rowFormat. Something like:
$rowFormat = "
 %error%%label%\n  %field%%help%\n%hidden_fields%
"
$decoratorFormat = "%content%"


text:
Q: Where can I see how OCaml's standard library functions are implemented? I'm interested in how List.init and other library functions are implemented in OCaml. Where can I see the implementations? I checked this official link: https://v2.ocaml.org/api/List.html and only found the function signatures.

A: OCaml, including its standard library, is entirely open source and at time of writing hosted on GitHub here: https://github.com/ocaml/ocaml/
The List.init function (located here) is split across a couple utility functions and actually has two different implementations with different performance characteristics that is selected based on a stack size heuristic and the length of the requested list:
let rec init_tailrec_aux acc i n f =
  if i >= n then acc
  else init_tailrec_aux (f i :: acc) (i+1) n f

let rec init_aux i n f =
  if i >= n then []
  else
    let r = f i in
    r :: init_aux (i+1) n f

let rev_init_threshold =
  match Sys.backend_type with
  | Sys.Native | Sys.Bytecode -> 10_000
  (* We don't know the size of the stack, better be safe and assume it's
     small. *)
  | Sys.Other _ -> 50

let init len f =
  if len < 0 then invalid_arg "List.init" else
  if len > rev_init_threshold then rev (init_tailrec_aux [] 0 len f)
  else init_aux 0 len f

A: If you have an OCaml source release, you can find the standard library implementation in the stdlib directory. The list implementation is stdlib/list.ml.
Here is List.init:
let rec init_tailrec_aux acc i n f =
  if i >= n then acc
  else init_tailrec_aux (f i :: acc) (i+1) n f

let rec init_aux i n f =
  if i >= n then []
  else
    let r = f i in
    r :: init_aux (i+1) n f

let rev_init_threshold =
  match Sys.backend_type with
  | Sys.Native | Sys.Bytecode -> 10_000
  (* We don't know the size of the stack, better be safe and assume it's
     small. *)
  | Sys.Other _ -> 50

let init len f =
  if len < 0 then invalid_arg "List.init" else
  if len > rev_init_threshold then rev (init_tailrec_aux [] 0 len f)
  else init_aux 0 len f

You can find recent OCaml releases on github. Here is a link to the latest release at the present time (I believe): OCaml 4.14.0 source tgz

A: You can always read the implementation in the sources: https://github.com/ocaml/ocaml/blob/trunk/stdlib/list.ml


text:
Q: What does the operator ! mean in F# What does the "!" operator means in F#?
For example it is here
    let x = !a * !b
    yield x

or here
    c := !c + 1.0

A: It's  ! (bang) operator
as msdn document says,

*

*Dereferences a reference cell.

*After a keyword, indicates a modified version of the keyword's    behavior as controlled by a workflow.

A: It's used to dereference a cell.  Check this page.


text:
Q: Erlang: How is distel for emacs "reload" command supposed to work? Here is what I do, based on how I thought reload should work.

*

*I start an erlang node.

*I connect to that node in distel.

*I edit a buffer whose beam file is in the node from step 1's beam paths. That means it's loaded, right?

*I edit an erlang buffer which represents a module loaded in a step one's node. I add a function.

*I run reload in distel.

*I try to run the new function, and it says it's not defined.

A: I guess you have to compile first. This makes sense except that I wish then that there were a compile and reload command. In the end, I found it easier to just create an Emakefile like so:
{"rest_api/src/*", [{outdir,"rest_api/ebin"},{i, "include"}]}.

...in the same directory as the start script for my application, then run make:all([load]) as needed in the erlang shell.


text:
Q: PnPJs Modern site webpart without SPFx - 404 error Want to use PnPJs on a content editor webpart added to a modern page. All attempts to use pnp results in a 404. What is seen is that pnp is inserting /SitePages into the API call.
https://{server}/sites/{site}/SitePages/_api/search/postquery
There are some solutions for SPFx where context is corrected with some modification to props; however, SPFx is not possible for me due to organization policy/access. Is there a way to set web to the correct url apart from SPFx?
Here is the code attempted:

A: You. need to get the PNPJS library loaded into the page before you can use it.
You'll need to add the built pnpjs libraries somewhere on your tenant, and the add script tags to your page to reference the libraries,


text:
Q: How to plot frequency distribution using seaborn in python/pandas for a bipartite text based graph data I have a dataframe with 70k rows, & it looks like this:
mirna   gene_id
osa-miR2873a    Os01g0100100
osa-miR169d Os01g0100100
osa-miR169a Os01g0100100
osa-miR396a-3p  Os01g0100200
osa-miR396b-3p  Os01g0100200
...             ...

I am using matplotlib & seaborn for plotting the data.
& I have managed to calculate the frequency using the value_counts() pandas function.
I need to plot a graph to show how many times a certain range of frequencies of 'mirna' occurences appear in the dataset. For example how many 'mirna' have 1-5 mirna-gene_id pairs, or 5-15 pairs, or 15-30 pairs & so on...
So essentially the plot should show that (1-5) pairs occur x-times, (5-15) pairs occur y-times etc.If I can plot the values in sorted order, all the more better. I have tried sns.distplot() but it is not working for me.
Any clues? Thanks.

A: You could groupby mirna and summarize by gene_id count. Then you could just do a histogram of that.


text:
Q: What is Flyway baseline feature good for? Despite reading all available docs on Flyway website, I still don't understand what is baseline good for. Could somebody explain it in plain English and mention some use cases for this command?

A: Baselining a database at version V1_0__baseline.sql, for example, instructs Flyway to only apply migration scripts that have been created after V1_0. It does this by inserting a migration entry in the SCHEMA_VERSION table used by Flyway. When you run a migration, available migration scripts will only be applied if their version is higher than the baseline version.
Example
You wish to use Flyway on a production and development database. You create a schema only dump of production. This will be the first migration script applied when you create a new empty database using Flyway.
However, because your existing production and development machines are already on this version, you don't want to apply this initial script. To prevent this, you create a SCHEMA_VERSION table and insert "1_0" into the table to instruct Flyway that the database is already at 1_0. Instead of manually creating this table and inserting a row via SQL, you can run the Flyway baseline command.
Then, a few weeks later, there is another database that you haven't brought onto Flyway, but have still been applying update scripts to (maybe you didn't have time). When you bring this database onto Flyway, you may need to baseline it at V3_0 or some other version.


text:
Q: The cursor is moving to the left of entered text instead of right on Honeycomb This is a kind of strange problem.  One of the EditText controls we are using is moving the cursor to the left of typed text instead of the right.  This only happens on Honeycomb (same code on Gingerbread works fine) and it only happens in this particular EditText control and only the first time you start typing.  Any ideas?
<EditText android:id="@+id/preview_range_edit"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:digits=",-0123456789"
    android:maxLines="1"
    android:singleLine="true"
    android:layout_toRightOf="@id/preview_range_txt"
    android:layout_toLeftOf="@id/preview_range_radio"
    android:layout_centerVertical="true"/>

Edited to add that after some additional testing I found this is only a problem if the device is in portrait orientation, not in landscape.

A: So I found the answer, had nothing to do with my layout.  Part of the processing of the data of my EditText control was calling a notifyDataSetChange that was taking the focus away from my EditText control and then returning it but on return it was resetting the cursor incorrectly.  This is probably a bug in the OS.  The workaround for me was to add an OnFocusChangeListener to my EditText control and store the cursor when focus was lost and restore the cursor when focus was returned.