text:
Q: Is there a way to analyze the amplitude from a spotify song using p5.js in browser? I am attempting to make a Spotify visualizer as a personal project, but can't seem to find a way to analyze the sound before it is played through the browser. I have the Spotify player playing music through the browser, and the visualizer is working with mp3 files stored on my machine. I just don't have the slightest clue on how to connect the two. Additionally, I looked through the Spotify API and couldn't seem to find anything there either.
If there is no way to analyze a Dpotify track directly, is there any way to capture the sound played through the browser first, then play through the p5.js loadSound() function?
Here are the code snippets for reference:
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.js">
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.sound.js"></script>
</head>

 <body>
<script src="https://sdk.scdn.co/spotify-player.js"></script>
<script>
    window.onSpotifyWebPlaybackSDKReady = () => {
        const token =
            'redacted';
        const player = new Spotify.Player({
            name: 'Web Playback SDK Quick Start Player',
            getOAuthToken: cb => {
                cb(token);
            }
        });

        // Error handling
        player.addListener('initialization_error', ({
            message
        }) => {
            console.error(message);
        });
        player.addListener('authentication_error', ({
            message
        }) => {
            console.error(message);
        });
        player.addListener('account_error', ({
            message
        }) => {
            console.error(message);
        });
        player.addListener('playback_error', ({
            message
        }) => {
            console.error(message);
        });

        // Playback status updates
        player.addListener('player_state_changed', state => {
            console.log(state);
        });

        // Ready
        player.addListener('ready', ({
            device_id
        }) => {
            console.log('Ready with Device ID', device_id);
        });

        // Not Ready
        player.addListener('not_ready', ({
            device_id
        }) => {
            console.log('Device ID has gone offline', device_id);
        });

        // Connect to the player!
        player.connect();
    };
</script>
<script src="visualizer.js"></script>

var spotifyToken = ""
 //["streaming", "user-read-birthdate", "user-read-email", "user-read-private"]
var song;
var amp;
var button;

var volHistory = [];

function toggleSong(){
if (song.isPlaying()){
    song.pause();
} else {
    song.play();
}
}

function preload(){
soundFormats('mp3');
song = loadSound('backgroundsong.mp3')
}

function setup(){
var canvas = createCanvas(window.innerWidth/2, 100);
//canvas.parent('div id')
canvas.position(0, (windowHeight - height) / 2)
//var canvasLeft = createCanvas(window.innerWidth/2, 100);
//canvasLeft.position(windowWidth/2, (windowHeight - height) / 2)
//createCanvas(window.innerWidth, window.innerHeight);
masterVolume(0.002,0,0);
button = createButton('toggle');
button.mousePressed(toggleSong);
song.loop();

amp = new p5.Amplitude();
 }

function draw(){
background(0);
var volume = amp.getLevel();
volHistory.push(volume * 400);

beginShape();
stroke(0, 255, 0);
strokeWeight(3);
strokeCap(ROUND);
strokeJoin(ROUND);
noFill();
for (var i = 0; i < volHistory.length; i++) {
    var y = map(volHistory[i], 0, 1, height, 0);
    vertex(i*1.5, y);
    if (i*1.5 > width) {
        volHistory.splice(0, 1);
    }
}
endShape();

//ellipse(400, 400, volume * 800, volume * 800);

}

A: Processing raw data samples is not possible using Spotify's Web Playback SDK. As seen in the following quote Spotify uses Encrypted Media Extensions in order to make playback possible within the browser.

The Web Playback SDK is client-side JavaScript library which allows you to create a new player in Spotify Connect and play any audio track from Spotify in the browser via Encrypted Media Extensions.

You could use this Spotify Web API endpoint and try to visualize one of those properties. There are no actual samples (which would be the amplitude you asked for) but maybe something those data sets include will fit your needs.
I found a reddit thread where some people showed off some visualizations mostly using the before mentioned API endpoint.

Another option is to use Spotify's Android or iOS SDK where you have access to raw data samples though I am not sure if it is allowed by Spotify's terms of service to process those samples. But due to you are looking for something client-sided within the browser this won't fit your needs.


text:
Q: Find entity that has related entities with given primary keys I have the following entities:
Chat
id: uuid // PK

ChatMember
chatId: uuid // PK
userId: uuid // PK

Chat entity relates to ChatMember entity as one to many
I want to find chat that has chat members with specific userIds (by two different userIds for example. Chat must have two members with given userIds)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Initializing private variables in typescript lead to corruption sometimes Sometimes when i initialize variables into the method body, and i try to use the variables, it often end up undefined but if i declare it as a global variable(var variable name etc) it will work out fine, here is an example:
var num = 0;
module test{
export class tester{
    increment(){
        num++;
    }
}
}

that works fine but if i change the code to
module test{
export class tester{
    num : number;
    increment(){
        this.num++;
    }
}
}

it would give some gibberish or corrupted value it seems. This happened various times to me while coding in typescript but i often just make the variables global to solve it but i think this is bad practice. Is there a reason why this seems to occur?

A: You need to initialize num with a value.
module test{
    export class tester{
        num : number = 0;
        increment(){
            this.num++;
        }
    }
}

Otherwise you're basically doing undefined++ which is NaN.
Also, if you want to make a variable private then you should explicitly mark it as private by doing private num : number = 0;


text:
Q: For Loop with Subset in R I have the following data in a csv file:
Date        Model      Color    Value   Samples
6/19/2017   Gold       Blue     0.5     500
6/19/2017   Gold       Red      0.0     449
6/19/2017   Silver     Blue     0.75    1320
6/19/2017   Silver     Blue     1.5     103
6/19/2017   Gold       Red      0.7     891
6/19/2017   Gold       Blue     0.41    18103
6/19/2017   Copper     Blue     0.83    564
6/19/2017   Silver     Pink     1.17    173
6/19/2017   Platinum   Brown    0.43    793
6/19/2017   Platinum   Red      0.71    1763
6/19/2017   Gold       Orange   1.92    503

I use the fread function to create a data.table:
library(dplyr)
library(data.table)

df <- fread("test_data.csv",
                 header = TRUE,
                 fill = TRUE,
                 sep = ",")

I then subset the data by Model, as follows:
df_subset <- subset(df, df$Model=='Gold' & df$Value > 0)

Then, I create some percentiles based on the Color variable, as follows:
df_subset[, .(Samples = sum(Samples),
    '50th'    = quantile(AvgValue, probs = c(0.50)),
    '99th'    = quantile(AvgValue, probs = c(0.99)),
    '99.9th'  = quantile(AvgValue, probs = c(0.999)),
    '99.99th' = quantile(AvgValue, probs = c(0.9999))),
by = Color]

Which gives the following output:
    Color Samples  50th   99th  99.9th  99.99th
1:   Blue   18603 0.455 0.4991 0.49991 0.499991
2:    Red    1340 0.975 1.2445 1.24945 1.249945
3: Orange     503 1.920 1.9200 1.92000 1.920000

I'm trying to iterate through the list of Model values and output the associated percentile values for each Model value.
I've tried the following (which fails):
models <- unique(df$Model)

for (model in models){

  df$model[, .(Samples = sum(Samples),
                '50th'    = quantile(Value, probs = c(0.50)),
                '99th'    = quantile(Value, probs = c(0.99)),
                '99.9th'  = quantile(Value, probs = c(0.999)),
                '99.99th' = quantile(Value, probs = c(0.9999))),
            by = Color]
}

The error message is:
Error in .(Samples = sum(Samples), `50th` = quantile(Value, probs = c(0.5)),  :  could not find function "."

A: This would probably resolve your problem
library(dplyr)

df [,-1] %>% filter(Value > 0) %>% group_by(Model, Color) %>%
        do(data.frame(t(quantile(.$Value, probs = c(0.50, 0.99, 0.999, 0.9999)))))

About your question in the comments, about how to concatenate samples sum: you can use aggregate; the reason I am not using dplyr::summarise is that I need to start a fresh piping after applying do which does not make sense.
data.frame(df %>% filter(Value > 0) %>% select(-Date) %>% group_by(Model, Color) %>%
              do(data.frame(t(quantile(.$Value, probs = c(0.50, 0.99, 0.999, 0.9999))))),
           aggregate(Samples ~ Color+Model, df, sum)["Samples"])

#      Model  Color  X50.   X99.  X99.9.  X99.99. Samples
# 1   Copper   Blue 0.830 0.8300 0.83000 0.830000     564
# 2     Gold   Blue 0.455 0.4991 0.49991 0.499991   18603
# 3     Gold Orange 1.920 1.9200 1.92000 1.920000     503
# 4     Gold    Red 0.700 0.7000 0.70000 0.700000    1340
# 5 Platinum  Brown 0.430 0.4300 0.43000 0.430000     793
# 6 Platinum    Red 0.710 0.7100 0.71000 0.710000    1763
# 7   Silver   Blue 1.125 1.4925 1.49925 1.499925    1423
# 8   Silver   Pink 1.170 1.1700 1.17000 1.170000     173

Data:
df <- structure(list(Date = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L), .Label = "6/19/2017", class = "factor"), Model = structure(c(2L,
2L, 4L, 4L, 2L, 2L, 1L, 4L, 3L, 3L, 2L), .Label = c("Copper",
"Gold", "Platinum", "Silver"), class = "factor"), Color = structure(
c(1L,5L, 1L, 1L, 5L, 1L, 1L, 4L, 2L, 5L, 3L), .Label = c("Blue", "Brown",
"Orange", "Pink", "Red"), class = "factor"), Value = c(0.5, 0,
0.75, 1.5, 0.7, 0.41, 0.83, 1.17, 0.43, 0.71, 1.92), Samples = c(500L,
449L, 1320L, 103L, 891L, 18103L, 564L, 173L, 793L, 1763L, 503L)),
.Names = c("Date", "Model", "Color", "Value", "Samples"),
class = "data.frame", row.names = c(NA, -11L))

A: Using your definitions you can try the following:
library(data.table)
df<-fread("~/theData.csv")
df$Value<-as.numeric(df$Value)
result<-data.frame()
for (i in seq_along(unique(df$Model))){
  temp <- subset(df, df$Model==unique(df$Model)[i] & df$Value > 0)
  temp<-temp[, .(Samples = sum(Samples),
  '50th'    = quantile(Value, probs = c(0.50)),
  '99th'    = quantile(Value, probs = c(0.99)),
  '99.9th'  = quantile(Value, probs = c(0.999)),
  '99.99th' = quantile(Value, probs = c(0.9999))),
   by = Color]
  temp$model<-unique(df$Model)[i]
  result<-rbind(result, temp)
}
rm(temp)

A: fread creates a data.table object rather than a data frame, so I would recommend sticking with data.table syntax and not mixing it up with dplyr. No need for a for loop either, we can use a list of two variables in the by argument to loop over both models and colors in one line of code:
qs = df[Value > 0, .(Samples = sum(Samples),
              '50th'    = quantile(Value, probs = c(0.50)),
              '99th'    = quantile(Value, probs = c(0.99)),
              '99.9th'  = quantile(Value, probs = c(0.999)),
              '99.99th' = quantile(Value, probs = c(0.9999))),
          by = .(Model, Color)]
