text:
Q: Не могу понять как работает метод componentWillUpdate Я весь день смотрел в интернете и не нашел ничего полезного по этой теме. У меня есть вот такой код:

class User extends React.PureComponent {
    componentDidMount() {
        console.log("Did mount " + this.props.name);
    }

    componentDidUpdate(prevProps) {
        console.log("Did update " + prevProps.name + " -> " + this.props.name);
    }

    componentWillUnmount() {
        console.log("Will unmount " + this.props.name);
    }

    render() {
        return (

{this.props.name}

        );
    }
}

class Users extends React.Component {
    constructor(props) {
        super(props);
        this.state = {usersList: props.usersList};
        this.removeUser = this.removeUser.bind(this);
    }

    removeUser(index) {
        let newUsers = this.state.usersList.filter((user, i) => i !== index);
        this.setState({
            usersList: newUsers
        });
    }

    render() {
        return (

                {this.state.usersList.map((user, index) => {
                    return <User key={user.id} name={user.name} onClick={() => this.removeUser(index)}/>
                })}
                <button onClick={() => this.removeUser(1)}>Delete second</button>

        );
    }
}

let users = [
    {
        id: 1,
        name: "Alexander"
    },
    {
        id: 2,
        name: "Anton"
    },
    {
        id: 3,
        name: "Dmitriy"
    },
    {
        id: 4,
        name: "Artem"
    },
    {
        id: 5,
        name: "Andrey"
    }
];

ReactDOM.render(
    <Users usersList={users}/>,
    document.getElementById('root')
);

Согласно тому, что я прочитал, PureComponent изменяется только при изменении state или props, но когда я нажимаю кнопку, я вижу сообщения от метода componentDidUpdate, даже если name не было изменено ни для одного User.

A: User получал функцию в пропс onClick которая пересоздавалась при каждом рендере, соответственно компонент обновлялся. Так же функция удаления-фильтрации пользователя была не правильно сделана. Нельзя использовать индекс массива. Нужно использовать индекс структуры данных. Получилось примерно так:
import React from "react";

class User extends React.PureComponent {
  componentDidMount() {
    console.log("Did mount " + this.props.name);
  }

  componentDidUpdate(prevProps) {
    console.log("Did update " + prevProps.name + " -> " + this.props.name);
  }

  componentWillUnmount() {
    console.log("Will unmount " + this.props.name);
  }

  render() {
    const { removeUser, id, name } = this.props;
    return
 removeUser(id)}>{name}
;
  }
}

const App = () => {
  return (

      <Users usersList={users} />

  );
};

export default App;

class Users extends React.Component {
  constructor(props) {
    super(props);
    this.state = { usersList: props.usersList };
    this.removeUser = this.removeUser.bind(this);
  }

  removeUser(id) {
    let newUsers = this.state.usersList.filter((user) => user.id !== id);
    this.setState({
      usersList: newUsers,
    });
  }

  render() {
    return (

        {this.state.usersList.map((user) => {
          return (
            <User
              key={user.id}
              id={user.id}
              name={user.name}
              removeUser={this.removeUser}
            />
          );
        })}
        <button onClick={() => this.removeUser(2)}>Delete second</button>

    );
  }
}

let users = [
  {
    id: 1,
    name: "Alexander",
  },
  {
    id: 2,
    name: "Anton",
  },
  {
    id: 3,
    name: "Dmitriy",
  },
  {
    id: 4,
    name: "Artem",
  },
  {
    id: 5,
    name: "Andrey",
  },
];

Если в Users написать вот так:
 <User
    key={user.id}
    id={user.id}
    name={user.name}
    removeUser={this.removeUser}
    onClick={() => {
       console.log("log");
    }}

то юзеры будут опять обновляться все. Можно добавить console.log в componentDidUpdate:
console.log(
      `prevProps.onClick === this.props.onClick`,
      prevProps.onClick === this.props.onClick
    );


text:
Q: How to trigger redux form validation I have two pages with two redux forms 7.0.3 .The user Enters Search criteria Information into the first page and presses a submit button and then navigates to the next page where they will get some more detailed information about their search .If they press the save button to save their search and this search was done before they will be returned to the first page where an error message will be displayed saying that this is a duplicate search .
I want to be able to trigger the first forms validation and some how put this error message in the error queue so that it is displayed through redux forms .
Any ideas how I could do this .
thanks for your help .

redpajama_set_name: RedPajamaStackExchange


text:
Q: Declaring class pointer variable outside class So let's say we have following structures in header file:
struct x {
    struct y {
        int a;
        y* b;
        y(int _a, y* _b) {
            a = _a;
            b = _b;
        }
    };
    void z() {
        y* c = NULL;
    }
};

We also have main file which looks like this:
void f() {
    //place for new pointer from question below
}

int main() {
    ...
}

Is there a possibility to declare new y type pointer in f that would work for f the same c pointer works for z (pointer can operate on y type and can't be used outside the function)?

A: The type y is nested inside x, so to access it from outside you will have to prefix it with x and the scope resolution operator ::.
void f() {
   x::y* c = nullptr;
}

should work.


text:
Q: Scope of PDO, error: Call to a member function prepare() on null It seems that my $pdo is out of scope for some reason because it returns null but when I move the function code block outside of the function it works.
db.php
<?php

$host = 'localhost';
$db = 'phpcms';
$user = 'root';
$pass = 'root';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
    PDO::ATTR_ERRMODE       =>  PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE    =>  PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES      =>  false,
];

$pdo = new PDO($dsn, $user, $pass, $opt);

functions.php
<?php require_once("include/db.php"); ?>
<?php require_once("include/sessions.php"); ?>
<?php

    function redirect_to($New_Location)
    {
        header("location:".$New_Location);
        exit();
    }

    function login_Attempt($Username, $Password)
    {
        $Query = $pdo->prepare('SELECT * FROM registration WHERE username=? AND password=?');
        $Query ->execute([$username, $password]);
        if($admin = $Query -> fetch())
        {
            $_SESSION['User_Id']=$admin['id'];
            $_SESSION['Username']=$admin['username'];
            $_SESSION['SuccessMessage']="Welcome Back, {$_SESSION['Username']}";
            redirect_to("dashboard.php");
        }
        else{
            $_SESSION['ErrorMessage']="Incorrect Username and Password Combination!";
            redirect_to("login.php");
        }
    }

?>

login.php
<?php require_once("include/db.php"); ?>
<?php require_once("include/sessions.php"); ?>
<?php require_once("include/functions.php"); ?>
<?php

    if(isset($_POST['Submit'])){

        $username               =   $_POST['Username'];
        $password               =   $_POST['Password'];

        if(empty($username) || empty($password))
        {
            $_SESSION['ErrorMessage']="All fields must be filled out!";
        }
        else
        {
            $user = login_Attempt($username, $password);
            //$Query = $pdo->prepare('SELECT * FROM registration WHERE username=? AND password=?');
            //$Query ->execute([$username, $password]);

            //if($admin=$Query -> fetch())
            //{
            //  $_SESSION['User_Id']=$admin['id'];
            //  $_SESSION['Username']=$admin['username'];
            //  $_SESSION['SuccessMessage']="Welcome Back, {$_SESSION['Username']}";
            //  redirect_to("dashboard.php");
            //}
            //else{
            //  $_SESSION['ErrorMessage']="Incorrect Username and Password Combination!";
            //}
        }
    }
?>

If I remove the commented out code everything works, but when I try to use the login_Attempt function it gives the error "Call to a member function prepare() on null". It doesn't matter where the login_Attempt function is declared, I tried in the functions.php first then I tried moving the method to login.php but still had the same error.
Since the db.php is inserted first, shouldn't the functions.php be inside the pdo's scope?


text:
Q: Why does chromium throw a Sandbox_lix error? When I run chromium in ubuntu terminal I get
Gtk-Message: 16:08:14.534: Failed to load module "canberra-gtk-module"
[2674:2674:0209/160818.019361:ERROR:sandbox_linux.cc(374)] InitializeSandbox() called with multiple threads in process gpu-process.
[2701:1:0209/160822.146414:ERROR:child_process_sandbox_support_impl_linux.cc(79)] FontService unique font name matching request did not receive a response.
[2701:1:0209/160822.146850:ERROR:child_process_sandbox_support_impl_linux.cc(79)] FontService unique font name matching request did not receive a response.

If instead I try chromium-browser
Gtk-Message: 16:08:14.534: Failed to load module "canberra-gtk-module"
[2674:2674:0209/160818.019361:ERROR:sandbox_linux.cc(374)] InitializeSandbox() called with multiple threads in process gpu-process.
[2701:1:0209/160822.146414:ERROR:child_process_sandbox_support_impl_linux.cc(79)] FontService unique font name matching request did not receive a response.
[2701:1:0209/160822.146850:ERROR:child_process_sandbox_support_impl_linux.cc(79)] FontService unique font name matching request did not receive a response.

I tried
sudo apt install canberra-gtk-module and got an unable to locate package error and successfully used
sudo apt install libcanberra-gtk-module
My concern is that the errors refer to Sandbox. Which makes me think the errors mean that the browser won't be sandboxed properly which is a safety concern. so how do I fix this error?


text:
Q: VLookup Letter Number Values - Delete Rows I'm really struggling with a VLookup situation right now. I'm trying to do something that is really over my head, but I think that with a little help I just might be able to do it.

*

*For starters, I created a separate sheet with a table so I can give a number to some letters so I may quantify their value.

*With this information, I would like to elaborate a VBA formula that would be able to check a table for those letter in a column (with a number) and delete every row that would present a letter value lower than the inputed Letter's given number. (Ignore the Ns in column I)

]

*What I have so far is something like this:
Sub DeletarIndices()

    indice = InputBox("Digite o IC/IV Desejado", "GBG Pneus")

    Set planilhaV = Sheets("IV")
    Dim vValores As String
    sResult = Application.VLookup("Y", planilhaV.Range("A2:B11"), 2)

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Dim i As Long
    For i = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
        If Not (Range("A" & i).Value > sResult) Then
            Range("A" & i).EntireRow.Delete
        End If
    Next i
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

What happens is that when I run the code, a inputbox opens and asks for a value that will be used in the code. The letter will be converted in to a number and will be used as a comparison to delete lower values. But...
Right here:
If Not (Range("A" & i).Value > sResult) Then

The letter is still a number, so when it checks the table, only numbers lower than the value will be deleted, not the letters with lower values. What I need is exactly that. That letters get analyzed and the rows deleted, not numbers.
Thank you to anyone that may help me with this!

