text:
Q: Is something wrong with my backpropagation calculation? For the last 3 days, I have been trying to build my first neural network to no avail. I'm asking this question here because I can't think of anywhere else to get quality feedback and I haven't found any solutions by searching so far.
The network takes in 784 inputs (pixels) and has 9 outputs (numbers 0-9), I am trying to train it on the mnist hand written digit dataset.
The problem is that after several iterations, the output explodes to a list of random +1s and -1s eg.
[-1., 1., 1., 1., -1., -1., 1., 1., 1.]
I will include code snippets of the ANNs init(), f_pass() and backpropagate() as I think if there is an error, it will likely be in the code containing the matrices. I can upload more code on request if needed.
 class Feedforward:

    def __init__(self, size_vector):

        self.nLayers = len(size_vector)
        self.size_vector = size_vector
        weight_matrix = lambda x: np.random.random((x[0],x[1]))
        self.weights = {}
        self.b = {}
        self.z = {}
        self.a = {}

        for i in range(0,self.nLayers,1):
            z = size_vector[i:i+2]
            try:
                self.b[i] = np.random.random((1,size_vector[i+1]))
            except IndexError:
                pass
            if len(z) == 2:
                self.weights[i] = weight_matrix(z)

f_pass():
def f_pass(self, data):
        for layer in range(self.nLayers-1):
            if layer == 0:
                self.z[layer] = data.dot(self.weights[0])+self.b[layer].reshape((1,self.size_vector[layer+1]))
                self.a[layer] = self.activation(self.z[layer]).reshape((1,self.size_vector[layer+1]))
            else:
                self.z[layer] = self.a[layer-1].dot(self.weights[layer])+self.b[layer]
                self.a[layer] = self.activation(self.z[layer]).reshape((1,self.size_vector[layer+1]))

Backprop():
def backporpagate(self, data):
        lr = .01
        expected, inputs = data
        cost = np.square(expected-self.a[self.nLayers-2])
        partial_layer_error = {}
        partial_weight_error = {}
        partial_bias_error = {}
        for i in range(self.nLayers-1):
            layer = self.nLayers-2-i
            if i == 0:
                partial_layer_error[layer] = 2*(expected-self.a[self.nLayers-2])*self.activation_prime(self.z[layer]).reshape(1,self.size_vector[layer+1])
                partial_weight_error[layer] = self.a[layer-1].transpose().dot(partial_layer_error[layer])
                partial_bias_error[layer] = partial_layer_error[layer].reshape(1,self.size_vector[layer+1])
            elif layer == 0:
                partial_layer_error[layer] = partial_layer_error[layer+1].dot(self.weights[layer+1].transpose())
                partial_weight_error[layer] = inputs.transpose().dot(partial_layer_error[layer])
                partial_bias_error[layer] = partial_layer_error[layer].reshape(1,self.size_vector[layer+1])
            else:
                partial_layer_error[layer] = self.weights[layer+1].transpose().dot(partial_layer_error[layer+1])*self.activation_prime(self.z[layer])
                partial_weight_error[layer] = self.a[layer-1].transpose().dot(partial_layer_error[layer])
                partial_bias_error[layer] = partial_layer_error[layer].reshape(1,self.size_vector[layer+1])

        for i in range(len(self.size_vector)-1):
            self.weights[i] -= lr*partial_weight_error[i]
            self.b[i] -= lr*partial_bias_error[i]
        print(self.a[len(self.size_vector)-2])
        print(expected)

The full code if anyone would like to view it is:
import numpy as np
import random
import pandas as pd
import scipy

class Feedforward:

    def __init__(self, size_vector):

        self.nLayers = len(size_vector)
        self.size_vector = size_vector
        weight_matrix = lambda x: np.random.random((x[0],x[1]))
        self.weights = {}
        self.b = {}
        self.z = {}
        self.a = {}

        for i in range(0,self.nLayers,1):
            z = size_vector[i:i+2]
            try:
                self.b[i] = np.random.random((1,size_vector[i+1]))
            except IndexError:
                pass
            if len(z) == 2:
                self.weights[i] = weight_matrix(z)

    def activation(self, matrix):
        #print(matrix)
        matrix = np.clip( matrix, -300, 300 )
        return (np.exp(2*matrix)-1)/(np.exp(2*matrix)+1)

    def activation_prime(self, matrix):
        return 1/(1-np.square(matrix))

    def f_pass(self, data):
        for layer in range(self.nLayers-1):
            if layer == 0:
                self.z[layer] = data.dot(self.weights[0])+self.b[layer].reshape((1,self.size_vector[layer+1]))
                self.a[layer] = self.activation(self.z[layer]).reshape((1,self.size_vector[layer+1]))
            else:
                self.z[layer] = self.a[layer-1].dot(self.weights[layer])+self.b[layer]
                self.a[layer] = self.activation(self.z[layer]).reshape((1,self.size_vector[layer+1]))

    def backporpagate(self, data):
        lr = .01
        expected, inputs = data
        cost = np.square(expected-self.a[self.nLayers-2])
        partial_layer_error = {}
        partial_weight_error = {}
        partial_bias_error = {}
        for i in range(self.nLayers-1):
            layer = self.nLayers-2-i
            if i == 0:
                partial_layer_error[layer] = 2*(expected-self.a[self.nLayers-2])*self.activation_prime(self.z[layer]).reshape(1,self.size_vector[layer+1])
                partial_weight_error[layer] = self.a[layer-1].transpose().dot(partial_layer_error[layer])
                partial_bias_error[layer] = partial_layer_error[layer].reshape(1,self.size_vector[layer+1])
            elif layer == 0:
                partial_layer_error[layer] = partial_layer_error[layer+1].dot(self.weights[layer+1].transpose())
                partial_weight_error[layer] = inputs.transpose().dot(partial_layer_error[layer])
                partial_bias_error[layer] = partial_layer_error[layer].reshape(1,self.size_vector[layer+1])
            else:
                partial_layer_error[layer] = self.weights[layer+1].transpose().dot(partial_layer_error[layer+1])*self.activation_prime(self.z[layer])
                partial_weight_error[layer] = self.a[layer-1].transpose().dot(partial_layer_error[layer])
                partial_bias_error[layer] = partial_layer_error[layer].reshape(1,self.size_vector[layer+1])

        for i in range(len(self.size_vector)-1):
            self.weights[i] -= lr*partial_weight_error[i]
            self.b[i] -= lr*partial_bias_error[i]
        print(self.a[len(self.size_vector)-2])
        print(expected)

    def train(self, data):
        batch = data.sample(2000)
        pairs = [batch.iloc[:,0],batch.iloc[:,1]]
        avg_I = np.zeros(9)
        avg_O = np.zeros(784)
        for index, (label, img) in batch.iterrows():
            label = np.array(label)
            img = np.array(img)[:,np.newaxis].transpose()/255
            self.f_pass(img)
            self.backporpagate((label, img))

def prepare_mnist():
    print('preparing MNIST: please wait' + '\n')
    with open('mnist_test.csv') as f:
        data = f.readlines()
    mnist = []
    print('Reading Data: \n')
    for i in data:
        key = []
        for j in range(9):
            if j == int(i[0])-1:
                key.append(1)
            else:
                key.append(0)

        value = i[1:]
        value = value.replace('\n','')
        value = value.split(',')
        value.pop(0)
        value = [int(x) for x in value]
        mnist.append((key,value))
    print("Converting to DataFrame \n")
    df = pd.DataFrame(mnist)
    return df

N = Feedforward([784,50,9])
N.train(prepare_mnist())

If anyone could help me out, I would really appreciate it. This has bothered me for days, and I really want to get to grips with building these things practically.


text:
Q: How do I insert hidden field (Javascript) into XML via JSP codes? I am trying to insert data from the Javascript hidden fields into an XML but however, only 'null' come out. I have declared the variables but it seems that it cannot capture the hidden field. I am at my wits end and I hope that my problem can be solved.
**<<-----I use session to pass the value to the XML page----->>**

<%
String X = (String)session.getAttribute("X");
    String Y = (String)session.getAttribute("Y");
    String W = (String)session.getAttribute("W");
    String H = (String)session.getAttribute("H");
session.setAttribute("X",X);
session.setAttribute("Y",Y);
session.setAttribute("W",W);
session.setAttribute("H",H);
%>

**<<------Snippet of Javascript codes------->>**

function moveIt(){

if (!moveEnabled||!MovableItem) return;

// display info during testing

X = MovableItem.offsetLeft;

Y = MovableItem.offsetTop;

W = MovableItem.offsetWidth;

H = MovableItem.offsetHeight;

 ==Some codes here==

  document.getElementById('X').value = X;
  document.getElementById('Y').value = Y;
  document.getElementById('W').value = W;
  document.getElementById('H').value = H;

}
**<<-----JSP codes that I need to pass the values onto an XML----->>**

 <form name='form1' action='UpdateXML.jsp' method='post'>

<input type='hidden' name=source value="<%=src%>" />
<input type='hidden' id="X" name="X" value="<%=X%>"/>
<input type='hidden' id="Y" name="Y" value="<%=Y%>"/>
<input type='hidden' id="W" name="W" value="<%=W%>"/>
<input type='hidden' id="H" name="H" value="<%=H%>"/>

<button type="button" onclick="window.location.href='editcompany.jsp'">Back!</button>
<button type="submit">Insert Into XML!</button>
</form>

I need to insert the hidden field(data) into an XML. I tried but it comes out as 'null'. Is there anyone that can help me solve this problem? Thanks a bunch!

A: Is the first file UpdateXML.jsp? If so, shouldn't there be request.getParameter()?
And it seems 4 lines of session.setAttribute() below do nothing useful:
<%
String X = (String)session.getAttribute("X");
String Y = (String)session.getAttribute("Y");
String W = (String)session.getAttribute("W");
String H = (String)session.getAttribute("H");
session.setAttribute("X",X);
session.setAttribute("Y",Y);
session.setAttribute("W",W);
session.setAttribute("H",H);
%>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Disable ANSI characters in put_time output I'm using the following code to get machine local timezone:
time_t t = time(nullptr);
tm* local = localtime(&t);
std::ostringstream ss;
//ss.imbue(std::locale("C")); -> tried this, and also with ".UTF8"
ss << std::put_time(local, "%Z");
std::string timezone = ss.str();

On some locales I'm getting output with ANSI characters, such as for German machine the output timezone is: Mitteleuropäische Zeit
I don't find a way to disable ANSI characters in the output. I want to either get UTF-8 output (cross platform) or disable the ANSI characters and get something like Mitteleuropsche Zeit. I tried the imbue above (with either C or UTF8 locale), but same output.


text:
Q: Definition of degree of invertible sheaf? In Hartshorne's, he states that #$C\cap D=deg_C(\mathcal{F}(D)\otimes\mathcal{O}_C)$, where $deg_C$ denotes the degree of the invertible sheaf $\mathcal{F}(D)\otimes\mathcal{O}_C$.
I couldn't find any explicit definition about degree of sheaf in the book, but there are some implications. Since divisor $D$ and the corresponding invertible sheaf $\mathcal{F}(D)$ is one to one. So the degree of an invertible sheaf means the degree of the corresponding divisor. Is that right?

A: Yes that's correct; alternatively you can define the degree of any coherent sheaf $\mathcal F$ as
$$\deg\mathcal F=\chi(C,\mathcal F)-(\operatorname{rank}\mathcal F)\,\chi(C,\mathcal O_C)$$
and notice that this is the same as what you're describing in the case that $\mathcal F$ is an invertible sheaf by using Riemann-Roch.