setkey(qs, 'Model')

#       Model  Color Samples  50th   99th  99.9th  99.99th
# 1:   Copper   Blue     564 0.830 0.8300 0.83000 0.830000
# 2:     Gold   Blue   18603 0.455 0.4991 0.49991 0.499991
# 3:     Gold    Red     891 0.700 0.7000 0.70000 0.700000
# 4:     Gold Orange     503 1.920 1.9200 1.92000 1.920000
# 5: Platinum  Brown     793 0.430 0.4300 0.43000 0.430000
# 6: Platinum    Red    1763 0.710 0.7100 0.71000 0.710000
# 7:   Silver   Blue    1423 1.125 1.4925 1.49925 1.499925
# 8:   Silver   Pink     173 1.170 1.1700 1.17000 1.170000


text:
Q: C++ runtime error in Linux ::glibc detected free(): invalid next size (fast): Stack with void ptr element This is my first question so i would apologize if this is too silly. I have tried to search and still unable to find the problem with the code. I am debugging someone else's code which is giving this error in linux and it ran just fine in Solaris.
*** glibc detected ***  free(): invalid next size (fast): 0x096c72b0 ***
======= Backtrace: =========
/lib/libc.so.6[0xa986c5]
/lib/libc.so.6(cfree+0x59)[0xa98b09]
...

The code is huge with lot of internal logic but i have tried to create a sample of where the problem might be..
Typedef Struct _FIELD
{
Int  size;
Char str[25];
Void *pData;
Void *pValue;
}FIELD;

Class ABC
{
 FIELD * field1;
 FIELD* getFIeld(int);
 …}

ABC::ABC()
{
field1=NULL;
}
ABC::~ABC()
{
for (int I = 0; I < total_num; i++)
{
    free (field1[i].pData);
   free(field1[i],pValue);
 }
free(field1);
}

FIELD* ABC::getField(int total_num)
{
FIELD *pFields = NULL;
pFields = GetValues( total_num);//just sets up pFields

field1 = malloc ( total_num * sizeof(FIELD));
for (int i =0 ; i<total_num; i++)
 {
 // earlier this code was memcpy, memcpy(&field1, &pFields, sizeof(FIELD)) I have       changed this to explicit copy
 Strcpy(field1[i].str, pFields[i].str);
  field1[i].size = pFields[i].size;
  field1[i].pData = malloc(fields[i].size);
  field1[i].pValue = malloc(fields[i].size);
   //I am not doing strdup for pData and PValue as I checked they are null at this point.
 }
 free(pFields);
 return(field1);

}
…
//Main
FIELD* field1 = NULL;

  ……
 field1 = getField(n);
  …….

 field1 =getField(n)
 …

Again I would like to apologize if this is some thing obvious..
I am sure this is due the way memory is allocated to the struct.
THanks!

A: You probably have a buffer overflow somewhere.  The error message that you're getting from glibc indicates that the heap has been corrupted, usually by overwriting the internal records that track used and free blocks.  glibc is very aggressive about trying to detect these sorts of errors, more so than other platforms; you probably have the same bug elsewhere, but the libc isn't detecting it.
As for exactly where the bug is, I don't see it directly in your code, but that code is making quite a few assumptions (such as pre-allocating buffers of the size recorded in the data structure) and the rest of the program may not be following those assumptions.
Short version: I would install valgrind and run your program under it.  This is a run-time memory debugger for UNIX that will tell you when you've written past the end of allocated memory and what line of code has that problem.  It's the first thing to reach for in this sort of problem.


text:
Q: Is it possible to have method binding in mvvmcross using Fluent API? I have an object structure that looks like this.
public class Model : MvxViewModel
{
    private IDictionary<string, string> _properties;

    public IDictionary<string, string> Properties
    {
        get { return _properties; }
    }

    public string this[string key]
    {
        get { return Get(key); }
        set { Set(key, value); ;}
    }

    public Model()
    {
        this._properties = new Dictionary<string, string>();
    }

    public void Set(string propertyName, string value)
    {
        if (!_properties.ContainsKey(propertyName))
        {
            _properties[propertyName].Value = value;
        }
    }

    public string Get(string propertyName)
    {
        return _properties[propertyName];
    }
}

I need to bind information from this object to a control using Fluent API.
My control is create in the code.
The code looks like this:
protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.Hello);

    Model employeeModel = new Model();
    model["Id"] = 1000;
    model["FirstName"] = "Stuart";
    model["MiddleName"] = "";
    model["LastName"] = "Lodge";
    TableLayout containerLayout = this.FindViewById<TableLayout>(Resource.Id.containerLayout);
    if (containerLayout != null)
    {
        TableRow newRow = new TableRow(base.ApplicationContext);
        newRow.SetMinimumHeight(50);

        var txtFirstName = new EditText(ApplicationContext);
        txtFirstName.Hint = "First Name";

        var bindingSet = this.CreateBindingSet<HelloView, Model>();
        bindingSet.Bind(txtFirstName).For("Text").To(vm => vm.Get("FirstName"));
        bindingSet.Apply();

        newRow.AddView(txtFirstName);
        containerLayout.AddView(newRow);
    }

}

Is it possible to do something like this?

A:
Is it possible to...

Yes, MvvmCross is very extensible so you could add this if you wanted to.
To do it, you'd need to:

*

*give this scheme a name of some kind - for convenience now, let's call it Amit-Binding as Method-Binding has already been used for Auto-ICommand binding - see N=36 in http://mvvmcross.wordpress.com

*work out it's spec a little more fully - e.g. just clarifying how changes will be published from the ViewModel

*work out how the Amit-binding will be presented in binding descriptions - and probably best to work out how to present them in text-format bindings too

*provide one or more extension methods which allow the FluentBinding to generate a binding description containing an Amit-Binding - this will involve parsing the Expressions using your generic parameterised method calls