A: Assuming that your order of priority for the letters is always alphabetical, you don't need to convert letters to numbers for this, you can simply compare letter to letter.  I would also note that your way to determine the last row (Range("A" & Rows.Count).End(xlUp).Row) is not good practice, I suggest you find a more reliable method.
Assuming your data is presented as you have shown - with data in column H as a 3-character code where the letter is the last character (e.g. "91B", "89D", etc.) - lets go through step by step: (note there is no lookup worksheet planilhaV any more)
1) Declare our variables
Dim indice As String   ' To hold our user input letter
Dim rowLetter As String   ' To hold the current row letter value
Dim firstRow As Long   ' First row of your data
Dim lastRow As Long   ' Last row of your data
Dim currentRow As Long   ' Current row for your loop counter
Dim sht As Worksheet   ' To hold the worksheet you're working on

2) Assign some values
Set sht = ThisWorkbook.Worksheets("*WORKSHEET NAME*")   ' Use the name of your worksheet
firstRow = 1
lastRow = sht.Range("A" & Rows.Count).End(xlUp).Row

3) Get your user input
indice = UCase(InputBox("Digite o IC/IV Desejado", "GBG Pneus"))   ' Convert user input to upper case and store

4) Do your processing
For currentRow = lastRow To firstRow Step -1
    rowLetter = UCase(Right(sht.Range("H" & currentRow).Value, 1))   ' Get letter from code in column H, converted to upper case
    If rowLetter < indice Then   ' Compare the letters, and if smaller than user input...
        sht.Rows(currentRow).EntireRow.Delete   ' Delete the row
    End If
Next currentRow

And that should about do it.  It's a good idea to declare all variables you plan to use, and using Option Explicit will ensure you can't use anything without declaring it first.
EDIT:
@LeonVFX: If the value of the letters doesn't always increase with alphabetical order then you could use a lookup table or you could do the comparison in code.
If you choose to use a lookup table like in your original example, then you could adjust the code above as follows:
Dim indice As String   ' To hold our user input letter
Dim indiceValue As Long   ' To hold the numeric value of our user input letter
Dim rowLetter As String   ' To hold the current row letter
Dim rowLetterValue As Long   ' To hold the numeric value of the current row letter
Dim firstRow As Long   ' First row of your data
Dim lastRow As Long   ' Last row of your data
Dim currentRow As Long   ' Current row for your loop counter
Dim sht As Worksheet   ' To hold the worksheet you're working on
Dim planilhaV As Worksheet   ' To hold your lookup worksheet

Set sht = ThisWorkbook.Worksheets("*WORKSHEET NAME*")   ' Use the name of your worksheet
Set planilhaV = ThisWorkbook.Worksheets("IV")   ' As in your original example
firstRow = 1
lastRow = sht.Range("A" & Rows.Count).End(xlUp).Row

indice = UCase(InputBox("Digite o IC/IV Desejado", "GBG Pneus"))   ' Convert user input to upper case and store
indiceValue = CLng(Application.VLookup(indice, planilhaV.Range("A2:B11"), 2, False))   ' Creating numeric indice value with lookup table

For currentRow = lastRow To firstRow Step -1
    rowLetter = UCase(Right(sht.Range("H" & currentRow).Value, 1))   ' Get letter from code in column H, converted to upper case
    rowLetterValue = CLng(Application.VLookup(rowLetter, planilhaV.Range("A2:B11"), 2, False))   ' Creating numeric value for current row letter with lookup table
    If rowLetterValue < indiceValue Then   ' Compare the numeric letter values, and if smaller than user input...
        sht.Rows(currentRow).EntireRow.Delete   ' Delete the row
    End If
Next currentRow

If you're finding that it's only deleting one row at a time, my guess is that using sht.Range("A" & Rows.Count).End(xlUp).Row to find the last row is the reason because you don't have any data in column A?  If your data is in column H as in your original example, change the A to an H in the code and you should be fine, or try and find a more reliable way to set your lastRow variable value.

A: After I got some help in a forum, I got to this answer, and I'll leave it here if anyone run into something like this.
' Verifies if the digit is a number. If it is, returns True, False if it isn't.
Function ehNumero(ByVal digito As String) As Boolean

    a = Asc(digito)
    If a >= 48 And a <= 57 Then
        ehNumero = True
    Else
        enNumero = False
    End If

End Function

' Separates the code in a numeric and a alphabetic part.
Function separaCodigo(ByVal codigo As String, ByRef numero As Integer, ByRef letras As String) As Boolean
    p = 0
    For i = 1 To Len(codigo)
        digito = Mid(codigo, i, 1)
        If Not ehNumero(digito) Then ' Found the point break when it finds the first non-numeric digit.
            p = i
            Exit For
        End If
    Next i

    If p = 0 Or p = 1 Then
        numero = 0
        letras = ""
        separaCodigo = False
    Else
        codigo = UCase(codigo)
        numero = Int(Mid(codigo, 1, p - 1))
        letras = Mid(codigo, p)
        separaCodigo = True
    End If
End Function

' Gets the values from the configuration table.
Function valorDasLetras(ByVal letras As String) As Integer
    On Error GoTo trataErro

    valorDasLetras = Application.VLookup(letras, Worksheets("Configuração").Range("A2:B11"), 2, False)

    Exit Function

trataErro:
    valorDasLetras = 0 '

End Function

'Deletes the lines in the table in the interval.
Function deletar(ByVal numero As Integer, letras As String) As Integer

    valor = valorDasLetras(letras)
    If valor = 0 Then
        deletar = -1
        Exit Function
    End If

    limInf = numero
    limSup = valor

    Dim dados As Worksheet
    Set dados = ActiveWorkbook.ActiveSheet

    Dim linhasPraDeletar As Range
    totalLinhas = 0

    linha = 1
    Do While True

        curCodigo = dados.Cells(linha, 7) ' Using Column G

        If curCodigo = "" Then
            Exit Do
        End If

        Dim curNumero As Integer
        Dim curLetras As String
        If Not separaCodigo(curCodigo, curNumero, curLetras) Then
            deletar = -1
            Exit Function
        End If

        ' Gets the values for the letters from the table
        curValor = valorDasLetras(curLetras)
        If curValor = 0 Then
            deletar = -1
            Exit Function
        End If

        If curNumero < limInf Or curValor < limSup Then
            If linhasPraDeletar Is Nothing Then
                Set linhasPraDeletar = dados.Rows(linha)
            Else
                Set linhasPraDeletar = Union(linhasPraDeletar, dados.Rows(linha))
            End If
            totalLinhas = totalLinhas + 1
        End If

        linha = linha + 1
    Loop

    linhasPraDeletar.Select
    linhasPraDeletar.EntireRow.Delete ' <===== Comment to select, but do not delete, the line

    deletar = totalLinhas

End Function

' Run the code
Sub LimparValores()
    'On Error GoTo trataErro

    ' Reads the user code
    msg = "Input your code"
    codigo = InputBox(msg, "Código")
    If codigo = "" Then ' Cancelado
        Exit Sub
    End If

    ' Separates the user code number from letters
    Dim numero As Integer
    Dim letras As String
    If Not separaCodigo(codigo, numero, letras) Then
        MsgBox ("Invalid code: " & codigo)
        Exit Sub
    End If

    ' Calls the delete function
    linhas = deletar(numero, letras)
    If linhas = -1 Then
        MsgBox ("There was an error with the code (the letter does not exist in configuration)")
    Else
        If linhas = 0 Then
            MsgBox ("There are no rows in the interval - no row was deleted")
        Else
            MsgBox (linhas & " rows deleted!")
        End If
    End If

    Exit Sub

trataErro:
    MsgBox ("The code is not in the expected format.")

End Sub

Hope it helps anyone in the future!


text:
Q: How to run on browser start I'm new to Firefox addon development.
I have the following code:
var windows = require("sdk/windows").browserWindows;
windows.on("open", function() {
    // do stuff
});

But this only runs for windows created after the browser is started, not the first one.
How can I fix this?
I know I could just copy the code outside of the open event, but then it also runs when the addon is installed and I don't want that.

A: I found the answer here.
exports.main = function (options, callbacks) {
    if (options.loadReason == "startup") {
        // do stuff
    }
};


text:
Q: Matlab. Extract specific data from struct field I have 66 csv files containing historical data from stocks.
At first i used this in order to import the data for my analysis but it is very time consuming for 66 csv files.
ADBE1=readtable('ADBE.csv');
Close=ADBE1(:,5);
ADBE=table2array(Close);

So later on i tried to make a struck from the directory , containing all the csv files, so that i could extract from each file the fifth column into a new matrix Y that will contain the closing prices from all stocks.
''' files = dir('*.csv'); '''
Now that my struct is created, i must reach each ''' files.name ''' with a loop and take the data. But how do i take the first file of files.name? ( something like files.name(i) ).
Thanks in advance

A: You get create a cell array of all the file name by doing
filenames = {files(:).name}


text:
Q: Simple HTTP request example in Android using Kotlin I am new to Android development with Kotlin and I am struggling on finding any useful documentation on how to create a simple GET and POST requests with the best current practices as possible. I am coming from an Angular development and there we used a reactive development using RxJS.
Normally I would create a service file that would hold all my request functions, then I would use this service in whichever component and subscribe to the observable.
How would you do this in Android? Is there a good started example of things that have to be created. From the first look, everything looks so complicated and over-engineered

A: I suggest you to use the official recommendation of OkHttp, or the Fuel library for easier side and it also has bindings for deserialization of response into objects using popular Json / ProtoBuf libraries.
Fuel example:
// Coroutines way:
// both are equivalent
val (request, response, result) = Fuel.get("https://httpbin.org/ip").awaitStringResponseResult()
val (request, response, result) = "https://httpbin.org/ip".httpGet().awaitStringResponseResult()

// process the response further:
result.fold(
    { data -> println(data) /* "{"origin":"127.0.0.1"}" */ },
    { error -> println("An error of type ${error.exception} happened: ${error.message}") }
)

// Or coroutines way + no callback style:
try {
    println(Fuel.get("https://httpbin.org/ip").awaitString()) // "{"origin":"127.0.0.1"}"
} catch(exception: Exception) {
    println("A network request exception was thrown: ${exception.message}")
}

// Or non-coroutine way / callback style:
val httpAsync = "https://httpbin.org/get"
    .httpGet()
    .responseString { request, response, result ->
        when (result) {
            is Result.Failure -> {
                val ex = result.getException()
                println(ex)
            }
            is Result.Success -> {
                val data = result.get()
                println(data)
            }
        }
    }

httpAsync.join()

OkHttp example:
val request = Request.Builder()
    .url("http://publicobject.com/helloworld.txt")
    .build()

