text:
Q: Server seems up, but accepts no connections whatsoever I have a problem with a Debian based Server, unfortunately housed in a remote location.
Two days ago, it was suddenly down and completely unreachable. After having someone reboot it, it worked for about a day, then seemed to be down again.
This time, however, it was different:
-The server reacts to pings
-It is scannable, and all the relevant ports are open
But:
-Open shells were immediately blocked, and no warning had been shown
-It's not possible to open any connection - the TCP/IP handshake seems to have some problems:
SSH handshake
As this is a private server of a small community, we don't have the resources to pay a technician to fix the problem for us, so any hints how to fix the problem after the next reboot would be highly appreciated...

A: It sounds like some process on the machine is going out of control and consuming so many resources the rest of the system can't function. (RAM, CPU, disk IO). (Or, as others point out, it could be a firewall issue. Or something on the network in between.)
But right now, you have no visibility into what's going on. You need that.
You should:

*

*set up remote logging with syslog

*set up a remote monitoring system of some sort

And, since the problem seems to be happening quickly and currently, you can take an ad hoc approach as well: run top remotely via ssh and leave that open. Watch what happens when the system dies next. But ultimately, you'll benefit from remote logging anyway, so might as well set that up.

A: If you have out-of-band access to the server such as serial console or KVM; you should log in and diagnose the server from there.
To me it sounds like either the whole system is hanged (but ping is handled at a low level by the kernel, which is why it still works) or you have a firewall that is blocking you.

A: It looks like a problem with the firewall.
1. client-> Server syn
2. server-> client syn,ack
3. client-> ack
From the screen shot it appears that your ACK in step 3 are not being acknowledged by the server. I think you firewall doesn't allow related connections.  You would need a similar rule in your iptables.
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

A: mattdm, it really was clogged up ram, and with your tips i was able to diagnose the faulty script fast enough - a runsv script in combination with an updated, but incompatible software package lead to the spawning of thousands of tasks...
However I'm still amazed by the effect that this had :-/


text:
Q: Mistake in fetching childNodes of HTML table I'm a bit confused regarding HTML DOM. I'm trying to get the rows of a particular
 so that I can interate through them.
HTML MARKUP:

      @Html.DisplayFor(m => m.FirstName)
      @Html.DisplayFor(m => m.JobLocation)

      @Html.DisplayFor(m => m.MiddleName)
      @Html.DisplayFor(m => m.StateOfResidence)

      @Html.DisplayFor(m => m.LastName)
      @Html.DisplayFor(m => m.SSN)

      @Html.DisplayFor(m => m.Suffix)
      @Html.DisplayFor(m => m.USDriversLicenseNumber)  @Html.DisplayFor(m => m.USDriversLicenseState)

  @Html.DisplayFor(m => m.DOB_Date) @Html.DisplayFor(m => m.DOB_Month) @Html.DisplayFor(m => m.DOB_Year)

What I've done in JS and Jquery:
var rows = document.getElementById(model + "_Table").childNodes;

The above line got me some weird childNodes. I got rows[] having a 'text' child, and a
 child!!
So I also tried:
var rows = document.getElementById(model + "_Table").childNodes[1].childNodes;

This second line gave the following childNodes as seen in Google Chrome while debugging:
0: HTMLTableRowElement
1: Text
2: HTMLTableRowElement
3: Text
4: HTMLTableRowElement
5: Text
6: HTMLTableRowElement
7: Text
8: HTMLTableRowElement
9: Text
Why did'nt the 2nd line get JUST the rows?? And why didn't the 1st line itself just fetch all the rows?

A:
The above line got me some weird childNodes. I got rows[] having a 'text' child, and a
 child!!