*possibly also extend the Tibet binding parser and the source property parser classes to allow it to parse the text format of these Amit-bindings (this may not be necessary if you've chosen an already-parseable format for the text version of these classes)

*provide a source property binding extension factory which will know when and how to create these Amit-Source bindings.

This may sound like a lot of effort - but it is actually quite doable. For an example of how INotifyChanged source binding has been added using a plugin, see https://github.com/slodge/MvvmCross/tree/v3/Plugins/Cirrious/FieldBinding/Cirrious.MvvmCross.Plugins.FieldBinding - although note that this was achieved without adding any new requirements to FluentBinding or to the parsers.

Alternatively...
You could just use string-indexer binding on "normal properties" or on fields (if using the FieldBinding plugin).
For an example of this in both Touch and Droid, see the ObservableDictionary example in https://github.com/slodge/MvvmCross-Tutorials/tree/master/ApiExamples

*

*the Core project includes an ObservableDictionary implementation reproduced from http://blogs.microsoft.co.il/blogs/shimmy/archive/2010/12/26/observabledictionary-lt-tkey-tvalue-gt-c.aspx (normal Dictionaries can be used if dynamic updating isn't required)

*the Touch UI project includes a fluent binding block of:
    var set = this.CreateBindingSet<ObservableDictionaryView, ObservableDictionaryViewModel>();
    set.Bind(label1).To(vm => vm.Items["One"]);
    set.Bind(label2).To(vm => vm.Items["Two"]);
    set.Bind(label3).To(vm => vm.Items["Three"]);
    set.Bind(all).To(vm => vm.ReplaceAllCommand);
    set.Bind(each).To(vm => vm.ReplaceEachCommand);
    set.Bind(makeNull).To(vm => vm.MakeNullCommand);
    set.Apply();


text:
Q: HTTP Post in Swift 3 using concatenated string as URL Trying to post xml to a smart TV to change the channel. I'm trying to create my first ever app in Swift to achieve this.
So far, it's proved to be incredibly difficult – running into errors constantly. I had a dictionary, but it didn't work. Here's the most simple version of my code:
@IBAction func SelectButtonA(_ sender: NSButton) {
    let prefix = "http://"
    var ip = "192.168.2.7"
    let suffix = "/sony/IRCC?"
    let url = prefix + ip + suffix as String
    let session = URLSession.shared
    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    let postData = "<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:X_SendIRCC xmlns:u="urn:schemas-sony-com:service:IRCC:1"><IRCCCode>AAAAAQAAAAEAAAAQAw==</IRCCCode></u:X_SendIRCC></s:Body></s:Envelope>"
}

How do I concatenate line 5 as a String, and not throw the error "Cannot convert value of type 'String' to expected argument type 'URL'" on line 7?


text:
Q: ploting two scattered graph in one graph I have two numpy array and want to plot them in the same graph
My current code is like this below
X1 # numpy array
X2 # numpy array

X1Df = pd.DataFrame(columns=['x','y'])
k = 0
for i in X1:                        # copy second numpy to DataFrome
    temp = pd.DataFrame({'x' : i[0],
                         'y' : i[1]},index=[k])
    k = k + 1
    X1Df = pd.concat([X1Df,temp])

X1Df.plot(kind='scatter',x = 'x',y='y')

X2Df = pd.DataFrame(columns=['x','y'])
k = 0
for i in X2: ## Copy second numpy to DataFrame
    temp = pd.DataFrame({'x' : i[0],
                         'y' : i[1]},
                        index=[k])
    k = k + 1
    X2Df = pd.concat([X2Df,temp])

X2Df.plot(kind='scatter',x = 'x',y='y')

#########
plt.show()

But it makea two graphs separately and I guess my code to copy from numpy to dataframe is ackward...
is ther any better solution??

A: Use axes handle and ax paramater in df.plot:
X1 = np.array([[1,2],[3,4]])
X2 = np.array([[2,3],[6,7]])

X1Df = pd.DataFrame(columns=['x','y'])
k = 0
for i in X1:                        # copy second numpy to DataFrome
    temp = pd.DataFrame({'x' : i[0],
                         'y' : i[1]},index=[k])
    k = k + 1
    X1Df = pd.concat([X1Df,temp])

ax = X1Df.plot(kind='scatter',x = 'x',y='y')

X2Df = pd.DataFrame(columns=['x','y'])
k = 0
for i in X2: ## Copy second numpy to DataFrame
    temp = pd.DataFrame({'x' : i[0],
                         'y' : i[1]},
                        index=[k])
    k = k + 1
    X2Df = pd.concat([X2Df,temp])

X2Df.plot(kind='scatter',x = 'x',y='y', ax=ax)

#########
plt.show()


text:
Q: Error when post message from C# program with server using Twisted python My Method to post a message to server using C# .NET 4.0
 private String postHTTP(String url)
    {
        String result = "";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        string postData = "Data has Posted";
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        **request.ContentType = "application/x-www-form-urlencoded";**
        request.Credentials = System.Net.CredentialCache.DefaultCredentials;
        request.ContentLength = byteArray.Length;
        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();
        WebResponse response = request.GetResponse();
        txtWebServerStatus.Text = ((HttpWebResponse)response).StatusDescription;
        dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        // Display the content.
        Console.WriteLine(responseFromServer);
        // Clean up the streams.
        reader.Close();
        dataStream.Close();
        response.Close();
        return responseFromServer;
    }

my server code to provide a form to type and print what you type in form
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.web.error import NoResource
import cgi

  class DynamicPage(Resource):
    def render_GET(self, request):
        return '<form method="POST"><input name="the-field" type="text" /></form>'

    def render_POST(self, request):
        return 'You submitted: %s' % (cgi.escape(request.args["the-field"][0]),)

root = Resource()
dynamic = DynamicPage()
root.putChild("fool", dynamic)
factory = Site(root)
reactor.listenTCP(7777, factory)
reactor.run()

Error on post method:
in line WebResponse response = request.GetResponse();

The remote server returned an error: (500) Internal Server Error.

When I using post method have error on server:
C:\Users\sepdau>C:\Python27\python.exe E:\server.py
Unhandled Error Traceback (most recent call last):

  File "C:\Python27\lib\site-packages\twisted\web\http.py", line 1349, in dataReceived  finishCallback(data[contentLength:])

  File "C:\Python27\lib\site-packages\twisted\web\http.py", line 1563, in _finishRequestBodyself.allContentReceived()

  File "C:\Python27\lib\site-packages\twisted\web\http.py", line 1618, in allContentReceived req.requestReceived(command, path, version)

  File "C:\Python27\lib\site-packages\twisted\web\http.py", line 773, in request Received self.process()

--- <exception caught here> ---

  File "C:\Python27\lib\site-packages\twisted\web\server.py", line 132, in process
    self.render(resrc)

  File "C:\Python27\lib\site-packages\twisted\web\server.py", line 167, in render
    body = resrc.render(self)

  File "C:\Python27\lib\site-packages\twisted\web\resource.py", line 216, in render
    return m(request)

  **File "E:\server.py", line 25, in render_POST
    return 'You submitted: %s' % (cgi.escape(request.a
rgs["the-field"][0]),)
exceptions.KeyError: 'the-field'**

I think error on Server or ContentType I use no correct.
Can you help me.
Thank for advance.

A: So the problem you're hitting is:
KeyError: 'the-field'

This is because your client is posting:
Data has Posted

There are no form fields in that post data.  There are two things you probably want to do.
First, make your server more robust against bad input.  It's already somewhat robust: bad input generates a 500, but the server continues to operate and process future requests.  You might want to generate a more useful error page to help clients figure out what they're doing wrong, though.  So, try handling the KeyError:
def render_POST(self, request):
    try:
        value = request.args["the-field"][0]
    except KeyError:
        value = "<missing the-field value>"
    return 'You submitted: %s' % (cgi.escape(value),)

Now your client should get a 200 response, even if it keeps submitting form data without the form field the server is looking for.
Next, fix your client to submit post data that includes the correct form fields.  Try a string like:
the-field=%5B%27some+value%27%5D

You can generate this in Python using urllib.urlencode, eg:
urllib.urlencode({'the-field': ['some value']})


text:
Q: If en Regex sigue entrando en la condición falsa cuando se debería cumplir la verdadera Alguien me pueda ayudar con los if en regex estoy usando un compilador de regex he hice esto
^\d{2}(02)?(?(1)(0\d$|1\d$|2[0-8]$)|(0[1-9]|1[0-2])(0\d$|1\d$|2\d$|3[0-1]$))

es para validar fechas AAMMDD correctas ya que febrero solo tiene 28 días pero el if me da un error, no de sintaxis si no lógico, ejemplo:
si yo pongo 200230 esto me lo pone correcto(aunque no debería ser correcto ya que febrero no tiene 30 dias) porque entra a la condición del if ya que si cumplió con tener un 02 después de los 2 dígitos del principio:
//entra aqui si el mes es 02 y valida que el día sea menor que 29
 (02)?(?(1)(0\d$|1\d$|2[0-8]$)|

como el día es 30 por alguna razón que desconozco se sale de este:
(?(1)(0\d|1\d|2[0-8])

y entra al segundo:
(0[1-9]|1[0-2])(0\d$|1\d$|2\d$|3[0-1]$)

y da match ¿alguien sabe por que no me funciona bien el if?

A: Toda tu lógica está perfecta hasta que llegás a decir "por alguna razón que desconozco".
Te cuento esa razón siguiendo el paso a paso que hace el motor de regex:

*

*Coincide con (02)?

*Entra en la parte verdadera del IF

*FALLA
¿Qué pasa acá, al igual que con cualquier construcción de regex cuando falla?
Hace backtracking. Es decir, vuelve para atrás para seguir intentando otras combinaciones que podrían dar una coincidencia.
¿Qué es lo que intenta?

*Intenta coincidir con (02)? repetido 0 veces (por el ?). O sea, no coincidir con ese grupo 1.

*Y bueno... el resto es historia... perfectamente puede coincidir con el resto, porque no captura el grupo 1, entra en la parte falsa del IF, (0[1-9]|1[0-2]) permite que coincida con "02", y coincide con todo.

Hay muchísimas formas de corregirlo, van algunas a modo de ejemplo:

*

*¿Leíste sobre cuantificadores posesivos? Es un + a continuación de un cuantificador. Hacen que si coincidió con una cantidad de repeticiones y más tarde falla, no intente con menos repeticiones. Es decir, que si coincidió con (02)?+, no pueda intentar con 0 repeticiones cuando vuelve por backtracking. Ese + de más te arregla el problema.
^\d{2}(02)?+(?(1)([01]\d|2[0-8])|(0[1-9]|1[0-2])([0-2]\d|3[0-1]))$

*¿Viste que un IF puede preguntar por un grupo capturado o sino usar un lookahead? Bueno...
^\d{2}(?(?=02)02([01]\d|2[0-8])|(0[1-9]|1[0-2])([0-2]\d|3[0-1]))$

*¿Querés hacer lo mismo sin un IF? Sólo es cuestión de armar las 2 alternativas, que sean excluyentes entre sí (una con febrero y la otra que no permita febrero de ninguna manera). (0[13-9]|1[0-2]) coincide con todos los meses menos el 02.
^\d{2}(02([01]\d|2[0-8])|(0[13-9]|1[0-2])([0-2]\d|3[0-1]))$

*Febrero tiene 29 días en años bisiestos. ¿Querés volarte la cabeza? Lee esta pregunta: Validar una fecha dd/mm/aaaa con expresiones regulares y fijate si podés adaptarla a aammdd.


text:
Q: Bulk Map Update on HERE platform I use a point of sale system that utilizes the HERE API to build maps of my delivery areas.  Recently, I provided my POS provider with an up-to-date parcels list and parcels shapefile and streets center line file from the County GIS department.
Despite providing this pristine data, my POS provider generated delivery maps that STILL do not include the proper streets and addresses.
After much prodding, I learned that my POS provider uses the HERE API to generate its maps.  Thus, it seems that HERE is the problem, not my POS provider.
There is a way to go into the HERE Map Creator and new addresses.  However, I don't have just one address.  I want to provide HERE with the ENTIRE County GIS database to ensure that their service has the most up-to-date maps.
I would call them about this, but they like to hide behind forms and not provide a telephone number.
Any idea how I can reach someone at HERE technologies to help them update entire counties worth of addresses?
Visited their website.  Realized that I could only add single addresses rather than an entire county.
N/A
N/a

A: Please create a free account on developer.here.com and visit our supplier-portal to upload your data:
https://upload.here.com
Our internal team will be able to verify the data, once it's uploaded. If you can also give your email address, and the name and description of the data you submit to this email address selfservesupport@here.com, then our team will verify the data and get back you.

A: There is a option to upload the data in the https://upload.here.com/


text:
Q: Is there a case-insensitive collation in MySQL that also insensitive towards a string and its trimmed version? I know, there is a lot of case-insensitive collations (e.g. utf8_bin), but besides that, I need a collation that also treats a string as its trimmed version (let's call it "trim-insensitivity"), so it can't distinguish the following two strings: "abc" and "    aBc "

A: try with collate utf8_general_ci
http://sqlfiddle.com/#!9/119bd9f/1


text:
Q: How do I capture images using webcam in Python? There are certain libraries such as fswebcam, cv2 etc. But pip cant find a matching distribution for Python3 on Win7 64bit. Are there any other libraries or how can i use these two to capture images from Python

A: I installed openCV on my 64-bit windows 10 machine using openCV and numpy wheels, which I installed using pip.
You can find the numpy wheels here:
https://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy
And the cv2 wheels here:
https://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv
Make sure you find the wheels specific to your setup, ie. 64-bit with python 3.6, use:
numpy‑1.14.5+mkl‑cp36‑cp36m‑win_amd64.whl
Save those in a folder, then navigate to that folder in a command window and install the files using pip.
The full guide is here if needed:
https://solarianprogrammer.com/2016/09/17/install-opencv-3-with-python-3-on-windows/

A: I guess the reason is that you have both Python2 and Python3 installed, and therefore pip only works for Python 2. You can install OpenCV as follows:
python3 -m pip install opencv-python

You have to make sure Python 3 has been added to the system path and the command Python3 is available. If the executable file of Python 3 is named Python, just rename it to Python3.


text:
Q: What is the bash equivalent to Python's `if __name__ == '__main__'`? In Bash, I would like to be able to both source a script and execute the file. What is Bash's equivalent to Python's if __name__ == '__main__'?
I didn't find a readily available question/solution about this topic on Stackoverflow (I suspect I am asking in such a way that doesn't match an existing question/answer, but this is the most obvious way I can think to phrase the question because of my Python experience).

p.s. regarding the possible duplicate question (if I had more time, I would have written a shorter response):
The linked to question asks "How to detect if a script is being sourced" but this question asks "how do you create a bash script that can be both sourced AND run as a script?". The answer to this question may use some aspects of the previous question but has additional requirements/questions as follows:

*

*Once you detect the script is being sourced what is the best way to not run the script (and avoid unintended side-effects (other than importing the functions of interest) like adding/removing/modifying the environment/variables)

*Once you detect the script is being run instead of sourced what is the canonical way of implementing your script (put it in a function? or maybe just put it after the if statement? if you put it after the if statement will it have side-affects?

*most google searches I found on Bash do not cover this topic (a bash script that can be both sourced and executed) what is the canonical way to implement this? is the topic not covered because it is discouraged or bad to do? are there gotchas?

A: There is none. I usually use this:
#!/bin/bash

main()
{
    # validate parameters

    echo "In main: $@"

    # your code here
}

main "$@"

If you'd like to know whether this script is being source'd, just wrap your main call in
if [[ "$_" != "$0" ]]; then
    echo "Script is being sourced, not calling main()"
else
    echo "Script is a subshell, calling main()"
    main "$@"
fi

Reference: How to detect if a script is being sourced

A: return 2> /dev/null
For an idiomatic Bash way to do this, you can use return like so:
_main(){
    echo hello
}

# End sourced section
return 2> /dev/null

_main

Example run:
$ bash return_test.sh
hello
$ source return_test.sh
$ _main
hello

If the script is sourced, return will return to the parent (of course), but if the script is executed, return will produce an error which gets hidden, and the script will continue execution.
I have tested this on GNU Bash 4.2 to 5.0, and it's my preferred solution.
Warning: This doesn't work in most other shells.
This is based on part of mr.spuratic's answer on How to detect if a script is being sourced.

A: Solution:
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi

I added this answer because I wanted an answer that was written in a style to mimic Python's if __name__ == '__main__' but in Bash.
Regarding the usage of BASH_SOURCE vs $_. I use BASH_SOURCE because it appears to be more robust than $_ (link1, link2).

Here is an example that I tested/verified with two Bash scripts.
script1.sh with xyz() function:
#!/bin/bash

xyz() {
    echo "Entering script1's xyz()"
}

main() {
    xyz
    echo "Entering script1's main()"
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi

script2.sh that tries to call function xyz():
#!/bin/bash

source script1.sh

xyz

A: I have been using the following construct at the bottom of all my scripts:
[[ "$(caller)" != "0 "* ]] || main "$@"

Everything else in the script is defined in a function or is a global variable.
caller is documented to "Return the context of the current subroutine call." When a script is sourced, the result of caller starts with the line number of the script sourcing this one. If this script is not being sourced, it starts with "0 "
The reason I use != and || instead of = and && is that the latter will cause the script to return false when sourced. This may cause your outer script to exit if it is running under set -e.
Note that I only know this works with bash. It wont work with a posix shell. I don't know about other shells such as ksh or zsh.

A: I really think this is the most Pythonic and beautiful way to accomplish the equivalent of if __name__ == "__main__" in Bash:
From hello_world_best.sh in my eRCaGuy_hello_world repo:
#!/usr/bin/env bash

main() {
    echo "Running main."
    # Add your main function code here
}

if [ "${BASH_SOURCE[0]}" = "$0" ]; then
    # This script is being run.
    __name__="__main__"
else
    # This script is being sourced.
    __name__="__source__"
fi

# Only run `main` if this script is being **run**, NOT sourced (imported)
if [ "$__name__" = "__main__" ]; then
    main
fi

To run it, run ./hello_world_best.sh. Here is a sample run and output:
eRCaGuy_hello_world/bash$ ./hello_world_best.sh
Running main.

To source (import) it, run . ./hello_world_best.sh, . hello_world_best.sh, or source hello_world_best.sh, etc. When you source it, you'll see no output in this case, but it will give you access to the functions therein, so you can manually call main for instance. If you want to learn more about what "sourcing" means, see my answer here: Unix: What is the difference between source and export?. Here is a sample run and output, including manually calling the main function after sourcing the file:
eRCaGuy_hello_world/bash$ . hello_world_best.sh
eRCaGuy_hello_world/bash$ main
Running main.

Important:
I used to believe that using a technique based on "${FUNCNAME[-1]}" was better, but that is not the case! It turns out that technique does not gracefully handle nested scripts, where one script calls or sources another. To make that work, you have to 1) put "${FUNCNAME[-1]}" inside a function, and 2) change the index into the FUNCNAME arrray based on the level of nested scripts, which isn't practical. So, do not use the "${FUNCNAME[-1]}" technique I used to recommend. Instead, use the if [ "${BASH_SOURCE[0]}" = "$0" ] technique I now recommend, as it perfectly handles nested scripts!
References

*

*The main answer here where I first learned about "${BASH_SOURCE[0]}" = "$0"

*Where I first learned about the ${FUNCNAME[-1]} trick: @mr.spuratic: How to detect if a script is being sourced - he learned it from Dennis Williamson apparently.

*A lot of personal study, trial, and effort over the last year.

*My code: eRCaGuy_hello_world/bash/if__name__==__main___check_if_sourced_or_executed_best.sh

*My other related but longer answer: How to detect if a script is being sourced

A: Use FUNCNAME
FUNCNAME is an array that's only available within a function, where FUNCNAME[0] is the name of the function, and FUNCNAME[1] is the name of the caller. So for a top-level function, FUNCNAME[1] will be main in an executed script, or source in a sourced script.
#!/bin/bash

get_funcname_1(){
    printf '%s\n' "${FUNCNAME[1]}"
}

_main(){
    echo hello
}

if [[ $(get_funcname_1) == main ]]; then
    _main
fi

Example run:
$ bash funcname_test.sh
hello
$ source funcname_test.sh
$ _main
hello

I'm not sure how I stumbled across this. man bash doesn't mention the source value.
Alternate method: Use FUNCNAME[0] outside a function
This only works in 4.3 and 4.4 and is not documented.
if [[ ${FUNCNAME[0]} == main ]]; then
    _main
fi


text:
Q: Superfish problem in IE6 I'm having issues with my Superfish third level menu items, it works fine in everything other than IE6!
You can view it here;
http://christhrower.com/newWork/Farhi
The sub-sub nav doesn't pop up in IE6.
Anybody have any ideas on this?
Cheers.

A: I has a similar problem with this years ago. My solution was to add an extra style="width:xx" into the div for that menu section which seemed to fix it for IE6.  Dont know if its the same problem you are having but might be wirth a try.


text:
Q: Python to Powerpoint: Export svg to a pptx file I was experimenting with the python-pptx library to automate the process of adding images to my presentations. I used code such as:
from pptx import Presentation
import os

prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[8])
placeholder = slide.placeholders[1]
picture = placeholder.insert_picture('pie.png')
prs.save("ESEMPIO.pptx")

This works just fine, but it was noted that when zooming in the pie chart contained in pie.png becomes quite pixelated. Someone suggested to use SVG format, so I saved the image as an SVG (unfortunately, I can't seem to add the SVG file here). Now, if I try to do:
from pptx import Presentation
import os

prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[8])
placeholder = slide.placeholders[1]
picture = placeholder.insert_picture('pie.svg')
prs.save("ESEMPIO.pptx")

I get the following error: UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f38da87c350>, which I guess is because it does not like the SVG format. Is there any workaround to get an SVG into a PowerPoint presentation?
PNG pie chart

A: According to this issue on the repository, svg support doesn't seem to be a priority for the devs, and they suggest manually converting to png and inserting that into your presentation. My best suggestion is converting to a relatively high resolution png so the pixelation is less noticeable.

A: A long-winded way to do this is to save your image as an emf (this involves calling Inkscape to do so but the process is explained quite well in this thread: Convert SVG/PDF to EMF) and then use this emf when you call insert_picture.
This image should render as a vectorized image in your powerpoint- meaning that it scales and remains editable (you'll need to right-click the image and select Group --> Ungroup if you want to edit).

A: In md2pptx we automate the conversion of SVG to .PNG under the covers. It uses CairoSVG to do it.
md2pptx relies heavily on python-pptx to convert Markdown to .pptx.
You can get md2pptx here:
https://github.com/MartinPacker/md2pptx
Sorry if this seems like an advert. I just wanted you to know there is automation available.


text:
Q: Как добавить поддержку соотношения сторон 18:9 в Ionic Cordova Никак не могу добавить поддержку нового формата соотношения сторон 18:9 в своё android приложение на ionic framework. Использую 6" смартфон Xiaomi Redmi S2. Приложение запускается, но внизу  висит черная полоса придающая приложению стандартное соотношение сторон 16:9. Прошу объяснить максимально простым языком, что надо сделать, что бы приложение работало в полную высоту.

A: Нашел ответ. Надо в файле My10 copy\platforms\android\CordovaLib\AndroidManifest.xml дописать следующее между тегами manifest
<application>
        <meta-data android:name="android.max_aspect" android:value="2.1" />
 </application>


text:
Q: Is there any api to find partition is balanced or not in kafka Is there any API or client library exist which can tell me how much percent topic is filled with data so that I can figure out is there any way to check whether partitions are balanced or not

A: This is a good strategy to discuss before designing and development on Kafka.
The first point you need to consider how you are defining your key and whats exactly partitioner you are planning to use while producing a message to the topics.
Thumb-rule:

*

*If you not bothering collecting messages in different groups based on key just pass the key as null to redistribute your messages in a round-robin manner.

*You can also use a custom partitioner to define partitioning in case you need to do some more refinement.

To check the partition distribution, the best approach is to check the lagging on each partition and rate byte/sec
There many ways to monitor
1.You can use simple API to get various matrices like lagging, rate, etc
You can refer here   Kafka Metrices
kafka.server:type=ReplicaFetcherManager,name=MaxLag,clientId=Replica

2.I generally prefer Grafana with JMX exported it will visualize matrices
Grafana
3.We can also use CLI to identify each partition offset and lagging, and really give you the overall figure instantly
bin/kafka-consumer-groups.sh --bootstrap-server broker1:9092 --describe --group consumer-group

TOPIC                          PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG        CONSUMER-ID                                       HOST                           CLIENT-ID
 test                              1          10               30           20         consumer-group

*You can also do with programmatically
How to identify partition lagging

*Confluent Control-Center is paid one but a very interesting tool to monitor overall Kafka including consumer and its partitions/
Confluent control center

A: Assume that you created a topic X. Your producers started to push tons of data into your topic. Your topic is growing exponentially. Depending on the configuration log.segment.bytes, Kafka will create a new segment and start writing data into it. Old segment will be kept for log.retention.ms milliseconds. Because of this, 100% of a topic itself is tricky calculate.
However, if you are looking for a tool that can allocate partitions depending on the load on each broker then I would recommend looking into Kafka-kit (https://www.datadoghq.com/blog/engineering/introducing-kafka-kit-tools-for-scaling-kafka/).


text:
Q: Mac Terminal link not working I am trying to make a command line link for Sublime Text 3.
If I run /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl Sublime Text opens like normal.
I then run sudo ln "/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl" /usr/bin/subl
Restart the terminal and I get this:
$ ls /usr/bin/subl
/usr/bin/subl
$ subl
-bash: subl: command not found

I also tried setting in my .profile alias subl="/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl"
but I also get command not found
EDIT:
/usr/bin/ is in my PATH as well
EDIT2:
I tried a restart of my computer but still doesn't work.
It seems any new alias I make won't work in my .profile.
I tried ln -s "/usr/bin/mail" /usr/bin/testln and it did work.
EDIT3:
I got it to work by putting an alias in .bash_profile instead.  I would still like to know why my ln doesn't work though.

A: Your symlink command
sudo ln "/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl" /usr/bin/subl

didn't work because you both enclosed the path in quotes and escaped the space with a backslash. The quotes make the symlink point to the literal path
/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl

which is not valid. You should use either
"/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl"

or
/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl

but don't combine the two.

A: You can add the alias in your .profile file as :
alias subl="open -a Sublime\ Text"

After you do that
subl .

Should work just fine


text:
Q: getAbsolutePath ignoring certain folders My problem is that getAbsolutePath is ignoring certain folders around the file that I'm trying to find. What I'm trying to do is get the filepath of a file only using its name. Here's the code I'm using:
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;

public class OpenFile {
    public static void main(String[] args) throws IOException{
        File file = new File("Point.java");
        String path = file.getCanonicalPath();

        try {
            Desktop.getDesktop().open(new File(path));
        } catch(IOException e) {
            System.out.println("not work");
        }
    }
}

I'm getting this error:
Exception in thread "main" java.lang.IllegalArgumentException: The file: /Users/default/Desktop/Eclipse/TreeThing/Point.java doesn't exist.
at java.awt.Desktop.checkFileValidation(Desktop.java:210)
at java.awt.Desktop.open(Desktop.java:270)
at ForkBomb.main(ForkBomb.java:11)

The real filepath is /Users/default/Desktop/Eclipse/TreeThing/src/Point.java, but because the directory src is being ignored the program won't run. How can I solve it?

A: It appears that you are running your code from the /Users/default/Desktop/Eclipse/TreeThing directory. This sets the 'current working directory' for your application.
So when you instantiate a File object without a path, the code assumes it is in the current working directory.
It does not perform a search for you.
If you want to refer to the existing Point.java, use either:
File file = new File("src/Point.java");

... or:
File file = new File("/Users/default/Desktop/Eclipse/TreeThing/src/Point.java");


text:
Q: How to dynamically render LWC Table Rows I am unable to dynamically render table rows as a row using a child component.
Parent:
<template>
        <template if:true={data.results}>

                    ID

        <template for:each={data.results} for:item="result">
            <c-child-table-row key={result.id} rowResult={result}></c-child-table-row>
        </template>

    </template>
 </template>

Child:
<template>

            {rowResult.id}

</template>

The rows rendered are not rendered as a table even though inspecting the DOM shows they have the appropriate classes.

A: LWC uses Shadow DOM and custom elements. You are wanting to generate a structure like:

X

...

However, what you actually get is something like:

  <c-child>

X

  </c-child>
...

To handle this:

*

*Add CSS to the child of the form: :host { display: table-row }

*Remove the tr tag from the child, since the above CSS means that the c-child element is treated like a TR (because this is what is actually included in the DOM in place of the outer-most template element in the child LWC's template).

This will result in markup of the form:

  <c-child>
    X
  </c-child>
...

with the c-child element being treated as if it were a tr, due to the child's CSS, so effectively:

    X

...

(I have ignored key values and looping you'll need for iteration)


text:
Q: Get rid of the disrupting points Here on the following picture, we can identify two clouds. We can identify a lot of points that are out of the two clouds and can disrupt a bit the the training and test accuracy (%). Is there an unsupervised machine learning model or other techniques we can use to get rid of those points?
I thought to try to train a neural network to maximize inter class distances, but minimize intra class distances, but it is a bit unclear.

To explain the image here, I have over 76 features I pass to a LSTM model. The graph axis you see are the three first principal components (i.e. related to PCA). The red dots are -1 labels and blue dots are the 1 labels.


text:
Q: Series with a reciprocal of the central binomial coefficient How can we prove the following identities
$$\sum_{n=1}^\infty n^{-3}{\binom{2n}n}^{-1}=\pi\operatorname{Cl}_2\left(\frac{2\pi}{3}\right)-\frac{4}{3}\zeta(3)\tag{1}$$
$$\sum_{n=1}^\infty (n+1)^{-2}{\binom{2n}n}^{-1}=\frac{2\pi^2}{9}-2\pi\operatorname{Cl}_2\left(\frac{2\pi}{3}\right)+\frac{8}{3}\zeta(3)-1\tag{2}$$
where $\operatorname{Cl}_2(x)$ is the Clausen integral?
Some identities of this sort are proved in this paper.

A: $(1)$: We want to evaluate $\quad\displaystyle S:=\sum_{m=1}^{\infty} \frac{1}{m^3\binom{2m}{m}}$
From this answer we obtained :
$$\tag{1}2(\arcsin(x))^2=\sum_{m=1}^{\infty} \frac{(2x)^{2m}}{m^2\binom{2m}{m}}$$
Integrating this multiplied by $\,\dfrac 2x\,$ from $\,0$ to $\dfrac 12$ will thus give :
\begin{align}
S&=2\sum_{m=1}^{\infty} \frac{1}{m^2\binom{2m}{m}}\int_0^{\frac12}\dfrac{(2x)^{2m}}{x}\,dx\\
\tag{2}S&=4\int_0^{\frac 12} \frac{(\arcsin(x))^2}x\,dx\\
\tag{3}S&=4\int_0^{\pi/6} \frac{t^2}{\tan(t)}\,dt\\
S&=4\left[\left.t^2\log(\sin(t))\right|_{\,0}^{\,\pi/6}-2\int_0^{\pi/6} t\,\log(\sin(t))\,dt\right]\\
\tag{4}S&=-\frac{\log(2)\pi^2}9-8\int_0^{\pi/6} t\,\log(\sin(t))\,dt\\
\end{align}
The Clausen integral verifies :
$\;\displaystyle\operatorname{Cl}_2(x)'=-\log(2\sin(t/2))\;$ so let's rewrite $(4)$ and use integration by parts of $\operatorname{Cl}_2(x)$ :
\begin{align}
S&=-\frac{\log(2)\pi^2}9-\frac 84\int_0^{\pi/3} t\;\log(2\sin(t/2))-t\log(2)\,dt\\
\tag{5}S&=-2\int_0^{\pi/3} t\;\log(2\sin(t/2))\,dt\\
&=2\left[t\;\operatorname{Cl}_2(x)\left.\right|_0^{\pi/3}-\int_0^{\pi/3} \operatorname{Cl}_2(t)\,dt\right]\\
&=\frac{2\pi}3\operatorname{Cl}_2\left(\frac{\pi}3\right)+2\,\left(\operatorname{Cl}_3\left(\frac{\pi}3\right)-\operatorname{Cl}_3\left(0\right)\right)\\
\end{align}
Since $\;\displaystyle\operatorname{Cl}_{2n}(x):=\sum_{k=1}^\infty \frac{\sin(k\,x)}{k^{\,2n}},\ \operatorname{Cl}_{2n+1}(x):=\sum_{k=1}^\infty \frac{\cos(k\,x)}{k^{\,2n+1}}\;$ we have indeed $\;\operatorname{Cl}_3(x)'=-\operatorname{Cl}_2(x)$.
Now $\,\operatorname{Cl}_3(0)=\zeta(3)\,$ and $\,\operatorname{Cl}_3\left(\dfrac{\pi}3\right)=\dfrac{\zeta(3)}3\,$ (prove this using the series for $\operatorname{Cl}_3$) while $\,\operatorname{Cl}_2\left(\dfrac{2\pi}3\right)=\dfrac 23\operatorname{Cl}_2\left(\dfrac{\pi}3\right)\,$ can't be written in simpler form (without using polylogarithms) so that your $(1)$ is indeed right :
$$\boxed{\displaystyle\sum_{n=1}^\infty \frac 1{n^{3}{\binom{2n}n}}=\pi\operatorname{Cl}_2\left(\frac{\pi}{3}\right)-\frac{4}{3}\zeta(3)}\tag{6}$$

$(2)$: Concerning $\;\displaystyle \sum_{m=1}^{\infty} \frac{1}{(m+1)^2\binom{2m}{m}}\ $ the link (i.e. the derivative of $(1)$ multiplied by $\dfrac x2$) gives us :
$$\tag{7}\frac{2x \arcsin\ x}{\sqrt{1-x^2}}=\sum_{m=1}^{\infty} \frac{(2x)^{2m}}{m\binom{2m}{m}}$$
The derivative of this (multiplied by $x/2$) will give us the general  :
$$\tag{8}\boxed{\frac {x^2}{1-x^2}+x\frac {\arcsin(x)}{\sqrt{1-x^2}^3}=\sum_{m=1}^{\infty} \frac{(2x)^{2m}}{\binom{2m}{m}}}$$
Multiplying by $\,x$, integrating and dividing by $x^2/2$ we get :
$$\tag{9}2\frac {\arcsin(x)}{x\,\sqrt{1-x^2}}-\frac{\arcsin(x)^2}{x^2}-1=\sum_{m=1}^{\infty} \frac{(2x)^{2m}}{(m+1)\binom{2m}{m}}$$
The indefinite integral of $\;\displaystyle 2\;x\frac {\arcsin(x)}{x\,\sqrt{1-x^2}}\;$ is simply $\,\arcsin(x)^2\,$ while the integral of $\;\displaystyle x\frac{\arcsin(x)^2}{x^2}$ is more complicated but we found $\;\displaystyle\int_0^{1/2}\frac {\arcsin(x)^2}x\,dx=\frac S4$ earlier and can therefore conclude that :
$$\int_0^{1/2} \sum_{m=1}^{\infty} \frac{x(2x)^{2m}}{(m+1)\binom{2m}{m}}\,dx=\sum_{m=1}^{\infty} \frac{2^{-3}(1)^{2m+2}}{(m+1)^2\binom{2m}{m}}=\left.\arcsin(x)^2-\frac{x^2}2\right|_{\,0}^{\,1/2}-\frac S4$$
or :
$$\sum_{m=1}^{\infty} \frac 1{(m+1)^2\binom{2m}{m}}=8\left(\frac{\pi}6\right)^2-\frac 88-2\left(\pi\operatorname{Cl}_2\left(\frac{\pi}{3}\right)-\frac{4}{3}\zeta(3)\right)$$
which is indeed your equality $(2)$ :
$$\tag{10}\boxed{\displaystyle\sum_{m=1}^{\infty} \frac 1{(m+1)^2\binom{2m}{m}}=\frac{2\pi^2}{9}-2\pi\operatorname{Cl}_2\left(\frac{2\pi}{3}\right)+\frac{8}{3}\zeta(3)-1}$$
To add to the links provided by Vladimir Reshetnikov :

*

*an excellent link concerning central binomial series is to Gourévitch's $\pi$ pages.

*here Sprugnoli's "Sums of reciprocals of the central binomial coefficients" may be helpful too.


text:
Q: How to show "Your Location " option in Google maps Place Autocomplete TextView How can I give the user the option of using their current location in place auto complete fragment
<fragment
    android:id="@+id/place_autocomplete"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
    />

Like this


text:
Q: What is the geometric meaning of the equation for a plane in $\mathbb{R}^3$? Context:
I am working through George Polya's book, Mathematics and Plausible Reasoning.
Let $P$ be a plane in $\mathbb{R}^3$ defined by $ax+by+cz=d$ where $a,b,c,$ and $d$ are constant real numbers.
My question:
What is the geometric significance and/or meaning of the constants $a,b,c,d$? What do they imply about the position and orientation of the plane in  $\mathbb{R}^3$?
Attempted solution:
I see that, for a vector $(x,y,z)$ in the plane, it is required that $(a,b,c) \cdot (x,y,z) = |(a,b,c)||(x,y,z)|\cos(\theta)=d$. This seems to imply that varying $d$ and keeping $a,b,c$ constant might affect the "orientation," $\theta$, but then again $(x,y,z)$ can vary.
When $d=0$ and $(a,b,c),(x,y,z) \neq \vec{0}$, we have $\theta=\pi/2$, which implies that any vector in plane $P$ is always perpendicular to $(a,b,c)$.
On the other hand, if we consider a plane parallel to the $xy$ plane, $0x+0y+z=d,$ then it seems that $d$ determines how far along the z-axis the plane is.
At any rate, these are my scrambled thoughts so far. Could anyone help me see the bigger picture here?

A: When $d=0$, we have $ax+by+cz=(a,b,c)\cdot(x,y,z)=0$ which is satisfied by vectors $(x,y,z)$ orthogonal to the fixed vector $(a,b,c)$.  Nonzero $d$ has the effect of shifting this plane in some direction.  For example you could say it is shifted in the x direction by $ d/a$: $ax+by+cz=d \Leftrightarrow a(x-d/a)+by+cz=0$.


text:
Q: Question regarding multiple Orchestration functions calling one Entity I was wondering if anyone could help me understand some behavior regarding orchestration functions and entities.
Say I have one HttpTriggered function that starts an orchestration that calls (not signal) a Durable Entity and runs a long process (30 seconds) to update some string member. I also have another HttpTriggered function that starts an orchestration to call the same Entity and get that string.
What I want to know is that if I trigger the first function "A" and then the second function "B" immediately after. When "B" calls the Entity to get the string, does it wait for "A" to finish its call to the Entity? Or will "B" get a "dirty" value from it?
Guess what I'm trying to figure out is if all calls to the Entity have to be synchronous in regards to the Control Queue.

A: Entities execute operations one-at-a-time in FIFO order, so if you have two orchestrations (A and B) that call some operation simultaneously, the second operation (B in your example) will be forced to wait for A's operation to finish, which could be as long as 30 seconds. Dirty reads therefore aren't possible when calling entities. This synchronization happens in memory in the Durable Functions extension itself.
This is mentioned in the documentation here:
https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-entities#general-concepts

To prevent conflicts, all operations on a single entity are guaranteed to execute serially, that is, one after another.

This applies both to entity calls and signals.


text:
Q: Edit fstab on unmounted device I tried to add swapfile to the root file system on AWS EC2 instance. Did  I made a mistake during the edit of fstab?
sudo dd if=/dev/zero of=/swapfile bs=1G count=4
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
swapon -s

I have edited /etc/fstab
vi /etc/fstab
/swapfile swap swap defaults 0 0

Swap worked fine but after reboot, a system doesn't work. I have decided to attach device to another instance and remove a line in fstab, but it can't be mounted on another instance.
mount: wrong fs type, bad option, bad superblock on /dev/xvdf,
       missing codepage or helper program, or other error

       In some cases useful info is found in syslog - try
       dmesg | tail or so.

How can I edit fstab and remove a line with swap data on unmounted device?
lsblk -f output
NAME    FSTYPE LABEL           UUID                             MOUNTPOINT
xvda
`-xvda1 ext4   cloudimg-rootfs 7b2XXX-16d3-XXXX-b32e-1857XXXXXXXX /
xvdf
`-xvdf1

A: It looks like you were able to pull that console output using a CLI command.
Unfortunately unless you are running your root filesystem device with Elastic Block Storage as an EBS-backed volume, there is no way to recover your root filesystem (which you will have to mount to actually modify /etc/fstab). If this is an instance-store volume, I don't believe there is a way to recover it.
Sorry for the bad news...


text:
Q: Form password entry not registering as post variable Would appreciate some help! For some reason, the password entered into the form field:

Confirm Password

<input id="password2" name="password2" type="password" maxlength="100">

Is not registering in the php code below when it comes to grabbing it as a POST variable:
$p2 = $_POST['password2'];

The the php code above is above the html form if that matters... and the form posts to update.php which is the name of the file both of these pieces of code are in.

A: Should be something like this
<form action="somewhere.php" method="post">
<input id="password2" name="password2" type="password" maxlength="100">
<input type="submit" name="submit">
</form>

And on your somewhere.php, you can check
if(isset($_POST['submit'])){
$p2 = $_POST['password2'];
}else{echo "sorry form not submitted";}


text:
Q: How to create a getter function without a setter function? I have multiple exported variables in my script and anytime a single one is changed I want to invoke a common getter and let the values be set automatically
tool

export(float) var sample1 setget ,smthn_changed;
export(float) var sample2 setget ,smthn_changed;
export(float) var sample3 setget ,smthn_changed;

func smthn_changed():
    print("something changed!")

but this doesn't work and I have to create a setter for every single variable
is there any solution around this?

A: Please notice that you are defining smthn_changed as getter for those properties. And the getters are called when you try to read them, not when you try to assign them.
Alright, let us say you do want to know when the variables are being assigned. For that you would usually use setters, like this:
export var property:bool setget set_property

func set_property(new_value:bool) -> void:
    if property == new_value:
        return

    property = new_value
    print("value changed") # or emit a signal or whatever

The setter will be called at any time the variable is asignad externally (or internally with self.property = value, if you don't use self you can assign the variable directly without trigering the setter).
However, since you need to write the actual variable from the setter, this implies making a setter for each variable (if you used the same setter for multiple variable, you would not know which to set).

There is something else you can try: _set. The issue with _set is that will only be called for variables that are not declared in the script.
So, here is the plan:

*

*We are going to declare backing variables with a different name, not export them.

*We are going to use _set and _set to handle them.

*And we are going to use _get_property_list to export them.

Let us see the case of just one variable:
tool
extends Spatial

var _x:String setget _no_set

func _set(property: String, value) -> bool:
    if property == "x":
        _x = value
        smth_changed()
        return true

    return false

func _get(property: String):
    if property == "x":
        return _x

    return null

func _get_property_list() -> Array:
    if not Engine.editor_hint or not is_inside_tree():
        return []

    return [
        {
            name = "x",
            type = TYPE_STRING,
            usage = PROPERTY_USAGE_DEFAULT
        }
    ]

func _no_set(_new_value) -> void:
    pass

func smth_changed() -> void:
    print("something changed!")

That is not worth the effort compared to a simple setter.
The setter _no_set is a setter that does nothing (not even set the variable). I have added it to prevent bypassing the mechanism externally by setting to the backing variable directly. You could add a warning there, as that is not something you code should be doing. On the flip the fact that your code should not be doing it could also be taken as an argument against having _no_set.
But let us see how it scales to multiple variables:
tool
extends Spatial

var _x:String setget _no_set
var _y:String setget _no_set

func _set(property: String, value) -> bool:
    match property:
        "x":
            _x = value
        "y":
            _y = value
        _:
            return false

    smth_changed()
    return true

func _get(property: String):
    match property:
        "x":
            return _x
        "y":
            return _y

    return null

func _get_property_list() -> Array:
    if not Engine.editor_hint or not is_inside_tree():
        return []

    return [
        {
            name = "x",
            type = TYPE_STRING,
            usage = PROPERTY_USAGE_DEFAULT
        },
        {
            name = "y",
            type = TYPE_STRING,
            usage = PROPERTY_USAGE_DEFAULT
        }
    ]

func _no_set(_new_value) -> void:
    pass

func smth_changed() -> void:
    print("something changed!")

Still not great, since we are having to repeat the variables multiple times. I would still prefer to have multiple setters, even if they all have the same code.

A generic case for an arbitrary set of properties is tricky, because calling get from _get, or set from _set, or get_property_list form _get_property_list in such way that it causes a stack overflow will crash Godot (and continue crashing it upon opening the project). So be careful when writing this code.
What I'm going to do to avoid calling get_property_list from _get_property_list is to put the properties we want in a dictionary:
tool
extends Spatial

var _properties := {
    "x": "",
    "y": ""
} setget _no_set, _no_get

func _set(property: String, value) -> bool:
    if _properties.has(property):
        _properties[property] = value
        smth_changed()
        return true

    return false

func _get(property: String):
    if _properties.has(property):
        return _properties[property]

    return null

func _get_property_list() -> Array:
    if not Engine.editor_hint or not is_inside_tree():
        return []

    var result := []
    for property_name in _properties.keys():
        result.append(
            {
                name = property_name,
                type = typeof(_properties[property_name]),
                usage = PROPERTY_USAGE_DEFAULT
            }
        )

    return result

func _no_set(_new_value) -> void:
    pass

func _no_get():
    return null

func smth_changed() -> void:
    print("something changed!")

Notice also that I'm reporting the type based on the value with typeof.
I'll leave it to you to decide if this approach is worth the effort. It might be, if the set of variables can change, for example. And I remind you that you can call property_list_changed_notify so that Godot calls _get_property_list and updates the inspector panel with the new set of properties.
Despite the _no_set, the dictionary could still be read and manipulated externally. So I added a getter _no_get that returns null to prevent that. If you like a warning in your _no_set, you may want a warning in your _no_get too.

Addendum: Here is a variation that uses an array for the names of the properties you want to export. This way you can still have regular variables instead of dealing with a dictionary. It is up to you to keep the array up to date.
tool
extends Spatial

var _property_names := ["x", "y"] setget _no_set, _no_get
var _x:String
var _y:String

func _set(property: String, value) -> bool:
    if _property_names.has(property):
        set("_" + property, value)
        smth_changed()
        return true

    return false

func _get(property: String):
    if _property_names.has(property):
        return get("_" + property)

    return null

func _get_property_list() -> Array:
    if not Engine.editor_hint or not is_inside_tree():
        return []

    var result := []
    for property_name in _property_names:
        if not "_" + property_name in self:
            push_warning("Not existing variable: " + property_name)
            continue

        result.append(
            {
                name = property_name,
                type = typeof(get("_" + property_name)),
                usage = PROPERTY_USAGE_DEFAULT
            }
        )

    return result

func _no_set(_new_value) -> void:
    pass

func _no_get():
    return null

func smth_changed() -> void:
    print("something changed!")

Note that I have added a check to prevent exporting without a backing variable, which also pushes a warning. It is not catastrophic to expose them as they would just be handled as null.
Also note that I had to remove the _no_set from the variables in this version. The reason being that I set them with set, which results in calling the setter, and since the _no_set didn't set the variable the result was it wasn't saving the values.

Addendum on resetting the value
If you want to add that arrow to reset the value you need to implement a couple of (yikes) undocumented methods:
func property_can_revert(property:String) -> bool:
    if property in self:
        return true

    return false

func property_get_revert(property:String):
    match typeof(get(property)):
        TYPE_NIL:
            return null
        TYPE_BOOL:
            return false
        TYPE_INT:
            return 0
        TYPE_REAL:
            return 0.0
        TYPE_STRING:
            return ""
        TYPE_VECTOR2:
            return Vector2()
        TYPE_RECT2:
            return Rect2()
        TYPE_VECTOR3:
            return Vector3()
        TYPE_TRANSFORM2D:
            return Transform2D()
        TYPE_PLANE:
            return Plane()
        TYPE_QUAT:
            return Quat()
        TYPE_AABB:
            return AABB()
        TYPE_BASIS:
            return Basis()
        TYPE_TRANSFORM:
            return Transform()
        TYPE_COLOR:
            return Color()
        TYPE_NODE_PATH:
            return NodePath()
        TYPE_RID:
            return RID(Object())
        TYPE_OBJECT:
            return Object()
        TYPE_DICTIONARY:
            return {}
        TYPE_ARRAY:
            return []
        TYPE_RAW_ARRAY:
            return PoolByteArray()
        TYPE_INT_ARRAY:
            return PoolIntArray()
        TYPE_REAL_ARRAY:
            return PoolRealArray()
        TYPE_STRING_ARRAY:
            return PoolStringArray()
        TYPE_VECTOR2_ARRAY:
            return PoolVector2Array()
        TYPE_VECTOR3_ARRAY:
            return PoolVector3Array()
        TYPE_COLOR_ARRAY:
            return PoolColorArray()

    return null

The idea is that property_can_revert will return true for any property that will have the reset arrow. And property_get_revert will give the value that will be set when you click said arrow. This had to be found in the source code since it is not documented.


text:
Q: Unable to use fwmark on Debian 11 (bulleyes) to change routing behavior I have a recipe I already use on many cases, but this time doesn't works on Debian 11 (kernel 5.10.0-10-amd64)
my setup is basically an internal interface eth0 for a RFC1918 LAN, and two external interfaces connected to some ISP's Box:
eth1 for ISP1 as default router at 10.0.0.254 with public IP 1.2.3.4 (figuratively)
eth2 for ISP2 has a router at 10.0.3.254 with public 2.3.4.5
I have different possible route. I want to control which route my packet takes, so I create some rule and fwmark. First I append  2<tab>secondrouter in /etc/iproute2/rt_tables
ip rule add fwmark 0x3 lookup secondrouter
ip route add default via 10.0.3.254 table secondrouter

everythings is fine regarding ip route list table secondrouter and ip rule list
at this time I am able to do:
curl -4 ifconfig.me
1.2.3.4 #<- public ip address of my default route

Then I do
iptables-legacy -t mangle -A OUTPUT -d 34.117.59.81 -j MARK --set-mark 0x3

now if I do
curl -4 ifconfig.me
<timeout>

Where I expected 2.3.4.5 as public IP.
So clearly the marked packet do not take the route from the ip route table, worse, it timeouts.
If I do this exactly the same way on older Debian, its works perfectly.
NB:if I do a
ip route add 34.117.59.81 via <second router IP>

my curl test works perfectly as expected
curl -4 ifconfig.me
2.3.4.5 #<- Pub ip address of my second router

My problem occurs when using iptables or iptables-legacy to mark packets to route.
BTW I have plenty of iptables rules that works fine, so it do not looks like an iptables issue.
iptables-legacy-save
# Generated by iptables-save v1.8.7 on Sun Jan 23 22:35:06 2022
*mangle
:PREROUTING ACCEPT [41:5019]
:INPUT ACCEPT [41:5019]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [44:4752]
:POSTROUTING ACCEPT [44:4752]
-A OUTPUT -d 192.168.0.0/16 -j RETURN
-A OUTPUT -d 172.16.0.0/12 -j RETURN
-A OUTPUT -d 10.0.0.0/8 -j RETURN
-A OUTPUT -d 34.117.59.81/32 -j MARK --set-xmark 0x3/0xffffffff
COMMIT
# Completed on Sun Jan 23 22:35:06 2022
# Generated by iptables-save v1.8.7 on Sun Jan 23 22:35:06 2022
*filter
:INPUT DROP [19:7746]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [846:62420]
-A INPUT -m state --state INVALID -j DROP
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -p udp -m udp --dport 500 -j ACCEPT
-A INPUT -p esp -j ACCEPT
-A INPUT -p ah -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -s 192.168.0.0/16 -p tcp -m tcp --dport 3128 -j ACCEPT
-A INPUT -s 172.16.0.0/12 -p tcp -m tcp --dport 3128 -j ACCEPT
-A INPUT -s 10.0.0.0/8 -p tcp -m tcp --dport 3128 -j ACCEPT
-A FORWARD -m state --state INVALID -j DROP
-A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -s 192.168.0.0/16 -d 10.0.6.0/24 -j ACCEPT
-A FORWARD -s 10.0.6.0/24 -d 192.168.0.0/16 -j ACCEPT
COMMIT
# Completed on Sun Jan 23 22:35:06 2022

A: When the packet get out of the machine it is given a source IP address corresponding to the default output interface.
So it is required to add a MASQUERADE rule on the output interface because the mark rules gives our packet another destination than the planned one.
iptables-legacy -t nat -A POSTROUTING -o eth2 -j MASQUERADE

for the sake of understanding netfilter order of processing : (via Plouf)
                     (input interface)
                             |
                             v
                     /-------+-------\
                     | sanity checks |
                     \-------+-------/
                             |
                             v hook NF_IP_PRE_ROUTING
                      +------+------+
                      | conntrack   |
                      | defrag.     |
                      +-------------+
                      | mangle      |
                      | PREROUTING  |
                      +-------------+
                      | nat (dst)   |
                      | PREROUTING  |
                      +------+------+
                             |
                             v
        local delivery  /----+----\    forward
       +---------------+   route   +---------------+
       |                \---------/                |
       v                                           v
 /-----+-----\                               /-----+-----\
 |  defrag.  |                               | TTL check |
 \-----+-----/                               | dec. TTL  |
       |                                     \-----+-----/
       v hook NF_IP_LOCAL_IN                       |
+------+------+                                    |
| mangle  (1) |                                    |
| INPUT       |                                    |
+-------------+                                    |
| filter      |                                    v
| INPUT       |                              /-----+-----\
+-------------+                              | DF check  |
| nat (src)(2)|                              \-----+-----/
+-------------+                                    |
| conntrack   |                                    |
| confirm     |                                    |
+------+------+                               hook v NF_IP_FORWARD
       |                                    +------+------+
       v                                    | mangle  (1) |
/------+--------\                           | FORWARD     |
| local process |                           +-------------|
\------+--------/                           | filter      |
       |                                    | FORWARD     |
       v                                    +------+------+
 /-----+-----\                                     |
 |   route   |                                     |
 |   frag.   |                                     |
 \-----+-----/                                     |
       |                                           |
       v hook NF_IP_LOCAL_OUT                      |
+------+------+                                    |
| conntrack   |                                    |
| defrag.     |                                    |
+-------------+                                    |
| mangle      |                                    |
| OUTPUT      |                                    |
+-------------+                                    v
| nat (dst)(3)|                              /-----+-----\
| OUTPUT      |                              |   frag.   |
+-------------+                              \-----+-----/
| filter      |                                    |
| OUTPUT      |                                    |
+------+------+                                    |
       |                                           |
       v                                           |
 /-----+-----\                                     |
 |  reroute  |                                     |
 \-----+-----/                                     |
       |                                           |
       +------------------+     +------------------+
                          |     |
                          v     v hook NF_IP_POST_ROUTING
                      +---+-----+---+
                      | mangle  (1) |
                      | POSTROUTING |
                      +-------------+
                      | nat (src)   |
                      | defrag.     |
                      | POSTROUTING |
                      +-------------+
                      | conntrack   |
                      | confirm     |
                      | frag.       |
                      +------+------+
                             |
                             v
                   (output interface)


text:
Q: The height of the video tag, depending on the width of the screen Please tell me how you can implement this possibility, depending on the width of the browser screen, the height of the video tag always kept 70%. Through css, I could not do it.
The video itself is on the full width of my screen. I would like to do this on js

     <video src="https://globecore.com/wp-content/themes/globecore2016/video/usa-lp-video.mp4" type="mp4" autoplay="true" loop="loop"></video>

CSS
.video-cont {
    overflow: hidden;
    margin: -32px;
    position: relative;
}
.overlay-video {
    position: absolute;
    top: 0px;
    background: rgba(0, 0, 0, 0.6);
    right: 0px;
    height: 670px;
    width: 100%;
    z-index: 8;
}

A: Try to use this css code:
video {height: 70vw;}

A: You can set sizes like vw or vh which is the viewportWidth or viewportHeight

.video-cont {
    overflow: hidden;
    margin: -32px;
    position: relative;
}
.overlay-video {
    position: absolute;
    top: 0px;
    background: rgba(0, 0, 0, 0.6);
    right: 0px;
    height: 670px;
    width: 100%;
    z-index: 8;
}

.video-cont video {
    height: 70vw;
}

     <video src="https://globecore.com/wp-content/themes/globecore2016/video/usa-lp-video.mp4" type="mp4" autoplay="true" loop="loop"></video>

A: You can get the browser screen width in javascript by using window.screen.width or screen.width and then do the necessary calculations.


text:
Q: string.split but keeping sequential matches I've sifted through many questions but haven't come across one that answered this for me.
string input = "~abc~~~123~~~hijkl~9";
string[] postSplit = input.Split('~');

The response I see is:

[0]-""
[1]-"abc"
[2]-""
[3]-""
[4]-"123"
...

Notice there are only 2 entries between "abc" and "123" though there are 3 delimiters.
NOTE: I've tried this with string.split and regex.split methods with the same results.
How can I go about making sure that regardless of the number of sequential delimiters, I get an array entry for each. (3 entries between "abc" and "123")
Thanks in advance.
UPDATE:

*

*I understand that this is expected behavior.

*If more information on the matter could be given, more might understand why the input should not be changed.

*My "expectation" for a workaround/answer to this... probably going to have to be an extension method hand built. Just wanted to see if anyone had solved this problem and already built this wheel.

UPDATE2: The tilde in this scenario represents either a delimiter of fields OR an empty value that was never placed into the string. ~a~b would be simply a delimiter between a and b, but ~a~~~c represents a delimiter, empty value, delimiter c
UPDATE3:
~~~ represents a~~~c       in the array [a][""][c]
~ represents a~b    in the array [a][b]
only 1 and multiples of 3 tilde appear between valid inputs
a~~~~~~~~~b should equate to [a][""][""][""][b]

A: Note: I've written another somewhat more helpful answer that should do what you want.

string.Split by itself is not appropriate to solve your issue, because this is how it works:

*

*Let's say you split the string "A,B" with ',' as the separator. You will get the parts "A" and "B". One separator character, zero empty parts.

*Now let's split "A,,B", again with ',' as the separator. You will get the parts "A", "", and "B". Two separator characters, one empty part.

*Then let's split "A,,,B", again with ',' as the separator. You will get the parts "A", "", "", and "B". Three separator characters, two empty parts.

*The general rule is: n consequtive separator characters produce n-1 empty parts.
Perhaps now you can see why ~~~ produces only two empty parts, not three.
(If you're willing to use string methods other than string.Split, then admittedly my answer is not very helpful.)

A: Note: This answer only addresses the parts of the question preceding its "update" paragraph, because it was written before the question was edited.
string.Split will produce n-1 empty parts for n consecutive separator characters. Since you want it to produce n empty parts instead, you are one tilde short wherever several of them occur consequtively. Add the "missing" tildes as follows before you perform the Split:
// using System.Text.RegularExpressions;

const string input = "~abc~~~123~~~hijkl~9";
string[] parts = Regex.Replace(input, "~~+", "$0~").Split('~');
//               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

A: From: String.Split:

If two delimiters are adjacent, or a delimiter is found at the
  beginning or end of this instance, the corresponding array element
  contains Empty.

Regarding this, Split method works as expected and the result you are currently getting is correct.

A: To add to @Amnon Shocot...
        string input = "~abc~~~123~~~hijkl~9";
        var postSplit = input.Split(new char[] {'~'}, StringSplitOptions.RemoveEmptyEntries);
        var postSplit2 = input.Split('~').Where(ss => ss != String.Empty);

with regurlar expressions, unfortunately we still need to filter out empty strings, because of the first match.
        Regex rr = new Regex("~+"); // you may have been missing the +
        var postSplit3 = rr.Split(input).Where(ss => ss != String.Empty);

A: In vb:
    Dim input As String = "~abc~~~123~~~hijkl~9"
    Dim post() As String = input.Split({"~"c}, 3, StringSplitOptions.RemoveEmptyEntries)

Looks like #3 has the remainder including the ~9

    Dim input As String = "~abc~~~123~~~hijkl~9".Replace("~~~", "~na~")
    If input.StartsWith("~") Then input = "na" & input
    If input.EndsWith("~~") Then input &= "~na"
    Dim post() As String = input.Split({"~"c})

This works on the sample string but if adjacent fields contain a placeholder it will get more complicated. you may have to iterate over the string making on replacement at a time until the string length doesn't change.


text:
Q: Referencing variables dynamically I'm trying to dynamically reference a variable based on the return of a function in Lua. I have several variables and I can reference them all individually, but I am trying to clean up the code and find a way to dynamically reference them.
I have tried several different ways to get this to function and I'm honestly not sure it can be done at all. Everywhere I look to solve this issue I have found only instructions on creating dynamic variables instead of referencing variables dynamically.
varExample_1 = 3,
varExample_2 = 3,
varExample_3 = 5,
varExample_5 = 4,
varExample_4 = 2,

newVar = "varExample_" .. GetExampleType(call)

--or more specifically

if 8 > varExample_ .. GetExampleType(call) then return false end

I'm attempting to get the variable values but with all examples, I can only get fo far as receiving the variable name as a string.

A: First things first, consider using table instead of global variables (always avoid them whenever possible):
local varExample = {}
varExample[1] = 3,
varExample[2] = 3,
varExample[3] = 5,
varExample[5] = 4,
varExample[4] = 2,

or even better
local varExample = {3, 3, 5, 4, 2}

and then
if 8 > varExample[GetExampleType(call)] then return false end

But you insist on using global variables, they can be accessed using _G:
if 8 > _G["varExample_"..GetExampleType(call)] then


text:
Q: particular word in an array I'm trying to find a way to check if the word "miami" appears in this array and print out if it does or doesn't. I'm not sur wether to use the for loop or forEach loop. How can I print "true" the fact that the word "miami" exists in the array bellow?
let word = "miami";
let arr = ["bcn", "mia", "sao", "mex", "par", "miami", "ams", "ber", "paris", "lis", "mad"];

for (let i = 1; i <= 11; i < arr.length; i++) {
  if (i === 21){
    console.log("miami");
    break;
  } else {
    console.log(i);
  }
}

A:

const word = "miami";
const arr = ["bcn", "mia", "sao", "mex", "par", "miami", "ams", "ber", "paris", "lis", "mad"];

const result = arr.find(item => item === word)

console.log(result);


text:
Q: Eigen: different row-wise memory reservation for row major sparse matrix Is it at all possible in the Eigen library to reserve space for a row-major sparse matrix row by row (different for each row)?
I am trying to optimize the memory consumtion of filling a pretty big sparse matrix (~70mio x 70mio with ~2 billion nnz is the biggest I could reach but I'd like go even further). To clearify the way I went:
First I was using the recommended setFromTriplets which is probably the fastest way filling the matrix, but checking on the memory consumption I found a peak about double the average memory at the point where I used this function, which makes sense since I - at some point - store the elments in both, the matrix and the vector of Triplets until the vector goes out of scope.
Using insert() improved the maximum memory consumption a lot obviously. Though, I still got a peak due to reallocation. I then also used reserve() so that there is no (or less) reallocation. It also lowers the peak quite a bit, but it is not completely gone, again due to some reallocation (if valgrind is correct). Since most of my rows have a lower NNZ than the max I get quite a few empty allocated entries in the storage which increases the average memory consumption. Using makeCompressed lowers the average again but obviously makes the peak higher again as well because more reallocation has to be done when calling it.
Why I asked the question above now is: I can calculate the NNZ for each row up front and also sort them so that I actually should be able to completely optimize this having a compressed matrix without any empty allocation and with no reallocation peak if I could reserve a different number of NNZ for each row.
I would be greatful if anybody would let me know if that is possible or not in Eigen and if not: do you know any library that supports it?
Thanks a bunch!

A: Yes, it is possible, and you perhaps could have found that function in the docu:
template<class SizesType>
void SparseMatrix::reserve(const SizesType & reserveSizes);
Note that SizesType can be, e.g., an std::vector (or std::deque) or an Eigen::VectorXi.
Also, if you are able to insert the elements to your matrix in order, you may also have a look at the (internal) function insertBack.


text:
Q: Implicit Casting vs Explicit Casting here the bit depth of int and float is same where implicit casting is done
and in second one bit depth of char and short is same but explicit casting is done. What is the reason behind this ?
Implicit Conversion
int k = 100; //32bits

float l = k ; //32bits

Explicit Conversion
 char e = 'B'; //16 bits

 short f = (short)e; //16 bits

A: Although short and char are both 16 bit (2-byte) variables their ranges differ.

Char is an unsigned variable.
Short is a signed variable.

The range of the a char type is from 0 up to 65535).
The range of a short is from (−32,768 up to 32,767).
Because of this difference java forces you to cast explicitly because a char that has value over 32,767 that is casted to a short can lead to an invalid conversion. The same goes for a negative short cast to a char.
This is also the reason you cast an int to long (since the value of an int will always fit in a long. But you have to explicitly cast a long to an int (telling the compiler that you are willing to accept the risk of dataloss / corruption)

A: In java widening type conversions are implicit and narrowing type conversions are explicit.
Even though their sizes are equal.
Date type heirarchy is as follows,
byte-->short-->int-->long-->float-->double
You can refer to the Java Language Specification


text:
Q: Primefaces TreeTable css style In my JSF web application I've inserted a simple TreeTable.
Where can I set up distance between left border and expanded child's icon?
I want this distance to be bigger when new level is expanded.
EDIT:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head>
        <title>Facelet Title</title>
        <link rel="stylesheet" type="text/css" href="css/treetable.css" />

    </h:head>
    <h:body>
        <h:form id="form">

                <f:facet name="header">
                    Single Selection
                </f:facet>

                    <f:facet name="header">
                        Name
                    </f:facet>
                    <h:outputText value="#{document.name}" />

                    <f:facet name="header">
                        Size
                    </f:facet>
                    <h:outputText value="#{document.size}" />

                    <f:facet name="header">
                        Type
                    </f:facet>
                    <h:outputText value="#{document.type}" />

                <f:facet name="footer">

                </f:facet>

                    <h:panelGrid  columns="2" cellpadding="5" rendered="#{not empty newJSFManagedBean.docCon.selectedNode}">
                        <h:outputLabel for="name" value="Name: " />
                        <h:outputText id="name" value="#{newJSFManagedBean.docCon.selectedNode.data.name}" style="font-weight:bold" />

                        <h:outputLabel for="size" value="Size: " />
                        <h:outputText id="size" value="#{newJSFManagedBean.docCon.selectedNode.data.size}" style="font-weight:bold" />

                        <h:outputLabel for="type" value="Type " />
                        <h:outputText id="type" value="#{newJSFManagedBean.docCon.selectedNode.data.type}" style="font-weight:bold" />
                    </h:panelGrid>

        </h:form>

    </h:body>

A: You need to create your own css and override the ui-treetable-indent css property originaly defined as :
.ui-treetable .ui-treetable-indent {
    float: left;
    height: 16px;
    width: 16px;
}

The simple way is to include your own stylesheet with h:outputStylesheet or <link rel="stylesheet">.


text:
Q: Removing all non-unique letters from a char [] array for hangman I am having trouble understanding how to remove a letter from a char array here is my code
import java.util.Random;
import java.util.Scanner;

public class Main {

    public static void main(String [] args)
    {

        start();

    }
    public static void start()
    {
        Scanner scan = new Scanner(System.in);
        Random rand = new Random();
        String [] Words = {"Dog","cat","Food","Bacon","Turkey","hood","poo","Good","look"};
        String RandomWord = Words[rand.nextInt(Words.length)];
        char [] array = RandomWord.toCharArray();
        boolean [] parrallelArray = new boolean[array.length];
        int i = 0;

        int placeholder = 0;
        System.out.println(findUniqueLetters(array));
        char input = 0;
        while(i<findUniqueLetters(array)){
            i++;

            System.out.println("You have a "+RandomWord.length()+" Word "+RandomWord);
            System.out.println("Guess a letter : ");
            input = scan.next().charAt(0);

            for(int j = placeholder; j<array.length;j++){

                if(input == array[j]){
                    j++;
                    placeholder = j;
                    System.out.println("You got it right");

                    break;
                }

                else if(!(input ==array[j])){
                        j++;
                        placeholder = j;
                        System.out.println("You got it wrong");
                        break;

                }

            }
        }
        System.out.println("You have wasted all your tries!");

    }

    public static int findUniqueLetters(char [] a){
        int Unique = 1;

        for(int i = 1; i<a.length;i++){
            if(!(a[i] == a[i-1])){
                Unique++;

            }

        }
        return Unique;
    }

}

Is there another way to do this or is deleting it the only way to do this?
I have tried to switch the repeated letter in the array with the non repeated one in the array but that only works for some words.

A: Please use a Set. more here - > http://docs.oracle.com/javase/7/docs/api/java/util/Set.html


text:
Q: Chrome won't display all HTML content I have a simple HTML document well displayed using Firefox. However, using Chrome, it will only display a part of it. Viewing the source code with Chrome, I see this:
ATTGATGATATGTTGGATCAAG<spa

<spa is broken, and what follows this is not displayed. My code in the HTML file is the following one:
ATTGATGATATGTTGGATCAAGTAAAATTTCCCTAATATTTGTATGATTTAACTTATCCGTTGCTTTGAA

My css for mnull:
.mnull {
        background-color: #FFFFCC;
        color: #000000;
}

I do not show the whole code because it is too large. Do you have any idea about why it is happening with Google Chrome?

A: Just an idea: does it help when you add line breaks to your code?
So, when you write
A
TTGATGATATGTTGGAT
C
AAG
T
A
A
A
ATTTC
C
CTAATATTTGTA
TGATT
T
AACTTATCCG
T
TGCTTTGA
A

instead of
ATTGATGATATGTTGGATCAAGTAAAATTTCCCTAATATTTGTATGATTTAACTTATCCGTTGCTTTGAA

?