// Coroutines not supported directly, use the basic Callback way:
client.newCall(request).enqueue(object : Callback {
    override fun onFailure(call: Call, e: IOException) {
        e.printStackTrace()
    }

    override fun onResponse(call: Call, response: Response) {
        response.use {
            if (!response.isSuccessful) throw IOException("Unexpected code $response")

            for ((name, value) in response.headers) {
                println("$name: $value")
            }

            println(response.body!!.string())
        }
    }
})

A: you can use something like that:
internal inner class RequestTask : AsyncTask<String?, String?, String?>() {
         override fun doInBackground(vararg params: String?): String? {
            val httpclient: HttpClient = DefaultHttpClient()
            val response: HttpResponse
            var responseString: String? = null
            try {
                response = httpclient.execute(HttpGet(uri[0]))
                val statusLine = response.statusLine
                if (statusLine.statusCode == HttpStatus.SC_OK) {
                    val out = ByteArrayOutputStream()
                    response.entity.writeTo(out)
                    responseString = out.toString()
                    out.close()
                } else {
                    //Closes the connection.
                    response.entity.content.close()
                    throw IOException(statusLine.reasonPhrase)
                }
            } catch (e: ClientProtocolException) {
                //TODO Handle problems..
            } catch (e: IOException) {
                //TODO Handle problems..
            }
            return responseString
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            //Do anything with response..
        }
    }

and for call:
        RequestTask().execute("https://v6.exchangerate-api.com/v6/")

HttpClient is not supported any more in sdk 23. You have to use URLConnection or downgrade to sdk 22 (compile 'com.android.support:appcompat-v7:22.2.0')
If you need sdk 23, add this to your gradle:
android {
    useLibrary 'org.apache.http.legacy'
}

You also may try to download and include HttpClient.jar directly into your project or use OkHttp instead

A: The best practice you ever get to just go through the basics of networking call and create some demo applications using Android Studio.
If you want to click start then follow this tutorial
Simplet netwroking call in Kotlin
https://www.androidhire.com/retrofit-tutorial-in-kotlin/
Also, I would like to suggest Please create some demo application for GET and POST request and then merge these examples into your project.


text:
Q: How to obtain all available Elastic IP addresses in boto3 What is the boto3 equivalent to:
import boto

conn = boto.connect_ec2()
addresses = conn.get_all_addresses()

(returning all Elastic IP addresses)
import boto3
ec2 = boto3.resource('ec2')
addresses = ec2.????

I am a little bit confused by the generalization that seem to apply to VPC setups as well.

What I found so far is following:
import boto3

client = boto3.client('ec2')
print client.describe_addresses()

This response does not seem to contain the association status.

A: This may help:
import boto3
ec2 = boto3.resource('ec2', region_name="ap-southeast-1")
client = boto3.client('ec2', region_name="ap-southeast-1")
# create 3 x Elastic IP Addresses.  Set to Domain='vpc' to allocate the address for use with instances in a VPC.
eip1 = client.allocate_address(Domain='vpc')
eip2 = client.allocate_address(Domain='vpc')
eip3 = client.allocate_address(Domain='vpc')

# A collection of VpcAddresses resources "vpc_addresses.all()"
print eip = list(ec2.vpc_addresses.all())
[ec2.VpcAddress(allocation_id='eipalloc-3f693f5a'), ec2.VpcAddress(allocation_id='eipalloc-7896c01d'),
ec2.VpcAddress(allocation_id='eipalloc-9997c1fc')]

Reference Link 1
Reference Link 2

A: Here's a simple example that prints all Elastic IP public IP addresses in the current account/region:
import boto3
client = boto3.client('ec2')
addresses_dict = client.describe_addresses()
for eip_dict in addresses_dict['Addresses']:
    print(eip_dict['PublicIp'])

For more, see the EC2.Client.describe_addresses reference documentation.


text:
Q: np.max not returning correct output when used on intergers In Python, why does
np.max(-2,0)

return
-2

when
max(-2, 0)

returns
0

Should they not have the same output for integers? Or is np.max used for something else?

A: The input value to the np.max() function must be a list, please take a look at the official Numpy documentation to know more about its functions, inputs and outputs:
import numpy as np
print(np.max([-2, 0]))

Output:
0


text:
Q: Rails - newbie association question with both has_many and HABTM models I have three models:
class Tenant < ActiveRecord::Base
  has_many :sites
end

class Site < ActiveRecord::Base
  belongs_to :tenant
  has_and_belongs_to_many :users
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :sites
end

For Site and Users, I have a join table (sites_users).
Every Site has n Users.  Every Tenant has n Sites.
To get a list of users for a specific site, it's easy:
t = Tenant.first
s = t.sites.first
s.users

But is there an association I can add to Tenant to provide a list of all users between all sites under that tenant?  So that I can do:
t = Tenant.first
t.users

A: A number of people have asked for this, you'll see some discussion in the Rails Lighthouse Ticket #8994 of some developers trying to merge in the functionality of the nested_has_many_through plugin.  If you're on Rails 2.3, the nested_has_many_through plugin might work for you, otherwise in Rails 3 you could write an ARel query to find the right set of studies.


text:
Q: Failed to launch GDB: .pioinit:11: Error in sourced command file: Remote communication error. Target disconnected VSCODE ver#    : 1.75.1
PlatformIO ver#: 3.0.0
GDB ver#       : 12.1
PlatformIO.ini file:
platform       : espressif32
board          : upesy_wroom
framework      : arduino
ESP32 Board connected directly to the PC USB port with no external debug board.  Trying to use the
onboard ESP32 debugger.
I'm using VSCode & PlatformIO to program & debug an ESP32 WRoom Dev Board.  I keep getting this error:
Failed to launch GDB: .pioinit:11: Error in
sourced command file: Remote communication error. Target disconnected.
The debug console displays:
undefinedC:\Users\Joel.platformio\packages\toolchain-xtensa-esp32\bin\xtensa-esp32-elf-gdb.exe: warning: Couldn't determine a path for the index cache directory.
Reading symbols from C:\Users\Joel\Documents\PlatformIO\Projects\BLINK.pio\build\upesy_wroom\firmware.elf...
PlatformIO: debug_tool = cmsis-dap
PlatformIO: Initializing remote target...
Open On-Chip Debugger  v0.11.0-esp32-20220706 (2022-07-06-15:48)
Licensed under GNU GPL v2
WARNING: boards/esp-wroom-32.cfg is deprecated, and may be removed in a future release.
adapter speed: 5000 kHz
Info : tcl server disabled
Info : telnet server disabled
Error: unable to find a matching CMSIS-DAP device
.pioinit:11: Error in sourced command file:
Remote communication error.  Target disconnected.: Success.
I installed the GCC and GDB at this location:  C:\msys64\mingw64\bin
I'm a beginner using VSCode & the ESP32.  I'm trying to follow the examples from the Random Nerd site, and since switching to a new PC, this has been tripping me up.
Any ideas for a fix?
Thanks in advance,
Joel
I tried using 4 different ESP32 boards to make sure it wasn't a hardware problem.
I uninstalled PlatformIO, VSCode, and deleted all project folders.  I re-installed everything and verified the GDB version that is installed:


text:
Q: Updating a column based on another column I have the following table:
ID  Type    Food    Drink   Animal
--------------------------------------
1   NULL    Y   N   N
2   NULL    Y   N   N
3   NULL    N   Y   N
4   NULL    N   Y   N
5   NULL    N   N   Y

How can I update the Type column based on what boolean is true in other columns. For example
If the 'Food' column is true then the Type would be 'Food' etc

A: You can use a CASE inside an UPDATE query:
UPDATE tbl SET Type =
  CASE
    WHEN Food = 'Y' THEN 'Food'
    WHEN Drink = 'Y' THEN 'Drink'
    WHEN Animal = 'Y' THEN 'Animal'
  END
WHERE ...some condition if necessary...

However, this probably isn't necessary at all.  You might consider creating a view that shows you this information rather than storing it in a column.  In case the other booleans change, you would need to always be updating the Type column to match.
CREATE OR REPLACE VIEW type_vw AS (
  SELECT
      ID,
      CASE
        WHEN Food = 'Y' THEN 'Food'
        WHEN Drink = 'Y' THEN 'Drink'
        WHEN Animal = 'Y' THEN 'Animal'
      END as Type
  FROM tbl
);

A: The correct answer (as per comment) is to have a normalized database - then it wouldn't be an issue.
The wrong answer is:
UPDATE badtable
SET type=(
    CASE
      WHEN Food='Y' THEN 'FOOD'
      WHEN Drink='Y' THEN 'DRINK'
      WHEN Animal='Y' THEN 'ANIMAL'
      ELSE 'WTF?'
)
WHERE type IS NULL
AND (Food='Y' OR Drink='Y' OR Animal='Y');

A: You don't need the Type column, you can derive that info, e.g.:
select ID,
    case
        when Food='Y' then 'Food'
        when Drink='Y' then 'Drink'
        when Animal='Y' then 'Animal'
        else 'None'
    end as Type
from mytable

But, I recommend that you change your schema so that you have a separate Type table with columns TypeID and Name. Then, in your main table, you would have a TypeID column.
If there is a requirement that an entity could have more than one Type, you would add an intersection table.

A: hmmmmm i think your table structure is incorrect.  it would be better to have the types e.g food drink animal in a lookup with a reference from the parent table e.g
parent table
id Type
-------
1  1
2  1
3  2
4  3

lookup
id name
-------
1  food
2  drink
3  animal

then you can just do a join on the tables


text:
Q: Telegram, getting all emoji from sticker pack Situation
I'm writing a Telegram bot.
I need to know how many emoji(stickers) in the pack.
What found
In the telegram bot api found, that we can get only emoji (and file_id) for sticker.
To discover a sticker's file_id:

*

*Send the sticker from Telegram App to bot.

*Use the bot's getUpdates method to receive the sticker. Receive sticker's file_id in the message.

I.e., it turns out you must send all stickers to bot manualy.
Question
Some sites(example: 1, 2) extracting stikers preview from stiker pack url:

https://telegram.me/addstickers/animals

Any ideas how to make it automatically?


text:
Q: Getting a Table Row from TableView in Titanium Mobile I'm trying to manipulate a tableViewRow inside a TableView but I can't find where it actually is stored. When inspecting Tableview, I get the headings under which the Rows should be, but I don't see any actual Rows.
Any idea in which Object these Rows are contained?

A: If you are not using table view section then, you can get all rows like this:
var rows = tableview.data[0].rows;


text:
Q: Definition of a function of a real variable Wikipedia says that