text:
Q: String Injection in Twitter's inputfield with Chrome extension I am trying to build a Chrome extension that generates texts on Twitter. I am struggling with injecting the text in the inputfield.
Here is how I do it:

*

*If the user has already input some content, it works great

*If the user has not already input content, I have to slightly change the HTML (remove the default <br> and add a <span>)

However, on the second use case, it just doesn't work. The placeholder stays visible and the inputfied is broken.
See it in action:
=> https://www.loom.com/share/4bac993ba2cd4ee4a38fc209e751e323
(images if you don't want to check the video)

Am I missing something?
Is there some kind of JS variable on change in addition to changes in the HTML?
Thanks


text:
Q: If $f$ is monotone on $[a,b]$, is $f'$ bounded a.e. on $[a,b]$? All the counterexamples I can develop for $f'$ being unbounded when $f$ is monotone only fail at one point. So I am wondering if it can only happen at a few points so that $f'$ is still bounded almost everywhere.

A: Of course $f'$ must be in $L^1$ because $\int_a^b f'(t)\; dt \le f(b) - f(a)$.
But $f'$ can be unbounded on every interval.  You can get this by taking the
sum of a suitable series of translated and scaled "ramp" functions.

A: If I understand your question, you can take some asymptotic function like $\sqrt{\cdot}$ and scale and shift it.  E.g. a scaling/shifting of:$$
    f(x) := \begin{cases}
-\sqrt{-x} & \text{if } x<0\\
\sqrt{x} & \text{if } x \ge 0\\
\end{cases}
$$Within a ball around $x=0$, $f'$ exists and is unbounded.  Furthermore, this is indeed a monotonically increasing function.
A flip-side example is a constant function (making $f'$ bounded).  Therefore I do not believe monotonicity on $[a,b]$ implies anything about the boundedness of $f'$.
The issue touched on in the comments applies: the extreme value theorem for $f'$ does not directly apply here, but a similar idea holds: if you require $f'$ to be unbounded on a closed interval $[a,b]$, then it must be undefined somewhere (you can consider a convergent sequence $\{x_i\in[a,b]\}_{i=0}^{\infty}\rightarrow x_c$ whose $f'$ values $\{f'(x_i)\}_{i=0}^{\infty}$ increase without bound; then $x_c$ must be contained in $[a,b]$ by definition of closed set).


text:
Q: Using localStorage to save Google Maps and driving directions I am trying to utilize localStorage with Google Maps to save the start, end, and driving directions to local storage so user input is retained after closing the active browser window. I'm pretty sure I can add functions here:
function calculateAndDisplayRoute(directionsService, directionsRenderer) {
  var start = document.getElementById("start").value;
  var end = document.getElementById("end").value;
  directionsService.route(
    {
      origin: start,
      destination: end,
      travelMode: "DRIVING",
    },
    function (response, status) {
      if (status === "OK") {
        directionsRenderer.setDirections(response);
      } else {
        window.alert("Directions request failed due to " + status);
      }
    }
  );
}

I have nested this function in the above function:
function showData() {
  localStorage.setItem("startData", JSON.stringify(start));
  localStorage.setItem("endData", JSON.stringify(end));

  var sData = localStorage.getItem("startData");
  var eData = localStorage.getItem("endData");

  var sObject = JSON.parse(sData);
  var eObject = JSON.parse(eData);
}

I am not seeing any JavaScript errors, and using the developer tools I can see the items being written into local storage.  However, when I reload or close the tab the user choices reset even though the local storage values are written.
How can I make the user choices persist when the application is refreshed?

A: Thanks everyone. I figured it out.  I was able to get what I needed with this loop:
if (
    first &&
    localStorage.getItem("startData") &&
    localStorage.getItem("endData")
  ) {
    start = localStorage.getItem("startData");
    end = localStorage.getItem("endData");
  } else {
    start = document.getElementById("start").value;
    end = document.getElementById("end").value;
  }


text:
Q: Importing Keras raises TypeError I'm doing a school project, and decided to work on an idea of using a django website to display a chatbot's response. The website should also allow users to add an intent for the chatbot to learn from. After working on the website, I tried importing Keras to begin writing the training file.
import random
import json
import pickle
import numpy as np

import nltk
from nltk.stem import WordNetLemmatizer

from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
from keras.optimizers import SGD

# Rest of the code isn't necessary as error is raised above

However, when I ran the file, it keeps giving me the following error:
Traceback (most recent call last):
  File "D:\User\SILPythonChatbot\SILProject\BotApp\training.py", line 9, in <module>
    from keras.models import Sequential
  File "D:\User\SILPythonChatbot\venv\lib\site-packages\keras\__init__.py", line 21, in <module>
    from keras import models
  File "D:\User\SILPythonChatbot\venv\lib\site-packages\keras\models\__init__.py", line 18, in <module>
    from keras.engine.functional import Functional
  File "D:\User\SILPythonChatbot\venv\lib\site-packages\keras\engine\functional.py", line 24, in <module>
    import tensorflow.compat.v2 as tf
  File "D:\User\SILPythonChatbot\venv\lib\site-packages\tensorflow\__init__.py", line 37, in <module>
    from tensorflow.python.tools import module_util as _module_util
  File "D:\User\SILPythonChatbot\venv\lib\site-packages\tensorflow\python\__init__.py", line 42, in <module>
    from tensorflow.python import data
  File "D:\User\SILPythonChatbot\venv\lib\site-packages\tensorflow\python\data\__init__.py", line 21, in <module>
    from tensorflow.python.data import experimental
  File "D:\User\SILPythonChatbot\venv\lib\site-packages\tensorflow\python\data\experimental\__init__.py", line 96, in <module>
    from tensorflow.python.data.experimental import service
  File "D:\User\SILPythonChatbot\venv\lib\site-packages\tensorflow\python\data\experimental\service\__init__.py", line 419, in <module>
    from tensorflow.python.data.experimental.ops.data_service_ops import distribute
  File "D:\UserSILPythonChatbot\venv\lib\site-packages\tensorflow\python\data\experimental\ops\data_service_ops.py", line 22, in <module>
    from tensorflow.python.data.experimental.ops import compression_ops
  File "D:\User\SILPythonChatbot\venv\lib\site-packages\tensorflow\python\data\experimental\ops\compression_ops.py", line 16, in <module>
    from tensorflow.python.data.util import structure
  File "D:\User\SILPythonChatbot\venv\lib\site-packages\tensorflow\python\data\util\structure.py", line 22, in <module>
    from tensorflow.python.data.util import nest
  File "D:\User\SILPythonChatbot\venv\lib\site-packages\tensorflow\python\data\util\nest.py", line 34, in <module>
    from tensorflow.python.framework import sparse_tensor as _sparse_tensor
  File "D:\User\SILPythonChatbot\venv\lib\site-packages\tensorflow\python\framework\sparse_tensor.py", line 24, in <module>
    from tensorflow.python.framework import constant_op
  File "D:\User\SILPythonChatbot\venv\lib\site-packages\tensorflow\python\framework\constant_op.py", line 25, in <module>
    from tensorflow.python.eager import execute
  File "D:\User\SILPythonChatbot\venv\lib\site-packages\tensorflow\python\eager\execute.py", line 22, in <module>
    from tensorflow.python.framework import ops
  File "D:\User\SILPythonChatbot\venv\lib\site-packages\tensorflow\python\framework\ops.py", line 49, in <module>
    from tensorflow.python.framework import cpp_shape_inference_pb2
  File "D:\User\SILPythonChatbot\venv\lib\site-packages\tensorflow\python\framework\cpp_shape_inference_pb2.py", line 203, in <module>
    'HandleShapeAndType' : _reflection.GeneratedProtocolMessageType('HandleShapeAndType', (_message.Message,), {
TypeError: 'DTypeMeta' object is not iterable

I tried reinstalling. However, that failed as well.
Does anybody know why this happens, or how to fix it? Thanks.


text:
Q: Calling a method on browser close I want to call a server method on browser close, is their a way, I have tried
window.onbeforeunload
but this gets call even when I refresh the page, I want to call it only when browser is closed is their a work around.

A: As far as I know, you can't differentiate between those events. Refreshing, loading another page or closing the browser is exactly the same (all the content is destroyed).


text:
Q: How to replace value in middle of varchar2 column in oracle I have a varchar2 column with value as - '20210103 20110109' which I want to change 2011 as 2022 that looks like '20210103 20220109'

A: The way you put it, it is just a simple replace:
SQL> select replace('20210103 20110109', '2011', '2022') result from dual;

RESULT
-----------------
20210103 20220109

SQL>

Could be more complicated if there were other 2011 substrings involved (but that's not what you said).

A: If you want to display different data then, if you only want to change the single value then you can use:
CASE column_name
WHEN '20210103 20110109'
THEN '20210103 20220109'
ELSE column_name
END

If you want to display all 2011 values in that substring as 2022 then you can use:
CASE
WHEN SUBSTR(column_name, 10, 4) = '2011'
THEN SUBSTR(column_name, 1, 9) || '2022' || SUBSTR(column_name, 14)
ELSE column_name
END

For example, given the sample data:
CREATE TABLE table_name (column_name) AS
SELECT '20210103 20110109' FROM DUAL UNION ALL
SELECT '20210103 20120109' FROM DUAL UNION ALL
SELECT '20210103 20130109' FROM DUAL UNION ALL
SELECT '20210103 20140109' FROM DUAL UNION ALL
SELECT '20212011 20112011' FROM DUAL;

Then:
SELECT column_name,
       CASE column_name
       WHEN '20210103 20110109'
       THEN '20210103 20220109'
       ELSE column_name
       END AS replacement1,
       CASE
       WHEN SUBSTR(column_name, 10, 4) = '2011'
       THEN SUBSTR(column_name, 1, 9) || '2022' || SUBSTR(column_name, 14)
       ELSE column_name
       END AS replacement2
FROM   table_name

Outputs:

COLUMN_NAME
REPLACEMENT1
REPLACEMENT2

20210103 20110109
20210103 20220109
20210103 20220109

20210103 20120109
20210103 20120109
20210103 20120109

20210103 20130109
20210103 20130109
20210103 20130109

20210103 20140109
20210103 20140109
20210103 20140109

20212011 20112011
20212011 20112011
20212011 20222011

If you just want to UPDATE a single value:
UPDATE table_name
SET    column_name = '20210103 20220109'
WHERE  column_name = '20210103 20110109'

or, if you want to change all substrings between the 10th and 13th characters from 2011 to 2022:
UPDATE table_name
SET    column_name = SUBSTR(column_name, 1, 9) || '2022' || SUBSTR(column_name, 14)
WHERE  SUBSTR(column_name, 10, 4) = '2011'

db<>fiddle here


text:
Q: Getting 'ORA-00907: missing right parenthesis' when I copy code from Oracle SQL Dev into Tableau even though there are no parentheses in the code As stated in the title, I'm getting an error when I copy the below code into Tableau - 'ORA-00907: missing right parenthesis'. Extremely weird since there are no parentheses at all in my code, which is simply pulling out a subset of columns and rows from a large table. The code works fine in Oracle SQL Developer... any ideas?
SELECT f.gl_date_revenue, f.gl_date_cogs, f.bill_to_customer_id, f.ship_to_customer_id, f.inventory_item_id, f.sob_currency_code, f.sob_extended_amount, f.usd_extended_amount, f.units, f.country_name, f.territory
FROM my_schema.my_table f
WHERE f.territory = 'Nordic';

A: Debug your code:

*

*Remove anything unnecessary.
In this case, you can remove the table alias and the trailing semi-colon:
SELECT gl_date_revenue, gl_date_cogs, bill_to_customer_id, ship_to_customer_id, inventory_item_id, sob_currency_code, sob_extended_amount, usd_extended_amount, units, country_name, territory
FROM my_schema.my_table
WHERE territory = 'Nordic'

*Remove necessary code until your code works.

*

*Remove the WHERE clause, does it work?

*Remove columns until it works.

*Put columns back one-by-one until you find the column that breaks it.

*Read the tableau documentation to see if that column name has any special meaning.


text:
Q: Postgresql: Execute query write results to csv file - datatype money gets broken into two columns because of comma After running Execute query write results to file - the columns in my output file for datatype money get broken into two columns. e.g if my revenue is $500 it is displayed correctly. But, if my revenue is $1,500.00 - there is an issue. It gets broken into two columns $1 and $500.00
Can you please help me getting my results in a csv file in a single column for datatype money?

A: What is this command "execute query write results to file"? Do you mean COPY? If so, have a look at the FORCE QUOTE option http://www.postgresql.org/docs/current/static/sql-copy.html
Eg.
COPY yourtable to '/some/path/and/file.csv' CSV HEADER FORCE QUOTE *;
Note: if the application that is consuming the csv files still fails because of the comma, you can change the delimiter from "," to whatever works for you (eg. "|").
Additionally, if you do not want CSV, but you do want TSV, you can omit the CSV HEADER keywords and the results will output in tab-separated format.

A: Comma is the list separator of our computer for some regions, some region semicolon is the list separator. so I think you need to replace the comma when you write it to csv.


text:
Q: How to combine callback-based library with asyncio library in Python? I have the following issue. I want to read out keystrokes with the pynput library and send them over websockets. Pynput proposes the following usage
from pynput import keyboard

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False

# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

# ...or, in a non-blocking fashion:
listener = keyboard.Listener(
    on_press=on_press,
    on_release=on_release)
listener.start()

(taken from https://pynput.readthedocs.io/en/latest/keyboard.html)
In contrast to that, the websocket-client library is called as follows:
import asyncio
import websockets

async def hello():
    uri = "ws://localhost:8765"
    async with websockets.connect(uri) as websocket:
        name = input("What's your name? ")

        await websocket.send(name)
        print(f"> {name}")

        greeting = await websocket.recv()
        print(f"< {greeting}")

asyncio.get_event_loop().run_until_complete(hello())

(taken from https://websockets.readthedocs.io/en/stable/intro.html).
I am now struggling how this can be done as the websocket library is asynchronous and pynput is synchronous. I somehow have to inject a "websocket.send()" into on_press/on_release - but currently I am struggling with this.

A: Note that your pynput example contains two different variants of using pynput, from which you need to choose the latter because it is easier to connect to asyncio. The keyboard listener will allow the program to proceed with the asyncio event loop, while invoking the callbacks from a separate thread. Inside the callback functions you can use call_soon_threadsafe to communicate the key-presses to asyncio, e.g. using a queue. For example (untested):
def transmit_keys():
    # Start a keyboard listener that transmits keypresses into an
    # asyncio queue, and immediately return the queue to the caller.
    queue = asyncio.Queue()
    loop = asyncio.get_event_loop()
    def on_press(key):
        # this callback is invoked from another thread, so we can't
        # just queue.put_nowait(key.char), we have to go through
        # call_soon_threadsafe
        loop.call_soon_threadsafe(queue.put_nowait, key.char)
    pynput.keyboard.Listener(on_press=on_press).start()
    return queue

async def main():
    key_queue = transmit_keys()
    async with websockets.connect("ws://localhost:8765") as websocket:
        while True:
            key = await key_queue.get()
            await websocket.send(f"key pressed: {key}")

asyncio.run(main())


text:
Q: Deleting duplicate equations from a list of equations Here is a list of algebraicly identical equations, and I like to delete all the duplicate equations from this list and get only two equations. I tried the following:
Clear[ss];
listEqs = {
   x + y == x^2 + z,
   y + z == x^2 + z,
   x + y == z + x^2,
   y + z == z + x^2,
   x^2 + z == x + y,
   z + x^2 == x + y,
   x^2 + z == y + z,
   z + x^2 == y + x
   };

DeleteDuplicates[listEqs]

I got:
{
 x + y == x^2 + z,
 y + z == x^2 + z,
 x^2 + z == x + y,
 x^2 + z == y + z
}

Can someone tell me how to reduce the list to only two equations?
EDIT 1
I noticed a misunderstanding of my question. Here is a second list:
listEqs = {
   y + z == x^2 + z,
   a + b == k + g,
   x + y == x^2 + z,
   b + a == g + k,
   x + y == z + x^2,
   a + b == g + k,
   y + z == z + x^2,
   x^2 + z == x + y,
   z + x^2 == x + y,
   x^2 + z == y + z,
   z + x^2 == y + x};

The code:
DeleteDuplicatesBy[listEqs, MemberQ@Level[listEqs, -1]]

picks the first element of the list, which is not what I asked. I want the following list to be the output of the code:
{
y + z == x^2 + z,
a + b == k + g,
x + y == x^2 + z
}

Basically, I just want to pick the non-identical equations from the list. The desired equations can be placed in the middle, end or beginning of the list. The position of the equations are not the issue.

A: Maybe
DeleteDuplicatesBy[listEqs, Reduce] (* or *)
DeleteDuplicatesBy[listEqs, Sort]

{x + y == x^2 + z, y + z == x^2 + z}

For the longer input list:
DeleteDuplicatesBy[listEqs2, Reduce]

{y + z == x^2 + z, a + b == g + k, x + y == x^2 + z}


text:
Q: Looking for alternative to Google Reader sync for RSS app I'm in the early stages of designing an RSS app, and I'd like to include syncing to an online RSS feed service as a feature. Most such apps make use of Google Reader's feed/syncing features, but Google is now moving sync out of its Reader service, and also its API remains undocumented. Are there any alternatives to Google Reader that offer online syncing of feeds with a desktop client, and which have a documented API?

A: There should be an answer to this question, but I don't think there is.
I think we got lazy. Maybe it's time to roll up our sleeves and get to work.

A: What about Newsblur?
http://www.newsblur.com/
Don't know anything about them, but they appear to have a reasonable facsimile of a product in this vein.
Here are their API docs.  http://www.newsblur.com/api
They are a subscription service, but you can have up to 64 feeds for free.

A: A couple suggestions, the original web RSS Reader BlogLines is still around, though now under new management since MerchantCircle purchased the service late last year.
The APIs maybe still functional:
Or they may be deprecated/turned off, haven't tried the APIs myself.
If BlogLines API is no longer around a better bet is LiveDoor Reader (along with it's open sourced version is called FastLadder).
Livedoor Reader is a Japanese service, but FastLadder pages and documentation are available in english and Japanese.
Downloadable Open sourced versions for running on your own machines be they windows, Mac OSX, or Linux from here
There's also a FastLadder Google source Code page.
There are RSS apps for both IOS and Android that sync with LiveDoor Reader/FastLadder instances. Just search for LDR in their respective app stores.

A: I don't think there's a ready answer yet, but I think Brent Simmons has a rough spec of what could be a start:
http://inessential.com/2010/02/08/idea_for_alternative_rss_syncing_system
Basically, imagine a server that manages feed subscription lists and captures annotations for feed items. Those annotations for items would be things like (un)read, starred, shared, saved, deleted, or whatever else an app might want to attach to a feed item. It should stay simple and not fetch or process feeds themselves - other apps and libraries do that fine already.

A: Feedlooks looks close too with no ties to Google Reader - not sure about the API, though
http://www.feedlooks.com/
Years back, I'd used a self hosted Open Source app called Gregarious - It appears to have gone missing recently.
Here's the Gregarious Archive from 2010
http://web.archive.org/web/20100925221312/http://gregarius.net/
Another contender for the do-it-yourselfer might be utilizing SimplePie.org


text:
Q: Update api in apim using az apim api In my azure devops pipeline i have a task AzureCLI@2 that deploys an api to apim. How can i use the same task using the az apim api to update the api? I know that there is an operation to do this but the documentantion don't show how to and i didn't find any example. I'm using an open api file generated in the pipeline to create and i would like to use it to update the api either.

A: Just use az apim api import again. It will replace existing API with new one, preserving policies for operations with the same template. --path and --api-id parameters must be the same as existing API. Provide url/path to the swagger/openapi and correct specification format. Example:
az apim api import --path "/myapi" --api-id "myapiid" --resource-group "test-rg" --service-name "test-apim" --specification-url "https://petstore.swagger.io/v2/swagger.json" --specification-format Swagger
If you want to add revision instead of updating existing one, add additional --api-revision parameter
az apim api update is suited for updating single properties or fields like description, api type etc.

A: You can create an API in APIM using this method and delete it using this method.

A: Please use the below script to create/update API in APIM using az cli.
I am assuming
A. Your api definition is in Open API definition file. B. You are identifying apim endpoints using path ($apiPrefix).
$apiPrefix="my-path"
$rgName="RG_NAME"
$apimS="APIM_SVC_NAME"
$apiDefinitionLocalPath="PATH_TO_APIM_DEFINITION_JSON"
$allAPIs= az apim api list --resource-group $rgName --service-name $apimS
$allAPIsJson= $allAPIs | ConvertFrom-Json
$apiWithMatchingPath=$allAPIsJson | Where-Object {$_.path -eq $apiPrefix }
if($apiWithMatchingPath){
    #it only requires the ID. using $apiWithMatchingPath.id will return the
    #fully qualified ID... which is not required.
    az apim api import --api-id $apiWithMatchingPath.name --resource-group `
    $rgName --service-name $apimS --path $apiPrefix --api-type http --protocols`
     https --specification-format OpenApi --specification-path `
    $apiDefinitionLocalPath
    }else{
      #IMPORT definition w/o name
      az apim api import --resource-group $rgName --service-name $apimS --path `
      $apiPrefix --api-type http --protocols https --specification-format `
      OpenApi --specification-path $apiDefinitionLocalPath
 }

A: In the azure devops pipeline, we can set the AzureCLI task like this:

We need to go to the azure portal and find our api ID, and then update the api info. Here is my test result:


text:
Q: how the area is exactly zero? I was reading this PDF which tries to explain the concept of poles and zeros of Laplace transform.
My question is about FIGURE 32-5(b) on page #591.

I don't understand why the area is said to be zero when, as shown, it should clearly be some negative number. The mentioned PDF does try to give an answer which I don't understand.

Figure (b) shows one of the special cases we have been looking for.
When this waveform is multiplied by the impulse response, the
resulting integral has a value of zero. This occurs because the area
above the x-axis (from the delta function) is exactly equal to the
area below (from the rectified sinusoid). The values for σ and ω that
produce this type of cancellation are called a zero of the system. As
shown in the s-plane diagram of Fig. 32-4, zeros are indicated by
small circles.

You can consider it to be a follow-on question to this comment where @AJN tried to explain it further but unfortunately I still couldn't get it. I thought it'd be better to ask it separately. I'd appreciate if you could help me with it?

A: The dirac-delta function has an area of 1 when integrated. The red area and the delta function have the same area. When integrated from t = (0-) to t -> inf the total area is 0.


text:
Q: Why can std::function get assigned to std::function but not std::function? In this code snippet, I don't understand why there is an error below:
#include <functional>

class Foo {};

int main()
{
    std::function<void(Foo)> func;

    std::function<void(Foo)> f1;
    std::function<void(Foo const&)> f2;
    std::function<void(Foo&)> f3;

    func = f1;
    func = f2;
    func = f3;  // error: no match for 'operator=' (operand types are 'std::function<void(Foo)>' and 'std::function<void(Foo&)>')

    return 0;
}

So, I'm wondering why is it OK to use a function taking the parameter by constant reference, but not as a non-constant reference?
Can somebody kindly explain it to me?
Thanks in advance!

A: Neither f1 nor f2 can modify their argument, f3 however can. Allowing a function that was bound to f3 to be called through f1 or f2 would either break const-correctness or allow to change a temporary and thus break semantical correctness.
How the implementation guarantees that these are not broken is secondary. The behaviour you describe must not work.

A: std::function uses std::forward to pass parameters from its operator() to its underlying callable.  That is, an abbreviated version of std::function looks something like this:
template <typename Ret, typename... Args>
class function
{
public:
    Ret operator()(Args... args)
    {
        return get_callable()(std::forward<Args>(args)...);
    }

    // Other stuff
};

That means that any parameters that are non-reference types will be passed to the underlying callable as rvalues.  References to non-const cannot bind to rvalues, and so a std::function<void(Foo)> is incompatible with std::function<void(Foo&)>, but it is compatible with both std::function<void(Foo const&)> and std::function<void(Foo&&)>.


text:
Q: How to write all DateTime fields as ISO 8601 strings? I'm writing CSV out of IEnumerable<dynamic> objects. I do not know how many DateTime fields these objects can have, nor its names.
Is there a way to tell CsvWriter to write all DateTime objects as ISO 8601 strings?
var records = new List<dynamic>();

dynamic record = new ExpandoObject();
record.Timestamp = DateTime.UtcNow;
records.Add(record);

using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.WriteRecords(records);
    writer.ToString().Dump(); // I want the DateTime to be in ISO 8601 format (2020-05-01T15:29:19Z)
}

https://dotnetfiddle.net/1ng5W9

A: You can use TypeConverterOptions and apply the options to DateTime.
using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    var options = new TypeConverterOptions { Formats = new [] {"s"} };
    //apply options to datetime
    csv.Configuration.TypeConverterOptionsCache.AddOptions<DateTime>(options);

    csv.WriteRecords(records);
    writer.ToString().Dump();
}

// output
// 2020-05-01T16:02:36

This uses "s" (sortable datetime format).
You could apply any format you like, for example: Formats = new [] { "yyyy-MM-ddTHH:mm:ss" } will give similar result.
See updated demo.


text:
Q: Начало изучения веб-программирования Здравствуйте!
Хочу начать изучать веб-программирование. Пожалуйста, посоветуйте книги по:

*

*HTML

*CSS

*Dreamweaver

*PHP

которые по вашему мнению наиболее будут полезны при изучении. Чтобы были понятны для новичка и в то же время актуальны. =)
Заранее огромное спасибо тем, кто откликнется! =)
A: Хороший сайт тебе в помощь http://htmlbook.ru. И про html, и про css.

A: Ну по CSS однозначно Э. Бадд. По HTML Матросов, Сергеев, Чаунин. По PHP Будилов. Сам не про, но книги у меня есть, все понятно.
Для изучения ООП Энди Гутман"Профессиональное программирование на PHP"
A: Я начинал таким образом: прочитал книгу Влада Мержевича, обзавелся его справочниками для того, чтобы нужная инфа была под рукой. За небольшой период времени обрел необходимую базу, и начал учиться самостоятельно - лучше этого метода не придумаешь. Имея стартовые знания, найдите простой сайт, разберите его по винтикам, вникни в структуру. Без подсказок соберите сами. Потом двигайтесь по нарастающей. Практика - лучший способ понять язык, а не тупо заучить его структуру.
A: Я когда-то начинал учить веб-программирование и была у меня книга "HTML, JAVASCRIPT, PHP и MYSQL. Джентельменский набор web-матера", автор Н.Прохоренок. Очень помогла. Хорошо изложен материал, с нее начинать учить хорошо.
Скачать можно например здесь.
A: Книги нужны по мере необходимости, какие - сами потом подберете. Поставьте себе задачу:
сделать сайт со своим дизайном, в нем должно присутствовать комментирование ваших статей другими пользователям.
Итак: дизайн и верстка (тут вы выстрадаете и изучите HTML и CSS). Потом прикрутите свой шаблон с помощью Smarty (это такой шаблонизатор). Ну, и далее к шаблону с помощью PHP прикрутите форму регистрации, админку (для добавления своих статей из текстового файла) и собственно функцию комментирования ваших статей. И весь контент сайта храните в MySQL, тем самым начнете изучать создание и запросы в БД.
С помощью чего все это делать? Я бы рекомендовал текстовый редактор, без дримвиверов и другого. Для новичка главное - набить руку в коде, запомнить, что писать и зачем, код все равно будет короткий и маленький.
A: По js: Дэвид Флэнаган - JavaScript. Подробное руководство.
По php: Котеров,Костарев - PHP 5.2ed.2009 ; PHP. Объекты, шаблоны и методики программирования; http://php.su,   http://php.net
По html: http://htmlbook.ru
A: я пользуюсь двумя книгами если, это- веб-мастеринг(Пётр Ташков), и (X)HTML-скрипты и стили (В. Дунаев)
В веб-мастеринг есть всё для начинающего и html, css, javascript +Apache
в (X)HTML - я смотрю как создавать сайты на основе блоков div
A: Все сводится к знанию html ибо по сути все прочие языки его генерируют и управляют его элементами. То есть для начала изучи HTML и CSS - т. е. вёрстку. А дальше когда научишся сам верстать будешь уже генерировать его с помощью серверных языков (PHP, ASP и т.п.)
Позже пойдет высший пилотаж DOM, JavaScript,JQuery и т.д.
Правильно говорят: сначала поставь себе маленькую задачу (типа странички о себе: текст разный, ссылки на сайты и другие страницы, картинки). По своему опыту книги нужны разные. В одних проще написано, в других бывает то чего нет в остальных. Все собирай и смотри.
Dreamweaver - скорее для удобства верстки, но не для изучения. На него можно обратить внимание когда освоишь HTML.


text:
Q: How to uninstall package using puppet I have installed mysql in a client node using Puppet. Now I want to uninstall it in the client node. I tried the following configuration in site.pp:
  package { '::mysql::server':
    ensure => 'purged'
  }

This did not work. Can someone show me how to uninstall mysql (or any package for that matter)?

A: That syntax is wrong. ::mysql::server is either referencing a puppet class or defined type. You only need to specify the package name to the package type.
 package { 'mysql_package_name':
   ensure => absent
 }

Replacing mysql_package_name with the name of the package for the distro you are using.


text:
Q: create a textarea dynamically with javascript I want create textarea with javascript when I click on the "yes" radio button in a appropriate div place with id?

<input type="radio" name="name" id="optionsRadios" value="no" checked>NO
<input type="radio" name="name" id="optionsRadios" value="yes" >YES

help me

A: Instead of creating & removing the textarea, I would set its display like

function nameChange(el) {
    document.getElementById('positiontext').style.display = el.value == 'yes' ? '' : 'none';
}

    <input type="radio" name="name" id="optionsRadios" value="no" onchange="nameChange(this)" checked />NO
    <input type="radio" name="name" id="optionsRadios" value="yes" onchange="nameChange(this)" />YES

    <textarea name=""></textarea>

A: Try this by  adding the onclick event to the yes radio button,
<input type="radio" name="name" id="optionsRadios" value="yes" onchange="addDIV()">

In javascript,

FIDDLE DEMO

A: i think you should need to do this by using gome function which are specially made for this:

<input type="radio" name="name" id="optionsRadios" value="no"  checked>NO
<input type="radio" name="name" id="optionsRadios" value="yes" onclick="addtxt();" >YES

javascript:
var addtxt = function(){
 var positiontext(parent) = document.getElementById("positiontext");
 var textarea(child) = document.createElement("textarea");
     textarea(child).addAttribute("style", "(some properties)") //there are other ways also to add some attribute but for now use this

positiontext(parent) .appendChild("textarea(child)")
}


text:
Q: How to filter JSON data in angular by using filter I am looking for good book or links to study to filter data from JSON to use in angular filter. Some complex data. Please, could someone help me on this.

A: Instead of filters more concentrate on custom directives, compare to filters it will improve the performance
Thank you,
Chaitanya


text:
Q: how to prove this function is one to one and onto? Let f(x,y)=2x+y where a (x, y) point in the grid plane.
Show that f is one to one. I have tried to solve it. Please, can you help me solve it?

A: For the function to be one-to-one, you would need to show that:
$$f(x,y) = f(a,b) \implies (x,y) = (a,b)$$
But this is false:
$$f(0, 2) = 2 = f(1,0)$$
and clearly
$$(0,2) \not= (1,0)$$

A: Take the number $4a+b$. This can be expressed as $f(2a,b)$ and also $f(a, 2a+b)$ so this function is not one-to-one.


text:
Q: Initialize data with props without making it reactive Is there a way to initialize an object in the data section data with a props object without making it reactive to the prop object itself?
I still want the object in the data section (currentUser) to be reactive to the view.
<template>

         {{ currentUser.name }}

    </template>

props: {
    user: Object,
  },
 data() {
    return {
      currentUser: {
         name: user.name
      }
    };
  },

A: Create local data that the component doesn't modify...
  props: {
    user: Object,
  },
  data: function () {
    return {
      userAsMounted,
    };
  },

Copy the prop at the time you want it to stop being reactive. (For the whole time, at mounted)...
  mounted() {
    Object.assign(this.userAsMounted, this.user)
  },

Refer to the copy...
<template>

    {{ userAsMounted.name }}

</template>

A: You can't disable reactivity, but you can control how/when the data in your component is set.
Specifically, you can use one of the initialization life-cycle hooks to set a data variable with the initial value passed to a prop:
// Will only be run when the component is created.
created() {
  const { user } = this;
  this.currentUser = user;
  // You could also use `this.currentUser = {...user};`
  //  (accomplishes the same thing as Object.assign), but vue won't react
  //  when modifying sub-properties of a reactive object within a component.
},

If the user prop is not set when created is run, you might try conditionally setting it in the updated hook:
updated() {
  const { currentUser, user } = this;
  // Only set current user if it has not yet been set.
  if (!currentUser) {
    this.currentUser = user;
  }
},


text:
Q: Microsoft Access attempting to find table in macro as field I am creating a database for my school which contains data for an event happening later on in the year. They need a query that displays the events and how many people are going. At the same time they want me to display an error if the venue is overbooked.
I attempted to do this via a macro. The macro would open the attendence_rpt report, then run the macro to see whether the venue is overbooked, like so:
'------------------------------------------------------------
' Macro1
'
'------------------------------------------------------------
Function Macro1()
On Error GoTo Macro1_Err

    DoCmd.OpenReport "attendence_rpt", acViewReport, "", "", acNormal
    If (Reports!attendence_rpt!CountOfAttendeeID > Reports!attendence_rpt!venue_tbl!Capacity) Then
        Beep
        MsgBox "test", vbOKOnly, "test"
    End If

Macro1_Exit:
    Exit Function

Macro1_Err:
    MsgBox Error$
    Resume Macro1_Exit

End Function

When I run the macro however, it comes up with this error:
Microsoft Access can't find the field 'venue_tbl' referred to in your expression

This means that the macro is trying to find the linked table 'venue_tbl' as a field.
Is there any way to fix this? Or is there an easier method to achieve the same goal?
Below are some photos of the database in Access:

A: Add a new field to the report that contains venue_tbl!Capacity and make it not visible (unless you want to show the new field to the user). Then change the line in your macro:
If (Reports!attendence_rpt!CountOfAttendeeID > Reports!attendence_rpt!venue_tbl!Capacity) Then

to:
If Reports!attendence_rpt!CountOfAttendeeID > Reports!attendence_rpt!NameOfNewField Then

where NameOfNewField is the name of the field you added.

A: You must not reference the table in the report.
So this is WRONG:
Reports!attendence_rpt!venue_tbl!Capacity

And this is CORRECT:
Reports!attendence_rpt!Capacity


text:
Q: .htaccess referrer rewrite rule for one pretty url I need to ensure that the user login form for Drupal can not be signed into when the referrer is from a remote domain.  It is a security vulnerability which impacts enterprise acceptance.
The path is: https://domain.com/user
There is currently a rule in place at the end of .htaccess to require https access
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

I looked at this to see how the rule might identify the url, but do not know how I would take that and implement it with the referrer and not impact the other rules for https

A: # if referer not empty
RewriteCond %{HTTP_REFERER} !^$
# and referer doesn't contain domain.com
RewriteCond %{HTTP_REFERER} !domain\.com
# and it is a POST request
RewriteCond %{REQUEST_METHOD} POST [NC]
# than redirect to current url to remove the POST data and show the default login screen
RewriteRule ^(user)$ /$1 [R=302,L]


text:
Q: How can I compile and run a C program (with OpenMP) in gem5 Full System? I am an undergraduate student working on my thesis about parallel programming.
I am using OpenMP model. Now i want to use gem5 for measure performance.
That's why i install gem5 Full System successfully by following link:
http://cearial01.kaist.ac.kr/index.php/2016/08/26/gem5-documentation/
Now i want to compile & run a c program with OpenMP (matmul.c) using gem5.
How can i compile & run this program?
I mean inside which folder i stored this program file (matmul.c) for compile?
How i create object file of this program?
How can i change no of processor, cache memory size, no of cpu during running & compilation?
I am new student of this section. That's why my asking list is too big!
Hope anybody don't mind.
Best Regards,
Litu

A:
How can I compile and run this program? I mean inside which folder I stored this program file (matmul.c) for compile? How I create object file of this program?

How to cross compile for an image is not gem5 specific, so I'll be brief.
First you must obtain a cross compiler for the image.
The best way to do that, is to get a cross compiler from the same source as the image to ensure compatibility.
My preferred approach is to use minimal Buildroot images. Buildroot:

*

*builds both the cross compiler and the image for me, and thus ensure compatibility

*makes it easy to automate building new software with its package system

*can produce very simple images, which are more suitable for gem5 and architecture research

This is my setup on GitHub. It contains a minimal OpenMP hello world which I have successfully run inside of gem5.
Another good option is to use https://crosstool-ng.github.io/
Since you want OpenMP support, you must build the GCC cross compiler compiler with support.
I think this is done in GCC with:
./configure --enable-libgomp

or through the Buildroot option:
BR2_GCC_ENABLE_OPENMP=y

And then when compiling, you must pass the -fopenmp option to gcc.

How can I change the number of processors and the cache memory size?

The best way to answer that question yourself is to use something like:
./build/ARM/gem5.opt configs/example/fs.py -h

and search the options.
You come across:

*

*-n NUM_CPUS, --num-cpus=NUM_CPUS.
For ARM you also need to pass a .dtb with the corresponding core count, e.g.: ./system/arm/dt/armv7_gem5_v1_2cpu.dtb for 2 cores.

*caches: you will find the following options easily:
 --caches --l1d_size=1024 --l1i_size=1024 --l2cache --l2_size=1024 --l3_size=1024

But keep in mind that:

*

*the Linux kernel does not see the cache sizes correctly as of fbe63074e3a8128bdbe1a5e8f6509c565a3abbd4
How to switch CPU models in gem5 after restoring a checkpoint and then observe the difference?

*caches only affect certain CPU types, usually the more detailed such as ARM HPI and x86 DerivO3CPU, but not AtomicSimpleCPU.


text:
Q: jstree plugin will not refresh the tree after ajax insertion I tried to use jsTree the first time. I managed to build the tree from json that I got from my server. I can even save my data through an ajax call, but after it I can not make the tree to refresh no matter what I try. If I hit f5 it loads the new children normally.
<script>
    $(document).ready(function(){

        function refresh_tree() {
            $.ajax({
                url: '<?php echo Yii::app()->baseUrl;?>' + '/index.php/category/generateTree',
                success: function(categories) {
                    $('#jstree').jstree({
                        'core' : {
                            'data': jQuery.parseJSON(categories),
                            'multiple' : false
                        }
                    });

                }
            });
        }

        $('#submit_button').click(function(button){
            button.preventDefault();
                $.ajax({
                    url:'<?php echo Yii::app()->baseUrl;?>' + '/index.php/category/add',
                    data:{cat_name: $('#name').val(), cat_desc: $('#description').val(), cat_parent: $('#parent').val()},
                    type:"POST",
                    dataType:"json",
                    success:function(){
                        refresh_tree();
                    }
                })
        })

        refresh_tree();

    });
</script>

I have tried a lot of different refresh functions aswell like:
$.jstree.reference("#jstree").refresh();
$("#jstree").jstree("refresh");
$.jstree._reference('#jstree').jstree.refresh();

I have tried to put these codes after the top ajax call and in the success part of the bottom ajax call, but nothing happens. The first ajax call gets the correct updated json after I add a new element but it wont get displayed no matter what.


text:
Q: Integer Composition Even and Odd Number of Parts Let $n \geq 2$. Show that the number of compositions of $n$ with an even number of parts is equal to the number of compositions of $n$ with an odd number of parts.
I am trying to take the difference with the two generating series but I am kind of stumped.

A: Take an integer $n\ge 2$, and write down $n$ consecutive $1$'s, with a little space between them, like this:
$$1\quad1\quad1\quad1\quad1\quad1\quad1\quad1\quad1\quad1$$
A composition of $n$ into $k$ parts is obtained by choosing $k-1$ of the $n-1$ "gaps" between consecutive $1$'s to insert a separator into.
For example, the composition $10=2+5+3$ is represented by
$$1\quad1\,\ast\,1\quad1\quad1\quad1\quad1\,\ast\,1\quad1\quad1$$
There are $\binom{n-1}{k-1}$ ways to choose $k-1$ gaps. So there are $\binom{n-1}{k-1}$ compositions of $n$ into $k$ parts.
The number of compositions of $n$ into an even number of parts is the sum of all $\binom{n-1}{k-1}$ where $k$ is even, that is, $k-1$ is odd.
The number of compositions of $n$ into an odd number of parts is the sum of all $\binom{n-1}{k-1}$ where $k$ is odd, that is, where $k-1$ is even.
It is a standard theorem that the sum of the binomial coefficients $\binom{m}{i}$ where $i$ ranges over the even integers is the same as the sum where $i$ ranges over the odd integers. There are many proofs. The easiest may be by considering the binomial expansion of $(1+(-1))^m$.


text:
Q: How to delete data from table cache using data factory? I have a data factory pipeline that is taking data from SQL Server and copying it to table storage:
Azure Sql Server View --> Table Storage Cache

This step is doing a REPLACE of the specific row based on a guid from the SQL Server view.
If a record is deleted from the source view, how do we delete that same record from table storage?

A: During the Copy Active, we couldn't do operation to the table data. Data Factory does not support this operation.
I have created a data pipeline to copy data from my SQL Server to the table storage for the test. Before your Copy Active begin, you can delete or insert your record as you want. And you can preview the data in Data Factory. Once the Copy Active is published and finished, it means that your data have been copied to the table storage.
If your really need to delete the same record in Table Storage, one of the ways is that you can login you Azure portal and using the "Storage Explorer(preview)" to delete the record:

Hope this helps.

A: Here is a hint -- some code I have run in production for years... the idea is to have the source use a timestamp (or simpler flag) on deleted records and then to have your MERGE respect it.
CREATE PROCEDURE [DataFactory].[MergeCompany]
(
  @Company [DataFactory].[CompanyType] READONLY
)
AS
BEGIN

  MERGE INTO [Company] AS TGT
  USING @Company As SRC
  ON TGT.pk = SRC.pk
  --
  WHEN MATCHED AND SRC.aud_delete_date IS NOT NULL
  THEN DELETE
  --
  WHEN MATCHED AND SRC.aud_delete_date IS NULL
  THEN UPDATE SET
     TGT.comp_number     = SRC.comp_number
    ,TGT.comp_name       = SRC.comp_name
    ,TGT.aud_update_date = SRC.aud_update_date
    ,TGT.aud_create_date = SRC.aud_create_date
  --
  WHEN NOT MATCHED BY TARGET
  THEN INSERT(
     pk
    ,comp_number
    ,comp_name
    ,aud_update_date
    ,aud_create_date
  )
  VALUES(
     SRC.pk
    ,SRC.comp_number
    ,SRC.comp_name
    ,SRC.aud_update_date
    ,SRC.aud_create_date
  )
  ; -- Required semicolon

END
GO


text:
Q: PExec doesn't exit after execute I'm writing a program with C# , that can create Users on remote Computers.
Actually it's done and working.
But I have one little problem.
In C# I use PowerShell to run a Script which runs then an Pexec, which executes a Batch file on a remote Computer.
C# :
private void executeScripts()
    {
        string _dirPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
        string _sPath = Path.GetDirectoryName(_dirPath) + @"\ExecuteScripts\FileToExecute.ps1";
        string _scriptPath = "& '" + _sPath + "'";

        using (PowerShellProcessInstance pspi = new PowerShellProcessInstance())
        {
            string psfn = pspi.Process.StartInfo.FileName;
            psfn = psfn.ToLowerInvariant().Replace("\\syswow64\\", "\\sysnative\\");
            pspi.Process.StartInfo.FileName = psfn;

            using (Runspace r = RunspaceFactory.CreateOutOfProcessRunspace(null, pspi))
            {
                r.Open();
                using (PowerShell ps = PowerShell.Create())
                {
                    ps.Runspace = r;
                    ps.AddScript(_scriptPath);
                    ps.Invoke();
                }
            }
        }
    }

PS Script :
#
# First there are some Copy-Items to the remote Computer
#

# Execute Above copied Bat File on remote Computer
[string] $IPAddress = "\\" + $XmlFile.ComputerSettings.LastChild.ChildNodes[1].InnerText
$PsTools = "\PsTools"
$PsToolsPath = Join-Path -path $ScriptParent -childpath $PsTools
& $PsToolsPath\PsExec.exe $IPAddress /accepteula -i -s -u $Login -p $LoginPassword Powershell  C:\Path\ToBatFile\Execute.bat > log.txt

Exit

I use this PExec 3 other times in my Program, creating a User, updating a User and removing a User, i just execute different files, scripts or batch files.
And it works perfectly.
But with the Script above, the PExec executes everything but doesn't exit. Neiter does it log something.
I tried it also with the -d switch, but that didn't work either. I also put an exit /b in the batch file but no luck.
When running the script manually from Powershell it works, it executes and it exits, but when running it from my Program it doesn't.
After some waiting my C# returns a timed-out Exception end exits.
Anyone seeing what I'm doing wrong ?

A: Powershell class itself has a method called Stop() which makes it pretty easy to stop this.
If you want to do it asynchronously here is an example of implementation:
using(cancellationToken.Register(() => powershell.Stop())
{
    await Task.Run(() => powershell.Invoke(powershellCommand), cancellationToken);
}


text:
Q: Count Text values, but not repeats To be honest, I don't even know what I am asking, but I think it should be possible. I am trying to count the number of groupings for a certain person given a specific condition (T/F).
For example, Let's assume these are all true
Orange   Alpha
Orange   Alpha
Black    Beta
Black    Beta
Blue     Beta
Blue     Beta
Blue     Beta
Green    Delta
Green    Alpha

I am trying to create a table that will say Beta: 2, Alpha 2, and Delta 1. Then vice versa I need something that will say Orange 1, Black 1, Blue 1, Green 2. Essentially count the number of names within in a color.
Thank you

A: For formula you will need to use Array formulas:
For the Alpha column:
=SUM(IF($B$1:$B$9=D1,1/COUNTIFS($A$1:$A$9,$A$1:$A$9,$B$1:$B$9,D1)))

For the Color column:
=SUM(IF($A$1:$A$9=G1,1/COUNTIFS($B$1:$B$9,$B$1:$B$9,$A$1:$A$9,G1)))

As these are array formulas they need to be confirmed with Ctrl-Shift-Enter on exiting edit mode instead of Enter.  If done properly then Excel will put {} around the formula.


text:
Q: Landscape figures in Classicthesis On Ubuntu 16.04, the pdflscape and lscape package no longer rotate a page correctly when using a vanilla classicthesis package, but instead gives the error Output loop---100 consecutive cycles for each landscape page.
This can be recreated by simply adding the following code to any chapter:
\usepackage{pdflscape}
\begin{landscape}
\begin{figure}
    \includegraphics{test.jpg}
\end{figure}
\end{landscape}

Landscape figures in a plain latex document did seem to work. And replacing the figure by text while in the classicthesis environment does work, so the issue must be related to the combination of the figure environment and the classicthesis environment.  Any ideas on how to resolve this?
Mimimum working example
A MWE can be found below, where the original classicthesis package has been stripped to the packages which could potentially influence the error
\RequirePackage{fix-cm}
\documentclass[ twoside,openright,titlepage,numbers=noenddot,headinclude,%1headlines,% letterpaper a4paper
            footinclude=true,cleardoublepage=empty,abstractoff, % <--- obsolete, remove (todo)
            BCOR=5mm,paper=a4,fontsize=11pt,%11pt,a4paper,%
            ngerman,american,%
            ]{scrreprt}
\PassOptionsToPackage{utf8}{inputenc}
\usepackage{inputenc}
\PassOptionsToPackage{eulerchapternumbers,listings,drafting,pdfspacing,subfig,beramono,eulermath,parts}{classicthesis}
\newcounter{dummy} % necessary for correct hyperlinks (to index, bib, etc.)
\newlength{\abcd} % for ab..z string length calculation
\PassOptionsToPackage{T1}{fontenc} % T2A for cyrillics
\usepackage{fontenc}
\usepackage{textcomp} % fix warning with missing font shapes
\usepackage{scrhack} % fix warnings when using KOMA with listings package
\usepackage{xspace} % to get the spacing after macros right
\usepackage{mparhack} % get marginpar right
\usepackage{caption}
\captionsetup{font=small} % format=hang,
\usepackage{subfig}
\PassOptionsToPackage{pdftex,hyperfootnotes=false,pdfpagelabels}{hyperref}
\usepackage{hyperref}  % backref linktocpage pagebackref
\pdfcompresslevel=9
\pdfadjustspacing=1
\PassOptionsToPackage{pdftex}{graphicx}
\usepackage{graphicx}
\listfiles
\usepackage{classicthesis}
\usepackage{pdflscape}
\begin{document}
\frenchspacing
\raggedbottom
\pagestyle{plain}
Testing
\begin{landscape}
\begin{figure}
    \includegraphics{test.jpg}
\end{figure}
\end{landscape}
Testing
\end{document}

A: It seems that using the float package together with the float specifier H solves this problem.


text:
Q: How to properly hash a pair of pointers? I have a std::unordered_map with keys of type std::pair<T*, T*> (i.e., a pair of pointers).
The code base has the following hash functor defined:
struct pair_hash {
  template<typename T>
  std::size_t operator()(std::pair<T, T> const &p) {
    return (std::hash<T>()(p.first) + 0x9e3779b9) ^ (std::hash<T>()(p.second) + 0x9e3779b9);
  }
};

And is used as:
std::unordered_map<std::pair<T*, T*>, U, pair_hash> myDictionary;

where U is an arbitrary object.
Now the hash functor displayed above must have certain issues because in VC++ it gives me an out of bounds crash in std::unordered_map::find.
Q:

*

*Could it be that my hash functor is problematic or this behaviour is attributed to VC++ itself?

*Is there a "proper/more proper" way to hash a pair of pointers?

A: return (std::hash<T>()(p.first) + 0x9e3779b9) ^ (std::hash<T>()(p.first) + 0x9e3779b9);
//                                                                ^^^^^
//                                                              p.second!
//                                                                         ^^^^^^^^^^
// Choose different magic constant to prevent collisions between (p1, p2) and (p2, p1)

Your function was returning zero for every pair of pointers. Therefore you were getting lots of collisions in the unordered_map.

A: If you can use Boost, there's a very useful hash_combine function that you could use.


text: Q: Executing one main method twice in Eclipse I was following this RabbitMQ tutorial and I was using Eclipse as IDE. In the tutorial, it has been asked to run Worker's main method on two instances of terminals/command prompts. After searching on the Internet I couldn't find a way to execute the same main method twice in Eclipse. Is it possible to run it twice and get output on two different consoles?


text:
Q: downloading images from web in android Ii am trying to download an image from web and dispaly it in an image view.
the problem is that nothing displays on the screen.
I am using the code below.
                      Thank you!
package com.example.citiestoremember;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class DisplayImage extends Activity {
ImageView img;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.image_city);
      Intent theIntent = getIntent();

    String urlImage = theIntent.getStringExtra("urlImage");
          try {
              img = (ImageView) findViewById(R.id.urlImage);
              Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new     URL(urlImage).getContent());
              img.setImageBitmap(bitmap);
            } catch (MalformedURLException e) {
              e.printStackTrace();
            } catch (IOException e) {
              e.printStackTrace();
            }
}

}

A: ImageLoader is not an Universal ImageLoader. Android is providing AQuery for Image Loading.
You will find aQuery jar file from below link:
http://code.google.com/p/android-query/
private AQuery androidAQuery;
androidAQuery = new AQuery(getActivity());
androidAQuery.id(your imageview).image(your image value, true, true,default icon(optional));


text:
Q: ASP.NET Web API - AutoMapper is not ignoring nullable booleans I'm writting web application in ASP.NET Web API and working on method to modify restaurant informations. The core entity is Restaurant that looks like this:
public class Restaurant
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string? Description { get; set; }
    public string Category { get; set; }
    public bool HasDelivery { get; set; }
    public string ContactEmail { get; set; }
    public string ContactNumber { get; set; }

    public int? CreatedById { get; set; }
    public virtual User CreatedBy { get; set; }

    public int AddressId { get; set; }
    public virtual Address Address { get; set; }

    public virtual List<Dish> Dishes { get; set; }
}

What is the most important in here - the HasDelivery property must be not-nullable. It has to take one of true or false value.
Next, I have ModifyRestaurantDto class which is given as a request from body while the app working. Just like the following:
public class ModifyRestaurantDto
{
    [MaxLength(25)]
    public string? Name { get; set; }

    [MaxLength(100)]
    public string? Description { get; set; }
    public bool? HasDelivery { get; set; }
}

To simplify I've just given a few of properties that are allowed to be changed. Note that all of them are nullable types.
I also have a service method called UpdateAsync, as follows:
public async Task UpdateAsync(int id, ModifyRestaurantDto modifyRestaurantDto)
{
    var restaurant = await _dbContext
        .Restaurants
        .FirstOrDefaultAsync(r => r.Id == id)
        ?? throw new NotFoundException("Restaurant not found...");

    var authorizationResult = _authorizationService
        .AuthorizeAsync(
            _userContextService.User,
            restaurant,
            new ResourceOperationRequirement(ResourceOperation.Update))
        .Result;

    if (!authorizationResult.Succeeded)
        throw new ForbidException();

    _mapper.Map(modifyRestaurantDto, restaurant);
    await _dbContext.SaveChangesAsync();
}

What I want to achieve is to change only values which has been given in request body (in ModifyRestaurantDto). E.g. if my json body was looking like this
{
    "name": "Foo"
}

I wouldn't want Description and HasDelivery props to change.
Now, I've created AutoMapper profile and configured it inside Program.cs of course.
public class RestaurantMappingProfile : Profile
{
    public RestaurantMappingProfile()
    {
        CreateMap<ModifyRestaurantDto, Restaurant>()
            .ForAllMembers(opts => opts.Condition((src, dest, value) => value is not null));
    }
}

And while given types are string everything works correctly. The problem is that nullable bool is always converted to false anyways. I'm using .NET 6.0 and have enabled Nullable and ImplicitUsings in .csproj.
Do you have some idea why only nullable booleans are not overlooked by AutoMapper?

A: It seems like a bug to me. A quick fix would be adding mapping from bool? to bool:
CreateMap<bool?, bool>().ConvertUsing((src, dest) => src ?? dest);
CreateMap<ModifyRestaurantDto, Restaurant>()
    .ForAllMembers(opts => opts.Condition((_, _, v) => v is not null));


text:
Q: How to bundle Python for AWS Lambda I have a project I'd like to run on AWS Lambda but it is exceeding the 50MB zipped limit. Right now it is at 128MB zipped and the project folder with the virtual environment sits at 623MB and includes (top users of space):

*

*scipy (~187MB)

*pandas (~108MB)

*numpy (~74.4MB)

*lambda_packages (~71.4MB)

Without the virtualenv the project is <2MB. The requirements.txt is:
click==6.7
cycler==0.10.0
ecdsa==0.13
Flask==0.12.2
Flask-Cors==3.0.3
future==0.16.0
itsdangerous==0.24
Jinja2==2.10
MarkupSafe==1.0
matplotlib==2.1.2
mpmath==1.0.0
numericalunits==1.19
numpy==1.14.0
pandas==0.22.0
pycryptodome==3.4.7
pyparsing==2.2.0
python-dateutil==2.6.1
python-dotenv==0.7.1
python-jose==2.0.2
pytz==2017.3
scipy==1.0.0
six==1.11.0
sympy==1.1.1
Werkzeug==0.14.1
xlrd==1.1.0

I deploy using Zappa, so my understanding of the whole infrastructure is limited. My understanding is that some (very few) of the libraries do not get uploaded so for e.g. numpy, that part does not get uploaded and Amazon's version gets used that is already available in that environment.
I propose the following workflow (without using S3 buckets for slim_handler):

*

*delete all the files that match "test_*.py" in all packages

*manually tree shake scipy as I only use scipy.minimize, by deleting most of it and re-running my tests

*minify all the code and obfuscate using pyminifier

*zappa deploy

Or:

*run compileall to get .pyc files

*delete all *.py files and let zappa upload .pyc files instead

*zappa deploy

I've had issues with slim_handler: true, either my connection drops and the upload fails or some other error occurs and at ~25% of the upload to S3 I get Could not connect to the endpoint URL. For the purposes of this question, I'd like to get the dependencies down to manageable levels.
Nevertheless, over half a gig of dependencies with the main app being less than 2MB has to be some sort of record.
My questions are:

*

*What is the unzipped limit for AWS? Is it 250MB or 500MB?

*Am I on the right track with the above method for reducing package sizes?

*Is it possible to go a step further and use .pyz files?

*Are there any standard utilities out there that help with the above?

*Is there no tree shaking library for python?

A: *

*The limit in AWS is for unpacked 250MB of code (as seen here https://hackernoon.com/exploring-the-aws-lambda-deployment-limits-9a8384b0bec3)

*I would suggest going for second method and compile everything.
I think you should also consider using serverless framework. It does not force you to create virtualenv which is very heavy.

I've seen that all your packages can be compressed up to 83MB (just the packages).
My workaround would be:

*

*use serverless framework (consider moving from flask directly to API Gateway)

*install your packages locally on the same folder using:
pip install -r requirements.txt -t .

*try your method of compiling to .pyc files, and remove others.

*Deploy:
sis deploy

Hope it helps.


text:
Q: Why has no core dump occurred when I use pthread_mutex_lock twice in the same thread? #include <pthread.h>
#include <iostream>

int main()
{
    pthread_mutex_t mtx;
    pthread_mutex_init(&mtx, NULL);
    pthread_mutex_lock(&mtx);
    pthread_mutex_lock(&mtx);
    return 0;
}

I run this code in Centos 7, and I except to have a core dump file, but it didn't, the program just dead in the command line.
I thought pthread mutex is non-recursive mutex by default and there is only one thread in my program, so it should be crush when I lock this mutex twice.

A: You are not guaranteed a core dump when things go wrong.  There are a few errors, like dereferencing a null pointer, which linux chooses to catch and provide a core dump file for you (in the right mode), but there's no guarantees.  Indeed, many logic errors cannot be detected, thus there is no way to identify that a dump is needed.
In the case of locking a mutex twice, this is "undefined behavior," meaning the library provides no guarantees as to what happens.  In the particular case of mutex locking, one could dive into the implementation to learn more of how that specific implementation handles it.
However, in general, its worth noting that there is a reentrant mutex in pthreads, whose sole job is to provide sane behavior if a thread locks the mutex twice.  Given that the pthreads developers felt the need to provide both reentrant and non-reentrant mutexes, this suggests that there's some optimizations that can be done on mutex locking that are only safe if a thread doesn't lock it twice.
In this case, it looks like your library has probably used a locking scheme which is unaware as to which thread did the locking.  Thus, when you lock it a second time, it doesn't realize that that thread already locks it, and calmly waits for the thread to unlock  itself.
A related set of curious behaviors occur if you try to lock a mutex on one thread and unlock it on another (if you need this behavior, use a semaphore instead)


text:
Q: Python datetime to Unix epoch timestamp I am trying to convert pandas datetime object to unix/epoch timestamp. I am getting an error for one particular date in the dataset.
The timestamps I am trying are these:
1) 2019-08-31 21:38:00
2) 2019-01-09 16:26:00
I am using Python's datetime module:
1) datetime.strptime('2019-08-31 21:38:00', '%Y-%m-%d %H:%M:%S').timestamp()
1567280280.0

2) datetime.strptime('2019-01-09 16:26:00', '%Y-%m-%d %H:%M:%S').timestamp()
1547047560.0

Although Object (2) is greater than (1), the epoch timestamps in python shows otherwise.
When I convert the same datetime objects to numerical values in excel, I get:
1) '2019-08-31 21:38:00' -> 43708.901389
2) '2019-01-09 16:26:00' -> 43709.684722
Which is correct. Object (2) > Object (1).
Clearly Date (1) is smaller than Date (2).
Why is it showing the wrong order using python?


text:
Q: get index of item in listbox c# I am trying to get index of each items in a listbox
Here is my code
           foreach (ListItem lstItem in lstCostCenter.Items)
           {
               int x = lstCostCenter.Items.IndexOf(lstItem);

           }

But each time its returning 0 only.
Please some one help me.
Thanks
Gulrej

A: Why not use a for loop?
for (int i = 0; i < lstCostCenter.Items.Count; i++)
{
    ListItem lstItem = lstCostCenter.Items[i];
}

The index of the current item is i.


text:
Q: How can I generate predictions from the randomSurvivalForest package in R? I'm trying to use the randomSurvivalForest package in R to predict the next event in a series of events (using res <- predict(fit,v)), but all I get is a total % survivors and then the cumulative hazard for each individual in the res$ensemble. Can I use this to predict/generate values matching what's in in res$time?

A: As you descibe it with:

next event in a series of events

It seems like you will definately want to look into time series analysis, perhaps an arima class model can provide you with some good results.


text:
Q: Dynamic Lookup for multiple values in a cell (comma separated) and return the corresponding ID to a single cell (comma separated also) The thing is not always the amount of values (IDs) will be the same within each cell (at least 1, max=several) that's why the fixed version of using concatenated vlookup+left/mid/right will not work for me due to that will solution will only work up to 3 values. The only fixed size is the size of the values to lookup (IDs - in green), 8 characters (letters+numbers).
I'm not sure but, is it possible to setup a loop within excel formulas/functions ?
Below is a table containing an example of the issue I'm trying to resolve and the expected values (tables are in different tab). Hope you can help.
Thanks.
example-tables

A: If you have windows Excel O365 with the TEXTJOIN and FILTERXML functions, you can use a formula:
=TEXTJOIN(",",TRUE,IFERROR(XLOOKUP(FILTERXML("<t><s>" & SUBSTITUTE(@[IDs],",","</s><s>") & "</s></t>","//s"),Table2[IDs],Table2[IDv2]),"""--"""))

Note that, in your data, there are two ID's in A4 that do not match any ID's in Table 2.  Although that may be a typo, I left them as is to demonstrate the error handling.
Table1

Table2

A: Here is a UDF that will do what you describe. Paste the code into a standard code module (not one already existing in the workbook but one that you create and that would have a name like Module1 before you change it to what you like best. You can also rename the function to give it a more suitable name.
Function ID_v2(Cell As Range) As String
    ' 035

    Dim Fun         As String           ' function return value
    Dim Sp()        As String           ' array of CSVs of CellVal
    Dim VLRng       As Range            ' the lookup range
    Dim VL          As Variant          ' result of VLookup
    Dim i           As Integer          ' loop counter

    ' this is a range similar to your sample A10:D19
    Set VLRng = ThisWorkbook.Names("Table2").RefersToRange
    Sp = Split(Cell.Cells(1).Value, ",")
    If UBound(Sp) >= 0 Then
        For i = 0 To UBound(Sp)
            On Error Resume Next
            VL = Application.VLookup(Trim(Sp(i)), VLRng, 3, False)
            If Err Then VL = "[ERROR]"
            Fun = Fun & VL & ","
        Next i
        ID_v2 = Left(Fun, Len(Fun) - 1)      ' remove final comma
    End If
End Function

Call the function with syntax like built-in functions. For example,
= ID_v2(A3)

This can be copied down like any other function. But remember to save the workbook as macro-enabled.

A: Try this:
Option Explicit

    Sub Cell2List()
        Dim wF As WorksheetFunction: Set wF = Application.WorksheetFunction 'To user Transpose
        Dim i As Range
        Dim j As Range
        Dim s As String: s = "," 'The separator of the list

        'Ask the user for the cell where are the list with the commas
        'Just need to select the cell
        Set i = Application.InputBox("Select just one cell where the values are", "01. Selecte the values", , , , , , 8)

        'Ask the for the separator. If you are completely sure the comma will never change just delete this line
        s = Application.InputBox("Tell me, what is the character separator, just one character! (optional)", "02. Separator (comma semicolon colon or any other char)", , , , , , 2)
        If s = "" Then s = "," 'Verifying...........

        'Ask the user where want to put the list
        'You need to get ready the cells to receive the list.
        'If there any data will be lost, the macro will overwrite anything in the cells
        Set j = Application.InputBox("Select just one cell where the values will go as a list, just one cell!", "03. Selecte the cell", , , , , , 8)

        Dim myArr: myArr = (Split(i.Value, s)) 'Split the list into a Array

        Range(Cells(j.Row, j.Column), Cells(j.Row + UBound(myArr), j.Column)).Value = wF.Transpose(myArr)
        'j.Row is the row of the cell the user selected to put the cell
        'j.Column the same, but the column
        'j.Row + UBound(myArr) =      UBound(myArr) is the total count of elements in the list
        '                            +j.Row
        '                            _______________
        '                            the last cell of the new list!
        'wF.Transpose(myArr) = we need to "flip" the array... Don't worry, but Don't change it!
    End Sub

You can put this macro with a button tin the ribbons, or use it as you can see in the gif

And this will be the result: (with a bigger list)

EDIT
You can use this UDF:
Function Cells2List(List As Range, Pos As Integer) As String
    Cells2List = Split(List, ",")(Pos - 1)
End Function

Just need to define and index this way:

To tell the function, what index you want to see. You can use the function using ROW()-# to define an 1 at the beginning and when the formula send a #VALUE! delete the formulas. Where $A$1 is where the list are, and D7 is where the index are.


text:
Q: A query to Find average value for each ranges? Here is my table

GID | Distance (KM) | Subdistance (KM) | Iri_avg
-------------------------------------------------
 1  |   13.952      |  0               | 0.34
 2  |   13.957      |  0.005           | 0.22
 3  |   13.962      |  0.010           | 0.33
 4  |   13.967      |  0.015           | 0.12
 5  |   13.972      |  0.020           | 0.35
 ...

I would like to find AVG of Iri_avg for each ranges,
for example..
each 5 metre (by default)
each 10 metre
each 100 metre
each 500 metre
What is the PostgreSQL query to solve this problem ?

A: Your question is unclear.  Your data has two distance columns, which one do you mean?
Here is an example of how to get averages based on the subdistance.
select floor(subdistance*1000)/5.0)*5.0 as lower_bound, avg(iri_avg) as avg_ari_avg
from t
group by floor(subdistance*1000)/5.0)*5.0
order by 1

The expression "floor(subdistance*1000)/5.0)*5.0" gets the closest 5 meter increment less than the value.  You can replace the "5" with "10" or "100" for other binning.
This is meant as an illustration.  It is unclear which column you want to bin, what you want to do about empty bins, and whether you are looking for all bin-widths in a single query versus the query to handle just one bin-width.


text:
Q: c++ Japanese characters command line output I am having problems to print Japanese characters on my command line (osx) with c++.
I would be happy to see any character printed correctly on my command line, but I dont get what my problem is. Nothing is printed, not even a wrong character nor any error occurs. My characters are just swallowed. What am I doing wrong here?
 #include <string>
#include <clocale>
#include<iostream>

int main(int argc, char** args){

    std::setlocale(LC_ALL,"");
    wchar_t c=L'あ';
    std::wcout<<c;

    std::wstring s = L"あ";
    std::wcout<<s;

    return 0;
}

A: You probably don't need the line:
std::setlocale(LC_ALL, "");

That's used for things like date and time formats.
Instead, imbue the output stream with a properly initialized locale object.
std::wcout.imbue(std::locale("ja_jp.utf-8"));


text:
Q: Global maxima for concave functions Let $D$ be a convex set in $\mathbb{R}^n$ and $f: D \to \mathbb{R}$ a concave and $C^1$ function. How do I show that $x^*$ is a global maximum
for $f$ if and only if $f^{(1)}(x^*)y \leq 0$ for all $y$ pointing into $D$ at $x^*$ (Here $f^{(1)}$ denotes the first derivative of $f$)

A: If we had $f^{(1)} (x^*)y > 0$ then by the definition of the derivative we could find a point close by in that direction for which the value $f$ is higher. That shows the only if part.
For the other direction, take any other point $y \in D$. Consider a straight path between the two points $v(t) : [0,1] \to \mathbb{R}^d$, $v(t) = x^* + t(y-x^*)$. $f(v(t))$ is concave and  continuously differentiable with respect to $t$, so must have nonincreasing derivative. Combining this observation with the fact that $f^{(1)} (x^*)y \le 0$ and the fundamental theorem of calculus, we see that $f(y) \le f(x^*)$.


text:
Q: Instagram subscription - Unable to reach callback URL - ONGOING This issue has been posted many times before but I haven't found a solution yet. I've contacted Instagram Developer support but a week later I've still had no luck or a response form them so hoping someone here can help me out. My app has been approved by Instagram for basic permissions.
Doing a Form POST to https://api.instagram.com/v1/subscriptions/ with all the relevant data (callback_url, object=user, aspect=media, verify_token, client_secret, client_id) to create a subscription for Instagram User Subscriptions yields the error: APISubscriptionError - Unable to reach callback URL

*

*The callback URL I'm using has logging on it to log all requests which works
when accessed directly via a browser. Using the logs I can see Instagram isn't even reached my callback URL.

*The callback URL is accessible publicly over the internet and the domain is being used in production.

*The callback URL implements both GET and POST methods (even PUT just in case).

*Worked a few weeks ago using a UAT URL.

*The callback URL still returns the 'Unable to reach callback URL' with http or https.

*I've changed IP addresses, used a VPN and run the post script form different locations.

*Tried different parts eg domain.com/instagram/subscriptions or
domain.com/instagramsubscriptions
-Tried a different sub domain and different URL.

*Have deleted all subscriptions using the DELETE request

Any help or suggestions would be greatly appreciated.


text:
Q: TLS/SSL RABBIT MQ (Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..) TLS/SSL following steps as:
To create the root CA certificate

*

*genrsa -des3 -out CA-key.pem 2048

*req -new -key CA-key.pem -x509 -days 1000 -out CA-cert.pem -subj "/C=US/ST=Oregon/L=Portland/O=user/OU=Org/CN=right.xcl.one"

To create a Signing a Server Certificate:

*

*genrsa -des3 -out server-key.pem 2048

*req –new –config openssl.cnf –key server-key.pem –out signingReq.csr

*x509 -req -days 365 -in signingReq.csr -CA CA-cert.pem -CAkey CA-key.pem -CAcreateserial -out server-cert.pem

Client Certificate :-

*

*pkcs12 -export -out client-cert.p12 -inkey server-key.pem -in server-cert.pem

Server RabbitMQ Config:-
[
{rabbit,  [
   {auth_mechanisms, ['EXTERNAL']},
   {loopback_users, []},
   {ssl_listeners, [5671]},
   {ssl_options, [{cacertfile,"D:/RabbitMQ/certs/CA-cert.pem"},
                 {certfile,"D:/RabbitMQ/certs/server-cert.pem"},
                 {keyfile,"D:/RabbitMQ/certs/server-key.pem"},
                 {verify,verify_peer},
                 {password,  "test"},
                {fail_if_no_peer_cert, false}]
               }
]}
].

In C# Calling from local:-
var hostName = "right.xcl.one";
           var cf = new ConnectionFactory
           {
               HostName = hostName,
               UserName = "user",
               Password = "user",
               VirtualHost = "/",
               AuthMechanisms = new IAuthMechanismFactory[] { new ExternalMechanismFactory() },
               Ssl = new SslOption
               {
                   Enabled = true,
                   ServerName = "right.xcl.one",
                   AcceptablePolicyErrors = SslPolicyErrors.RemoteCertificateNameMismatch |
                                           SslPolicyErrors.RemoteCertificateChainErrors,
                   CertPath = @"D:\client-cert.p12",
                   CertPassphrase = "test",
                }
           };
           using (IConnection conn = cf.CreateConnection())

OpenSSL> s_client -connect malta1597.startdedicated.com:5671 -cert client-cert.pem -key client-key.pem -CAfile CA-cert.pem -verify 8 -verify_hostname malta1597.startdedicated.com\ -state -debug
verify depth is 8
Enter pass phrase for client-key.pem:
CONNECTED(00000144)
SSL_connect:before SSL initialization
write to 0x1924d107020 [0x1924d1267b0] (330 bytes => 330 (0x14A))
0000 - 16 03 01 01 45 01 00 01-41 03 03 f7 84 a2 00 f6   ....E...A.......
0010 - 82 f2 f0 ef 26 79 3d fb-56 dd f9 37 79 fd 19 58   ....&y=.V..7y..X
0020 - 81 c8 a0 bc b3 5f f3 b5-29 a3 73 20 f8 06 9d 28   ....._..).s ...(
0030 - ec eb 1b c8 e6 f8 4f fe-97 1c 74 23 93 8f db ef   ......O...t#....
0040 - 8a ad 18 af 71 96 c2 40-b1 99 9d 92 00 3e 13 02   ....q..@.....>..
0050 - 13 03 13 01 c0 2c c0 30-00 9f cc a9 cc a8 cc aa   .....,.0........
0060 - c0 2b c0 2f 00 9e c0 24-c0 28 00 6b c0 23 c0 27   .+./...$.(.k.#.'
0070 - 00 67 c0 0a c0 14 00 39-c0 09 c0 13 00 33 00 9d   .g.....9.....3..
0080 - 00 9c 00 3d 00 3c 00 35-00 2f 00 ff 01 00 00 ba   ...=.<.5./......
0090 - 00 00 00 21 00 1f 00 00-1c 6d 61 6c 74 61 31 35   ...!.....malta15
00a0 - 39 37 2e 73 74 61 72 74-64 65 64 69 63 61 74 65   97.startdedicate
00b0 - 64 2e 63 6f 6d 00 0b 00-04 03 00 01 02 00 0a 00   d.com...........
00c0 - 0c 00 0a 00 1d 00 17 00-1e 00 19 00 18 00 23 00   ..............#.
00d0 - 00 00 16 00 00 00 17 00-00 00 0d 00 30 00 2e 04   ............0...
00e0 - 03 05 03 06 03 08 07 08-08 08 09 08 0a 08 0b 08   ................
00f0 - 04 08 05 08 06 04 01 05-01 06 01 03 03 02 03 03   ................
0100 - 01 02 01 03 02 02 02 04-02 05 02 06 02 00 2b 00   ..............+.
0110 - 09 08 03 04 03 03 03 02-03 01 00 2d 00 02 01 01   ...........-....
0120 - 00 33 00 26 00 24 00 1d-00 20 d3 71 9e 9a b6 7d   .3.&.$... .q...}
0130 - 1f 40 6c f3 35 dc b0 86-bc 52 c9 7e ba b8 64 0b   .@l.5....R.~..d.
0140 - d7 09 df b9 a5 34 15 f4-0f 1e                     .....4....
SSL_connect:SSLv3/TLS write client hello
read from 0x1924d107020 [0x1924d11d593] (5 bytes => -1 (0xFFFFFFFF))
SSL_connect:error in SSLv3/TLS write client hello
write:errno=10054
no peer certificate available
No client certificate CA names sent
SSL handshake has read 0 bytes and written 330 bytes
Verification: OK
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 0 (ok)
read from 0x1924d107020 [0x1924d0fb0a0] (8192 bytes => -1 (0xFFFFFFFF))
error in s_client
OpenSSL>
Authenticated successfully but the error is now:-
One or more errors occurred. (Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..)
Please help.


text:
Q: What is the better way to string format a double quote if the element inside the quote is a variable? I have made a code like this:
TextWriter tw = File.CreateText(@"D:\output.txt");

tw.Write(@"{""lon"":" + grid.point[0].ToString("###.####") + ",");
tw.Write(@"""latt"":" + grid.point[1].ToString("###.####") + ",");

char c = '"';
////improve the last line pls
tw.Write(@"""color"":" + c.ToString() + "#" + grid.Color.ToString("X").Substring(2) + c.ToString() + "},\n");

With the above code, I had successfully made a JSON format look like below:
{"lon":121,"latt":40.5025,"color":"#3EC1FF"},

Now My question is:
How to improve the string format without using the c.toString()?

A: You can use the format overload of the Write method e.g. Write(String, Object[]).
Something like this:
tw.Write("\"color\":\"#{0}\"}},\n", grid.Color.ToString("X").Substring(2));

A: StringBuilder jsonBuilder=new StringBuilder();
 jsonBuilder.AppendFormat("{0}", "{");

 jsonBuilder.AppendFormat("\"Lat\":{0:0.000},", 584.25689);
 jsonBuilder.AppendFormat("\"Lon\":{0:0.000},", 784.25689);

 jsonBuilder.AppendFormat("Color:{0}","\"#3EC1FF\"");
 jsonBuilder.AppendFormat("{0}", "}");

  string json = jsonBuilder.ToString();


text:
Q: More than one quantifiers for one variable: $\forall x\exists x P(x)$ I couldn't find any definiton about this:
$\forall x\exists x P(x)$
Is here the for all or the there exists stronger?
Cheers

A: The formula as written is quite well formed; it just is not very human readable.
It is best practice to avoid reusing symbols for bound entities when nesting quantifiers.   Thus wise, confusion in the given formula may be averted by a change of symbols for the quantified entities within their own scope.
The entity in the predicate is bound to the scope of the existential quantifier.   As such it does not occur free within the scope of the universal.   We can change symbol for the entity bound within the scope of the existential quantifier, without affecting the symbol of the entity bound in the scope of the universal.   Thusly:
$$\color{red}{\color{black}{
\forall x \color{silver}{\big( \color{black}{\exists x \; P(x)}\big)} \;\equiv\; \forall x \color{silver}{\big(\color{black}{\exists y \; P(y)}\big)} \;\equiv\; \exists y \; P(y)
}}$$

Further   Just to be clear, suppose we had a nested statement with more predicates, such as: $$\forall x\;\Big(Q(x) \wedge \exists x\; \big(P(x)\vee R(x)\big)\Big)$$
To preserve meaning of the statement, we do not touch any of the $x$ symbols that lie outside the scope of the existential quantifier when  we change the variable bound within its scope.
$$\forall x\;\Big(Q(x) \wedge \exists y\; \big(P(y)\vee R(y)\big)\Big)$$


text:
Q: $(S^1 \times [0,1])/\sim$ homeomorphic to unit disk $ D^2$ Let $\sim$ be the equivalence relation on $S_1 \times I$ given by $(x,t)\sim(y,s)$ if and only if $xt=ys$
where $I=[0,1]$
How do I prove that $(S_1 \times I)/\sim$ is homeomorphic to the unit disk $D^2$ with the induced topology?

A: The map $f:S^1×I→D^2$ which maps $(x,s)$ to $xs$ is continuous, closed, and surjective as each $y\ne 0\in D^2$ is the image of $\left(\frac y{||y||},||y||\right)$. Since $f(x,s)=f(y,t)\iff xs=yt\iff (x,s)\sim (y,t)$, the universal property of quotient spaces induces a homeomorphism $\dfrac{S^1×I}\sim \to D^2$