I suspect you're seeing a tbody child, not a table child. All tables have at least one tbody element. If you don't supply one in your markup, the browser will add it for you (in standards mode; I don't know what happens in quirks mode as I never work in quirks mode). The table may also have a Text node for the whitespace in it. You mentioned Chrome; you can use the "Elements" tab of the dev tools to explore the DOM created by the browser in response to your markup.
If you want to get the tr elements from the table, if there are no nested tables, you can do this:
var rows = document.getElementById(model + "_Table").getElementsByTagName('tr');

Alternately, you can use the rows property, which gives you the table's own rows (and not the rows of nested tables):
var rows = document.getElementById(model + "_Table").rows;

Note that the rows on the table element will include all rows in tbody, thead, and tfoot child elements of the table. If you only want the rows of a particular tbody, each tbody has its own rows property.

A: *

*The browser adds a
 which is why you can't acess the
 directly.

*The childnodes "Text"  refer to the whitespaces between your rows. Just remove the linebreaks and you are fine.
I prefer using querySelectorAll:
document.querySelectorAll("#"+model + "_Table tr")

but if you are concerned about IE6 users, your selection would look like this:
var rows = document.getElementById(model + "_Table").rows;

redpajama_set_name: RedPajamaStackExchange


text:
Q: How To pass Some value from a form page To another using Angular2 I have two forms (register and login) Features:When the user clicks on the register button the data will be stored in an array that is in register.component.ts after it is redirected to the login page it must connect by its data entered in the register page How to pass the values from forms To another??please ?? PS: I use angular2thank you in advance

A: Make use of Shared Services to pass data between components or even you can make use of event emitters for these purpose

A: import {Injectable, Injector} from '@angular/core';

@Injectable()
export class DataService {
    data;
    constructor() {}
}

in your component
constructor(private dataService: DataService ){}
this.dataService.data= somedata;

in the other component
constructor(private dataService: DataService ){}
somedata= this.dataService.data;

remember to register your ap in the providers of the module being used;
providers: [DataService]

this can be used because the service injected in both components will be a singleton


text:
Q: Jhipster - use of isInAnyRole I have set up several roles in MySql, and I want to use the function
isInAnyRole in navbar.html in order to display a menu for users with roles 'ROLE_USER' and ROLE_SUPERVISOR'.
I have replace isInRole('ROLE_USER') by isInAnyRole(['ROLE_USER','ROLE_SUPERVISOR']).
But isInAnyRole is not called and none of the menus are displayed.
What is the good way to use isInAnyRole function?
Thanks

and
isInAnyRole: function (roles) {
    if (!_authenticated || !_identity.roles) {
        return false;
    }

    for (var i = 0; i < roles.length; i++) {
        if (_identity.roles.indexOf(roles[i]) !== -1) {
            return true;
        }
    }

    return false;
}

A: You're using an old version of JHipster, since release 2.7.0 we provide a directive authority.directive.js which does exactly what you want. You should consider upgrading your app.


text:
Q: Creating a map of earth from an unknown region of the sphere Lately I've been trying to use Mathematica to plot a map of earth.
I have an analytic function from a known triangle to some part of a unit sphere, described by unknown parametrization. This function $f$ gets a point $(x,y)$ and returns a point on the sphere $(X,Y,Z)$. I can invert the function numerically to get $f^{-1}$ using findroot.
I want to plot a map of earth on the triangluar region – the map that you get by using $f^{-1}$ on the corresponding region of the sphere.
I've tried many things but none worked. At the begining I thought to use GeoProjection from Maps & Cartography, but it doesn't seem to support projections that are not predefined. It also provieds very pixelated maps, and I hoped to get a higher resolution one.
I also tried to use ParametricPlot to map from the triangle to the sphere by using $f$, using TextureCoordinateFunction to plot a texture of earth on the sphere, and map back to the triangle by $f^{-1}$, but didn't mange to get it work.
How can you make such a map in Mathematica?
Thanks!


text:
Q: Execution of a stored procedure with an input parameter and insert into specific cells in excel I have the following vba routine
Private Sub cmdStartDate_Click()

'Set Variables
Dim conn As ADODB.Connection
Dim str As String
Dim exeStr As String
Dim rs As ADODB.Recordset
Dim fld
Dim i As Integer
Dim connStr As String
Dim cmd As New ADODB.Command

'Error Handler
On Error GoTo errlbl

'Open the database connection
Set conn = New ADODB.Connection

'Construct the connection string
conn = "Driver={SQL Server};Server=10.50.50.140;Database=tbjc;UID=oe;PWD=Orth03c0"

'Open the connection
conn.Open

'Create the command object
Set cmd = New ADODB.Command

'Create and store the start date parameter
With cmd
    .CommandText = "dbo.cusUltrasoundReport"
    .CommandType = adCmdStoredProc
    .Parameters.Append .CreateParameter("@Start", adVarChar, adParamInput, 12, txtStartDate.Text)
    .Parameters("@Start").Value = txtStartDate.Text
    .ActiveConnection = conn
End With

'Create the recordset
Set rs = cmd.Execute

'str = txtStartDate.Text

'exeStr = "exec dbo.UltrasoundReport(" & str & ")"

'Open recordset
'rs.Open

If Not IsEmpty(rs) Then
    rs.MoveFirst

    'Populate the first row of the sheet with recordset's field name
    i = 0
    For Each fld In rs.Fields
        Sheet1.Cells(1, i + 1).Value = rs.Fields.Item(i).Name
        i = i + 1
    Next fld

    'Populate the sheet with the data from the recordset
    Sheet1.Range("A49:Q49").CopyFromRecordset rs
Else
    MsgBox "Unable to open recordset, or unable to connect to database.", vbCritical, "Can't get requested records"
End If

'Cleanup
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing

exitlbl:
Debug.Print "Error: " & Err.Number
    If Err.Number = 0 Then
        MsgBox "Done", vbOKOnly, "All Done."
    End If
Exit Sub

errlbl:
MsgBox "Error #: " & Err.Number & ", Description: " & Err.Description, vbCritical,    "Error in OpenConnection()"
Exit Sub

Resume exitlbl

End Sub

It works just fine to get the information and pass the parameter to the sproc
What I need it to do is insert each of the field values into specific cells in excel and I am not sure how to do that.  Has anyone done this before?
Thank you

A: The following article provides different methods to achieve that: http://support.microsoft.com/kb/246335


text:
Q: Invalid Argument Error Making Search Bar I'm making a search bar for a site it works in one page but the other one I keep getting invalid argument error. Hopefully everything that is needed is below. I am using codeigniter. Please help. Thanks.
//Doesnt Work//
private function getUsers () {
    $search = $this->input->post('search');

    if($search && filter_var($search, FILTER_VALIDATE_EMAIL)) {
        $where = 'WHERE source_adusers.ad_Email="'.$search.'"';
    } else if ($search) {
        $where = "WHERE source_adusers.ad_account='".$search."'";
    } else if (!$search) {
        $where = '';
    }

    $query = $this->db->query('SELECT *, COUNT(rollout_systems.EAM_USER) as systems FROM source_adusers
        LEFT JOIN rollout_systems ON rollout_systems.EAM_User = source_adusers.ad_account '.$where.' GROUP BY source_adusers.ad_account LIMIT 0,50');

    $users = null;

    foreach ($query->result() as $row) {
        $data['account'] = $row->ad_account;
        $data['email'] = $row->ad_Email;
        $data['name'] = $row->ad_DispName;
        $data['systems'] = $row->systems;

        $users[] = $data;
    }

    if(isset($this->data['users'])) {
        $this->data['users'] = $users;
    } else {
        $this->data['users'] = $users;
    }
}

//Does Work//
private function getSystems () {
    $search = $this->input->post('search');

    if ($search) {
        $where = 'WHERE disc_systempool.ad_name="'.$search.'"';
    } else {
        $where = '';
    }

    $query = $this->db->query('SELECT *, COUNT(rollout_systems.sys_name) as scopes FROM disc_systempool LEFT JOIN rollout_systems
        ON rollout_systems.sys_name=disc_systempool.ad_name '.$where.' GROUP BY disc_systempool.ad_name LIMIT 0,50');

    foreach ($query->result() as $row) {
        $data['model'] = $row->eam_Model;
        $data['account'] = $row->ad_name;
        $data['city'] = $row->eam_City;
        $data['scopes'] = $row->scopes;
        $data['search'] = $this->input->post('search');

        $systems[] = $data;
    }

    if(isset($this->data['systems'])) {
        $this->data['systems'] = $systems;
    } else {
        $this->data['systems'] = $systems;
    }
}

//Where I'm getting the error//

    <? foreach ($users as $user) { ?>                      <---- Line 18

        <?=$user['account']?>
        <?=$user['name']?>
        <?=$user['email']?>
        <?=$user['systems']?>
        View Details

    <? } ?>

//Error//
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: headquarters/users.php
Line Number: 18

A: It shows the right thing. I fixed the problem. I misunderstood what the guy that hired me asked me to do. He said search account name. I was search display name which kept giving me the error.

A: Try making a var_dump($data); inside your view. If empty. Do the same in your controller by just printing it out. If you see data inside the $data array. Make sure that you are sending the $data array with you into the view $this->load->view("view",$data);
Besides that, i might be wondering why you do foreach on your rows inside of the controller instead of just using the object right in your view
return $query->result();

in view
foreach($users as $user) { print $user->account; }

Hope you figure it out.
Best regards
Jonas


text: Q: Access external network from container based service I have been searching a bit, but I think I am using the wrong terminology or something as what I am after does not seem like a special case.  We are in the process of looking how we can move our system from a bunch of windows/Linux based services into a container-based infrastructure.  Most of these services interface with some feed of data that is on another network.  I have been looking at the different container networks available both with Windows and Linux and am having a hard time finding the proper path to go about having a process that is running in a container be able to access some external data feed someplace out on a network that is not the container based network.  The closest thing I have found is using a host network on Linux which will put me on the host network, but am not seeing much support for that on the windows side.  I would like to be able to use the container network, but be able to route outside that network as well.  This seems like a valid use case, so I was wondering if anyone could point me in a general direction of how to go about accomplishing this.


text:
Q: Syncing Processing to an Arduino that is Multiplexing I am sending 2 bytes from Processing to Arduino. These bytes are then stored in two values on the Arduino side, and then sent to a function that will then display them on a 7 segment 4 digit display.
The numbers are displayed fine! Yes, until about 5 seconds. I recorded it in slow motion.
9561 runs for about 5 seconds,
then a flash of 6100 very shortly,
and then 6195 very shortly
then it returns to 9561 for about 5 seconds again.
This can be changed slightly by altering the time each number is on the display, and I try to keep it below 4.
Anyways then changing the speeds on both programs also alters it, but I can't seem to get it right. Do I have to sync the programs through altering the speeds or is there a way to sync the numbers? I read into serialEvent() but not sure how to incorporate it into my project.
Here's my code below for the PROCESSING
void setup()
{
  myPort = new Serial(this, Serial.list()[0], 9600);
}

void draw() {
  seg[0] = 9;
  seg[1] = 5;
  seg[2] = 6;
  seg[3] = 1;

  int x = (seg[pos+1] & 0x000f)<<4|(seg[pos]) & 0x000f; //3210
  int x2 = (seg[pos+3] & 0x000f)<<4|(seg[pos+2] & 0x000f);
myPort.write(x);
myPort.write(x2);
  //0123
  int disp1 = x;
  int disp2 = (x & 0x00f0)>>4;
  int disp3 = (x2 & 0x000f);
  int disp4 = (x2 & 0x00f0)>>4;

  //0123
  print(disp1, '\n', disp2, '\n', disp3, '\n', disp4, '\n', '\n');
}

And ARDUINO
void setup() {
  pinMode(GND1, OUTPUT);
  pinMode(GND2, OUTPUT);
  pinMode(GND3, OUTPUT);
  pinMode(GND4, OUTPUT);

  pinMode(aPin, OUTPUT);
  pinMode(bPin, OUTPUT);
  pinMode(cPin, OUTPUT);
  pinMode(dPin, OUTPUT);
  pinMode(ePin, OUTPUT);
  pinMode(fPin, OUTPUT);
  pinMode(gPin, OUTPUT);
  pinMode(light, OUTPUT);

  Serial.begin(9600);
}

void digitdisplay(byte x,byte x2)
{
//unsigned char tn = int (num/1000);
//if (tn>10)
//{
//  tn = tn - 10;
//}
//
//unsigned char hn = int (num/100)%10;
//unsigned char tenn = int (num/10)%10;
//unsigned char on = int (num%10);
int disp[4];

disp[0] = ( x & 0x000f);
disp[1] = ( x & 0x00f0)>>4;
disp[2] = ( x2 & 0x000f);
disp[3] = ( x2 & 0x00f0)>>4;

  numberselect(disp[0]);
  digitselect(1);
  delay(t);

  numberselect(disp[1]);
  digitselect(2);
  delay(t);

  numberselect(disp[2]);
  digitselect(3);
  delay(t);

  numberselect(disp[3]);
  digitselect(4);
  delay(t);
}

void loop()
{
int x,x2;

 if (Serial.available()>0)
   { // If data is available to read,

 x=Serial.read();
 x2=Serial.read();

   }

//shiftlight(maxrange);
digitdisplay(x,x2);
}


text:
Q: Automate Letsencrypt SSL Certificate installation with PHP shell_exec command via acme.sh snap package I install lets encrypt certificates through acme.sh snap package
https://github.com/acmesh-official/acme.sh
I am wondering if there is any way to automate certificate installation via PHP default shell_exec() command.
This shell command used to get certificates works just fine when logged in via SSH

acme.sh --issue --dns dns_gd -d example.com -d *.example.com

However, if I call the same command via PHP shell_exec, it always throws an error
$domainName = 'example.com';
$initCommand = "acme.sh --issue --dns dns_gd -d $domainName -d *.$domainName";
$output = shell_exec("$initCommand 2>&1 | tee -a /var/www/html/sshout.txt 2>/dev/null >/dev/null &");

sshout.txt - The output I am getting on sshout is as following
ssh: 1: /home/ubuntu/.acme.sh: Permission denied
sudo: no tty present and no askpass program specified

Is it possible to get certificates this way?
Or any other way to automate it via  PHP? by setting cron, or creating a bash script and calling it from PHP?
I am running PHP 7.2 on ubuntu 18 on an apache server.

A: You should have permission and the right path to run the bash script. I guess this topic is what you need PHP script can't run bash script. sh: Permission denied
the other way is using acmephp


text:
Q: Magento 2: How to move product attribute group tab I want to move 'Discogs Listing' tab after the content tab. I dont know how to do it. drag and drop from attribute set move my tab after the 'Product Reviews' but i want after the 'content' tab

Any help would be appreciate. thank you

A: Through this method \Magento\Eav\Setup\EavSetup::addAttributeGroup it is understood that the groups have a sort order. Below is the table that contains them

Through the repository you can modify its sortOrder:
\Magento\Eav\Model\Attribute\GroupRepository
Cheers

A: This is how I achieved it using modifier
in your

app\code\vendor\module\etc\adminhtml\di.xml

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
      <virtualType name="Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Pool">
        <arguments>
            <argument name="modifiers" xsi:type="array">
                <item name="sap_product" xsi:type="array">
                    <item name="class" xsi:type="string">vendor\module\Ui\DataProvider\Product\Form\Modifier\Group</item>
                    <item name="sortOrder" xsi:type="number">1000</item>
                </item>
            </argument>
        </arguments>
    </virtualType>
</config>

and

app\code\vendor\module\Ui\DataProvider\Product\Form\Modifier\Group.php

<?php
namespace vendor\module\Ui\DataProvider\Product\Form\Modifier;

use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\AbstractModifier;
use Magento\Framework\Stdlib\ArrayManager;

class Group extends AbstractModifier
{
    public function __construct(ArrayManager $arrayManager)
    {
        $this->arrayManager = $arrayManager;
    }

    public function modifyData(array $data)
    {
        return $data;
    }
    public function modifyMeta(array $meta)
    {

        $meta['discogs-listing']['arguments']['data']['config']['sortOrder'] = 20;
        return $meta;
    }
}


text:
Q: Is Tensor Flow compatible with Julia 0.6.4? So I have a project in my machine learning class and we are using Julia as our programming language. We can use any packages we want to build neural networks but I can't seem to get Tensor Flow to test correctly. Pkg.add("TensorFlow") works seemingly fine but here is the output for Pkg.test("TensorFlow")
julia> Pkg.test("TensorFlow")
INFO: Testing TensorFlow
ERROR: LoadError: LoadError: could not load library "C:\Users\Ryan .LAPTOP-
KJUJGIC7\.julia\v0.6\TensorFlow\src\..\deps\usr\bin\libtensorflow"
The specified module could not be found.

Stacktrace:
 [1] dlopen(::String, ::UInt32) at .\libdl.jl:97
 [2] TensorFlow.Graph() at C:\Users\Ryan .LAPTOP-   KJUJGIC7\.julia\v0.6\TensorFlow\src\core.jl:21
 [3] include_from_node1(::String) at .\loading.jl:576
 [4] include(::String) at .\sysimg.jl:14
 [5] include_from_node1(::String) at .\loading.jl:576
 [6] include(::String) at .\sysimg.jl:14
 [7] process_options(::Base.JLOptions) at .\client.jl:305
 [8] _start() at .\client.jl:371
while loading C:\Users\Ryan .LAPTOP-KJUJGIC7\.julia\v0.6\TensorFlow\test\..\examples\logistic.jl, in expression     starting on line 22
while loading C:\Users\Ryan .LAPTOP-KJUJGIC7\.julia\v0.6\TensorFlow\test\runtests.jl, in expression starting on line 6
=================================================[ ERROR: TensorFlow ]==================================================

failed process: Process(`'C:\Users\Ryan .LAPTOP-KJUJGIC7\AppData\Local\Julia-0.6.4\bin\julia.exe' -Cgeneric '-JC:\Users\Ryan .LAPTOP-KJUJGIC7\AppData\Local\Julia-0.6.4\lib\julia\sys.dll' --compile=yes --depwarn=yes --check-bounds=yes --code-coverage=none --color=yes --compilecache=yes 'C:\Users\Ryan .LAPTOP-KJUJGIC7\.julia\v0.6\TensorFlow\test\runtests.jl'`, ProcessExited(1)) [1]

========================================================================================================================
ERROR: TensorFlow had test errors

I'm running Julia Version 0.6.4 on Windows 10; if there's a way to resolve this error or a workaround I'd love some suggestions.

A: TensorFlow.jl does not support Windows.
You have two options:
(1) Try using TensorFlow via PyCall.jl:
using Conda
Conda.runconda("install -c conda-forge tensorflow")

(2) Use Flux.jl instead


text:
Q: Facing error while restarting npm , npm start is showing error I am new to react ,I have tried npm start, after I closed my pc once, after I restarted npm start is showing error, I have tried adding start command to my JSON file , still its not starting, I have googled it , even I tried all the methods mentioned here in stack overflow , but its showing error all the time.

A: You have 2 package.json file
First under \Covid 19 Tracker folder
Second under \Covid 19 Tracker\Covid_19 folder
Seems like First Package.json doesn't have start script.
If you are trying to start app from wrong package.json, you will get this error. You should cd into the inner folder (if you are trying to start react app).


text:
Q: Summing a function using modulus The problem:
If the infinite sum of a function is known, how to find:
$$\begin{align*}
\sum_{i\equiv 0 \mod m}f(x_0+i)=\\ f(x_0)+f(x_0+m)+f(x_0+2m)+f(x_0+3m)+\ldots
\end{align*}$$
And if the finite sum of a function is known, how to find:
$$\begin{align*}
\sum_{i\equiv 0 \mod m}^{i = {(x_0+\lfloor \frac{x-x_0+1}{m}\rfloor m)}}f(x_0+i)=\\f(x_0)+f(x_0+m)+f(x_0+2m)+f(x_0+3m)
&\quad +\ldots+f\left(x_0+\left\lfloor \frac{x-x_0+1}{m}\right\rfloor m\right)
\end{align*}$$
Details:
If we know a function $f$ and we can find the sum of its terms (defined as $S_f$), how to find the sum, but jumping some factors (defined as $MS_f$, where M representes modular)?
What's the relation with the sum function ($S_f$)? (I think this uses the root of the unity, but don't know how.)
For example, if:

$S_f=\displaystyle\sum_{i=1}^{\infty}f(i)=f(1)+f(2)+\ldots$

with infinite terms, how to find

$$\begin{align*}
  MS_f(x_0,m)&=\sum_{i\equiv 0 \mod m}f(x_0+i)=\ f(x_0)+f(x_0+m)+f(x_0+2m)+f(x_0+3m)+\ldots
  \end{align*}$$

And if:

$S_f(x)=\displaystyle\sum_{i=1}^{x}f(i)=f(1)+\ldots+f(x-1)+f(x),$

how to find

$$\begin{align*}
MS_f(x,x_0,m)&=\sum_{i\equiv 0 \mod m}^{i = {(x_0+\lfloor \frac{x-x_0+1}{m}\rfloor m)}}f(x_0+i)=\\f(x_0)+f(x_0+m)+f(x_0+2m)+f(x_0+3m)
&\quad +\ldots+f\left(x_0+\left\lfloor \frac{x-x_0+1}{m}\right\rfloor m\right)
\end{align*}$$

where $(x_0+\lfloor \frac{x-x_0+1}{m}\rfloor m)$ is the ultimate term of the arithmetic progression $x_0+k\times m$ which not exceeds $x$.
Maybe:
$MS_f(x,x_0,m)=\displaystyle\sum_{i=0}^{m-1}a_iS_f(w^ix)$ or $\displaystyle\sum_{i=0}^{m-1}a_iS_f(w^i(x+x0))$
but I don't know exactly.
Example:
$$S_f=\sum_{i=1}^{\infty}\frac{x^{i-1}}{(i-1)!}=e^x, \quad f(i)=\frac{x^{i-1}}{(i-1)!}$$
$$\begin{align*}
MS_f(x_0,m)=\sum_{i\equiv 0 \mod m}f(x_0+i)=\sum_{i\equiv 0 \mod m}\frac{x^{(x_0+i)-1}}{((x_0+i)-1)!}\implies\\
MS_f(3,2)=\sum_{i\equiv 0 \mod 2}\frac{x^{(3+i)-1}}{((3+i)-1)!}=\sum_{j=0}^{\infty}\frac{x^{3+2j-1}}{(3+2j-1)!}=\cosh (x)-1
\end{align*}$$

A: In the comment at your question I mentioned Bernoulli-polynomials; in fact I approach such problems using a variant which I call "zeta-polynomials". These are that polynomials that originally were used by Bernoulli and Faulhaber for the sums-of-like-powers and actually are the integrals of the Bernoulli-polynomials. I'll reflect my type of proceeding here only cursory but I think it will be sufficient to show the principle.
Ingredients are a matrix-notation, the concept of indefinite summation and two standard-matrices: the upper triangular standard Pascalmatrix P and the Z-matrix which contains the coefficients of the zeta-polynomials. For the algebra with formal power series I denote their coefficients in a vector, say A and the powers of x in some vector V(x) of "vandermonde-type", such that always $\small V(x)=[1,x,x^2,x^3,x^4,...] $.
Then, if your function f(x) has a power series representation, its coefficients may be assumed in a vector A, thus we'll have f(x) denoted by the dot-product
$$\small f(x) = V(x) \cdot A $$
Now the pascalmatrix P comes into play. Since it is upper triangular we have the identity
$$\small V(x) \cdot P = V(x+1) $$
due to the binomial-theorem applied to all nonnegative integer powers and in generalization
$$\small \begin{eqnarray}
 V(x) \cdot P &=& V(x+1) \\
 V(x) \cdot P^2 &=& V(x+2) \\
 V(x) \cdot P^3 &=& V(x+3) \\
 \ldots \\
 V(x) \cdot P^h &=& V(x+h) \\
\end{eqnarray} $$
On the other hand, your problem is first, to find the sum
$$\small S(1,n)=V(1) \cdot A + V(2)\cdot A + V(3) \cdot A + \cdots V(n)\cdot A=
 \sum_{k=0}^{n-1} f(1+k) $$
For finite sums it is obvious how to rewrite this using sums of powers of of P:
$$\small S(1,n)=V(1) \cdot (I + P + P^2 + \ldots + P^{n-1}) \cdot A $$
Now the idea of Bernoulli to introduce polynomials for the sum-of-like-powers can elegantly be modeled by this approach. We provisorically assume the possibility of some matrix Z which represents the geometric series of powers of P:
$$\small Z = I+ P + P^2 + \ldots = (I - P)^{-1} $$
which then would allow to write
$$\small T(a)=V(a) \cdot \left( I + P + P^2 + \ldots + P^n + \cdots \right) \cdot A = V(a) \cdot Z \cdot A = \sum_{k=0}^\infty f(a+k)$$
and then $$\small S(a,b) = T(a) - T(b+1) = (V(a)-V(b+1) )\cdot Z \cdot A = \sum_{k=a}^b f(k) $$
The clue is now, that such a matrix Z in fact can be found and just contains the mentioned zeta-polynomials (or integrals of Bernoulli-polynomials) and is a not-strictly upper-triangular variant of P (it contains one additional subdiagonal).
The evaluation for the coefficients of the resulting formal power-series for S(a,b) by the evaluation of the dot product $\small F=Z \cdot A $ includes now in many cases the summation of divergent series but can also be rewritten in terms of the Euler-MacLaurin-series.
The generalization to bigger steps than 1 (in your example m>1 can then simply be expressed by the introduction of the m'th power of P instead of P and a similarity-transform of the Z by just $\small Z_m = V(m) \cdot Z \cdot V(1/m) $ (where the V() are taken as diagonal-matrices. Since Z is column-finite this is also well defined.
What you get by this tiny pieces of matrix-algebra is the expression of your problem in terms of a series whose coefficients are polynomials involving zeta-values at nonpositive integers or better known: of the bernoulli-numbers.
I've described that procedere at many and various places and don't know at the moment which would be the best example. Here is a text about it, still in an unfinished draft-mode. And here is the text, where I initially described the matrix Z of zeta-polynomials  and which might give a further clue (relevant pages 14..19). Also here on MSE you might search for hte keyword of  "indefinite summation" (or even in Wikipedia) to find more hints in more common notation.

A: Agree with others on that your question is too broad, and no general formula is there. The way you phrased the question means (among other things) that given, for example, that
$$1= a_0+a_1+a_2+\cdot$$
you ask for the value of the sum
$$
a_1+a_3+a_5+\cdots?
$$
This is so obviously impossible: after all the $a_i$:s could be all zero starting from the second, it might be that $a_i=2^{-i}$, it might be that $a_i=6/(\pi i^2),\ldots$. Consequently we all had to put some effort in trying to guess what did you really want to ask.

My best guess is that you are only interested in power series (judging from your example with $e^x$ and $\cosh x$). If that is so, then something like the following may be useful to you? If the Maclaurin series
$$
f(x)=\sum_{n=0}^\infty a_n x^n
$$
converges in some circle about the origin, and $\zeta$ is a root of unity of order $m$, then
for all integers $k, 0\le k <m$ we have
$$
f(\zeta^k x)=\sum_{n=0}^\infty a_n (\zeta^k)^n x^n=\sum_{\ell=0}^{m-1}\zeta^{k\ell}\sum_{j=0}^\infty a_{\ell+jm}x^{\ell+jm},
$$
where I wrote $n=\ell+jm$ in the last step and grouped the terms according to the power of $\zeta$ that appears as a factor.
The usual sums involving $n$th roots of unity (or discrete Fourier transform, if you prefer that term) then show that
$$
\sum_{k=0}^{m-1}\frac{\zeta^{-k\ell}}m f(\zeta^k x)=\sum_{n\ge0, n\equiv \ell\pmod{m}}a_nx^n.
$$
Your $e^x$ vs. $\cosh x$ example arises as the case $m=2$, $\zeta=-1$, $\ell=0$, $a_n=1/n!$.

A: (My apologies if this is more of a comment than an answer, but I don't have the ability to leave comments yet)
As I understand it, you're hoping to express your sum in the form
$$S=g\left( S_f(a_1, b_1), S_f(a_2, b_2), S_f(a_3, b_3), \dots, S_f(a_j, b_j) \right)$$
for some $g$ and some choice of the $a$ and $b$, where $j$ is significantly smaller than $\frac{b-a}{m}$.  In general, I don't think this is possible without further assumptions.  If $j$ is much smaller than $m$ there will always be a $k$ such that neither $a+i+km$ and $a+i+km+1$ appear at the end of one of your $j$ intervals.  In that case you can replace $\{f(a+i+km), f(a+i+km+1)\}$ by $\{f(a+i+km)+\epsilon, f(a+i+km+1)-\epsilon\}$ and change the left side but not the right side.
I think what you're thinking of is the situation where you know not only $S_f(a,b)$ but $$S_f(a,b,x)=\sum_{i=a}^b f(i) x^i$$
In that case you can extract the sum you want by considering $S_f(a,b,x)$ for $x$ being various $m^{th}$ roots of unity.


text:
Q: Why does this prepared statement binding fail? Using PHP with PDO to access a MyISAM table...
This case fails:
SELECT
                id,
                title,
                content,
                (MATCH(title) AGAINST(:fulltext IN BOOLEAN MODE)*10)+(MATCH(content) AGAINST(:fulltext IN BOOLEAN MODE)*3) AS relevancy
            FROM
                mytable
            WHERE
                enabled = 1
                AND `date` >= CURRENT_DATE
                AND MATCH (title, content) AGAINST (:fulltext IN BOOLEAN MODE)
            ORDER BY relevancy DESC, `date` ASC
            LIMIT 50

$stmt->bindParam(":fulltext", $fulltext);
$stmt->execute();

Error:
exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number'
Now I reworked the code into this:
SELECT
                id,
                title,
                content,
                (MATCH(title) AGAINST(? IN BOOLEAN MODE)*10)+(MATCH(content) AGAINST(? IN BOOLEAN MODE)*3) AS relevancy
            FROM
                mytable
            WHERE
                enabled = 1
                AND `date` >= CURRENT_DATE
                AND MATCH (title, content) AGAINST (? IN BOOLEAN MODE)
            ORDER BY relevancy DESC, `date` ASC
            LIMIT 50

$stmt->execute(Array($fulltext, $fulltext, $fulltext));
And this works.
The question: Can anyone explain why this is? Why does binding :fulltext fail in the first case?
Using the same binding multiple times works in other, similar statements that access a Postgres DB instead of the MariaDB MyISAM table:
WHERE           customer.first_name ILIKE :term
                OR customer.city ILIKE :term
                OR customer.street ILIKE :term
                OR customer.zip ILIKE :term
                OR customer.email ILIKE :term
                OR customer.email_private ILIKE :term
                OR customer.company_email ILIKE :term


text:
Q: Add option to show all hot network questions in addition to 15, 30 and 50 Hot Network Questions page is set up to show links to popular questions divided into pages. Pages are perfect for cases where their contents don't change between flipping, like posts sorted by "newest". But if you've been on the internet and browsed sites like reddit with posts sorted by current popularity (hotness, bestness), you know how you still get to see posts you've just seen on the previous page if you're not flipping fast enough (too fast). Same happens here. It's frustrating and there's an easy fix.
You've already given us the option to get 50 posts per page, making it just 2 pages. Would it be much more load on the server to allow people to see all 100 hottest posts on one page? Pretty please?


text:
Q: Fitting variogram R I have created a data frame like this
 head(df)
DISTBin   MSDBin
1       0  4.301515
2      20  5.599879
3      40  5.883236
4      60  6.430584
5      80  7.396374
6     100  7.561652

where the first column is a vector of distances (binned) and the second one is a vector of mean square differences for a given quantity.
I would like then to fit df$MSDBin ~ df$DISTBin using a Gaussian model.
I cannot use gstat or similar since I don't have a variogram object (I had to compute the variogram by myself to discard pairs from the same ID).
Any help?

A: I have found the answer myself.
Gau <- function(h,tau,sigma.sq,range){
    return(tau + sigma.sq * (1-exp(-(h*h)/(range*range))))
}

Gau_Fit <- nls(MSDBin ~ Gau(DISTBin,tau,sigma.sq,range),
                 data = df,
                 start = list(tau = 0, sigma.sq = 10, range = 1000))


text:
Q: Connecting Arduino to PC without powering it I'm doing a project with solar cell which is connected to battery. This battery should power the Arduino (some sensors are attached to it). At the same time, I need to keep the Arduino connected to my PC to finish my code depending on the values coming from sensors. The problem I'm facing is that the Arduino is taking power from the PC, and I don't want it to do so.
I know that the cable is for power and data, so I searched for a data-only cable, but it is not available in my region. Is there is any way to disable the power coming from PC?

A: There is no "data only" usb cable.
I assume you are talking about an Uno or Mega 2560 with an USB plug and an ATmega16U2 handling the USB connection.
If battery power is available at Vin or the barrel jack, it will be used to power the Arduino.
Check https://www.arduino.cc/en/Main/ArduinoBoardMega2560 or the corresponding Uno page and see the linked schematic PDF. I wouldn't break the polyfuse or apply other hacks.
If you want to inhibit your sketch from running while the battery is low but USB connected (why?), you could

*

*pull RESET to LOW

*check battery voltage via analogRead and act accordingly in the sketch.


text:
Q: Runnable not work Hi i create a test java code but class runnable not work. the code inside runnable builder work but override run not work
import java.util.Timer;
import java.util.TimerTask;
import java.util.Random;

public class Test
{
    //timer for change zone
    private Timer timeZoneChange;

    Test()
    {
        timeZoneChange = new Timer();

        timeZoneChange.schedule(new TimeForChangeZone(), 1 * 1000);
    }

    public class TimeForChangeZone extends TimerTask
    {
        @Override
        public void run()
        {
            System.out.println("testing..");
            new UpdatePvpFlagZone(false);
            //change zone flag
            timeZoneChange.schedule(new TimeForChangeZone(), 1 * 60000);
        }
    }

    public class UpdatePvpFlagZone implements Runnable
    {
        //remove pvp flag
        private boolean removePvpFlag;

        public UpdatePvpFlagZone(boolean removePvpFlag)
        {
            removePvpFlag = removePvpFlag;
        }

        @Override
        public void run()
        {
            for (int i = 0; i<10; i++)
            {
                if (i == 5)
                    break;
                //update flag
                if (!removePvpFlag)
                {
                    if (i == 6)
                        break;
                    System.out.println(i);
                    break;
                }
                //remove flag
                if (i == 7)
                    break;
                System.out.println(i);
            }
        }
    }

    public static void main(String[] args)
    {
        new Test();
    }
}

console print this but inside override run not print.
> java Test
testing..

A: On this line new UpdatePvpFlagZone(false);, The constructor is called, but the runnable has yet to be started.
Start the runnable like so:
UpdatePvpFlagZone upfz new UpdatePvpFlagZone(false);
upfz.run();


text:
Q: Indexing one-dimensional numpy.array as matrix I am trying to index a numpy.array with varying dimensions during runtime. To retrieve e.g. the first row of a n*m array a, you can simply do
a[0,:]

However, in case a happens to be a 1xn vector, this code above returns an index error:

IndexError: too many indices

As the code needs to be executed as efficiently as possible I don't want to introduce an if statement. Does anybody have a convenient solution that ideally doesn't involve changing any data structure types?

A: Just use a[0] instead of a[0,:].  It will return the first line for a matrix and the first entry for a vector.  Is this what you are looking for?
If you want to get the whole vector in the one-dimensional case instead, you can use numpy.atleast_2d(a)[0].  It won't copy your vector -- it will just access it as a two-dimensional 1 x n-array.

A: From the 'array' or 'matrix'? Which should I use? section of the Numpy for Matlab Users wiki page:

For array, the vector shapes 1xN, Nx1, and N are all different things. Operations like A[:,1] return a rank-1 array of shape N, not a rank-2 of shape Nx1. Transpose on a rank-1 array does nothing.

Here's an example showing that they are not the same:
>>> import numpy as np
>>> a1 = np.array([1,2,3])
>>> a1
array([1, 2, 3])
>>> a2 = np.array([[1,2,3]])    // Notice the two sets of brackets
>>> a2
array([[1, 2, 3]])
>>> a3 = np.array([[1],[2],[3]])
>>> a3
array([[1],
       [2],
       [3]])

So, are you sure that all of your arrays are 2d arrays, or are some of them 1d arrays?
If you want to use your command of array[0,:], I would recommend actually using 1xN 2d arrays instead of 1d arrays. Here's an example:
>>> a2 = np.array([[1,2,3]])    // Notice the two sets of brackets
>>> a2
array([[1, 2, 3]])
>>> a2[0,:]
array([1, 2, 3])
>>> b2 = np.array([[1,2,3],[4,5,6]])
>>> b2
array([[1, 2, 3],
       [4, 5, 6]])
>>> b2[0,:]
array([1, 2, 3])


text:
Q: Can I transfer my Google Play music onto my iPhone? I had a Galaxy S4 and I just bought a iPhone 6. Is there a way I can transfer my music using an app to iTunes? Or do I have to download iTunes onto a computer?

A: you won't be able to transfer your music directly to iTunes.
You can download this music on your computer per Goolge Music Manager and them sync with your iPhone
(https://play.google.com/music/listen?u=0#/manager)
Obviously you can use the Google Music apps on your phone too and have the music to play offline too.

A: Google has iOS versions of most of their  apps.
For music, download the "Google Play Music" in the App Store, and log in with your Google account.


text:
Q: Как правильно определить многострочные аргумент в angular/typescript? Здравствуйте у if есть два аргумента, как это должно выглядеть с точки зрения код стайла?  Допустим такой перенос на другую строку? Или это должна быть одна строка, но тогда она очень длинная выходит.  Или возможно эти аргументы стоит присвоить переменным и работать с ними? Подскажите пожалуйста.
 private isTest() {
    if ((this.argSorce.nativeElement.clientWidth < this.maxWidthBlock) ||
      (this.argSorce.nativeElement.clientWidth < this.maxBlockContainer)) {
    }
  }

A: Если хочется читабельно, то должно быть примерно так:
  private isTest() {
    if (
      this.argSorce.nativeElement.clientWidth < this.maxWidthBlock ||
      this.argSorce.nativeElement.clientWidth < this.maxBlockContainer
    ) {
    }
  }


text:
Q: PyQt label with pixmap not resizing correctly In PyQt I'm trying to create a label which contains a pixmap and have the pixmap automatically resize as the label resizes — say, as a result of the window the label is in resizing.
I am experiencing several problems:

*

*The window refuses to resize smaller than its original size.

*If you resize the window to a larger size, you can never resize back to a smaller    size.

*As the window resizes, the label also resizes correctly, but its pixmap does not repaint properly. It appears to "tear" or repeat pixels horizontally and/or vertically.

I started by creating a class PixmapLabel that inherits from QLabel since I wanted to override the resizeEvent event:
import sys

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

# You can plug in a path to an image of your choosing.
IMAGE_PATH = '../assets/launch_image.jpeg'

class PixmapLabel(QLabel):
    """
    A label widget that has a pixmap. As the label resizes so does the
    pixmap.
    """

    def __init__(self, pixmap: QPixmap = None):
        super().__init__()
        self.setStyleSheet('background-color: lightgray')
        self.setPixmap(pixmap)

    def resizeEvent(self, event: QResizeEvent):
        """As the PixmapLabel resizes, resize its pixmap."""
        super().resizeEvent(event)
        self.setPixmap(self.pixmap())

    def setPixmap(self, pixmap: QPixmap):
        if pixmap is None:
            return

        # Resize the widget's pixmap to match the width of the widget preserving
        # the aspect ratio.
        width = self.width()
        pixmap = pixmap.scaledToWidth(width)
        super().setPixmap(pixmap)

Here is the code for the MainWindow (which derives from QDialog):
class MainWindow(QDialog):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('PyQt PixmapLabelWidget Test')
        self.resize(300, 300)

        # Set the window's main layout.
        self.main_layout = QVBoxLayout()
        self.setLayout(self.main_layout)

        # Add a single widget — a PixmapLabel — to the main layout.
        self.lbl_image = PixmapLabel()
        self.main_layout.addWidget(self.lbl_image)
        pixmap = QPixmap(IMAGE_PATH)
        self.lbl_image.setPixmap(pixmap)

Finally, here's the code to run the Python app/script:
if __name__ == '__main__':
    app = QApplication([])
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

Here's how the window initially renders with the label and its pixmap: https://cln.sh/gEldrO+.
Here's what it looks like after it has been resized: https://cln.sh/MuhknK+.
You should be able to see the "tearing."
Any suggestions about how to make this widget resize its pixmap correctly?


text:
Q: How can I make a generic sort method to sort a HashMap of ArrayLists of multiple types? I'm trying to selection sort a passed HashMap of ArrayLists but I'm kind of stuck. I'm not sure how to make it a generic method that works on ints, doubles, and strings. I've looked at past questions similar to this but I still don't understand.Any help or guidance is appreciated.
public static HashMap sort_list(HashMap lists) {

    HashMap sorted_lists = new HashMap();

    ArrayList<Integer> sorted_ints = new ArrayList<>();
    ArrayList<Double> sorted_doubles = new ArrayList<>();
    ArrayList<String> sorted_strings = new ArrayList<>();

    ArrayList list_of_ints = (ArrayList) lists.get("ints");
    ArrayList list_of_doubles = (ArrayList) lists.get("doubles");
    ArrayList list_of_strings = (ArrayList) lists.get("strings");

    //My sort code below (which doesn't work with this implementation)
    int min;

    for(int i = 0; i < arr.size() - 1; i++) {

        min = i;

        for(int j = i + 1; j < arr.size(); j++) {

            if(arr.get(j) < arr.get(min)) {
                min = j;
            }
        }

        int temp = arr.get(min);
        arr.set(min, arr.get(i));
        arr.set(i, temp);
    }
    // return hashmap
    return sorted_lists;
}

A: Java already provides a facility to sort Lists, provided the elements in the List implement the Comparable interface. It's called Collections.sort check it out. That is the correct way to do a "generic sort": implement the appropriate interface exactly like Collections.sort requires.


text:
Q: How does NumPy's transpose() method permute the axes of an array? In [28]: arr = np.arange(16).reshape((2, 2, 4))

In [29]: arr
Out[29]:
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 8,  9, 10, 11],
        [12, 13, 14, 15]]])

In [32]: arr.transpose((1, 0, 2))
Out[32]:
array([[[ 0,  1,  2,  3],
        [ 8,  9, 10, 11]],

       [[ 4,  5,  6,  7],
        [12, 13, 14, 15]]])

When we pass a tuple of integers to the transpose() function, what happens?
To be specific, this is a 3D array: how does NumPy transform the array when I pass the tuple of axes (1, 0 ,2)? Can you explain which row or column these integers refer to? And what are axis numbers in the context of NumPy?

A: In C notation, your array would be:
int arr[2][2][4]

which is an 3D array having 2 2D arrays. Each of those 2D arrays has 2 1D array, each of those 1D arrays has 4 elements.
So you have three dimensions. The axes are 0, 1, 2, with sizes 2, 2, 4. This is exactly how numpy treats the axes of an N-dimensional array.
So, arr.transpose((1, 0, 2)) would take axis 1 and put it in position 0, axis 0 and put it in position 1, and axis 2 and leave it in position 2. You are effectively permuting the axes:
0 -\/-> 0
1 -/\-> 1
2 ----> 2

In other words, 1 -> 0, 0 -> 1, 2 -> 2. The destination axes are always in order, so all you need is to specify the source axes. Read off the tuple in that order: (1, 0, 2).
In this case your new array dimensions are again [2][2][4], only because axes 0 and 1 had the same size (2).
More interesting is a transpose by (2, 1, 0) which gives you an array of [4][2][2].
0 -\ /--> 0
1 --X---> 1
2 -/ \--> 2

In other words, 2 -> 0, 1 -> 1, 0 -> 2. Read off the tuple in that order: (2, 1, 0).
>>> arr.transpose((2,1,0))
array([[[ 0,  8],
        [ 4, 12]],

       [[ 1,  9],
        [ 5, 13]],

       [[ 2, 10],
        [ 6, 14]],

       [[ 3, 11],
        [ 7, 15]]])

You ended up with an int[4][2][2].
You'll probably get better understanding if all dimensions were of different size, so you could see where each axis went.
Why is the first inner element [0, 8]? Because if you visualize your 3D array as two sheets of paper, 0 and 8 are lined up, one on one paper and one on the other paper, both in the upper left. By transposing (2, 1, 0) you're saying that you want the direction of paper-to-paper to now march along the paper from left to right, and the direction of left to right to now go from paper to paper. You had 4 elements going from left to right, so now you have four pieces of paper instead. And you had 2 papers, so now you have 2 elements going from left to right.
Sorry for the terrible ASCII art. ¯\_(ツ)_/¯

A: It seems the question and the example originates from the book Python for Data Analysis by Wes McKinney. This feature of transpose is mentioned in Chapter 4.1. Transposing Arrays and Swapping Axes.

For higher dimensional arrays, transpose will accept a tuple of axis numbers to permute the axes (for extra mind bending).

Here "permute" means "rearrange", so rearranging the order of axes.
The numbers in .transpose(1, 0, 2) determines how the order of axes are changed compared to the original. By using .transpose(1, 0, 2), we mean, "Change the 1st axis with the 2nd." If we use .transpose(0, 1, 2), the array will stay the same because there is nothing to change; it is the default order.
The example in the book with a (2, 2, 4) sized array is not very clear since 1st and 2nd axes has the same size. So the end result doesn't seem to change except the reordering of rows arr[0, 1] and arr[1, 0].
If we try a different example with a 3 dimensional array with each dimension having a different size, the rearrangement part becomes more clear.
In [2]: x = np.arange(24).reshape(2, 3, 4)

In [3]: x
Out[3]:
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])