a function of a real variable is a function whose domain is the real numbers $\mathbb R$, or a subset of $\mathbb R$ that contains an interval of positive length.

I don't understand what it means for a subset of $\mathbb R$ to have an interval of positive length. Does this mean that the subset cannot have only integers since this particular subset would be just points on a number line and not a length on the number line? What if the subset of $\mathbb R$ was $\{1,2\}\cup[3,4]$? Is this a valid subset? It has 2 points and a length on the number line but the only condition is that the subset has an interval of positive length so it seems that this is a valid subset of $\mathbb R$. Also, what is the point of saying "positive length"? Why can't the definition of a function of a real variable just say "length"?

A: This is the definition provided on Wikipedia.

A function of a real variable is a function whose domain is the real numbers $\mathbb R$, or a subset $D\subseteq\mathbb R$, which contains an interval of positive length.

This means that the function $f$ is called a function of a real variable if and only if $f:D\to E$ for some set $E$ (common examples are the real numbers $\mathbb R$ or the complex numbers $\mathbb C$), where the domain $D$ is  a subset of $\mathbb R$ and in addition, $D$ has a subset $(a,b)\subseteq D$ so that $b>a$. Here, the "length" of an interval of the forms $(a,b),[a,b],[a,b),(a,b]$ are all defined to be $b-a$. So by "positive length" we mean that the length $(b-a)>0$, i.e. $b>a$. The reason we need to make this definition is because usually, we consider sets of the form $[a,a]=\{ a\}$ as intervals too. But of course, this set has zero length.
In your example, the domain $D=\{1,2\}\cup[3,4]$ does satisfy this criterion, because the interval $[3,4]\subset D$ is an interval of positive length (in particcular, it has length $1>0$). On the other hand, sets like the rational numbers $\mathbb Q$ but also more "pathological" sets like the Cantor set can be shown to contain no intervals of positive length, and will not therefore suffice as an example of the domain of a real variable, as it is defined on Wikipedia. The formal definition of this is in terms of measures, specifically the Lebesgue measure, which formalises the idea of lengths. The Lebesgue measure of the Cantor set is $0$ [see here], so that it does not contain an interval of positive length.
The reason we often impose the restriction that $D$ has an interval of positive length is because we often want to study changes in $f$ around the neighbourhood of a particular point $x$ in the domain. We want to ask questions you might have seen in Calculus, such as "if we change $x$ by a little bit, how much does $f(x)$ change?". We can do so if there is a connected set (i.e. an interval) to deal with. But if our set looks like $D=\mathbb Q$ for example, it makes our life harder. So we exclude those sets from definition just so that we don't need to think about them.


text:
Q: How to identify if the DBlink created in Oracle12c is shared or not I have created couple of DB links. Some are shared and some are not.
I created shared DB Link:
CREATE SHARED DATABASE LINK dblink_name CONNECT TO username IDENTIFIED BY password AUTHENTICATED BY schema_name IDENTIFIED BY password USING 'service_name';

I created Normal DBlink as:
create database link dblink_name connect to username identified by password using service_name;

Is there a way where i can identify if the dblink created is shared mode or not.

A: There's no simple way to check the data dictionary to determine if a link is shared or not.  Below are two workarounds, using SYS.LINK$ and DBMS_METADATA, but they each have problems.
SYS.LINK$
The undocumented table SYS.LINK$ contains this information in a bitmap, as explained by Solomon Yakobson in this thread:
select name from sys.link$ where bitand(flag,1) = 1;

But that table contains password hashes and is only viewable by SYS.  You could perhaps grant permission to that table, which could raise some security concerns.  Or create a view on top of it and then grant that view, although you're typically not supposed to create objects in the SYS schema.
DBMS_METADATA
The package DBMS_METADATA recreates the link DDL and can be used to check for the "SHARED" keyword.
select owner, db_link
from dba_db_links
where lower(dbms_metadata.get_ddl('DB_LINK', db_link, owner)) like '%create shared%';

This solution can be slow, especially if the system has a large number of database links.  And searching for text strings in source code may not be reliable.  According to the syntax diagrams in the manual there are no other keywords that could come between CREATE and SHARED, but that may change or there may be undocumented features or behavior.


text:
Q: Epics in Jira whose Epic-Story Link is from specific project I would like to find all epics that have "Issues in Epic" from a specific Project.
Current JQL:
project = FOO AND issuetype = Epic AND key in (FOO-1, FOO-2, FOO-3)

I can add and issueFunction in linkedIssuesOf("project = BAR and issueFunction in hasLinkType('Epic-Story Link')"), but it gives me epics which have other types of linked issues (eg. clones, related ..)

A: I was able to reproduce the described behavior.
These are all link types: Blocks, Cloners, Duplicate, Epic-Story Link, Gantt End to End, Gantt End to Start, Gantt Start to End, Gantt Start to Start, Parent-Child Link, Problem/Incident, Relates, Solves
It seems that Epic-Story Link is handled like a super type of some of the other ones during query evulation. That's just a suggestion and I dunno why this should be.
However, the following query should work for your purpose
project = FOO AND issuetype = Epic AND issueFunction in linkedIssuesOf("project = BAR AND 'Epic Link' is not EMPTY")

A: Why not just create a scrum board, import all issues you want to sort on and see which ones are empty opening the epics panel?


text:
Q: Two different JSON views with Rails Consider the following, I have a Job class that has inputs and one output. I have the following in my job.rb
  def as_json(options={})
    super(include: [:inputs,:output])
  end

So this has been working very well and my JobController has been dolling out well formatted and useful JSON responses.
I am working on a way to display a version of the Job JSON to the user that only showed the inputs, so I did the following and got some weird behavior:
@job.to_json(include: [:inputs])
This method ignores the options passed to it, and calls the as_json method on the model
So my question is, once you have defined as_json, how do you get a different json view of the object?
Thanks!

A: You could try this to pass output and inputs by default :
def as_json( options = { :include => {:inputs, :output} } )
   super(options)
end

then you can pass your options for special cases :
@job.as_json( :include => {:inputs} )

More info here : http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/


text:
Q: Coupled oscillators - why is the order of $x_2 - x_1$ or vice versa the way it is? In my physics class, we have been working on the two mass, three spring (coupled oscillator) problem and I found this great video that helps explain how to set up one of these problems. (Link: Coupled oscillator video at time 7:00) However, I don't understand why we take the order of change in $x$ such that it is the position associated with that mass minus the position associated with the other mass...for example, what is we were looking at mass 1 but mass 2 was much heavier or a Spring not directly connected was much stronger?

A:
I don't understand why we take the order of change in x such that it is the position associated with that mass minus the position associated with the other mass

Because the stretch of the middle spring depends on the position of both masses, and we defined both $x_1$ and $x_2$ to be positive if the masses move to the right.

what is we were looking at mass 1 but mass 2 was much heavier

Then the l.h.s.'s of the two equations would be $m_1\ddot{x}_1$ and $m_2\ddot{x}_2$ instead of both using the same mass.

or a Spring not directly connected was much stronger?

You have to solve the complete system of equations to find how a not-directly-connected spring affects each mass. (Actually true in the presented case as well as if you assumed unequal spring constants, but if the problem isn't symmetrical of course you'll get different amplitudes of displacement and velocity for each mass)
Edit
In comments you asked,

is the defining rightward motion as positive a convention or a requirement?

In principle it's an arbitrary choice. In practice, most people seem to choose to have a position variable increase as an object moves to the right (and draw their x-y graphs with positive x to the right, etc).
In your problem this choice was clearly communicated in the diagram showing the mechanical setup:


text:
Q: Getting Error :MERGE statement has an INSTEAD OF trigger on some, but not all, of the actions specified in the MERGE statement I have a 'instead of insert' trigger on a table to generate custom unique code and on that same table inserting bulk data by store procedure but some how getting error as below :

The target 'xyz' of the MERGE statement has an INSTEAD OF trigger on some, but not all, of the actions specified in the MERGE statement. In a MERGE statement, if any action has an enabled INSTEAD OF trigger on the target, then all actions must have enabled INSTEAD OF triggers

Any input or comment on this would be greatly appreciated.

A: The error message is very clear - When using merge, instead of triggers must be applied for all or none of the actions the merge statement may perform.
If your merge have an insert when not matched, and an update when matched, the target table must have either instead of insert as well as an instead of update triggers, or none of them.
This is also well documented in the merge page on Microsoft docs, under the title Trigger Implementation:

If the target table has an enabled INSTEAD OF trigger defined on it for an insert, update, or delete action performed by a MERGE statement, then it must have an enabled INSTEAD OF trigger for all of the actions specified in the MERGE statement.


text:
Q: Can I print a numpy array's values in green if positive and red if negative? I'd like a quick visual cue when printing a numpy array of floats to console. How can I use colors to indicate positivity/negativity?
I've found this hacky way of changing the color of the console, but I'm not sure it's helpful in my case:
>>>YELLOW = '\033[93m'
>>>ENDCOLOR = '\033[0m'
>>>print(YELLOW+'hello'+ENDCOLOR)
hello # <-- this is yellow
>>>this is in your regular console color

but if you leave out the last string:
>>>YELLOW = '\033[93m'
>>>ENDCOLOR = '\033[0m'
>>>print(YELLOW+'hello')
hello #<-- it's yellow
>>>this is yellow as well, until you print ENDCOLOR

A: The cleanest way is to use the formatter kwarg in np.set_printoptions and colorama as suggested by Vikas Damodar:
import colorama
import numpy as np

def color_sign(x):
    c = colorama.Fore.GREEN if x > 0 else colorama.Fore.RED
    return f'{c}{x}'

np.set_printoptions(formatter={'float': color_sign})

Note that this is a global config and will print all arrays with this convention.

A: I think colorama is a good way to do this :
from colorama import fore

print(f'{fore.Green}green color')


text:
Q: не могу понять часть кода, все что понятно, а так же суть проблемы описал в коментах

<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

A:
return function(e) {
  //  9- функция принимает ProgressEvent - событие
  продолжения загрузки, выгрузки или чтения файла.
  //НО ГДЕ УКАЗАННО
  ЧТО ОНА ПРИНИМАЕТ ИМЕННО ЭТО СОБЫТИЯ?
  ОТ  КУДА ВООБШЕ ЭТА ФУНКЦИЯ БЕРЕТ ИМЕННО ЕГО???

здесь (e) - краткая запись (event), на самом деле можно задать любое имя, это формальность.
На англоязычном SO есть обсуждение аналогичного вопроса.
Подробнее о event object можно прочитать здесь.

A: кароче порылся я в документацыи и решил сделать то же только под конкретно мои нужды, и что бы мой мозг не закипал при виде того кода, делает то же смое что и тот чудо код но как по мне более прост и понятен, закину может кому пригодится) пользуйтесь, только расчитана на чтения одного файла, но кому надо цыкл прилепит) или проверки какие)