In [4]: x.transpose(1, 0, 2)
Out[4]:
array([[[ 0,  1,  2,  3],
        [12, 13, 14, 15]],

       [[ 4,  5,  6,  7],
        [16, 17, 18, 19]],

       [[ 8,  9, 10, 11],
        [20, 21, 22, 23]]])

Here, original array sizes are (2, 3, 4). We changed the 1st and 2nd, so it becomes (3, 2, 4) in size. If we look closer to see how the rearrangement exactly happened;  arrays of  numbers seems to have changed in a particular pattern. Using the paper analogy of @RobertB, if we were to take the 2 chunks of numbers, and write each one on sheets, then take one row from each sheet to construct one dimension of the array, we would now have a 3x2x4-sized array, counting from the outermost to the innermost layer.
[ 0,  1,  2,  3] \ [12, 13, 14, 15]

[ 4,  5,  6,  7] \ [16, 17, 18, 19]

[ 8,  9, 10, 11] \ [20, 21, 22, 23]

It could be a good idea to play with different sized arrays, and change different axes to gain a better intuition of how it works.

A: I ran across this in Python for Data Analysis by Wes McKinney as well.
I will show the simplest way of solving this for a 3-dimensional tensor, then describe the general approach that can be used for n-dimensional tensors.
Simple 3-dimensional tensor example
Suppose you have the (2,2,4)-tensor
[[[ 0  1  2  3]
  [ 4  5  6  7]]

 [[ 8  9 10 11]
  [12 13 14 15]]]