<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>


text:
Q: How to send value with react-navigation in static filed? I have a screen set a <Switch /> in header by using react navigation.
I know how to get this.state value from outside function by  this.props.navigation.setParams.
But I don't know how to send the <Switch /> value to outside function.
I try it with the code onValueChange={value => params.handleThis(value)}
but in my case handleThis is key-value, it can't get the value obviously.
this.props.navigation.setParams({
   handleThis: this.changeSwitch
 });
How to send <Switch /> onChange value to outside function ?
Here is my code:
      static navigationOptions = ({ navigation }) => {
        const { params = {} } = navigation.state;
        return {
          title: 'Title',
          headerStyle: {
            backgroundColor: ColorSetting.headerColor,
            elevation: null,
          },
          headerTitleStyle: {
            fontWeight: '300',
            fontFamily: 'FFF Tusj',
            fontSize: 18
          },
          headerRight:
            <View style={{ marginRight: 15 }}>
              <Switch
                onValueChange={value => params.handleThis()}
                value={params.switchOn}
                onTintColor='#444444'
                tintColor='#444444'
              />
            </View>,
        };
      };

      constructor(props) {
        super(props);

        this.state = {
          switchOn: false
        };
      }

      componentDidMount() {
        this.props.navigation.setParams({
          handleThis: this.changeSwitch
        });
      }

  changeSwitch = () => {
    const { switchOn, titleVersion } = this.state;

    this.props.navigation.setParams({ switchOn: !switchOn });
    this.setState({ switchOn: !switchOn });
  }

Any help would be appreciated. Thanks in advance.

A: You can use params.handleThis as the handler, there is no need for an inline function.
static navigationOptions = ({ navigation }) => {
  const { params = {} } = navigation.state;
  return {
    title: 'SO Question',
    headerStyle: {
      elevation: null,
    },
    headerTitleStyle: {
      fontFamily: 'FFF Tusj',
      fontSize: 18
    },
    headerRight:
      <View style={{ marginRight: 15 }}>
        <Switch
          onValueChange={params.handleThis}
          value={params.switchOn}
          onTintColor='#444444'
          tintColor='#444444'
        />
      </View>,
  };
};

after that changeSwitch will receive the new value as the first parameter.
changeSwitch = (switchOn) => {
  this.props.navigation.setParams({ switchOn });
  this.setState({ switchOn });
}

Here's a working example


text:
Q: What does "sensitive for" mean in this sentence?
The BLOSUM matrices are calculated matrices, most sensitive for local alignment of related sequences, ideal when trying to identify an unknown nucleotide sequence.

What is the meaning of "sensitive for" here?

A: This is a scientific bit of jargon.
Here we have an algorithm used in DNA sequencing that is used to search for sequences that at similar to other sequences. Searching instruments, whether physical or mathematical, can be more or less sensitive.  A sensitive thermometer detects smaller changes; a sensitive voltmeter measures smaller differences in voltage than a less sensitive meter. This calculational method is 'more sensitive' when used to look for some things than for others. It's a typical sentence structure when discussing this sort of thing.


text:
Q: Error while running " jekyll serve " command I followed the following link to install jekyll
https://davidburela.wordpress.com/2015/11/28/easily-install-jekyll-on-windows-with-3-command-prompt-entries-and-chocolatey/
However when I run " jekyll serve" , I get the following error

jekyll 3.2.0 | Error:  different prefix: "/" and
  "C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/minima-1.0.1"

I am using os windows 10.pls help.
Update1:
I installed 3.1.6, but I am getting the follwoing error
c:\myblog>jekyll build C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/bundler-1.12.5/lib/bundler/spec_set.rb:95:in block in materialize': Could not find j ekyll-3.2.0 in any of the sources (Bundler::GemNotFound) from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/bundler-1.12.5/lib/bundler/spec_set.rb:88:inmap!' from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/bundler-1.12.5/lib/bundler/spec_set.rb:88:in materialize' from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/bundler-1.12.5/lib/bundler/definition.rb:140:inspecs' from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/bundler-1.12.5/lib/bundler/definition.rb:185:in specs_for' from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/bundler-1.12.5/lib/bundler/definition.rb:174:inrequested_specs' from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/bundler-1.12.5/lib/bundler/environment.rb:19:in requested_specs' from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/bundler-1.12.5/lib/bundler/runtime.rb:14:insetup' from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/bundler-1.12.5/lib/bundler.rb:95:in setup' from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/jekyll-3.1.6/lib/jekyll/plugin_manager.rb:33:inrequire_from_bundler' from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/jekyll-3.1.6/bin/jekyll:9:in <top (required)>' from C:/Ruby200-x64/bin/jekyll:23:inload' from C:/Ruby200-x64/bin/jekyll:23:in `

Update2:
Updated to jekyll 3.2.1, working now. Thanks everybody.

A: Identical issue here.
The 3.2.0 build is currently broken for Windows. Anomaly logged on project here https://github.com/jekyll/jekyll/issues/5146 and should be fixed on a future release.
Continuing to try for a workaround. (Roll-back Jekyll version...?)
I rolled back for now :
gem uninstall jekyll -v 3.2.0
gem install jekyll -v 3.1.6

A: Jekyll 3.2.0 was broken on Windows. Run gem update jekyll to upgrade to 3.2.1 which supports Windows.

A: I found out that jekyll 3.2.1 works on versions of windows 7 but does not on later versions....


text:
Q: In R replace punctuation "." within a string I have look into the web and found this webpage In R, replace text within a string to replace a text within in a string.
I tried the same method to replace the punctuation "." into another punctuation "-" but it did not work.
 group <- c("12357.", "12575.", "197.18", ".18947")
 gsub(".", "-", group)

gives this output
 [1] "------" "------" "------" "------"

instead of
 [1] "12357-" "12575-" "197-18" "-18947"

Is there an alternate way to do this ?

A: "." in regex langage means "any character". To capture the actual point, you need to escape it, so:
gsub("\\.", "-", group)
#[1] "12357-" "12575-" "197-18" "-18947"

As mentioned by @akrun in the comments, if you prefer, you can also enclosed it in between brackets, then you don't need to escape it:
gsub('[.]', '-', group)
[1] "12357-" "12575-" "197-18" "-18947"


text:
Q: How can you disable the buffer in a boost::iostreams sink? I've written a 'sink' using boost::iostreams, so that I can essentially have my own code run when someone tries to write to an iostream object.
Unfortunately there is a buffer somewhere in the system, so that my Sink's write() function only gets called every 4kB or so.  This is a problem because the sink I am implementing is a fixed size (e.g. 128 bytes) so once this much data has been written it needs to return an error to the caller (something like 'disk full'.)
Because of the buffer the caller is able to write a few kilobytes of data and no errors are returned, then later when the buffer is flushed the extra data is silently lost, which is causing me problems.
Does anyone know if it's possible to somehow disable this buffer?  I've tried many of the suggestions here for generic iostreams (e.g. pubsetbuf) but none of them seem to apply to the Boost implementation.
The problem code is part of a library I am working on, which is available from GitHub if it helps (run 'make check' and you will see one failure because of this problem.)
Any suggestions would be greatly appreciated!

A: I think I've found a workaround.  You have to manually decide when you want to perform a flush, but if you do a seek - even seeking to the same position, i.e. stream.seekp(0, std::ios::cur) - then it will cause everything to be flushed as expected.
It's a bit of a horrible workaround but it seems to do the job most of the time.


text:
Q: System.Data.DataException error occurred in EntityFramework.dll I have been following this tutorial Getting Started with Entity Framework 6 Code First using MVC 5.
When I got to the section where I need to run the program and click on Student so that the program would create database I get the following error.

System.Data.DataException was unhandled by user code
    HResult=-2146233087
    Message=An exception occurred while initializing the database. See the InnerException for details.
    Source=EntityFramework
    StackTrace:
         at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
         at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
         at System.Data.Entity.Internal.LazyInternalContext.b__4(InternalContext c)
         at System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input)
         at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action)
         at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
         at System.Data.Entity.Internal.InternalContext.Initialize()
         at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
         at System.Data.Entity.Internal.Linq.InternalSet1.Initialize()
         at System.Data.Entity.Internal.Linq.InternalSet1.GetEnumerator()
         at System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
         at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
         at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)
         at ContosoUniversityFollow.Controllers.StudentController.Index() in c:\Users\Office\Documents\Visual Studio 2013\Projects\ContosoUniversityFollow\ContosoUniversityFollow\Controllers\StudentController.cs:line 21
         at lambda_method(Closure , ControllerBase , Object[] )
         at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
         at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters)
         at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters)
         at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
         at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
         at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult)
         at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End()
         at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
         at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
         at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3c()
         at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass45.b__3e()
    InnerException: System.Data.Entity.Core.EntityException
         HResult=-2146233087
         Message=The underlying provider failed on Open.
         Source=EntityFramework
         StackTrace:
              at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
              at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection()
              at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
              at System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClassb.b__9()
              at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation)
              at System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption)
              at System.Data.Entity.Core.Objects.ObjectQuery1..GetEnumerator>b__0()
              at System.Lazy1.CreateValue()
              at System.Lazy1.LazyInitValue()
              at System.Lazy1.get_Value()
              at System.Data.Entity.Internal.LazyEnumerator1.MoveNext()
              at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source)
              at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1[TResult](IEnumerable1 sequence)
              at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable1 query, Expression queryRoot)
              at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
              at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
              at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 source)
              at System.Data.Entity.Internal.EdmMetadataRepository.QueryForModelHash(Func2 createContext)
              at System.Data.Entity.Internal.InternalContext.QueryForModelHash()
              at System.Data.Entity.Internal.ModelCompatibilityChecker.CompatibleWithModel(InternalContext internalContext, ModelHashCalculator modelHashCalculator, Boolean throwIfNoMetadata)
              at System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean throwIfNoMetadata)
              at System.Data.Entity.Database.CompatibleWithModel(Boolean throwIfNoMetadata)
              at System.Data.Entity.DropCreateDatabaseIfModelChanges1.InitializeDatabase(TContext context)
              at System.Data.Entity.Internal.InternalContext.<>c__DisplayClasse1.<CreateInitializationAction>b__d()
              at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
         InnerException: System.Data.SqlClient.SqlException
              HResult=-2146232060
              Message=Cannot open database "ContosoUniversity1" requested by the login. The login failed.
  Login failed for user 'Office-PC\Office'.
              Source=.Net SqlClient Data Provider
              ErrorCode=-2146232060
              Class=11
              LineNumber=65536
              Number=4060
              Procedure=""
              Server=(LocalDb)\v11.0
              State=1
              StackTrace:
                   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
                   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
                   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
                   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
                   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
                   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry)
                   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry)
                   at System.Data.SqlClient.SqlConnection.Open()
                   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
                   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation)
                   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
                   at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
              InnerException:

I have a hard time trying to fix the problem. I follow everything and even redo it just to make sure I got it right. I don't think I miss any steps. But there is something wrong. If I run the whole sample code, everything works fine.
Any help is appreciated.
Thanks,
Pheap
EDIT:
It was really frustrating for a simple thing that lead to an error like this.
@mmeasor, I just saw that error as well. It cannot connect to database. So that lead me to check the connection.
What happen was that at first I used this connection string:

So EntityFramework created a database file ContosoUniversity1.mdf in here like C:\Users\Office\ContosoUniversity1.mdf. But then I want it to create another one and use that instead and this time I want it to be in the program App_Data\ folder instead.
So I modified the web.config file to:

I thought if I do that, EF will create a new database for me in the \App_Data\ folder and link to that instead of the old on in C:\Users\Office.
I was so wrong! that was when I start getting the error posted above. And I cannot find what causes the problem.
With the second web.config, I tried to copy the database file to the App_Data folder, but that still doesn't work.
Now I use the first connection string and it works fine.
So now the question is: How to make the program links to database file in the \App_Data\ folder instead?
Thanks,
Pheap

A: I had the same problem in trying to change location of Conosto University tutorial database from User folder to App_Data folder.  John Locke keyed me into the idea that it may have something to do with having to change the name of the database.
Change name slightly of database named in the web.config file (This works inconsistently, but does work consistently inconsistently.  If I had to test this again...and I'm sure I will at some point...I would stay away from reusing names - i.e. don't toggle back and forth between two name preferences (e.g. database1 and database2 back to database1 - I would use completely novel names e.g. databse7...database8...database9 - get name away from previously used names)
I also had luck, once a database was created with the name I didn't want, changing the database name to what I wanted it to be and matching that name in web.config (i.e. I was able to create a "database3.mdf" file successfully and then changed it in the OS to what I wanted - "database1.mdf" and matched the web.config file to database1 and it connected up on the first try)

A: I had this problem for days ("An exception of type 'System.Data.DataException' occurred in EntityFramework.dll but was not handled in user code") and I tried everything since changing the connection string to many different methods I saw on Internet questions and answers,
My solution?...
Created a new proyect with another name, and it saved me.

A: Here EmployeeDetail is a table name and Employee is a model name.  And
 ID,Branch, Salary and UID are table fields:
public ActionResult Index()
{
    List<EmployeeDetail> employees = context.EmployeeDetails.ToList();
    List<Employee> emp = new List<Employee>();
    foreach(EmployeeDetail item in employees)
    {
        emp.Add(new Employee
            {
                ID=Convert.ToInt32(item.ID),
                Branch=item.Branch,`enter code here`
                Salary=Conve`enter code here`rt.ToInt32(item.Salary),
                UID = Convert.ToInt32(item.ID),
            });
    }
    return View(emp);
}

view page code

Index

            @foreach (var emp in Model)
            {

                    @Html.ActionLink(emp.Branch, "Details", new { id = emp.ID });

            }


text:
Q: How to write java streams for the nested loops How do I use the java streams for the below scenario with nested loops...
package test;
import java.util.ArrayList;
import java.util.List;
import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
class Car {
  String carName;
  int wheelNo;
  WheelDetails wheelDetails;

  Car(String carName, int wheelNo) {
    this.carName = carName;
    this.wheelNo = wheelNo;
  }
}

@Getter
@Setter
class WheelDetails {
  int wheelNo;
  String wheelColour;
  int Size;

  WheelDetails(int wheelNo, String wheelColour, int Size) {
    this.wheelNo = wheelNo;
    this.wheelColour = wheelColour;
    this.Size = Size;
  }
}

public class testMain {

  public static void main(String[] args) {

    List<Car> cars = new ArrayList<Car>();
    cars.add(new Car("CarOne", 1));
    cars.add(new Car("CarTwo", 2));

    List<WheelDetails> wheelDetailsList = new ArrayList<WheelDetails>();
    wheelDetailsList.add(new WheelDetails(1, "Black", 16));
    wheelDetailsList.add(new WheelDetails(2, "Grey", 17));
    for (Car car : cars) {
      for (WheelDetails wheelDetails : wheelDetailsList) {
        if (car.getWheelNo() == wheelDetails.getWheelNo()) {
          car.setWheelDetails(wheelDetails);
        }
      }
    }
  }
}

not able to find the options to do the above in the streams it will be great helpful
have gone trough the other areas but could not find it... any link or solution will be helpful......

A: Try this:
cars.forEach(car -> wheelDetailsList.stream()
    .filter(wheelDetails -> wheelDetails.wheelNo == car.wheelNo).forEach(car::setWheelDetails));

A: The following solution modifies elements in the list of cars:
cars.forEach(car -> car.setWheelDetails(
    wheelDetailsList.stream()
                    .filter(wd -> car.getWheelNo() == wd.getWheelNo())
                    .findFirst()
                    .orElse(null)
));

Another faster solution is based on a temporary map <Integer, WheelDetails>:
Map<Integer, WheelDetails> wheelMap = wheelDetailsList
        .stream()
        .collect(Collectors.toMap(
            WheelDetails::getWheelNo, // key
            wd -> wd,                 // value
            (wd1, wd2) -> wd1,        // (optional) merge function to resolve conflicts
            LinkedHashMap::new        // keep insertion order
        ));
cars.forEach(car -> car.setWheelDetails(wheelMap.get(car.getWheelNo())));


text:
Q: Python Requests ConnectionErrorr [11001] getaddrinfo failed I'm making a stock index webscraper using beautifulsoup and requests but I can't figure out what's blocking the connection.
Here's my code:
from bs4 import BeautifulSoup
import requests

def scraper(link):
    response = requests.get(link, verify=False)
    soup = BeautifulSoup(response.content, 'html.parser')
    company = soup.find(class_="D(ib) ").get_text()
    response.close()
    return company

def main():
    ticker = input("Input stock ticker symbol:")
    site = ("http://finace.yahoo.com/quote/" + ticker.upper().strip())
    data = scraper(site)
    print(data)

main()

And Here's the exception:
C:\Python37-32\python.exe C:\Users\lucas\CS\Final_Project\Stock_Index_Scraper.py
Input stock ticker symbol:tsla
Traceback (most recent call last):
  File "C:\Python37-32\lib\site-packages\urllib3\connection.py", line 157, in _new_conn
    (self._dns_host, self.port), self.timeout, **extra_kw
  File "C:\Python37-32\lib\site-packages\urllib3\util\connection.py", line 61, in create_connection
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  File "C:\Python37-32\lib\socket.py", line 748, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 672, in urlopen
    chunked=chunked,
  File "C:\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 387, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "C:\Python37-32\lib\http\client.py", line 1244, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "C:\Python37-32\lib\http\client.py", line 1290, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "C:\Python37-32\lib\http\client.py", line 1239, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "C:\Python37-32\lib\http\client.py", line 1026, in _send_output
    self.send(msg)
  File "C:\Python37-32\lib\http\client.py", line 966, in send
    self.connect()
  File "C:\Python37-32\lib\site-packages\urllib3\connection.py", line 184, in connect
    conn = self._new_conn()
  File "C:\Python37-32\lib\site-packages\urllib3\connection.py", line 169, in _new_conn
    self, "Failed to establish a new connection: %s" % e
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x039969D0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python37-32\lib\site-packages\requests\adapters.py", line 449, in send
    timeout=timeout
  File "C:\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 720, in urlopen
    method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
  File "C:\Python37-32\lib\site-packages\urllib3\util\retry.py", line 436, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='finace.yahoo.com', port=80): Max retries exceeded with url: /quote/TSLA (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x039969D0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\lucas\CS\Final_Project\Stock_Index_Scraper.py", line 27, in <module>
    main()
  File "C:\Users\lucas\CS\Final_Project\Stock_Index_Scraper.py", line 17, in main
    data = scraper(site)
  File "C:\Users\lucas\CS\Final_Project\Stock_Index_Scraper.py", line 8, in scraper
    response = requests.get(link, verify=False)
  File "C:\Python37-32\lib\site-packages\requests\api.py", line 75, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Python37-32\lib\site-packages\requests\api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Python37-32\lib\site-packages\requests\sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Python37-32\lib\site-packages\requests\sessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File "C:\Python37-32\lib\site-packages\requests\adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='finace.yahoo.com', port=80): Max retries exceeded with url: /quote/TSLA (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x039969D0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

Process finished with exit code 1

A: The url address that you are calling contains a typo
http://finace.yahoo.com/quote/ -> http://finaNce.yahoo.com/quote/
As a rule of thumb, whenever your scraper behaves in an unexpected way, it is always recommended to run the scenario in a browser and/or curl command line to debug any connection/javascript issues.


text:
Q: Polynomial remainder when divisor has double roots How to find the remainder of the division of $P(x) = x^{444} + x^{111} + x - 1$ by $Q(x) = (x^2 + 1)^2$?
By the little Bézout's theorem, we can write
$$P(x) = (x^2 + 1)^2 W(x) + ax^3+bx^2+cx+d.$$
In fact, I've found out that, since $(x^2 + 1)$ divides $P(x)$, we can write:
$$P(x) = (x^2 + 1)^2 W(x) + cx^3+dx^2+cx+d.$$
Next, I'd usually plug the roots of $(x^2 + 1)^2$, which are $\{-i,i\}$, into the preceding expression, to get a system of equations that would allow me to find the unknowns $a,b,c,d$ (or just $c,d$ in this case). But as each root has multiplicity 2, I end up with an indeterminate system. What am I missing?

A: We have
\begin{eqnarray}
P(x)&=&(x^2+1)^2W(x)+ax^3+bx^2+cx+d\\
P'(x)&=&4x(x^2+1)W(x)+(x^2+1)^2W'(x)+3ax^2+2bx+c
\end{eqnarray}
and
$$
P(i)=i^{444}+i^{111}+i-1=(i^4)^{111}+i^{108}i^3+i-1=1-i+i-1=0
$$
It follows that
$$
0=P(i)=ai^3+bi^2+ci+d=-ai-b+ci+d=(d-b)+(c-a)i
$$
Therefore
$$
a=c,\quad b=d
$$
Also
$$
P'(x)=444x^{443}-111x^{110}-1
$$
therefore
$$
P'(i)=444i^{443}-111i^{110}-1=444i^{440}i^3-111i^{108}i^2-1=110-444i
$$
Substituting $c=a$, we get
$$
110-444i=P'(i)=3ai^2+2bi+c=c-3a+2bi=-2a+2bi
$$
it follows that
$$
a-bi=-55+222i
$$
Therefore
$$
a=c=-55,\quad b=d=-222.
$$
Hence the remainder is
$$
R(x)=-55x^3-222x^2-55x-222=-(55x+222)(x^2+1).
$$


text:
Q: Exception in Nested StreamWriter and StreamReader I have 2 pieces of code.
Take a look at this one.
static void Main(string[] args)
    {
        using (FileStream fs = new FileStream("temp.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            using (StreamWriter writer = new StreamWriter(fs))
            {
                writer.WriteLine("Hello World");
                using (StreamReader reader = new StreamReader(fs))
                {
                    Console.WriteLine(reader.ReadToEnd());
                } // Line-1
            } //Line-2 -> System.ObjectDisposedException: 'Cannot access a closed  file.'
        }
    }

At the Line-2 I get System.ObjectDisposedException occurs.
Why do I get this exception here?
After a little bit of thinking I thought that the exception occurred at Line-2 because the Stream associated with reference 'fs' is already closed at Line-1. And at Line-2 it is trying to close the same stream again. And this answer made sense. Hence, I thought I had found the right answer to my question but then I tried something a little bit different.
Now look at this piece of code.
static void Main(string[] args)
    {
        using (FileStream fs = new FileStream("temp.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            using (StreamReader reader = new StreamReader(fs))
            {
                Console.WriteLine(reader.ReadToEnd());
                using (StreamWriter writer = new StreamWriter(fs))
                {
                    writer.WriteLine("Hello World");
                } // Line-1
            } // Line-2 -> No Exception occurred.
        }
    }

In this piece of code I didn't get any exception. Even though I am doing the same thing again. Here also the stream associated with reference 'fs' is already closed at Line-1 and it is also trying to close the stream at Line-2.
So why didn't I get any exception here?
My question is different from this Is there any way to close a StreamWriter without closing its BaseStream? because I am trying to do the same thing with the second code and despite the fact (in second code) that using statement already closed the base stream (fs) in Line-1. I still don't get any exception in Line-2.
Since @mjwills and @evk said the exception occurred because of flushing the contents of the stream after the file had been closed.
I tried this.
static void Main(string[] args)
    {
        using (FileStream fs = new FileStream("temp.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            using (StreamWriter writer = new StreamWriter(fs))
            {
                writer.WriteLine("Hello World");
                writer.Flush(); // Flushed the contents explicitly.
                using (StreamReader reader = new StreamReader(fs))
                {
                    Console.WriteLine(reader.ReadToEnd());
                } // Line-1
            } // Line-2 -> System.ObjectDisposedException: 'Cannot access a closed  file.'
        }
    }

And the result is same I still have that exception even though I have explicitly flushed the contents. Please help.

A: StreamWriter's Dispose method flushes to disk.
StreamReader's Dispose method does not (why would it? it is just a reader...).
As such, it is "kind of" safe to dispose the writer then the reader (in the sense that it works), but not vice versa.
Consider using leaveOpen on your StreamWriter and StreamReader to avoid this class of problem. By using leaveOpen, you are then able to manually Dispose the Stream which means you can be 100% confident the code will work - and not have to concern yourself with flushing behaviour etc etc.


text:
Q: Window focus for a faster loading pop-up I am very new to JavaScript. Kindly note that I am trying below issue in a shell which overrides many JavaScript functions.
I have an issue with focusing a window: on a single "click" action, I navigate to a new page which has two JavaScript methods which launch two external URLs which I don't own. For example I launch Yahoo.com and Google.com. My JS launches Yahoo.com in current window (as a page navigate) and Google.com as a pop-up. I WANT Google.com WINDOW TO BE FOCUSED irrespective of loading time of either URLs. The major issue is I cannot use the setTimeout JS function as this function's behavior is altered within the shell and is not usable.
Note: I am using a custom reusable JS function to launch external URLs and I just pass values to that method. So I don't even have access to window object. If I can somehow achieve a time delay without using setTimeout, it will be ideal case. If not, I will have to override that custom JS function, get access to the window object. Even if I have control over those window objects for external URLs, since loading times are different, setting focus to the Google window object is not always giving me the focus on Google window.
(IE6 & 7)

A: You cannot guarantee the behavior you want, in general; browsers will not let you.
Safari generally ignores requests to focus windows. Firefox and I think Chrome can be configured by their users (not by your code) to allow focus requests, but by default they won't.


text:
Q: Перебрать массив объектов с ключами Есть массив Users, который состоит из n объектов.
let users = [
{
    idu: 'btI3E8AHH0ct80V5nwvVBfXnCDh2', name: 'Илья', score: 10
},
{
    idu: 'btI3E8AHH0ct80V5nwvVBfXnCDh2', name: 'Илья', score: 15
},
{
    idu: '45gtGXaFghNc3x3n7WFFd5etSfS2', name: 'Петя', score: 6
},
{
    idu: '45gtGXaFghNc3x3n7WFFd5etSfS2', name: Петя, score: 2
}
]

Необходимо сложить score у каждого отдельного юзера.
Ожидаемый результат - массив с объектами
{
    idu: 'btI3E8AHH0ct80V5nwvVBfXnCDh2', name: 'Илья', score: 25
},
{
    idu: '45gtGXaFghNc3x3n7WFFd5etSfS2', name: 'Петя', score: 8
}

Подскажите пожалуйста, как это сделать?

A: Когда вам нужно объединить массив объектов на основании какого-то ключа, удобнее всего использовать временный объект со значениями этого ключа, а потом просто превратить его в массив его значений. Например, так:

let users = [
  {
      idu: 'btI3E8AHH0ct80V5nwvVBfXnCDh2', name: 'Илья', score: 10
  },
  {
      idu: 'btI3E8AHH0ct80V5nwvVBfXnCDh2', name: 'Илья', score: 15
  },
  {
      idu: '45gtGXaFghNc3x3n7WFFd5etSfS2', name: 'Петя', score: 6
  },
  {
      idu: '45gtGXaFghNc3x3n7WFFd5etSfS2', name: 'Петя', score: 2
  }
];

const usersSum = Object.values(users.reduce(
  (acc, { idu, name, score }) => {
    acc[idu] ??= { idu, name, score: 0 };
    acc[idu].score += score;
    return acc;
  },
  {},
));

console.log(usersSum);

Или чуть более развёрнуто:

let users = [
  {
      idu: 'btI3E8AHH0ct80V5nwvVBfXnCDh2', name: 'Илья', score: 10
  },
  {
      idu: 'btI3E8AHH0ct80V5nwvVBfXnCDh2', name: 'Илья', score: 15
  },
  {
      idu: '45gtGXaFghNc3x3n7WFFd5etSfS2', name: 'Петя', score: 6
  },
  {
      idu: '45gtGXaFghNc3x3n7WFFd5etSfS2', name: 'Петя', score: 2
  }
];

const temp = {};

for (const user of users) {
  if (!temp[user.idu]) temp[user.idu] = { idu: user.idu, name: user.name, score: 0 };
  temp[user.idu].score += user.score;
}

const usersSum = Object.values(temp);

console.log(usersSum);


text:
Q: ASP.Net Core 2.2 or 3.1 SPA with React and Docker I am trying two days already to containerize ASP.NET Core 2.2, but without any luck, I have read most than 20 articles about it, and I am not sure if it is even possible. It leads me to an error page stating that it cannot find npm and to check if it exists and is added to PATH.
I tried adding this
RUN apt-get install --yes curl
RUN curl --silent --location https://deb.nodesource.com/setup_10.x | bash -
RUN apt-get install --yes nodejs

to the dockerfile, also added **/node_modules to the .dockerignore file as I read in the articles but without luck
Read that someone has succeeded on .NET Core 2.1, but I haven't tried it because it won't work for me. Can someone please share if it is possible with dot net core 2.2 or above, I can settle for 2.2, 3.0, 3.1.

A: I finally managed to do it.
the trick was to use another image (node:13-alpine) to do the npm install and to add a condition in the .cproj file for the publish part.
It is explained better in this article:
Link


text:
Q: Xcode IDE 6.3.2 slowdown and Crashes when programming in Swift in Playgrounds Xcode slowdown and Crashes
I am currently learning Swift using the playground in Xcode, but every few minutes I get a multi-colored progress bar which renders Xcode unusable. I then have to restart Xcode which causes me to lose unsaved data. It's really terrible and causing me a lot of stress. Any suggestions or tips to solve this?

A: You might want to reinstall your Xcode, but if that does not fix any the problem, it might be the error in the log then, I'm assuming that your code is causing the crash, not Xcode. Can you paste the code from the playground it's crashing on.


text:
Q: Add routes/special messages to akka router In my application I have to send subscription messages to actors, which may or may not be routers. If they are routers, the messages have to be send to all routees. Broadcast is not applicable here, because the actors may not be routers and I don't want to handle Broadcast messages inside of the actors receive block. I also don't want to create a custom router, because the router can be of any type. So what I would like to do is something like this:
system.actorOf(Props[MyActor].withRouter(FromConfig().withRoute { routeeProvider => {
  case (sender, Subscribe) => routeeProvider.routees.map(Destination(sender, _))
}}))

Is there some way to do this, or any other way to add special routing behaviour like this?

A: You can define a parent abstract class for all your actors where you can handle all special messages needed and inherit all your non-router actors from it. Something like this:
abstract class MyActor extends Actor {

  protected def receiveMsg: Receive // will substitute "receive" in your actors

  def receive = receiveMsg orElse {

    case Broadcast(msg) => self ! msg

    ...

  }

}

A: Just create a normal actor, have routees/actors dial-in and/or created as children and forward inbound messages as you like.

A: You can use a BroadcastRouter for your routers. Unlike other routers which only broadcast if the message is a broadcast message this router will broadcast every message to its children.


text:
Q: Is Modus Tollens just an implied Modus Ponens on the Contrapositive? In propositional logic, you must explicitly state each transformation even when they are obvious, like resolving double negatives.
Insufficient
1 P -> Q   Hypothesis
2 --P      Hypothesis
∴ Q        Modus Ponens 1,2 # <- this implicitly relies on --P == P

Sufficient
1 P -> Q  Hypothesis
2 --P     Hypothesis
3 P       Double Negation 2 # <- explicitly resolve the double negation before using it
∴ Q       Modus Ponens 1,3

However, it seems like we might be allowing an implicit step in the case of Modus Tollens. Modus Tollens can be seen as simply Modus Ponens applied on the contrapositive.
Standard Modus Tollens
1 P -> Q   Hypothesis
2 -Q       Hypothesis
∴ -P       Modus Tollens 1,2

But is this not implicitly relying on the fact that P -> Q == -Q -> -P in the same way that the double negative example implicitly relied on the fact that --P == P? We can express the argument purely in terms of Modus Ponens by explicitly stating the contrapositive.
1 P -> Q   Hypothesis
2 -Q -> -P Contrapositive 1
3 -Q       Hypothesis
∴ -P       Modus Ponens 2,3

Is this more explicit? Is Modus Tollens simply a derivation of Modus Ponens and Contrapositive, or do they merely happen to correspond? (identity-vs-value equality distinction). Does Modus Ponens have a more fundamental ontological status, or are they equally derivable in terms of each other?

A: It is good to recognize the close connections that different inference patterns have to each other as it deepens one's understanding of logical concepts and principles. However, I would discourage you from seeing certain rules as 'just an applied application' of some other rule.
Yes, Modus Ponens and Modus Tollens are closely related, but they are also each their own distinct pattern. And why would I see Modus Tollens as just an implied Modus Ponens, if I can regard Modus Ponens as just an implied Modus Tollens?  Or maybe I should regard both rules as just implied versions of Disjunction Syllogism:
Modus Ponens is just implied Disjunctive Syllogism:
$1. P \to Q \text{ given}$
$2. P \text{ given}$
$3. \neg P \lor Q \text{ Implication } 1$
$4. \neg \neg P \text{ Double Negation } 2$
$5. Q \text{ Disjunctive Syllogism } 3,4$
Modus Tollens is just implied Disjunctive Syllogism:
$1. P \to Q \text{ given}$
$2. \neg Q \text{ given}$
$3. \neg P \lor Q \text{ Implication } 1$
$4. \neg P \text{ Disjunctive Syllogism } 2,3$
Or maybe I should regard Disjunctive Syllogism as just implied Modus Ponens?
$1. P \lor Q \text{ given}$
$2. \neg P \text{ given}$
$3. \neg \neg P \lor Q \text{ Double Negation }12$
$4. \neg P \to Q \text{ Implication } 3$
$5. Q \text{ Modus Ponens } 3,4$
The point is: once you go down this road as seeing certain rules as 'just implied' applications of other rules, you find that you can play that game in many, many different ways, and there seems little reason to prefer to do it one way or the other.  So, it's best to just recognize the connections as they exist, and leave it at that.

A: Wikipedia explicitly states that

*

*modus tollens can always be rewritten as modus ponens plus contrapositive (it calls the latter transposition)

*modus ponens can always be rewritten as modus tollens plus contrapositive

Thus if you treat modus ponens and contrapositive as axioms, then modus tollens is a derived rule. We write it in one step for the sake of conciseness, and expanding it would make the proof less explicit and more obscure.
But if you treat modus tollens and contrapositive as axioms, modus ponens is a derived rule. Hence modus ponens and tollens are equally derivable in a pure sense — the reason modus ponens is often listed first is because its implication aligns with the "arrow of time", our natural train of thought.


text:
Q: How to fix Boot layer in initialization in selenium webdriver I'm using selenium webdriver tool for automation testing. In this, I am facing an error whenever I import the safariwebdriver class and Webdriver method. The error sign not resolve.

Error occurred during initialization of boot layer
  java.lang.module.ResolutionException: Modules
  selenium.server.standalone and okio export package
  org.openqa.selenium.safari to module net.bytebuddy

A: Kindly insert external jar of selenium from here, as its not detected by eclipse as shown in screenshot
OR
If those jars are already present,
This happens when you have added the external jars in the ModulePath.
Solution:

*

*Remove the external jars from the node "Modulepath".

*Select the node "Classpath" then add the external jars.

*Review that all the jars are under the node "Classpath".


text:
Q: Standalone MySQL instance I would like to use a standalone MySQL instance specifically for one of my programs.
I am thinking about a situation, where my program spawns the MySQL server as a child process to perform a very specific task and shuts the instance down afterwards. Ideally all files needed to run MySQL, including database files, are within the installation directory of my program.
My questions are:

*

*Is this possible?

*What are files needed to run such an instance?

*Do I need a custom my.ini or can I control everything via parameters?

*How do I do initial setup steps, like setting the root password, programatically?

A: You should look at the embedded mysql server library.  It allows you to run a mysql server inside a client application:
http://dev.mysql.com/doc/refman/5.1/en/libmysqld.html
But why not use something more suited to this sort of task like SQLite (http://www.sqlite.org/)


text:
Q: How do I calculate the percentage of a value in a column based on constraints on it , in sql? I was wondering how to calculate the percentage of a certain value based on constraints on it
For instance, let's say I have a hypothetical table called Cats. I insert the following values into it:
Create table Cats (Cat_ID int, Cat_name varchar(max), Cat_Hometown varchar(max), Gender varchar(max), Birth_Year int);

INSERT INTO Cats (Cat_ID, Cat_Name, Cat_Hometown, Gender, Birth_year)
VALUES (1, 'Blue','Boston','M', 1980),
(2, 'Steamer','Plymouth','F', 1999),
(3, 'Stack','Newton','F', 1980),
(4, 'Overflow','Boston','M', 1978),
(5, 'CatorDog','Allston','F', 1999);

What if I want to determine the percentage of the female cats that were born in the leading hometown of the year 1980? I can't seem to figure it out.
By leading hometown I mean the most common hometown.

A: Assuming leading hometown means the most number of rows in the table for a given year, you can order by the count and get the most common one. Then use conditional aggregation to get the percentage. AVG(gender='F') uses the fact that MySQL treats conditions as booleans returning 1 for True and 0 for False.
select AVG(gender='F')
from cats
where birth_year=1980  and
cat_hometown in (select cat_hometown
                 from cats
                 where birth_year=1980
                 group by cat_hometown
                 order by count(*) desc
                 limit 1)

A: You need to figure out the most common home town.  That is a bit challenging, but a subquery helps.  So:
select avg(c.Gender = 'Female' and c.Birth_Year = 1980 and c.Cat_Hometown = ch.Cat_Hometown)
from cats c cross join
     (select c2.Cat_Hometown
      from cats c2
      group by c2.Cat_Hometown
      order by count(*) desc
      limit 1
     ) ch;


text:
Q: How to install and load dplyr without errors? I am currently practicing R programming through swirl package. And I am stuck at the installation steps in one of the courses with the following error.
| This lesson requires the 'dplyr' package. Would you like me to install it for
| you now?

1: Yes
2: No

Selection: 1

| Trying to install package 'dplyr' now...
package 'dplyr' successfully unpacked and MD5 sums checked

| Could not install package 'dplyr'!

  |
  |                                                                      |   0%Error in seq.default(0, 1, length.out = nrow(e$les)) :
  argument 'length.out' must be of length 1

| Leaving swirl now. Type swirl() to resume.

Even if I try to install it manually and it succeeds I am unable to load it because of following error.
> library(dplyr)
Error: package or namespace load failed for 'dplyr' in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]):
 namespace 'rlang' 0.4.5 is already loaded, but >= 0.4.6 is required

I have tried to remove, reinstall and update the packages. Nothing seems to work. Please Help

A: Either
install.packages("dplyr", dependencies = TRUE)

Or go back and first do
install.pacakges("rlang")

and then install dplyr.
Welcome to Package Hell.  Here is your banjo.  Last night I had to install packages 4 levels deep before I could get all of tidyverse to load.  It's tedious but do-able.
https://www.google.com/search?source=univ&tbm=isch&q=welcome+to+hell.+here%27s+your+banjo&client=firefox-b-1-e&sa=X&ved=2ahUKEwi2wMPGosnpAhWSIDQIHX7JBC0QsAR6BAgIEAE&biw=1600&bih=805#imgrc=mlE1KJg7CKY-5M

A: My suggestion is uninstalling the Package
remove.packages("dplyr")

then re-installing the entire package
install.packages("dplyr", dependencies = TRUE)

Also check out pacman package
The package includes tools for conveniently controlling R add-on packages.
[https://www.geeksforgeeks.org/pacman-package-in-r/][1]
p_load(ggplot2, dplyr, stringr)

it might save you some lines of code

A: Try the following steps:

*

*If you are running RStudio close it;

*open a command window or terminal window and run

R -q -e "install.packages('dplyr', dependencies = TRUE)"


text:
Q: Power Symbol Does Not Shown Correctly The Problem occurs when I open my laptop that is plugged in. My battery does now shown as charging but it actually is. And If I plug out and again plug in, It works normally.
Why can it be happened and how to solve it


text:
Q: When new strings to be translated will be available on Launchpad for the next release? Does anybody know when new strings to be translated will be available on Launchpad? If I try to open the translation page for this new version, I receive this notification:

Translations for this release series are not available yet.

However in the past translations were available in advance.

A: Ubuntu release schedule, hasn't reach the User Interface Freeze. It's counter productive allow people to translate stuff that latter on will get modified.
Remember that most of the strings are already translated from the previous release (less than two months ago, at December 9) so only the new strings that gets added (which can change) and the changed strings (from upstream) will get translated.

The user interface must be stabilized at some point, so that documentation writers and translators can work on a fixed target that doesn't obsolete screenshots or documentation.
After the user interface freeze (UIF), the following things must not change any more without approval of the release team and notification (usually via email, with a link to the mail in your exception bug) to the documentation and translation teams.


text:
Q: Can someone explain a part a small piece of Django code? I was following this tutorial and trying to implement a profile updating tool. One piece of code they provided was as follows:
@login_required
@transaction.atomic
def update_profile(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, instance=request.user.profile)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request, _('Your profile was successfully updated!'))
            return redirect('settings:profile')
        else:
            messages.error(request, _('Please correct the error below.'))
    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)
    return render(request, 'profiles/profile.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })

I managed to work out what all of meant apart from the line
return redirect('settings:profile')

After changing the variables, I get the error :

NoReverseMatch at /profile/
'settings' is not a registered namespace

Do I need to create something else? Any help would be appreciated.

A: Redirect required your view name or some  url
Call like:-
redirect('profile')
profile define view name in your url file.
url like:-
path('profile', profileView, name='profile'),