If we look at the coordinates of each point, they are as follows:
[[[ (0,0,0)  (0,0,1)  (0,0,2)  (0,0,3)]
  [ (0,1,0)  (0,1,1)  (0,1,2)  (0,1,3)]]

 [[ (1,0,0)  (1,0,1) (1,0,2) (0,0,3)]
  [ (1,1,0)  (1,1,1) (1,1,2) (0,1,3)]]

Now suppose that the array above is example_array and we want to perform the operation: example_array.transpose(1,2,0)
For the (1,2,0)-transformation, we shuffle the coordinates as follows (note that this particular transformation amounts to a "left-shift":
(0,0,0)  ->  (0,0,0)
(0,0,1)  ->  (0,1,0)
(0,0,2)  ->  (0,2,0)
(0,0,3)  ->  (0,3,0)
(0,1,0)  ->  (1,0,0)
(0,1,1)  ->  (1,1,0)
(0,1,2)  ->  (1,2,0)
(0,1,3)  ->  (1,3,0)
(1,0,0)  ->  (0,0,1)
(1,0,1)  ->  (0,1,1)
(1,0,2)  ->  (0,2,1)
(0,0,3)  ->  (0,3,0)
(1,1,0)  ->  (1,0,1)
(1,1,1)  ->  (1,1,1)
(1,1,2)  ->  (1,2,1)
(0,1,3)  ->  (1,3,0)

Now, for each original value, place it into the shifted coordinates in the result matrix.
For instance, the value 10 has coordinates (1, 0, 2) in the original matrix and will have coordinates (0, 2, 1) in the result matrix. It is placed into the first 2d tensor submatrix in the third row of that submatrix, in the second column of that row.
Hence, the resulting matrix is:
array([[[ 0,  8],
        [ 1,  9],
        [ 2, 10],
        [ 3, 11]],

       [[ 4, 12],
        [ 5, 13],
        [ 6, 14],
        [ 7, 15]]])

General n-dimensional tensor approach
For n-dimensional tensors, the algorithm is the same. Consider all of the coordinates of a single value in the original matrix. Shuffle the axes for that individual coordinate. Place the value into the resulting, shuffled coordinates in the result matrix. Repeat for all of the remaining values.

A: To transpose an array, NumPy just swaps the shape and stride information for each axis. Here are the strides:
>>> arr.strides
(64, 32, 8)

>>> arr.transpose(1, 0, 2).strides
(32, 64, 8)

Notice that the transpose operation swapped the strides for axis 0 and axis 1. The lengths of these axes were also swapped (both lengths are 2 in this example).
No data needs to be copied for this to happen; NumPy can simply change how it looks at the underlying memory to construct the new array.

Visualising strides
The stride value represents the number of bytes that must be travelled in memory in order to reach the next value of an axis of an array.
Now, our 3D array arr looks this (with labelled axes):

This array is stored in a contiguous block of memory; essentially it is one-dimensional. To interpret it as a 3D object, NumPy must jump over a certain constant number of bytes in order to move along one of the three axes:

Since each integer takes up 8 bytes of memory (we're using the int64 dtype), the stride value for each dimension is 8 times the number of values that we need to jump. For instance, to move along axis 1, four values (32 bytes) are jumped, and to move along axis 0, eight values (64 bytes) need to be jumped.
When we write arr.transpose(1, 0, 2) we are swapping axes 0 and 1. The transposed array looks like this:

All that NumPy needs to do is to swap the stride information for axis 0 and axis 1 (axis 2 is unchanged). Now we must jump further to move along axis 1 than axis 0:

This basic concept works for any permutation of an array's axes. The actual code that handles the transpose is written in C and can be found here.

A: As explained in the documentation:

By default, reverse the dimensions, otherwise permute the axes according to the values given.

So you can pass an optional parameter axes defining the new order of dimensions.
E.g. transposing the first two dimensions of an RGB VGA pixel array:
 >>> x = np.ones((480, 640, 3))
 >>> np.transpose(x, (1, 0, 2)).shape
 (640, 480, 3)

A: To summarise a.transpose()[i,j,k] = a[k,j,i]
a = np.array( range(24), int).reshape((2,3,4))
a.shape gives (2,3,4)
a.transpose().shape gives (4,3,2)  shape tuple is reversed.

when is a tuple parameter is passed axes are permuted according to the tuple.
For example
a = np.array( range(24), int).reshape((2,3,4))
a[i,j,k] equals a.transpose((2,0,1))[k,i,j]
axis 0 takes 2nd place
axis 1 takes 3rd place
axis 2 tales 1st place
of course we need to take care that values in tuple parameter passed to transpose are unique and in range(number of axis)


text:
Q: VSCode terminal is using the wrong python version I have a new mac with python 3 installed from homebrew and visual studio code. I am not a python person by default I tend to use java but wanted to try a project for fun.
Just my terminal in VSCode has a system install of python 3.8 version that I am not using I want to use my brew install version as shown in screen shots. if I do echo $path it shows correct, my mac terminal shows correct and my VSCode python plugin has the correct version showing. I have rebooted several times in case it was cached.
I want to use the brew version 3.9.7. My project is failing to load imports such as "import requests" I assume because of this. The import fail error is.
Import "requests" could not be resolved from sourcePylancereportMissingModuleSource
I have installed and uninstalled requests many times always through VSCode command line.

A: Perhaps the values in $PATH of VS Code is in a different order than that of Terminal.app.
See https://github.com/microsoft/vscode/issues/70248 for more informations.
You can simply set "terminal.integrated.inheritEnv": false. This works well for me.

A: Try putting the following in settings.json:
"terminal.integrated.env.osx": {
        "PATH": ""
}

Save the file, close any terminal window and restart VS Code.
You can read more here.

A: Go into VS Code settings: Code->Preferences->Settings. Type the following in the search box:
terminal.integrated.inheritEnv": false

Uncheck the option box beside the setting "whether new shells should inherit their environment from VS Code..." to set it to False.
Restart VS code and try again, you should have the same version of python as on your standard terminal.


text:
Q: MSB3073: The command dotnet bundle clean exited with code 1 in a Visual Studio 2019 Asp.NetCore project I got the error MSB3073: The command dotnet bundle clean exited with code 1 in a Visual Studio 2019 Asp.NetCore project. This issue only occured after I updated my Visual Studio yesterday.
> dotnet bundle clean

NuGet.Packaging.Core.PackagingException: Der Fallbackpaketordner "C:\ProgramData\Xamarin\NuGet" wurde nicht gefunden.
   at NuGet.Packaging.FallbackPackagePathResolver..ctor(String userPackageFolder, IEnumerable`1 fallbackPackageFolders)
   at Microsoft.DotNet.Cli.Utils.LockFileExtensions.GetPackageDirectory(LockFile lockFile, LockFileTargetLibrary library)
   at Microsoft.DotNet.Cli.Utils.PackagedCommandSpecFactory.GetCommandFilePath(LockFile lockFile, LockFileTargetLibrary toolLibrary, LockFileItem runtimeAssembly)
   at Microsoft.DotNet.Cli.Utils.PackagedCommandSpecFactory.CreateCommandSpecFromLibrary(LockFileTargetLibrary toolLibrary, String commandName, IEnumerable`1 commandArguments, IEnumerable`1 allowedExtensions, LockFile lockFile, CommandResolutionStrategy commandResolutionStrategy, String depsFilePath, String runtimeConfigPath)
   at Microsoft.DotNet.Cli.Utils.ProjectToolsCommandResolver.ResolveCommandSpecFromToolLibrary(SingleProjectInfo toolLibraryRange, String commandName, IEnumerable`1 args, IProject project)
   at Microsoft.DotNet.Cli.Utils.ProjectToolsCommandResolver.ResolveCommandSpecFromAllToolLibraries(IEnumerable`1 toolsLibraries, String commandName, IEnumerable`1 args, IProject project)
   at Microsoft.DotNet.Cli.Utils.ProjectToolsCommandResolver.ResolveFromProjectTools(CommandResolverArguments commandResolverArguments)
   at Microsoft.DotNet.Cli.Utils.ProjectToolsCommandResolver.Resolve(CommandResolverArguments commandResolverArguments)
   at Microsoft.DotNet.Cli.Utils.CompositeCommandResolver.Resolve(CommandResolverArguments commandResolverArguments)
   at Microsoft.DotNet.Cli.Utils.CommandResolver.TryResolveCommandSpec(ICommandResolverPolicy commandResolverPolicy, String commandName, IEnumerable`1 args, NuGetFramework framework, String configuration, String outputPath, String applicationName)
   at Microsoft.DotNet.Cli.Utils.Command.Create(ICommandResolverPolicy commandResolverPolicy, String commandName, IEnumerable`1 args, NuGetFramework framework, String configuration, String outputPath, String applicationName)
   at Microsoft.DotNet.Cli.Utils.Command.Create(String commandName, IEnumerable`1 args, NuGetFramework framework, String configuration, String outputPath, String applicationName)
   at Microsoft.DotNet.Cli.Program.ProcessArgs(String[] args, ITelemetry telemetryClient)
   at Microsoft.DotNet.Cli.Program.Main(String[] args)

The Visual Studio version is 16.1.0.
I don't know why dotnet uses the fallback folder. Neither do I know why the folder isn't there because I have installed Xamarin support in Visual Studio 2019.

A: The issue can be solved quite easily: Just add the folder(s) C:\ProgramData\Xamarin\NuGet as empty folders to avoid this issue.


text:
Q: Changing CSS variable based on the parent class || Sass and Tailwind CSS I'm styling a Next.js website using Tailwind CSS and trying to build a theme switching mechanism using CSS (Sass) variables.
Mainly I have two modes:

*

*Default mode: Includes light and dark themes.

*Minimalist mode: also includes light and dark themes but with much fewer colours (black and white mostly).

So generally the user has four options, and the same tailwind colour changes based on the dynamically provided classes.
Based on the main div class bg-primary should be as follows:

*

*no class provided => default light theme, bg-primary = #79A542; // works perfectly

*"dark" => default dark theme, bg-primary = #03004C; // works perfectly

*"minimalist" => minimalist light theme, bg-primary = #FEFDF8; // works perfectly

*"minimalist dark" => minimalist dark theme, bg-primary = #0f0f0f; // doesn't work

All of the theme combinations work except for "minimalist dark", the bg-primary is #03004C not #0f0f0f why is that? Why is the minimalist dark theme overridden by the default one?
This is my globals.scss file configuration:
@tailwind base;
@import url('https://fonts.googleapis.com/css2?family=Amiri&family=Montserrat&family=Rakkas&family=Roboto&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Aref+Ruqaa&family=Lateef&display=swap');

:root {
/*default mode*/
  --primary:  #79A542;
  --secondary: #CFF0A5;
  --third: #CFF0A5;
  --inverse: #0f0f0f;
  --font-mono: 'Roboto Mono',monospace;
  --font-sans: 'Montserrat', sans-serif;
  & .arabic {
    --font-mono: 'Amiri', serif;
    --font-sans: 'Rakkas', cursive;
  }
  & .dark {
    --primary: #03004C;
    --secondary: #6A1497;
    --third: #E61D6D;
    --inverse: #7C54E1;
  }
}

.minimalist {
/*Minimalist mode*/
  --third: #98999B;
  --inverse: transparent;
  --primary: #FEFDF8;
  --secondary: #0f0f0f;
  & .dark {
    --primary: #0f0f0f;
    --secondary: #FEFDF8;
  }
  & .arabic {
    --font-mono: 'Aref Ruqaa', serif;
    --font-sans: 'Lateef', cursive;
  }
}

@tailwind components;
@tailwind utilities;

This is my _app.js file:
import '../styles/globals.css'
import Nav from '../components/Nav'
import { useState} from 'react'

function MyApp({ Component, pageProps }) {
  const [attributes, setAttributes] = useState("minimalist dark") // Themes are changed here

  return (
    <div className={attributes}>
      <main className="bg-primary">
        <Nav/>
      </main>
    </div>
  )
}

export default MyApp

And this is my tailwind.config.js file:
module.exports = {
  purge: ['./pages/**/*.js', './components/**/*.js'],
  darkMode: 'class', // or 'media' or 'class'
  theme: {
    extends: {
    },
    colors: {},
    textColor: {
      primary: 'var(--primary)',
      secondary: 'var(--secondary)',
      third: 'var(--third)',
      inverse: 'var(--inverse)',
      white: 'var(--white)',
      black: 'var(--black)',
    },
    backgroundColor: {
      primary: 'var(--primary)',
      secondary: 'var(--secondary)',
      third: 'var(--third)',
      inverse: 'var(--inverse)',
      white: 'var(--white)',
      black: 'var(--black)',
    },
    fontFamily: {
      'sans': 'var(--font-sans)',
      'mono': 'var(--font-mono)',
    },
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

Has the issue something to do with reusing the same dark class? How do I resolve this?

A: Your current CSS selector will be .minimalist .dark which means the dark class inside the minimalist class. You want to have the minimalist class that's also have a class of dark. In CSS that's .mimimalist.dark, without a space.
In SCSS, you need to remove the space between the parent selector (&) and the class name, like this:
.minimalist {
  --third: #98999B;
  --inverse: transparent;
  --primary: #FEFDF8;
  --secondary: #0f0f0f;

  &.dark {
    --primary: #0f0f0f;
    --secondary: #FEFDF8;
  }
}

The default .dark class works fine, because it's inside the :root class.


text:
Q: Select data in Userform based on data selected in filtered Search Form I have a search form where I can filter my search and list all common items per my search text. I have it where I can double click on the row I need and fill in the test boxes on my User Form, but I need it to also select the same data in the User Form listbox. Is that possible and how would I go about doing that
Any suggestion are greatly appreciated.
V/R
Michael


text:
Q: How do I fix monitor detection in Windows 7? I'm using Windows 7 + Windows Media Center for my HTPC. It works great except from one annoying issue. Whenever I turn off my TV while listening to music, the music stops for a second or while Windows 7 tries to figure out what monitor is attached. After that second it settles down on a default 800x640. While not a big deal, it is annoying as I don't want to have the TV on while playing music.
Is there anyway to fix the monitor/disable monitor auto-detection on Windows 7 so it would not start recalibrating everything when I turn off my TV?

A: This just in!   Block pin 19 on your hdmi cable with a small piece of electrical tape
like so
http://postimage.org/image/2g8p5dwdg/
This pin is responsible for sending on/off signals
Not my solution but I thought I would take a minute to propagate working intel as this solved the headache for me

A: You can disable the auto-detection feature of your graphics card through the advanced display properties or the driver management utility.
If yours is a ATI card, check the Catalyst Control Center:

A: I have a solution but I don't know if it only works for me.
You have to setup in display/screen resolution your monitors(plasma whatever) to be generic non-pnp monitor
For example: I started Windows 7 with my monitor closed and  plasma didnt get recognized
And I didn't clicked on detect, I leaved the greyed out display and just select the  option:
multiple displays:extend these displays
I also did that before with my main display Sony CRT monitor.
So now I can start Windows with everything turn off and  when Windows 7 loads up and i  turn on my plasma and sony crt everything is in place
And doesnt get undetected.
If your generic non-pnp monitor doesnt give you resolutions you need you can create them (custom resolution) with Nvidia control panel.

A: This fixed it for me.
Newest version of Catalyst Control Center as of today. 6-24-2014
Preferences - Advanced View
Left side column - Open My VGA Displays - Click on properties (VGA Display)
Uncheck EDID
Set display size and frequency. I recommend 60 hz unless you know for sure it can handle other frequencies as this is default for any monitor.

A: Add this reg entry by typing in regedit into the start search bar and hitting enter:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\TMM]
"UseIViewHelper"=dword:00000000
@="0"
==========================================================================

or save:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\TMM]
"UseIViewHelper"=dword:00000000
@="0"

in a .reg file (if your folder extensions are visible). If they're not - go to the folder you're in (Organize > Folder and Search Options) and enable "Show extensions for known file types".
You can now save this file as .txt and rename to .reg or whatever method you may choose to save this as a registry file.
When you double click on a registry file, it asks you if you want to enter this into the system registry - Say yes.

A: open regedit and find
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Contro l\Video{XXXX...}\0000
( 'XXXX' means device number. There are several device number folder and u should find 'AdapterDesc' in 0000 folder which key value is 'amd radeon HD 7XXX Series'. )
At that '0000' folder, Change 'PP_SclkDeepSleepDisable REG_DWORD' value 0 to 1.
and reboot!
worked for me

A: Have a look at your services, the graphics card may have a service to detect this such as "AMD External Events Utility" or "ati hotkey poller". Disable it and see if that makes a difference.

A: Here's a solution that worked for me. Windows 7, NVidia Quadro NVS 295. But that's largely irrelevant.
The important part is, these are HP monitors EliteDisplay 241i.
Go to the on screen menu > Input Control > DP Hot-Plug Detection > switch it from Low Power to Always Active.
Doing this on both monitors has resolved the problem for me.
I suspect other monitors will have similar settings.


text:
Q: Change font in all tables of the document I would like to change the default font in all tables of my document. Instead of the Computer Modern Roman font I prefer Bitstream Charter Mathdesign (the same family), which is "condensed":
\documentclass{article}
\usepackage[charter, uppercase=upright]{mathdesign}

\makeatletter
\renewcommand{\sfdefault}{cmr}

\g@addto@macro{\table}{\fontencoding{T1}\fontfamily{mdbch}\selectfont}
\makeatother

\begin{document}

\begin{table}
    \caption{My Table}\label{tab:table}
    \centering
    \begin{tabular}{cc}\hline
      X & Y \\ \hline
      x1 & y1 \\
      x2 & y2 \\ \hline
    \end{tabular}
\end{table}

Some short text outside a table in a current font.

\end{document}

Using the following code, the Mathdesign font is used for the entire document :-(
Thank you very much for your help.

A: Probably solved in a different way, using the environment command and a different nick:
\documentclass{article}

\makeatletter
\renewenvironment{table}
     {\renewcommand\familydefault{mdbch}
      \@float{table}}
     {\end@float}
\makeatother

\begin{document}

\begin{table}
    \caption{My Table}\label{tab:table}
    \centering
    \begin{tabular}{cc}\hline
      X & Y \\ \hline
      x1 & y1 \\
      x2 & y2 \\ \hline
    \end{tabular}
\end{table}

Some short text outside a table in a current font.

\end{document}

Maybe, it helps....


text:
Q: Where should I install template scripts? If I have a program that copies and modifies scripts or code-files as part of its operation, where should these other "default" or "template" scripts be installed?

A: /usr/local/share, /opt, or users directory.

*

*/usr/local follows the same structure as /usr however it is for you to put your own stuff into. /usr is for the system installer to manage. Don't get in its way. /usr/local will not be touched by built in tools, so can be backed up and managed more easily.

*/opt is also (like /usr/local) for your own use. However if follows a different pattern. It is one directory per package, everything in one directory.

*You can also put it in your own directory. This needs no special permission, but will be harder for other users to know it is there.


text:
Q: Counting binary forms inside of an orbit having bounded height Let $V_n(\mathbb{Z})$ denote the $\mathbb{Z}$-lattice of integral binary $n$-ic forms: that is,
$$\displaystyle V_n(\mathbb{Z}) = \{a_n x^n + a_{n-1} x^{n-1} y + \cdots + a_0 y^n : a_i \in \mathbb{Z}, 0 \leq i \leq n \}.$$
The group $\text{GL}_2(\mathbb{Z})$ acts on $V_n(\mathbb{Z})$ by substitution.
We denote by $H(f) = \max\{|a_n|, \cdots, |a_0|\}$ for the (naive) height of an element $f \in V_n \mathbb{Z}$.
Now fix $f \in V_n(\mathbb{Z})$, not identically zero. Let $O(f)$ denote the orbit of $f$ under $\text{GL}_2(\mathbb{Z})$. Do we know how to count
$$\displaystyle \{g \in O(f) : H(g) \leq X\}?$$


text:
Q: "QObject::~QObject: Timers cannot be stopped from another thread" in C++ I got the problem about timers which is

QObject::~QObject: Timers cannot be stopped from another thread

Below is the log data from my terminal.
$ ./boost_tutorials
init done
All done. Exit safely!
QObject::~QObject: Timers cannot be stopped from another thread

Here is my C++ code with thread from boost. I build it via CMakeLists.
#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <iostream>
#include <opencv2/opencv.hpp>

class Robot {
public:
  Robot() {
    cap.open(-1);
    SYSTEM_QUIT = false;
    if (!cap.isOpened()) {
      cout << "Error opening the video" << endl;
      SYSTEM_QUIT = true;
    }
  }

  ~Robot() {
    destroyAllWindows();
    cout << "All done. Exit safely!" << endl;
  }

  void run() {
    boost::thread* t1 = new boost::thread(boost::bind(&Robot::imageProcCallback, this));
    boost::thread* t2 = new boost::thread(boost::bind(&Robot::simpleCallback, this));
    t1->join();
    t2->join();
  }

  void imageProcCallback() {
    Mat frame;
    int cc = 0;
    while(!SYSTEM_QUIT) {
      cap >> frame;
      if (!msgs.empty()) {
        Point pt(rand()%frame.cols, rand()%frame.rows);
        putText(frame, msgs.back(), pt, cv::FONT_HERSHEY_COMPLEX, 2, Scalar(0, 255, 0));
     }

     imshow(filename, frame);
     if (waitKey(5) == 27)
       SYSTEM_QUIT = true;
     }
     frame.release();
  }

  void simpleCallback() {
    while(!SYSTEM_QUIT) {
      int count = rand() % 100;
      std::string str = std::to_string(count);
      msgs.push_back(str);
    }
  }

private:
  string filename;
  VideoCapture cap;
  bool SYSTEM_QUIT;
  std::vector<std::string> msgs;
};

void main() {
  Robot robot;
  robot.run();
}


text:
Q: Pie Chart to Cylinder in CSS HTML I'm new to coding in CSS and HTML.
I want to have a pie chart convert into a 3d cylinder with the pie chart still remaining at the top. This animation would occur as you scroll down the page.
Does anyone have any tips?
I have tried doing some animation with the pie chart and seeing if maybe I could just have a 3D element that changes sides when scrolling but I don't know the best way to go about it. I can't seem to have the pie chart be on the top of the 3D element.


text:
Q: Spring Cloud function Routing I am trying to create a kafka via implementation of Spring cloud function. I am using spring-boot version 2.4.0 and spring cloud version: 2020.0.0
@Slf4j
@Component
public class ArticleEventPublisher implements Function<ArticleAggregatedDocument, Message<ArticleMessage>> {

    private final ArticleMessageMapper articleMessageMapper;

    public ArticleEventPublisher(
        ArticleMessageMapper articleMessageMapper) {
        this.articleMessageMapper = articleMessageMapper;
    }

    @Override
    public Message<ArticleMessage> apply(ArticleAggregatedDocument articleAggregatedDocument) {
        String destination ="articleAggregated";
        log.info("CREATING MESSAGE IN FUNCTION BEAN");
        return createMessage( articleAggregatedDocument, destination);
    }

    private Message<ArticleMessage> createMessage(ArticleAggregatedDocument articleAggregatedDocument, String destination) {
        ArticleMessage articleMessage = articleMessageMapper.apply(articleAggregatedDocument);

        return MessageBuilder
            .withPayload(articleMessage)
            .setHeader(KafkaHeaders.MESSAGE_KEY, articleMessage.getKey().getBytes())
            .setHeader("spring.cloud.stream.sendto.destination", destination)
            .build();
    }
}

I understand it's not dynamic binding and the destination is hard coded, however, I want to test for now this particular implementation.
Although the control in the application does go to the class and messages are being created, I don't see them in the 'destination'.
I added following in my application.properties:
spring.cloud.function.routing.enabled= true
spring.cloud.function.scan.packages= **publisher package name**
spring.cloud.stream.bindings.articleAggregated.destination=article.aggregated
spring.cloud.stream.bindings.articleAggregated.contentType=application/json
spring.cloud.stream.bindings.articleAggregated.producer.autoStartup=false
spring.cloud.stream.bindings.articleAggregated.producer.headerMode=none
spring.cloud.stream.kafka.bindings.articleAggregated.producer.configuration.client.id=articleAggregated
spring.cloud.stream.kafka.bindings.articleAggregated.producer.sync=true

I would also like to mention here that the following properties configuration are not resolved anymore in the IDEA intelliJ:
spring.cloud.function.routing.enabled
spring.cloud.function.scan.packages

Are they deprecated? I couldn't find anything about it on the documentation.
From the documentation I also read that the binders should be added for each producer/consumer in case of multibinders, but we are using only one binder for all consumers and producers in the application, so I did not add it. But I did try this in my desperate moment:
spring.cloud.stream.bindings.articleAggregated.binder=kafka

What am I missing here? I have been stuck at this for a while and in the meantime switched to Sink+Supplier implementation as an alternative. But I want to understand why this implementation won't work.

A: Thank you Rashmi.
Let me come up with the best answer I can, but feel free to follow up with more questions. So. . .

*

*In your example, I see a single function userInfo. This would result in two bindings - userInfo-in-0 for input and userInfo-out-0 for output.

*Since this function produces Message with . . .sendto.destination header the userInfo-out-0 binding will only be used s output destination for cases when sendto.destination header is not set.

*In your configuration i see the the spring.cloud.function.routing.enabled, spring.cloud.function.scan.packages, spring.kafka.bootstrap-servers and three spring.cloud.stream.kafka.* properties which point to default localhost kafka instance, which we already know by default, so non of those properties are necessary.

*You also don't need spring.cloud.stream.bindings.articleAggregated.binder=kafka property unless you have multiple binders on your classpath which you don't.

Now I am confused about spring.cloud.stream.bindings.userAggregated.destination property. The userAggregated is a dynamic destination. By simply sending to it s-c-stream will automatically provision it in Kafka if it doesn't exist, otherwise it will be used and you can see your messages there.
In other words you can remove all of the properties you have configured, send message to userInfo-out-0 destination in Kafka and your should successfully retrieve it in userAggregated destination.
Please let me know if I am missing something.


text:
Q: Usage of local variables in closures when accessing Spark RDDs I have a question regarding the usage of local variables in closures when accessing Spark RDDs. The problem I would like to solve looks as follows:
I have a list of textfiles that should be read into an RDD.
However, first I need to add additional information to an RDD that is created from a single textfile. This additional information is extracted from the filename. Then, the RDDs are put into one big RDD using union().
from pyspark import SparkConf, SparkContext
spark_conf = SparkConf().setAppName("SparkTest")
spark_context = SparkContext(conf=spark_conf)

list_of_filenames = ['file_from_Ernie.txt', 'file_from_Bert.txt']
rdd_list = []
for filename in list_of_filenames:
    tmp_rdd = spark_context.textFile(filename)
    # extract_file_info('file_from_Owner.txt') == 'Owner'
    file_owner = extract_file_info(filename)
    tmp_rdd = tmp_rdd.map(lambda x : (x, file_owner))
    rdd_list.append(tmp_rdd)
overall_content_rdd = spark_context.union(rdd_list)
# ...do something...
overall_content_rdd.collect()
# However, this does not work:
# The result is that always Bert will be the owner, i.e., never Ernie.

The problem is that the map() function within the loop does not refer to the "correct" file_owner. Instead, it will refer to the latest value of file_owner. On my local machine, I managed to fix the problem by calling the cache() function for each single RDD:
# ..
tmp_rdd = tmp_rdd.map(lambda x : (x, file_owner))
tmp_rdd.cache()
# ..

My Question: Is using cache() the correct solution for my problem? Are there any alternatives?
Many Thanks!

A: This is not a Spark phenomenon, but a plain Python one.
>>> fns = []
>>> for i in range(3):
...   fns.append(lambda: i)
...
>>> for fn in fns:
...   print fn()
...
2
2
2

One way to avoid it is to declare functions which default arguments. The default value is evaluated at the time of declaration.
>>> fns = []
>>> for i in range(3):
...   def f(i=i):
...     return i
...   fns.append(f)
...
>>> for fn in fns:
...   print fn()
...
0
1
2

This comes up a lot, see these other questions:

*

*Lexical closures in Python

*What do (lambda) function closures capture?

A: So the cache() method that you are doing won't necessarily work 100% of the time, it works provided that no nodes fail and no partitions need to be recomputed. A simple solution would be to make a function that will "capture" the value of file_owner. Here is a quick little illustration in the pyspark shell of a potential solution:
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /__ / .__/\_,_/_/ /_/\_\   version 1.2.0-SNAPSHOT
      /_/

Using Python version 2.7.6 (default, Mar 22 2014 22:59:56)
SparkContext available as sc.
>>> hi = "hi"
>>> sc.parallelize(["panda"])
ParallelCollectionRDD[0] at parallelize at PythonRDD.scala:365
>>> r = sc.parallelize(["panda"])
>>> meeps = r.map(lambda x : x + hi)
>>> hi = "by"
>>> meeps.collect()
['pandaby']
>>> hi = "hi"
>>> def makeGreetFunction(param):
...     return (lambda x: x + param)
...
>>> f = makeGreetFunction(hi)
>>> hi="by"
>>> meeps = r.map(f)
>>> meeps.collect()
['pandahi']
>>>

A: You could make an array of file owners and use that in the map transformation:
file_owner[i] = extract_file_info(filename)
tmp_rdd = tmp_rdd.map(lambda x : (x, file_owner[i]))

A: As others explained, the problem with your lambda function is that it will evaluate file_owner at the time of execution. To force its evaluation during the iteration of your for loop, you have to create and execute construction function. Here is how to do it with lambdas:
# ...
file_owner = extract_file_info(filename)
tmp_rdd = tmp_rdd.map((lambda owner: lambda line: (line,owner))(file_owner))
# ...


text:
Q: How to send C++ data to PHP with post request and what is allowed to send? Okay, so I got a game, that needs to send some stuff from C++ to a PHP page using a post request.
My questions are:
How can I send a post request?
What kind of data can I send over to PHP? (just strings and ints or also entire collections?)

A:
How can I send a post request?

This is normally done using an HTTP library. I've not used one in C++ myself, but cURL is popular across platforms and has [C++ bindings][1] (although the documentation seems to be undergoing migration at the moment).
There is more information on the subject in this question.

What kind of data can I send over to PHP?

Pretty much any data you like - but it has to be a data format rather then a data structure. If you want to send a collection you would need to serialise it to some format. JSON is a popular one. Binary data can be encoded using base64.
If you do use JSON you could either then add a second layer of encoding to send it application/x-www-form-urlencoded and access the raw JSON via $_POST or you can make the JSON the whole body of the POST request and  get the body of the post in PHP.

A: The fact that you say you're sending via POST request tells me that you're using a HTTP server to serve your PHP script. In which case, you want a library that allows you to send HTTP requests. A very popular choice is libcURL. What can you send? You can send anything that a HTTP request would allow you to send. So anything you like.

A: You can use JSON or SOAP for sending the data. When passing small amount of data JSON is preferred. More info on JSON/SOAP

A: To build HTTP request consider using libcurl and eventually its c++ wrapper curlpp
You can send whatever you want to php but don't forget that all the data comming from HTTP will be string for php.
PHP can cast to some type like int with intval() or (int) but binary data will be more complex to handle.
Consider using some standars like json and REST to build a robust communication.


text:
Q: how to set a starting page in a ionic project Sorry if this is a stupid question I am still fairly new to this. I have a basic understanding of how the navigation works with angular js but I cant figure out how to set a starting page. I want to set my login page as my start page the url shows that the login page is open ("http://localhost:8100/#/template/login") but it only displays a blank header which I suspect is from my index (ion-nav-bar).
thank you.
index.html

    <ion-nav-bar class="bar-stable">
      <ion-nav-back-button>
      </ion-nav-back-button>
    </ion-nav-bar>

    <ion-nav-view class="slide-left-right"></ion-nav-view>

login.html
<ion-view view-title="Login" name="login-view">
  <ion-content class="padding">

lalalalala

              Username
              <input type="text">

              Password
              <input type="password">

      <button class="button button-block button-calm" ng-click="login()">Login</button>
  </ion-content>
</ion-view>

app.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleLightContent();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider) {

  // Ionic uses AngularUI Router which uses the concept of states
  // Learn more here: https://github.com/angular-ui/ui-router
  // Set up the various states which the app can be in.
  // Each state's controller can be found in controllers.js
  $stateProvider

  // setup an abstract state for the tabs directive
    .state('tab', {
    url: "/tab",
    abstract: true,
    templateUrl: "templates/tabs.html"
  })

  // Each tab has its own nav history stack:

.state('tab.login', {
    url: '/login',
    views: {
      'login': {
        templateUrl: 'templates/login.html',
        controller: 'loginCtrl'
      }
    }
  })

  .state('tab.dash', {
    url: '/dash',
    views: {
      'tab-dash': {
        templateUrl: 'templates/tab-dash.html',
        controller: 'DashCtrl'
      }
    }
  })

  .state('tab.projects', {
      url: '/projects',
      views: {
        'tab-projects': {
          templateUrl: 'templates/tab-projects.html',
          controller: 'projectsCtrl'
        }
      }
    })
    .state('tab.projects-detail', {
      url: '/projects/:projectsId',
      views: {
        'tab-projects': {
          templateUrl: 'templates/projects-detail.html',
          controller: 'projectsDetailCtrl'
        }
      }
    })

  .state('tab.account', {
    url: '/account',
    views: {
      'tab-account': {
        templateUrl: 'templates/tab-account.html',
        controller: 'AccountCtrl'
      }
    }
  });

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('login');

});

controllers.js
angular.module('starter.controllers', [])

.controller('loginCtrl', function($scope) {})

.controller('DashCtrl', function($scope) {})

.controller('projectsCtrl', function($scope, Chats) {
  $scope.chats = Chats.all();
  $scope.remove = function(chat) {
    Chats.remove(chat);
  }
})

.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
  $scope.chat = Chats.get($stateParams.chatId);
})

.controller('AccountCtrl', function($scope) {
  $scope.settings = {
    enableFriends: true
  };
});

A: I guess the problems is in your default route:
$urlRouterProvider.otherwise('/tab/login');

You have defined it depending from the abastract tab:
$stateProvider

  // setup an abstract state for the tabs directive
  .state('tab', {
    url: "/tab",
    abstract: true,
    templateUrl: "templates/tabs.html"
  })

and this is your login:
.state('tab.login', {
    url: '/login',
    views: {
      'login': {
        templateUrl: 'templates/login.html',
        controller: 'loginCtrl'
      }
    }
  })

the state name is tab.login which means it inherits from tab.
so your root is /tab/login.
this should be your tabs.html:
<ion-tabs class="tabs-icon-top tabs-color-active-positive">

  <ion-tab title="Login" icon-off="ion-ios-pulse" icon-on="ion-ios-pulse-strong" href="#/tab/login">
    <ion-nav-view name="login"></ion-nav-view>
  </ion-tab>

  <ion-tab title="Status" icon-off="ion-ios-pulse" icon-on="ion-ios-pulse-strong" href="#/tab/dash">
    <ion-nav-view name="tab-dash"></ion-nav-view>
  </ion-tab>

</ion-tabs>

as you can see your ion-nav-view name:
<ion-nav-view name="login"></ion-nav-view>

must match the one defined in your state:
.state('tab.login', {
        url: '/login',
        views: {
          'login': {
            templateUrl: 'login.html',
            controller: 'loginCtrl'
          }
        }
      })

You don't need to set the view's name here (login.html):
<ion-view view-title="Login" name="login-view">

Another thing I've noticed, you use the same name for two different views: tab-projects:
.state('tab.projects', {
      url: '/projects',
      views: {
        'tab-projects': {
          templateUrl: 'templates/tab-projects.html',
          controller: 'projectsCtrl'
        }
      }
    })
.state('tab.projects-detail', {
      url: '/projects/:projectsId',
      views: {
        'tab-projects': {
          templateUrl: 'templates/projects-detail.html',
          controller: 'projectsDetailCtrl'
        }
      }
    })

another thing has more to do with conventions. If you use for your views names starting with tab-, probably you should do the same for the login.
Here is a plunker with some of your code.

A: Change your app.js to
.state('login', {
   url: '/login',
   controller: 'LoginCtrl',
   templateUrl: 'templates/login.html'
})

and  $urlRouterProvider.otherwise('/login');
If you place your login.html in correct folder then there is not going to be any problem.

A: I've been putting comments regarding your code, so let me formulate an answer with some steps you would like to follow
1:
You have a mess once you declare your controllers, try to follow a guide like this, at least declare your controllers/services/directives and so on in the same way, LoginCtrl and not loginCtrl and the other stuff with no capital as a first letter. It is just an advise my friend.
2:
.state('tab.login', {
    url: '/login',
    views: {
      'login': {
        templateUrl: 'templates/login.html',
        controller: 'loginCtrl'
      }
    }
  })

here something you need to check, the name of your view, you have login but
<ion-view view-title="Login" name="login-view">
  ...
</ion-view>

so change it to login only. And do the same in your abstract route.
like this
<ion-view view-title="Login" name="login">

And this so important
$urlRouterProvider.otherwise('/login');

which goes at the end of the $stateProvider. The otherwise method will always redirect to /login in case that any other route it's been matched

A: You should give a name to your <ion-nav-view> in your index.html template.
e.g. <ion-nav-view name="viewContent"></ion-nav-view>
Then, in your routes, you specify into which part of your app you want your template to be rendered, e.g.:
.state('login', {
    url: '/login',
    views: {
      'viewContent': {
        templateUrl: 'templates/login.html',
        controller: 'loginCtrl'
      }
    }
  })

this will render templates/login.html into the viewContent area.
That's why UI-router is so flexible, because you can tell it exactly which parts should be replaced when routing.
If you don't need that flexibility, just write your routes without the views part and add controller and templateUrl directly to each state.
also your fallback probably should be $urlRouterProvider.otherwise('/login');

A: If you want to evaluate a success at login to show certain views should not be in the same state.
This should be true:
.state('login',{
  url: "/login",
  views : {
    'menuContent' : {
      templateUrl : "login.html",
      controller : "LoginCtrl"
    }
  }
})

$urlRouterProvider.otherwise("/login");

Follow the order as advice or guide on how to write their app.js

A: I had a similar problem..simply open your app.js file..then right at the bottom you will find  $urlRouterProvider.otherwise('/app/tabs'); so for instance if the page thats currently loading is "tabs"
simply change the value tabs to your prefered page name inorder for that page to load as the first default page.

A: There is config.xml file. Open it and and you will see 'Start Page' Option. Then enter any page you want to start.


text:
Q: Embedding an animated matplotlib in tk I am fairly new to python and a real beginner to tkinter and matplotlib.
I have the following code which essentially is a testbed for what I eventually want to do.
#!/usr/bin/env python
import  numpy as np
from  matplotlib import  pyplot as plt
import time

top = 100
plt.ion () # set plot to animated
xdata = []
c = 0
for a in range(0,top):
 xdata.append(a)
 c+=1
ydata =  [ 0 ] *  top * 10
ax1 = plt.axes ()
c = 0
myfile = open("rdata.txt", "r")
for myline in myfile:
q = myline
ydata[c] = q
c+=1
c = 0
# Make plot
line, =  plt.plot (ydata[0:60])

myfile = open("rdata.txt", "r")

for p in range(0, top * 10):
for myline in myfile:
      q = int(myline)
      ydata.append (q)
      del  ydata [ 0 ]
      line.set_xdata (np.arange ( len (ydata)))
      line.set_ydata (ydata)   # update the data
      time.sleep(0.01)
      plt.draw () # update the plot

#   c +=1

file.close(myfile)

How can I embed this in tkinter.
I have searched for hours and have come across many suggestions but it seems none of them apply to dynamic plots.
If anyone wants to see the data this program is using I created it with the following code.
#!/usr/bin/env python
import random

myfile = open("rdata.txt", "w")
myfile.write("100\n")
myfile.write("0\n")
for x in range(2,100):
 q = random.randint(10,90)
 myfile.write(str(q))
 myfile.write("\n")

file.close(myfile)

Of course it may just be that I am just not understanding this correctly

A: Here is an example, I added a button that will start animation:
import numpy as np
import matplotlib

matplotlib.use("TKAgg")
import pylab as pl
fig, ax = pl.subplots()
p = 0
x = np.linspace(0, 10, 200)
y = np.sin(x+p)
line, = ax.plot(x, y)
canvas = fig.canvas.get_tk_widget()

from Tkinter import Button

def anim():
    global p
    p += 0.04
    y = np.sin(x+p)
    line.set_data(x, y)
    fig.canvas.draw()
    canvas.after(50, anim)

def go():
    anim()

b = Button(canvas.master, text="go", command=go)
b.pack()
pl.show()


text:
Q: Using php Reflection API to make dynamic getters and setters I have some classes that do have a lot of properties!
Instead of creating a lot of getters and setters foreach class I decided to create an abstract class as templeate where I have a magic function __call to set and get properties values using Php Reflection API like below:
public function __call($name, $args)
{
    //Check to see if we are getting a property value.
    if (preg_match("/get/i", $name)) {
        //Normalize method name, in case of camel case.
        $name = strtolower($name);

        //Find the start of get/set in the method.
        $pos = strpos($name, "get") + strlen("get");

        //Strip get / set from method. Get only property name.
        $name = substr($name, $pos, strlen($name) - $pos);

        //Refelct child class object.
        $reflection = new \ReflectionClass($this);

        //Get child class properties.
        $props = $reflection->getProperties();

        //Loop through the init. class properties.
        foreach ($props as $prop) {
            //Check if the property its array so we can search the keys in an array.
            if (is_array($this->{$prop->getName()})) {
                //So it's an array, check if array property has the key that we are looking for.
                if (array_key_exists($name, $this->{$prop->getName()})) {
                    return $this->{$prop->getName()}[$name];
                }

            }
            //If its not array then check for the property name that we are looking for.
            else if ($prop->getName() == $name) {
                return $this->$name;
            }
        }
        return null;

    }
    //Same thing here same like in get method, but instead of getting the method
    //here we will be setting a property value.
    else if (preg_match("/set/i", $name)) {
        $name  = strtolower($name);
        $pos   = strpos($name, "set") + strlen("set");
        $name  = substr($name, $pos, strlen($name) - $pos);
        $value = "";

        //Make sure that we have an argument in there.
        if (count($args) >= 1) {
            $value = $args[0];
        }

        $reflection = new \ReflectionClass($this);
        $props      = $reflection->getProperties();

        foreach ($props as $prop) {
            if (is_array($this->{$prop->getName()})) {

                if (array_key_exists($name, $this->{$prop->getName()})) {
                    $this->{$prop->getName()}[$name] = $value;
                }

            } else if ($prop->getName() == $name) {
                $this->$name = $value;
            }
        }
    }
}

My questions is:

Is this a good approach to make dynamic getters and setters or what
  are the downsides of this compare to child classes getters and
  setters! And what is the best way of handling not found properties
  throwing an exception or return null ?