text:
Q: "map" strings to tuple elements in c++ I am writing an ODBC wrapper library, and I'm trying to find a nice way of saving the results of a select query. This would preferably be by using tuples so the SQL types are respected in the C++ code. But I am stuck at trying to "map" the result table's column names to these tuple elements.
What I am trying to do is the following:
template<typename... _TArgs>
class result_row {
private:
    std::tuple<std::optional<_TArgs>...> m_columns; // std::optional allows for NULL values.
    static constexpr size_t m_column_count = sizeof...(_TArgs);

    // The column names will be filled out after the query is executed.
    std::array<std::string, m_column_count> m_column_names;
public:
    template<typename _Ty>
    _Ty get(std::string col_name) {
        // How do I find the corresponding column here?
    }
}

Is there any neat way to accomplish this, or would I have to just save all results as strings and then force the user to convert to the desired types?

A: AFAIU get tries to bind runtime info (column name) to compile-time info (column type)
possible options:

*

*use std::variant<_TArgs...> as a return type of get
see C++11 way to index tuple at runtime without using switch

*the user provides  _Ty type and get checks at runtime if _Ty matches the actual type of the column. if yes - return the value and if not - throw an exception
both options:
    template<typename... _TArgs>
    class result_row {
    private:
    std::tuple<_TArgs...> m_columns;
    static constexpr size_t m_column_count = sizeof...(_TArgs);

    // The column names will be filled out after the query is executed.
    std::array<std::string, m_column_count> m_column_names;

    template <size_t N = 0>
    std::variant<_TArgs...> runtime_get(size_t idx) {
        if (N == idx) {
            return std::variant<_TArgs...>(std::in_place_index_t<N>(), std::get<N>(m_columns));
        }
        if constexpr (N + 1 < m_column_count) {
            return runtime_get<N + 1>(idx);
        }
        return std::variant<_TArgs...>();
    }

    template <class T, size_t N = 0>
    T runtime_get_typed(std:: size_t idx) {
        if  (N == idx) {
            if constexpr (std::is_same_v<T, std::tuple_element_t<N, std::tuple<_TArgs...>>>)
            {
                return std::get<N>(m_columns);
            }
            else
            {
                throw std::runtime_error("invalid column type");
            }
        }
        if constexpr (N + 1 < m_column_count) {
            return runtime_get_typed<T, N + 1>(idx);
        }
        return T();
    }

    public:
    std::variant<_TArgs...> get(std::string col_name) {
        auto it = std::find(std::begin(m_column_names), std::end(m_column_names), col_name);
        if (it == std::end(m_column_names)) throw std::runtime_error("invalid column name: " + col_name);
        return runtime_get(std::distance(std::begin(m_column_names), it));
    }
    template <class T>
    T get_typed(std::string col_name) {
        auto it = std::find(std::begin(m_column_names), std::end(m_column_names), col_name);
        if (it == std::end(m_column_names)) throw std::runtime_error("invalid column name: " + col_name);
        return runtime_get_typed<T>(std::distance(std::begin(m_column_names), it));
    }
    };

a working example for both options


text:
Q: Printing Magento Page prints blank in the content area For one of our clients their customers need to be able to print out certain pages on the website. Whenever we try and print it will print out a page as it normally would putting the title tag / url at the top and time / number of pages at the bottom. However, the content area is blank.
Any ideas?
I've tried across all browsers and we have the same issue

A: To me it sounds like a CSS issue, I suggest you look at this post to be able to view the print version of your page in your browser so you can inspect the content element and see if the content is not hidden by a CSS rule
https://stackoverflow.com/questions/16105147/see-print-css-in-the-browser

redpajama_set_name: RedPajamaStackExchange


text:
Q: Obtain a barplot from boolean values? I'm facing a bit of a problem. This is my dataframe:
Students     Subject       Mark
1            M F           7 4 3 7
2            I             5 6
3            M F I S       2 3 0
4            M             2 2
5            F M I         5 1
6            I M F         6 2 3
7            I M           7

I want to plot a barplot with four "bars", for students respecting the next four conditions:

*

*Have 3 ore more letters in the column "Subject"

*Have at least one 3 in the colum "Marks"

*Have both things

*Have neither things

At first I was stuck, but I was suggested to proceed this way:
df["Subject"].str.count("\w+") >= 3

df["Mark"].str.count("3") >= 1

(df["Subject"].str.count("\w+") >= 3) & (df["Mark"].str.count("3") >= 1)

What I obtain are three boolean columns, but I don't know how to go from here to plot the barplot.
I was thinking about counting the values in each column, but I don't seem to find a way to do so, since it looks like I can't apply value_counts() to the boolean columns.
If you have any idea, please help!

A: I think you need create DataFrame with all 4 masks, then count Trues by sum and last plot:
m1 = df["Subject"].str.count("\w+") >= 3
m2 = df["Mark"].str.count("3") >= 1

df1 = pd.concat([m1, m2, m1 & m2, ~m1 & ~m2], axis=1, keys=('a','b','c','d'))

out = df1.sum()

If need seaborn solution:
import seaborn as sns

ax = sns.barplot(x="index", y="val", data=out.reset_index(name='val'))

For pandas (matplotlib) solution:
out.plot.bar()


text:
Q: How to pass audio stream recorded with WebRTC to Google Speech api for realtime transcription? What I'm trying to do is get real time transcription for video recorded in the browser with webRTC. Use case is basically subtitles in real time like google hangouts has.
So I have a WebRTC program running in the browser. It sends webm objects back to the server. They are linear32 audio encodings. Google speech to text only accepts linear16 or Flac files.
Is there a way to convert linear32 to linear16 in real time?
Otherwise has anyone been able to hook up webRTC with Google speech to get real time transcriptions working?
Any advice on where to look to solve this problem would be great

A: Check out this repository it might help you - https://github.com/muaz-khan/Translator
Translator.js is a JavaScript library built top on Google Speech-Recognition & Translation API to transcript and translate voice and text. It supports many locales and brings globalization in WebRTC!

A: I had the same problem and failed with webRTC. I recommend you use the Web Audio Api instead if you are just interested in transcribing the audio from the video.
Here is how I did it with a nodejs sever and react client app. It is uploaded to github here

*

*You need an audio worklet script. (Put it in the public folder because that is where the API expects to find it)

recorderWorkletProcessor.js (saved in public/src/worklets/recorderWorkletProcessor.js)
/**
  An in-place replacement for ScriptProcessorNode using AudioWorklet
*/
class RecorderProcessor extends AudioWorkletProcessor {
  // 0. Determine the buffer size (this is the same as the 1st argument of ScriptProcessor)
  bufferSize = 2048;
  // 1. Track the current buffer fill level
  _bytesWritten = 0;

  // 2. Create a buffer of fixed size
  _buffer = new Float32Array(this.bufferSize);

  constructor() {
    super();
    this.initBuffer();
  }

  initBuffer() {
    this._bytesWritten = 0;
  }

  isBufferEmpty() {
    return this._bytesWritten === 0;
  }

  isBufferFull() {
    return this._bytesWritten === this.bufferSize;
  }

  /**
   * @param {Float32Array[][]} inputs
   * @returns {boolean}
   */
  process(inputs) {
    // Grabbing the 1st channel similar to ScriptProcessorNode
    this.append(inputs[0][0]);

    return true;
  }

  /**
   *
   * @param {Float32Array} channelData
   */
  append(channelData) {
    if (this.isBufferFull()) {
      this.flush();
    }

    if (!channelData) return;

    for (let i = 0; i < channelData.length; i++) {
      this._buffer[this._bytesWritten++] = channelData[i];
    }
  }

  flush() {
    // trim the buffer if ended prematurely
    const buffer = this._bytesWritten < this.bufferSize ? this._buffer.slice(0, this._bytesWritten) : this._buffer;
    const result = this.downsampleBuffer(buffer, 44100, 16000);
    this.port.postMessage(result);
    this.initBuffer();
  }

  downsampleBuffer(buffer, sampleRate, outSampleRate) {
    if (outSampleRate == sampleRate) {
      return buffer;
    }
    if (outSampleRate > sampleRate) {
      throw new Error("downsampling rate show be smaller than original sample rate");
    }
    var sampleRateRatio = sampleRate / outSampleRate;
    var newLength = Math.round(buffer.length / sampleRateRatio);
    var result = new Int16Array(newLength);
    var offsetResult = 0;
    var offsetBuffer = 0;
    while (offsetResult < result.length) {
      var nextOffsetBuffer = Math.round((offsetResult + 1) * sampleRateRatio);
      var accum = 0,
        count = 0;
      for (var i = offsetBuffer; i < nextOffsetBuffer && i < buffer.length; i++) {
        accum += buffer[i];
        count++;
      }

      result[offsetResult] = Math.min(1, accum / count) * 0x7fff;
      offsetResult++;
      offsetBuffer = nextOffsetBuffer;
    }
    return result.buffer;
  }
}

registerProcessor("recorder.worklet", RecorderProcessor);

Install Socket.io-client on front end
npm i socket.io-client

React component code
/* eslint-disable react-hooks/exhaustive-deps */
import { default as React, useEffect, useState, useRef } from "react";
import { Button } from "react-bootstrap";
import Container from "react-bootstrap/Container";
import * as io from "socket.io-client";

const sampleRate = 16000;

const getMediaStream = () =>
  navigator.mediaDevices.getUserMedia({
    audio: {
      deviceId: "default",
      sampleRate: sampleRate,
      sampleSize: 16,
      channelCount: 1,
    },
    video: false,
  });

interface WordRecognized {
  final: boolean;
  text: string;
}

const AudioToText: React.FC = () => {
  const [connection, setConnection] = useState<io.Socket>();
  const [currentRecognition, setCurrentRecognition] = useState<string>();
  const [recognitionHistory, setRecognitionHistory] = useState<string[]>([]);
  const [isRecording, setIsRecording] = useState<boolean>(false);
  const [recorder, setRecorder] = useState<any>();
  const processorRef = useRef<any>();
  const audioContextRef = useRef<any>();
  const audioInputRef = useRef<any>();

  const speechRecognized = (data: WordRecognized) => {
    if (data.final) {
      setCurrentRecognition("...");
      setRecognitionHistory((old) => [data.text, ...old]);
    } else setCurrentRecognition(data.text + "...");
  };

  const connect = () => {
    connection?.disconnect();
    const socket = io.connect("http://localhost:8081");
    socket.on("connect", () => {
      console.log("connected", socket.id);
      setConnection(socket);
    });

    socket.emit("send_message", "hello world");

    socket.emit("startGoogleCloudStream");

    socket.on("receive_message", (data) => {
      console.log("received message", data);
    });

    socket.on("receive_audio_text", (data) => {
      speechRecognized(data);
      console.log("received audio text", data);
    });

    socket.on("disconnect", () => {
      console.log("disconnected", socket.id);
    });
  };

  const disconnect = () => {
    if (!connection) return;
    connection?.emit("endGoogleCloudStream");
    connection?.disconnect();
    processorRef.current?.disconnect();
    audioInputRef.current?.disconnect();
    audioContextRef.current?.close();
    setConnection(undefined);
    setRecorder(undefined);
    setIsRecording(false);
  };

  useEffect(() => {
    (async () => {
      if (connection) {
        if (isRecording) {
          return;
        }

        const stream = await getMediaStream();

        audioContextRef.current = new window.AudioContext();

        await audioContextRef.current.audioWorklet.addModule(
          "/src/worklets/recorderWorkletProcessor.js"
        );

        audioContextRef.current.resume();

        audioInputRef.current =
          audioContextRef.current.createMediaStreamSource(stream);

        processorRef.current = new AudioWorkletNode(
          audioContextRef.current,
          "recorder.worklet"
        );

        processorRef.current.connect(audioContextRef.current.destination);
        audioContextRef.current.resume();

        audioInputRef.current.connect(processorRef.current);

        processorRef.current.port.onmessage = (event: any) => {
          const audioData = event.data;
          connection.emit("send_audio_data", { audio: audioData });
        };
        setIsRecording(true);
      } else {
        console.error("No connection");
      }
    })();
    return () => {
      if (isRecording) {
        processorRef.current?.disconnect();
        audioInputRef.current?.disconnect();
        if (audioContextRef.current?.state !== "closed") {
          audioContextRef.current?.close();
        }
      }
    };
  }, [connection, isRecording, recorder]);

  return (
    <React.Fragment>
      <Container className="py-5 text-center">
        <Container fluid className="py-5 bg-primary text-light text-center ">
          <Container>
            <Button
              className={isRecording ? "btn-danger" : "btn-outline-light"}
              onClick={connect}
              disabled={isRecording}
            >
              Start
            </Button>
            <Button
              className="btn-outline-light"
              onClick={disconnect}
              disabled={!isRecording}
            >
              Stop
            </Button>
          </Container>
        </Container>
        <Container className="py-5 text-center">
          {recognitionHistory.map((tx, idx) => (

{tx}

          ))}

{currentRecognition}

        </Container>
      </Container>
    </React.Fragment>
  );
};

export default AudioToText;

server.js
const express = require("express");
const speech = require("@google-cloud/speech");

//use logger
const logger = require("morgan");

//use body parser
const bodyParser = require("body-parser");

//use corrs
const cors = require("cors");

const http = require("http");
const { Server } = require("socket.io");

const app = express();

app.use(cors());
app.use(logger("dev"));

app.use(bodyParser.json());

const server = http.createServer(app);

const io = new Server(server, {
  cors: {
    origin: "http://localhost:3000",
    methods: ["GET", "POST"],
  },
});

//TODO: run in terminal first to setup credentials export GOOGLE_APPLICATION_CREDENTIALS="./speech-to-text-key.json"

const speechClient = new speech.SpeechClient();

io.on("connection", (socket) => {
  let recognizeStream = null;
  console.log("** a user connected - " + socket.id + " **\n");

  socket.on("disconnect", () => {
    console.log("** user disconnected ** \n");
  });

  socket.on("send_message", (message) => {
    console.log("message: " + message);
    setTimeout(() => {
      io.emit("receive_message", "got this message" + message);
    }, 1000);
  });

  socket.on("startGoogleCloudStream", function (data) {
    startRecognitionStream(this, data);
  });

  socket.on("endGoogleCloudStream", function () {
    console.log("** ending google cloud stream **\n");
    stopRecognitionStream();
  });

  socket.on("send_audio_data", async (audioData) => {
    io.emit("receive_message", "Got audio data");
    if (recognizeStream !== null) {
      try {
        recognizeStream.write(audioData.audio);
      } catch (err) {
        console.log("Error calling google api " + err);
      }
    } else {
      console.log("RecognizeStream is null");
    }
  });

  function startRecognitionStream(client) {
    console.log("* StartRecognitionStream\n");
    try {
      recognizeStream = speechClient
        .streamingRecognize(request)
        .on("error", console.error)
        .on("data", (data) => {
          const result = data.results[0];
          const isFinal = result.isFinal;

          const transcription = data.results
            .map((result) => result.alternatives[0].transcript)
            .join("\n");

          console.log(`Transcription: `, transcription);

          client.emit("receive_audio_text", {
            text: transcription,
            final: isFinal,
          });
        });
    } catch (err) {
      console.error("Error streaming google api " + err);
    }
  }

  function stopRecognitionStream() {
    if (recognizeStream) {
      console.log("* StopRecognitionStream \n");
      recognizeStream.end();
    }
    recognizeStream = null;
  }
});

server.listen(8081, () => {
  console.log("WebSocket server listening on port 8081.");
});

// =========================== GOOGLE CLOUD SETTINGS ================================ //

// The encoding of the audio file, e.g. 'LINEAR16'
// The sample rate of the audio file in hertz, e.g. 16000
// The BCP-47 language code to use, e.g. 'en-US'
const encoding = "LINEAR16";
const sampleRateHertz = 16000;
const languageCode = "en-US"; //en-US
const alternativeLanguageCodes = ["en-US", "ko-KR"];

const request = {
  config: {
    encoding: encoding,
    sampleRateHertz: sampleRateHertz,
    languageCode: languageCode,
    //alternativeLanguageCodes: alternativeLanguageCodes,
    enableWordTimeOffsets: true,
    enableAutomaticPunctuation: true,
    enableWordConfidence: true,
    enableSpeakerDiarization: true,
    diarizationSpeakerCount: 2,
    model: "video",
    //model: "command_and_search",
    useEnhanced: true,
    speechContexts: [
      {
        phrases: ["hello", "안녕하세요"],
      },
    ],
  },
  interimResults: true,
};


text:
Q: Why does Bootstrap destroys my normal css layout and how do I fix it? first of all excuse my language, this is my third language and I'm new.
I'd like to do a little website with html, css and bootstrap that doesn't need to be responsive.
So I did a sticky Navbar with javascript and css  which looks pretty good. Because I want to use ajax (for not having to write the navbar on each html-file) and Bootstrap (for some buttons, modals etc..)
So I added Bootstrap in my html-doc and now the style of my whole navbar is different. It's not even sticky anymore and has a weird white border at the bottom.
Would be great if you could help me.
I am using Brackets, so all this stuff is local and I am not planning to  make a real website out of it.
Merry Christmas to you all!
Basti

A: WHY?
Your css declaretions had overrided by bootstrap declaretions:
For example I tried to set color:red but look what happend:

You have to use this steps to minimize the conflict between your css and bootstrap css:

*

*Set your css link below bootstrap links
<link href="css/bootstrap.min.css" rel="stylesheet">
 <link href="yourCss.css" rel="stylesheet">

*Use Specificity in css as own id or class

Specificity is the means by which browsers decide which CSS property
  values are the most relevant to an element and, therefore, will be
  applied. Specificity is based on the matching rules which are composed
  of different sorts of CSS selectors.

*In case that your css declaretion had overrided use !important
For eample color:red!important

A: Bootstrap is the frontend framework it comes with pre defined classes that is the main reason your website style got changed to fix this you can add a custom css so for example one of the pre defined class in bootstrap looks like this

  A simple primary alert—check it out!

Notice that "alert alert-primary" classes (there are 2 classes used first one is alert and second one is alert-primary), This is responsible for the pre defined styles.
So, To fix your issue you can add another class similarly and define its custom style in CSS file as per your need.
So adding another class in the above example will look like this

  A simple primary alert—check it out!

and then style this by targeting the same class in CSS like this

.anotherClass {
  /*your styles go here*/
}

Do not forget to link the CSS file.


text:
Q: How to remove falsy values when splitting a string with a non-whitespace separator According to the docs:

str.split(sep=None, maxsplit=-1)
If sep is given, consecutive delimiters are not grouped together and
  are deemed to delimit empty strings (for example, '1,,2'.split(',')
  returns ['1', '', '2']). The sep argument may consist of multiple
  characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']).
  Splitting an empty string with a specified separator returns
  [''].
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

So to use the keyword argument sep=, is the following the pythonic way to remove the falsy items?
[w for w in s.strip().split(' ') if w]

If it's just whitespaces (\s\t\n), str.split() will suffice but let's say we are trying to split on another character/substring, the if-condition in the list comprehension is necessary. Is that right?

A: If you want to be obtuse, you could use filter(None, x) to remove falsey items:
>>> list(filter(None, '1,2,,3,'.split(',')))
['1', '2', '3']

Probably less Pythonic. It might be clearer to iterate over the items specifically:
for w in '1,2,,3,'.split(','):
    if w:
        …

This makes it clear that you're skipping the empty items and not relying on the fact that str.split sometimes skips empty items.
I'd just as soon use a regex, either to skip consecutive runs of the separator (but watch out for the end):
>>> re.split(r',+', '1,2,,3,')
['1', '2', '3', '']

or to find everything that's not a separator:
>>> re.findall(r'[^,]+', '1,2,,3,')
['1', '2', '3']

If you want to go way back in Python's history, there were two separate functions, split and splitfields. I think the name explains the purpose. The first splits on any whitespace, useful for arbitrary text input, and the second behaves predictably on some delimited input. They were implemented in pure Python before v1.6.

A: Well, I think you might just need a hand in understanding the documentation.  In your example, you pretty much are demonstrating the differences in the algorithm mentioned in documentation. Not using the sep keyword argument more or less is like using sep=' ' and then throwing out the empty strings. When you have multiple spaces in a row the algorithm splits those and finds None. Because you were explicit that you wanted everything split by a space it converts None to an empty string. Changing None to an empty string is good practice in this case, because it avoids changing the signature of the function (or in other words what the functions returns), in this case it returns a list of strings.
Below is showing how an empty string with 4 spaces is treated differently...
>>> empty = '   '
>>> s = 'this is   an   irritating string with  random spacing  .'
>>> empty.split()
[]
>>> empty.split(' ')
['', '', '', '']

For you question, just use split() with no sep argument

A: well your string
s = 'this is   an   irritating string with  random spacing  .',
which is containing more than one white spaces that's why empty.split(' ')  is  returning noney value.
you would have to remove extra white space from string s and can get desired result.


text:
Q: Javascript Object.innerHtml is not substituting the whole string parameter provided newcell.innerHTML=''+BLAH+'	';
For some strange reason my BLAH	 is correctly rendered on the page but any attributes that I give inside the td tag just don't display. Any pointers?
Sorry if this might sound very silly, I have very less experience in front end. Any 'must look' tutorials would be appreciated. Thanks

A: If newCell in this case represents a  then you need to either use outerHTML instead of innerHTML, or programmatically set the properties you need.
var newCell = document.createElement("td");
newCell.outerHTML = ''+BLAH+'	';

or
var newCell = document.createElement("td");
newCell.id = "blah1";
newCell.innerHTML = BLAH;

A: If you're declaring a Javascript string with single quotes, you don't need to escape any double-quotes that you use inside it. Try newcell.innerHTML=''+BLAH+'	';.


text:
Q: Solve $\arg\min_{x \in \mathbb{R}^n} I_C(x) + \alpha \sum_i \left\|y_i -x \right\|_2^2$, where $I_C(x)$: indicator function; set $C$: norm 2 ball I have a problem on hand that I am not sure how to handle it. Can you please help/guide me to solve this optimization problem?
\begin{align}
\arg\min_{x \in \mathbb{R}^n} I_C(x) + \alpha \sum_i \left\|y_i -x \right\|_2^2 \ ,
\end{align}
where $I_C(x)$ is an indicator or characteristic function and the set $C$ can be a norm-2 ball, i.e., $C = \left\{x \in \mathbb{R}^n : \left\|x - c \right\|_2^2 \leq r\right\}$, $y_i, c \in \mathbb{R}^n$ are given, and $r \in \mathbb{R}$.

My partial attempt:
The above problem can be rewritten as
\begin{equation} \label{eqn:weighted_projection_problem_definition_3}
\begin{aligned}
& \underset{x}{\text{minimize}}
& & \alpha \sum_i \left\|y_i -x \right\|_2^2 \\
& \text{subject to}
& &  \left\|x - c \right\|_2^2 \leq r \ ,\\
%&&& X \succeq 0.
\end{aligned}
\end{equation}
Right?
If yes, then I think it is possible to solve in the closed form.

A: Let's complete the square: $\| y_i - x \|^2 = \|y_i\|^2 - 2 \langle y_i, x \rangle + \|x\|^2$, so
\begin{align}
\sum_{i=1}^N \|y_i - x \|^2 &= -2 \left \langle \sum_{i=1}^N y_i, x \right\rangle + N \|x\|^2 + \ldots \\
&=N \left(-2 \left \langle \frac{1}{N}\sum_{i=1}^N y_i, x \right\rangle  + \|x\|^2 \right) + \ldots \\
&= N \left\|x - \frac{1}{N} \sum_{i=1}^N y_i \right\|^2 + \ldots
\end{align}
where the ellipses ($\ldots$) indicate terms that do not depend on $x$. It follows that
\begin{align}
\arg\min_x \, I_C(x) + \alpha \sum_{i=1}^N \|y_i - x \|^2&=
\arg\min_x I_C(x) + \alpha N \left\|x - \frac{1}{N} \sum_{i=1}^N y_i \right\|^2 \\
&= \text{projection of } \frac{1}{N} \sum_{i=1}^N y_i \text{ onto } C.
\end{align}


text:
Q: How safe is ref when used with unsafe code? Using Microsoft Visual C# 2010, I recently noticed that you can pass objects by ref to unmanaged code. So I tasked myself with attempting to write some unmanaged code that converts a C++ char* to a a C# string using a callback to managed code. I made two attempts.
Attempt 1: Call unmanaged function that stores a ref parameter. Then, once that function has returned to managed code, call a another unmanaged function that calls a callback function that converts the char* to a managed string.
C++
typedef void (_stdcall* CallbackFunc)(void* ManagedString, char* UnmanagedString);

CallbackFunc UnmanagedToManaged = 0;
void* ManagedString = 0;

extern "C" __declspec(dllexport) void __stdcall StoreCallback(CallbackFunc X) {
    UnmanagedToManaged = X;
}
extern "C" __declspec(dllexport) void __stdcall StoreManagedStringRef(void* X) {
    ManagedString = X;
}
extern "C" __declspec(dllexport) void __stdcall CallCallback() {
    UnmanagedToManaged(ManagedString, "This is an unmanaged string produced by unmanaged code");
}

C#
[DllImport("Name.dll", CallingConvention = CallingConvention.StdCall)]
public static extern void StoreCallback(CallbackFunc X);
[DllImport("Name.dll", CallingConvention = CallingConvention.StdCall)]
public static extern void StoreManagedStringRef(ref string X);
[DllImport("Name.dll", CallingConvention = CallingConvention.StdCall)]
public static extern void CallCallback();

[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void CallbackFunc(ref string Managed, IntPtr Native);

static void Main(string[] args) {
    string a = "This string should be replaced";

    StoreCallback(UnmanagedToManaged);
    StoreManagedStringRef(ref a);
    CallCallback();
}

static void UnmanagedToManaged(ref string Managed, IntPtr Unmanaged) {
    Managed = Marshal.PtrToStringAnsi(Unmanaged);
}

Attempt 2: Pass string ref to unmanaged function that passes the string ref to the managed callback.
C++
typedef void (_stdcall* CallbackFunc)(void* ManagedString, char* UnmanagedString);

CallbackFunc UnmanagedToManaged = 0;

extern "C" __declspec(dllexport) void __stdcall StoreCallback(CallbackFunc X) {
    UnmanagedToManaged = X;
}
extern "C" __declspec(dllexport) void __stdcall DoEverything(void* X) {
    UnmanagedToManaged(X, "This is an unmanaged string produced by unmanaged code");
}

C#
[DllImport("Name.dll", CallingConvention = CallingConvention.StdCall)]
public static extern void StoreCallback(CallbackFunc X);
[DllImport("Name.dll", CallingConvention = CallingConvention.StdCall)]
public static extern void DoEverything(ref string X);

[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void CallbackFunc(ref string Managed, IntPtr Unmanaged);

static void Main(string[] args) {
    string a = "This string should be replaced";

    StoreCallback(UnmanagedToManaged);
    DoEverything(ref a);
}

static void UnmanagedToManaged(ref string Managed, IntPtr Unmanaged) {
    Managed = Marshal.PtrToStringAnsi(Unmanaged);
}

Attempt 1 doesn't work but attempt 2 does. In attempt 1 it seems that as soon as the unmanaged code returns after storing the ref, the ref becomes invalid. Why is this happening?
Given the outcomes of attempt 1, I have doubts that attempt 2 will work reliably. So, how safe is ref on the unmanaged side of code when used with unmanaged code? Or in other words, what won't work in unmanaged code when using ref?
Things I'd like to know are are:
What exactly happens when objects are passed using ref to unmanaged code?
Does it guarantee that the objects will stay at their current position in memory while the ref is being used in unmanaged code?
What are the limitations of ref (what can't I do with a ref) in unmanaged code?

A: A complete discussion of how p/invoke works is beyond the proper scope of a Stack Overflow Q&A. But briefly:
In neither of your examples are you really passing the address of your managed variable to the unmanaged code. The p/invoke layer includes marshaling logic that translates your managed data to something usable by the unmanaged code, and then translates back when the unmanaged code returns.
In both examples, the p/invoke layer has to create an intermediate object for the purpose of marshaling. In the first example, this object is gone by the time you call the unmanaged code again. Of course in the second example, it's not, since all of the work happens all at once.
I believe that your second example should be safe to use. That is, the p/invoke layer is smart enough to handle ref correctly in that case. The first example is unreliable because p/invoke is being misused, not because of any fundamental limitation of ref parameters.

A couple of additional points:

*

*I wouldn't use the word "unsafe" here. Yes, calling out to unmanaged code is in some ways unsafe, but in C# "unsafe" has a very specific meaning, related to the use of the unsafe keyword. I don't see anything in your code example that actually uses unsafe.

*In both examples, you have a bug related to your use of the delegate passed to unmanaged code. In particular, while the p/invoke layer can translate your managed delegate reference to a function pointer that unmanaged code can use, it doesn't know anything about the lifetime of the delegate object. It will keep the object alive long enough for the p/invoked method call to complete, but if you need it to live longer than that (as would be the case here), you need to do that yourself. For example, use GC.KeepAlive() on a variable in which you've stored the reference. (You likely can reproduce a crash by inserting a call to GC.Collect() between the call to StoreCallback() and the later call to unmanaged code where the function pointer would be used).


text:
Q: How to understand the following code, this serves as a pipe in an Angular project Background:
I am building a SIM project with Angular 7.
Using this following pipe to select the corresponding items inside an array(list[]), and display it to the UI. With the title(filterField) of each item and input string(keyword).
therefore I have the following code:
pipe
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  transform(list:any[], filterField:string, keyword:string){
    if(!filterField || !keyword){return list;}else{
      return list.filter(item =>{
          let fieldValue = item[filterField];
          return fieldValue.indexOf(keyword)>=0;
        }
      )
    }
  }
}

These are the list [] details:
 private products: Product[] = [
    new Product(1, '1st Product', 1.99, 3.5, 'This is the 1st product, which is used for display', ['Electronics', 'Hardware']),
    new Product(2, '2nd Product', 2.99, 2.5, 'This is the 2nd product, which is used for display', ['Books']),
    new Product(3, '3rd Product', 3.99, 4.5, 'This is the 3rd product, which is used for display', ['Hardware']),
    new Product(4, '4th Product', 4.99, 1.5, 'This is the 4th product, which is used for display', ['Electronics', 'Hardware']),
    new Product(5, '5th Product', 5.99, 3.5, 'This is the 5th product, which is used for display', ['Electronics']),
    new Product(6, '6th Product', 6.99, 2.5, 'This is the 6th product, which is used for display', ['Books'])
  ]

export class Product {

  constructor(
    public id: number,
    public title: string,
    public price: number,
    public rating: number,
    public desc: string,
    public categories: Array<string>
  ) {
  }
}

product.component.html

      <input class="form-control" placeholder="Please Input" [formControl]="titleFilter">

{{product.price}} Euro

{{product.title}}

{{product.desc}}

      <app-stars [rating]="product.rating"></app-stars>

product.component.ts
export class ProductComponent implements OnInit {

products:Array<Product>;
keywordInput:string;
titleFilter:FormControl=new FormControl;

  constructor(private productService:ProductService) {
    this.titleFilter.valueChanges.pipe(debounceTime(500))
      .subscribe(
        value => this.keywordInput = value,
      );
   }

  ngOnInit() {
    this.products=this.productService.getProducts();

  }
}

Questions:

1. how to understand
itemTitle => {
          let fieldValue = itemTitle[filterField];
          return fieldValue.indexOf(keyword) >= 0;
        }

I could not understand the itemTitle[filterField] part, I assume itemTitle is the title of each item, but how does the  [ ] works?

*is .filter already deprecated in Angular 7? Is there an alternative for that?

*for the following part
return fieldValue.indexOf(keyword) >= 0;

could I use this for alternative?
if (fieldValue.indexOf(keyword) >= 0) {
  return fieldValue.indexOf(keyword)
} else {return null;}

When I run it, it is not working,
thank you!

A:
I assume itemTitle is the title of each item, but how does the [ ] works?

It's property accessor. It's not an Angular thing, it's a JS thing. Basically, obj['foo'] is an equivalent of obj.foo, but with the [] notation the name of the property can be dynamic, it can be passed as an argument. Just like in your pipe.

A:
how to understand
itemTitle => {
      let fieldValue = itemTitle[filterField];
      return fieldValue.indexOf(keyword) >= 0;
}

It is probably item not itemTitle in your code.
So item is each of the Product objects in the list.
filterField is the second argument to the pipe, which in your case is title.
let fieldValue = itemTitle[filterField]; will fetch the title of the product object. Which can be "1st Product", "2nd Product", etc.
fieldValue.indexOf(keyword) will look for the presence of the keyword value(probably what you type in an input box) in the fieldValue string. If the keyword is present in the string, then it will return the starting index, if not it will return -1
return fieldValue.indexOf(keyword) >= 0; will return true or false depending on whether the keyword string was present in the the title or not.

is .filter already deprecated in Angular 7? Is there an alternative for that?

No, filter is a method on JavaScript's Array prototype, it has nothing to do with angular here. And no, it is not deprecated.

could I use this for alternative?
if (fieldValue.indexOf(keyword) >= 0) {
  return fieldValue.indexOf(keyword)
} else {return null;}

No, you can't use this to achieve what being achieved already.
You see, if you are using Array filter, if you want to remove an item from the Array, you return a falsy value, if you want to keep an element, you return a truthy value. In this code of yours, you are returning either the index of the found string or null. This will work in all the cases except when the found index will be 0. If the keyword was found at the start itself then that product object will be removed from the list since you will be returning 0 (which is falsy).


text:
Q: Switching to some apps in a different virtual display doesn't work I have OS X El Capitan (10.11.6) installed on my MacBook Pro 2015. I use Spotlight a lot to switch between apps in different virtual desktops and one day some months ago I noticed that it won't switch to the virtual desktop of the app I wanted to switch to. The same happens if I click on the icon in the dock.
Some apps that it doesn't switch to are Skype, FileZilla, IntelliJ Idea and more.

A: The setting System Preferences > Mission Control > "When switching to an application, switch to a Space with open windows for the application" must be enabled for OS X to automatically switch your desktop/Space when changing to an open program.
Otherwise, it will stay in the current space and one of a couple of things will happen, depending on the way the application is programmed:

*

*The menu bar will change to that program's, but nothing else on the screen will change, or

*A new window for that program will be opened (think a text editor opening a new, blank document), along with the menu bar changing


text:
Q: Username and password authentication for Solr I am inserting and querying data to Solr using solrj.
I am using the following methods to save/query data.
SolrClient client = getSolrClient();
final Map<String, String> queryParamMap = new HashMap<>();
queryParamMap.put("q", "*:*");
queryParamMap.put("fl", "id, name");
MapSolrParams queryParams = new MapSolrParams(queryParamMap);
final QueryResponse response = client.query("testcore1", queryParams);
final SolrDocumentList documents = response.getResults();

--
final SolrClient client = getSolrClient();
final SolrInputDocument doc = new SolrInputDocument();
doc.addField("id", UUID.randomUUID().toString());
doc.addField("name", "Amazon Kindle Paperwhite");
final UpdateResponse updateResponse = client.add("testcore1", doc);
client.commit("testcore1");

I have added username and password authentication for Solr.
I changed the Solr client method and added UsernamePasswordCredentials
private SolrClient getSolrClient() {
        String solrUrl = "http://localhost:8983/solr";
        //return new HttpSolrClient.Builder(solrUrl).build();
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("username", "password");
        provider.setCredentials(AuthScope.ANY, credentials);
        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
        return new HttpSolrClient.Builder().withBaseSolrUrl(solrUrl).withHttpClient(client).build();
}

Still, it's showing the following error
Exception in thread "main" org.apache.solr.client.solrj.SolrServerException: IOException occured when talking to server at: http://localhost:8983/solr

How do I add authentication to these functions?

A: I had the same Problem. For me using "ConcurrentUpdateSolrClient" solved the problem:
    public static SolrClient getUpdateClient() {
    SolrClient solrClient = new ConcurrentUpdateSolrClient.Builder("http://USERNAME:PASSWORD@localhost:8983/solr")
      .build();
    return solrClient;
  }

A: Try with HttpSolrClientFactory, so method look like:
private SolrClientFactory getClientFactory(final SolrClient client, String coreName) {
    Credentials credentials = new UsernamePasswordCredentials(
        env.getProperty("solr.user"),
        env.getProperty("solr.password")
    );
    return new HttpSolrClientFactory(client, coreName, credentials, "BASIC");
}

SolrClient client = getClientFactory(new HttpSolrClient(SOLR_URL), coreName).getSolrClient()
final Map<String, String> queryParamMap = new HashMap<>();
queryParamMap.put("q", "*:*");
queryParamMap.put("fl", "id, name");
MapSolrParams queryParams = new MapSolrParams(queryParamMap);
final QueryResponse response = client.query("testcore1", queryParams);
final SolrDocumentList documents = response.getResults();

Hope this help you !!


text:
Q: Как на PHP из многомерного массива получить двумерный? Подскажите, пожалуйста, как из многоуровневого массива такого типа:
array:3 [▼
  "name" => "futbolki"
  "title" => "футболки"
  "parrent" => array:3 [▼
    "name" => "futbolki-i-polo"
    "title" => "футболки и поло"
    "parrent" => array:3 [▼
      "name" => "odezhda"
      "title" => "одежда"
      "parrent" => array:2 [▼
        "name" => "odezhda-obuv-i-aksessuary"
        "title" => "одежда, обувь и аксессуары"
      ]
    ]
  ]
]

получить нечто похожее на такой формат:
$array[0] = [
  "name" => "futbolki"
  "title" => "футболки"
]
$array[1] = [
  "name" => "futbolki-i-polo"
  "title" => "футболки и поло"
]
$array[2] = [
  "name" => "odezhda"
  "title" => "одежда"
]
$array[3] = [
  "name" => "odezhda-obuv-i-aksessuary"
  "title" => "одежда, обувь и аксессуары"
]

Заранее спасибо!

A: Вот рабочее решение, но в следующий раз сделайте сами, ведь это так просто (:
<?php
function convert(array $array) {
    $result = [];
    $result[] = [
        "name" => $array["name"],
        "title" => $array["title"]
    ];
    if (isset($array["parrent"]))
        $result = array_merge($result, convert($array["parrent"]));
    return $result;
}
var_dump(convert([
  "name" => "futbolki",
  "title" => "футболки",
  "parrent" => [
    "name" => "futbolki-i-polo",
    "title" => "футболки и поло",
    "parrent" => [
      "name" => "odezhda",
      "title" => "одежда",
      "parrent" => [
        "name" => "odezhda-obuv-i-aksessuary",
        "title" => "одежда, обувь и аксессуары"
      ]
    ]
  ]
]));

Результат:
array(4) {
  [0]=>
  array(2) {
    ["name"]=>
    string(8) "futbolki"
    ["title"]=>
    string(16) "футболки"
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(15) "futbolki-i-polo"
    ["title"]=>
    string(28) "футболки и поло"
  }
  [2]=>
  array(2) {
    ["name"]=>
    string(7) "odezhda"
    ["title"]=>
    string(12) "одежда"
  }
  [3]=>
  array(2) {
    ["name"]=>
    string(25) "odezhda-obuv-i-aksessuary"
    ["title"]=>
    string(48) "одежда, обувь и аксессуары"
  }
}

P.s.Хочу заметить, что в этом коде НЕ проверяются типы значений и НЕ добавляются в результат значения кроме "name" и "title"!

A: При такой структуре данных можно обойтись без рекурсии, что всегда хорошо:
function convert(array $array)
{
    $result = [];
    while($array) {
        $result[] = [
            "name" => $array["name"],
            "title" => $array["title"]
        ];
        $array = $array["parrent"] ?? [];
    }
    return $result;
}


text:
Q: Javascript - Multi-Usage of General Function I have a example of a situation here, I want to change the color of a div when clicked. Do I have to have two different functions, one for each div? What if the functions that I wanted to apply to the div was very complex? What if I had hundereds of the div? Can I make a general function, that can be applied for every div? By this I do not mean for example document.getElementsByClassName(" ... "), I want to for example change the color of the separately.
To be clear, how can I apply the same function to different objects? Something like document.getElementThatIsClicked(" ... " ) Thank you.

function changeColor1() {
  document.getElementById("div1").style.backgroundColor = "#21a9c9";
}
function changeColor2() {
  document.getElementById("div2").style.backgroundColor = "#21a9c9";
}

A: You can make a function that accepts the element you want to change the color and make the function change the background color for that element

 function changeColor(elem) {
   elem.style.backgroundColor = "#21a9c9"
 }

A: Copied from https://stackoverflow.com/a/32828729/227299 but:

*

*Avoids setting handlers using  inline HTML attributes in favor of unobtrusively setting handlers from JavaScript itself. See onclick="" vs event handler

*Avoid setting CSS attributes from HTML attributes. See What's so bad about in-line CSS?

function changeColor(elem) {
  elem.style.backgroundColor = "#21a9c9"
}

var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
  divs[i].addEventListener('click', function(e) {
    changeColor(this);
  });
}
#div1,#div2 {
  display: inline-block;
  width: 200px;
  height: 200px;
  background-color:#000000;
}


text:
Q: C++ Vector of Struct using push_back This is an assignment for a course that I am having problems with. Until now I thought I was fairly familiar with vectors in C++. This program is supposed to take a file from the user calculate the users pay then spit back out in a nice table all the information relevant.
It must contain a vector of struct and I must use push_back. I get two errors that I cannot figure out at this moment. In the for loop at the end of main() it tells me a reference type of vector cannot be initialized with Employee. The two functions after ward tell me that I for example .HoursWorked is not a member of the struct.
I tried looking around other questions for help but they all mentioned not using pointers which I'm 100% positive there are no pointers in my program. The txt file I am using for testing the program looks as follows:

John Smith 123-09-8765 9.00 46 F
Kevin Ashes 321-09-8444 9.50 40 F
Kim Cares 131-12-1231 11.25 50 P
Trish Dish 141-51-4564 7.52 24 P
Kyle Wader 432-12-9889 5.75 48 F

Code:
    #include <iostream>
    #include <string>
    #include <fstream>
    #include <sstream>
    #include <iomanip>
    #include <vector>

    using namespace std;

    struct Employee
    {
        string name;
        string ssn;
        double hourlyWage;
        double HoursWorked;
        char status;
        double straightTimePay;
        double overTimePay;
        double netPay;
    };

    void calculatePay(vector<Employee>& buisness);

    void displayEmployee(vector<Employee> buisness);

    int main()
    {
        vector<Employee> buisness;
        string fileName, line;
        ifstream inFile;
        stringstream ss;

        cout << "Please input the file name to read: ";
        cin >> fileName;

        inFile.open(fileName);
        if (!inFile)
        {
            cout << "Cannot open file " << fileName << " Aborting!" << endl;
            exit(1);
        }

        int index = 0;
        string firstName, lastName;

        getline(inFile, line);
        while (!inFile.eof())
        {
            if (line.length() > 0)
            {
                ss.clear();
                ss.str(line);
                buisness.push_back;

                ss >> firstName >> lastName;
                buisness[index].name = firstName + " " + lastName;
                ss >> buisness[index].ssn;
                ss >> buisness[index].hourlyWage >> buisness[index].HoursWorked;
                ss >> buisness[index].status;
                index++;
            }

            getline(inFile, line);
        }

        inFile.close();

        cout << "The information of the buisness:" << endl;
        cout << setw(20) << "Name" << setw(15) << "SSN" << setw(12) << "Hourly Wage";
        cout << setw(14) << "Hours Worked" << setw(18) << "Straight Time Pay";
        cout << setw(14) << "Over Time Pay" << setw(6) << "Status" << setw(10) << "Net Pay" << endl;

        for (index = 0; index < buisness.size(); index++)
        {
            calculatePay(buisness[index]);
            displayEmployee(buisness[index]);
        }

        return 0;
    }

    void calculatePay(vector<Employee>& buisness)
    {
        if (buisness.HoursWorked <= 40)
        {
            buisness.straightTimePay = buisness.hourlyWage * buisness.HoursWorked;
            buisness.overTimePay = 0;
        }
        else
        {
            buisness.straightTimePay = buisness.hourlyWage * 40;
            buisness.overTimePay = buisness.hourlyWage * 1.5 * (buisness.HoursWorked - 40);
        }

        buisness.netPay = buisness.straightTimePay + buisness.overTimePay;

        if (buisness.status == 'F')
            buisness.netPay -= 10;
    }

    void displayEmployee(vector<Employee> buisness)
    {
        int precisionSetting = cout.precision();
        long flagSettings = cout.flags();
        cout.setf(ios::fixed | ios::showpoint);
        cout.precision(2);

        cout << setw(20) << buisness.name << setw(15) << buisness.ssn << setw(12) << buisness.hourlyWage;
        cout << setw(14) << buisness.HoursWorked << setw(18) << buisness.straightTimePay;
        cout << setw(14) << buisness.overTimePay << setw(6) << buisness.status << setw(10) << buisness.netPay << endl;

        cout.precision(precisionSetting);
        cout.flags(flagSettings);
    }

A: At the very least.. You have the line:
        calculatePay(buisness[index]);

So clearly we all calling a function calculatePay and we're passing it an Employee.
But your function prototype says that it takes a std::vector<Employee>. You probably intended for the functions to take Employee & instead.

A: You should call vector push_back with the element to put in:
Employee employee;
// assign values to employee
ss << employee.ssn;
ss << employee.name;
business.push_back(employee);

Although the compiler error logs seem tedious, but you can almost always get enough information from the error logs. Compiling under gcc 4.2.1, the error logs says :
error: invalid initialization of reference of type 'std::vector<Employee, std::allocator<Employee> >&' from expression of type 'Employee' on the line of calling method calculatePay(). We can infer that you passed Employee to and function which want an vector of Employee as parameter. You can fix this by change calculatePay(vector<Employee>& buisness) to calculatePay(Employee& buisness). And that will fix  error: 'class std::vector<Employee, std::allocator<Employee> >' has no member named 'HoursWorked'


text:
Q: How to return back json data from script page? I had a json file results.json Which shown below. And I had a html file contain  some script. This is for retrieve data data. When I am enter into the html page which call a script function  get_machFollow(que_script) this function is for receive json file data. The function is works fine and which alert correct output, But after this function return some data to my HTML page.
My JSON file
{"mach_fol_4": {"match_l":
       ["7","8","99"],"attempts":"0","feedback_true":"You are right!",
  "feedback_false":"Sorry! wrong answer."}}

This is my script function. This function is works fine but I can't alert the return  value from HTML page. That shows undefined.
function get_machFollow(que_script)
{

        var return_var;
      $.getJSON('results.json', function(data) {
            return_var=data[que_script].match_r;
            alert(return_var);//Working alert show correct output
            return return_var;
                 });

}

This is my html file


text:
Q: PHP Download Script Creates Unreadable ZIP File on Mac For reference, I have already read and tried the answers in these and several other threads:
Creating and serving zipped files with php
Opening downloaded zip file creates cpgz file?
I have a zip file on my server.

*

*When I use Filezilla to move that Zip file from my server to my Mac, I can open it normally.

*When I use this PHP code to download the Zip file to my Linux machine, it opens normally.

*When I use this PHP code to download the Zip file to my Mac, using Safari or Firefox, I get an error saying "Decompression Failed" or "The structure of the archive is damaged" or I get a .cpgz file - which I believe means that the computer is zipping the file, not unzipping it.
Here is the PHP code I am using to deliver the zip file.
$zipname = "myfile.zip";
$zippath = "/path/to/" . $zipname;

      if ($downloadzip = fopen ($zippath, "r")) {
            $fsize = filesize($zippath);

            header("Content-type: application/zip");
            header("Content-Disposition: attachment; filename=\"".$zipname."\"");
            header("Content-length: $fsize");
            header('Content-Transfer-Encoding: binary');
            #header("Cache-control: private"); //use this to open files directly

            echo fpassthru($downloadzip); // deliver the zip file

        }
        fclose ($downloadzip);

I found some headers that work. I don't really know or care why it work, I am just happy it works... I tried a ton of different things, .htaccess files, php.ini / zlib settings.
Here's the answer
http://perishablepress.com/http-headers-file-downloads/
$zipName = 'myfile.zip';
$zipPath = 'mydirectory/' . $zipName;

    if (file_exists($zipPath)) {

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-type: application/octet-stream");
        header("Content-Disposition: attachment; filename=\"".$zipName."\"");
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".filesize($zipPath));
        ob_end_flush();
        @readfile($zipPath);
}

A: Often the issue is caused by extra characters that have been printed or echo'd to the page before you read out the file. Even a space will cause the failure. To fix that issue, call ob_end_clean(); before you read the file which will clear the output buffer and turn off buffering.
But keep in mind you can have nested output buffers, and this will corrupt your download as well (cheers to Vladamir for figuring this out). So to clear the output buffer completely run this before you read your file:
while (ob_get_level()) {
    ob_end_clean();
}

This will clear out your entire buffer and you won't have any extra characters to mess up your download.
For those interested i've pasted my download script below. My zip files now download perfectly, and so far this works great.
if (file_exists($zip_file_path)) {

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        //We can likely use the 'application/zip' type, but the octet-stream 'catch all' works just fine.
        header("Content-type: application/octet-stream");
        header("Content-Disposition: attachment; filename='$zip_file_name'");
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".filesize($zip_file_path));

        while (ob_get_level()) {
             ob_end_clean();
        }

        @readfile($zip_file_path);

        exit;
}

A: Here is what works
$zipName = 'myfile.zip';
$zipPath = 'mydirectory/' . $zipName;

    if (file_exists($zipPath)) {

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-type: application/octet-stream");
        header("Content-Disposition: attachment; filename=\"".$zipName."\"");
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".filesize($zipPath));
        ob_end_flush();
        @readfile($zipPath);
}

A: Well, I presume you know that your $fsize variable is not being written to that header because it's enclosed by quotes.
You could try something like this:
header('Cache-Control: public');
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename=\"".$zipname."\"');
header('Content-Type: application/zip');


text:
Q: SlidingTab in a fragment I am trying to add a sliding tab in a fragment. Here's the tab layout
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimaryDark" />

        <com.example.materialdrawerfragment.SlidingTabLayout
                android:id="@+id/sliding_tabs"
                android:background="?attr/colorPrimaryDark"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <android.support.v4.view.ViewPager
                android:id="@+id/pager"
                android:layout_width="match_parent"
                android:layout_height="0px"
                android:layout_weight="1"
                android:background="@android:color/white" />
        </LinearLayout>

And the Fragment class,
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_cont, container, false);

         pager = (ViewPager) getActivity().findViewById(R.id.viewpager);
         slidingTabLayout = (SlidingTabLayout) getActivity().findViewById(R.id.sliding_tabs);
         pager.setAdapter(new ViewPagerAdapter(getActivity().getSupportFragmentManager(), titles));

         slidingTabLayout.setViewPager(pager);
        return v;
    }

Error I am getting is,
04-11 00:40:31.759: E/AndroidRuntime(11107): FATAL EXCEPTION: main
04-11 00:40:31.759: E/AndroidRuntime(11107): java.lang.NullPointerException
04-11 00:40:31.759: E/AndroidRuntime(11107):    at com.example.materialdrawerfragment.MyFragment.onCreateView(MyFragment.java:54)
04-11 00:40:31.759: E/AndroidRuntime(11107):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
04-11 00:40:31.759: E/AndroidRuntime(11107):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:953)
04-11 00:40:31.759: E/AndroidRuntime(11107):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136)
04-11 00:40:31.759: E/AndroidRuntime(11107):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
04-11 00:40:31.759: E/AndroidRuntime(11107):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499)
04-11 00:40:31.759: E/AndroidRuntime(11107):    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:456)
04-11 00:40:31.759: E/AndroidRuntime(11107):    at android.os.Handler.handleCallback(Handler.java:615)
04-11 00:40:31.759: E/AndroidRuntime(11107):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-11 00:40:31.759: E/AndroidRuntime(11107):    at android.os.Looper.loop(Looper.java:137)
04-11 00:40:31.759: E/AndroidRuntime(11107):    at android.app.ActivityThread.main(ActivityThread.java:4931)
04-11 00:40:31.759: E/AndroidRuntime(11107):    at java.lang.reflect.Method.invokeNative(Native Method)
04-11 00:40:31.759: E/AndroidRuntime(11107):    at java.lang.reflect.Method.invoke(Method.java:511)
04-11 00:40:31.759: E/AndroidRuntime(11107):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
04-11 00:40:31.759: E/AndroidRuntime(11107):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
04-11 00:40:31.759: E/AndroidRuntime(11107):    at dalvik.system.NativeStart.main(Native Method)


text:
Q: How to force `findstr` to ignore `Cannot open` returns I'm trying to use findstr to search inside a folder looking for some string:
findstr /spin /c:"string" *

however it returns back with a lot of Cannot open errors which make it difficult for me to find the exact matches found.
When using Cmder command:
grep -r "string" .

I got Permission denied error for the same folders. If I use the command:
grep -rs "string" .

it gives me the results nice and clean. Is there a similar flag for findstr or a combination of cmd commands to do the same?
there are already some posts for findstr Cannot open error, explaining what is wrong and how to solve it, but I don't care why it is happening. I just want the command to ignore the Cannot open lines and prints out just the lines with exact matches.

A: You can make use of 2>nul:
FINDSTR /SPIN /C:"string" * 2>nul

This will pipe the standard-error stream to null (read more), thus only matches are displayed.


text:
Q: Continuity of barycentre in Hausdorff metric Let $K_1$, $K_2$ be two convex compact sets in $\mathbb{R}^d$, and $p_1,p_2$ be their barycenters. Is it true that the distance between $p_1$ and $p_2$ does not exceed a Hausdorff distance between $K_1$ and $K_2$? If not, maybe there is some weaker estimate, say, uniform continuity of the map (convex body)$\rightarrow$ (its barycenter) for bodies inside, say, unit ball?
UPDATE. As Anton pointed out, the answer is obviously no, just take rectangle $\varepsilon\times 1$ and divide it by diagonal onto two triangles. Let me ask another question: is the barycentre of a closed $\varepsilon$-neighborhood close to the barycentre of initial body uniformly for all bodies inside unit ball?

A: *

*This question has been first discussed in the paper [ABB] below. They show that, in the plane, the barycenter of the boundary has the desired property: It is Lipschitz-continuous with respect to the Hausdorff distance. (However, the Lipschitz constant is larger than 1.)

*Other such "reference points" which are Lipschitz-continuous w.r.t. the Hausdorff-distance, or w.r.t. some other metric (like the area of the symmetric difference) have been investigated. The objective is to get a fast heuristic or initial solution for matching two shapes under translation. A good starting point into the literature might be Oliver Klein's Ph.D. thesis "Shape Matching With Reference Points" from 2008.

*The best Lipschitz constant (for the Hausdorff distance) is achieved by the so-called Steiner point (or Steiner center). In functional analysis, such "reference points" are known under the name "continuous selectors". It has been proved (by non-constructive methods, however) that the Steiner point has the smallest possible Lipschitz constant w.r.t. the Hausdorff distance.

*One can show by an elementary example that a reference point (a mapping from compact convex sets to points that is equivariant under, say, isometries) cannot have Lipschitz-constant 1 in dimension 2 or larger. (Thus the answer to the first, strong, part of the original question is NO, even if you think of other points than the barycenter.)

[ABB] Helmut Alt, Bernd Behrends, Johannes Blömer. Approximate matching of polygonal shapes.
Ann. Math. Artif. Intell., Volume 13, Pages 251-266, 1995,
doi:10.1007/BF01530830. The conference version may be easier to access:
Proceedings of the seventh annual symposium on computational geometry, pp.186-193, June 10-12, 1991, North Conway, New Hampshire. ACM Press. doi:10.1145/109648.109669.

A: No, the distance can be as big as you want.
Take two isosceles triangles with small bases,
which "look" in the opposite directions.

For the updated question, the answer is still "NO".
Again take long thin isosceles triangle with small base $\ll\varepsilon$.
The distance between the barycentre of triangle and its $\varepsilon$-neigborhood
is about
$$\tfrac16{\cdot}\mathop{\rm diam}.$$
This is the upper bound for $\mathbb R^2$;
for $\mathbb R^n$ you should get $$(\tfrac12-\tfrac1{n+1}){\cdot}\mathop{\rm diam}.$$


text:
Q: Use .ascx to render content from ajax call Assume I have on a page an article with the possibility to comment it. I have a submit form that submits via ajax and the OnComplete javascript method intercepts the result of the form submit.
Each comment is smth like:

User Always_Dreaming at 01/01/2009 - 11:13:52

Here goes my text   :D

I made an .ascx file from it, and I do tml.RenderPartial foreach comment. Now the question is how can I use this .ascx control to output the inserted content to the OnComplete method from client side.
PS. I want to use this approach and not to serialize the Comment object and to return the serialized data, take it wioth my js code and generate on the fly the html with data from the deserialized Comment object.

A: What you need to do is use the PartialViewResult from the action that's invoked by your javascript call. The client side code can append it to the html using something like the jQuery append or html method calls.

A: for those who are interested, I found a sample :)
here


text:
Q: Sharing data between app extension and conainer app I'm trying to share data between an app extension and my container app.
I setup an app group in the container app and referenced it my app extension.
When my app extension is accessed, I save an object to NSUserDefaults
//in the app extension
-(void)viewDidLoad {
NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.mygroup.com"];
[defaults setObject:[NSDate date] forKey:@"Date"];
[defaults synchronize];
}

and in the container app - when it is launched I setup an observer:
// in the container app
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDefaultChanged:) name:NSUserDefaultsDidChangeNotification object:nil];
}
-(void)userDefaultChanged:(NSNotification *)note
{
    NSLog(@"Changed");
}

But if my container app was sent to the background, this notification is never called - so I have no way of knowing when the user default was changed.
How can I get the info in the container app (In order to update internally)?

A: I might be mistaken but NSNotification run mainly in the main thread, which means that you will never get that notification.
Also you should unsubscribe to any notification when the view is unloaded, in this case I don't think it's a good idea to have a subscription sitting there.
What I'd do in this case is just check the NSUserDefaults every time the app awakens (there are Delegate methods that you can activate on AppDelegate such as: "applicationDidBecomeActive"


text:
Q: delete row confirm with jquery and jsf I tried my solution in this forum for five days and found some similar situations, but still could not solve my problem.
1- I am using pure jsf
2- I need before deleting a row from my table, there is a confirmation, a modal (I'm trying to use the smartNotifications)
3 - I can call the javascript function and suspend the delete action, but after clicking the button "Yes, I want to delete the record" does not continue the process of erasing the record, stands in the same place.
Follow my example below
Java code
<h:form id="form1">
    <h:datatable id="tab1">
      <h:column id="column1">
        <f:facet name="header">User</f:facet>
        <h:outputText rendered="#{bean.User}"></h:outputText>
      </h:column>
      <h:column id="column2">
        <h:commandlink onclick="delete();" action="#{bean.deleteUser}" />
      </h:column>
    </h:datatable>
</h:form>

Javascript:
function delete(e) {
  $.SmartMessageBox({
    title: "Are you Sure?",
    content: "This action can not be undone",
    buttons: '[Yes][No]'
 }, function (ButtonPressed) {
    if (ButtonPressed === "Yes") {
        return true;
    }
    if (ButtonPressed === "No") {
        return false;
    }
});
e.preventDefault();

}
Please help me

A: They way your code is run e.preventDefault() get's called in any case. What you want (I'm assuming) is to put e.preventDefault(); in the if Button === No Section
function delete(e) {
  $.SmartMessageBox({
    title: "Are you Sure?",
    content: "This action can not be undone",
    buttons: '[Yes][No]'
 }, function (ButtonPressed) {
    if (ButtonPressed === "Yes") {
        return true;
    }
    if (ButtonPressed === "No") {
        e.preventDefault();
    }
});
}


text:
Q: Volume of a Pyramid Linear Algebra Find the volume of a pyramid with triangular base bounded by vectors (1,-1, 2) and (1, 1, 1)
and vertex located at (3, 2, 5).
I am not sure how I would solve this. I know the volume of a pyramid is: 1/3 (base * height), but with the given vectors, I am unsure how to solve this.
Hope someone can help me, would really appreciate it.
Thanks.

A: I'm guessing since you're only given two vectors $\vec{a}, \vec{b}$ on the base that the third is found by connecting the heads.  In that case, the area of the base is
$$A_{base} = \frac{1}{2}|\vec{a} \times \vec{b}| = \frac{1}{2}|-3\hat{x} + \hat{y} + 2 \hat{z}| = \sqrt{14}/2.$$
The cross product also defines a normal to the plane containing $\vec{a}, \vec{b}$.  The equation of this plane is $-3x + y + 2z = 0$ since the origin is contained in the plane.
The distance to the plane, which is the height of the pyramid, is then
$$h = \frac{-3(3) + 1(2) + 2(5)}{\sqrt{14}} = \frac{3}{\sqrt{14}}.$$
Then your volume is
$$V = \frac{1}{3}A_{base}h = \frac{1}{3} \frac{\sqrt{14}}{2} \frac{3}{\sqrt{14}} = \frac{1}{2}.$$

A: Hint 1: For two arbitrary vectors $v_1$ and $v_2$, $\|v_1 \times v_2\| = \|v_1\| \|v_2\|\sin(\theta)$.  You should be able to find the area of the base using this fact.
Hint 2: $v_1 \times v_2 $ will give you a vector perpendicular to the base.
Hint 3: Let $u = \frac {v_1 \times v_2}{\|v_1 \times v_2\| }$, then $u \cdot v_3$ will give you the height of the pyramid, where $v_3$ is the vector to the vertex from the corner at the origin.
Hint 4 (bonus): The vector triple product $|v_3 \cdot (v_1 \times v_2)|$ gives you the volume of the parallelepiped defined by the three vectors.  How many pyramids will fit in the parallelepiped?


text:
Q: Getting Runtime Error(SIGSEGV) on SPOJ , can't find out what's wrong in my code I know this type of question has been asked before but I can't find a solution to this, I know its a invalid memory reference error or array out of bounds, but I can't seem to find the cause of the error in my code.
I just tried this problem on SPOJ, it was the 'Transform the Expression'
https://www.spoj.com/problems/ONP/
my all test cases are right!
here is my code:
#include <bits/stdc++.h>
#include<string>
using namespace std;

int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long int t;
string str;
std::stack<char> f ;
cin>>t;
while(t--){
    cin>>str;
    string ans="";
    for(int i=0;i<str.size();i++){
        switch(str[i]){
            case '(':break;
            case '+':
            case '*':
            case '-':
            case '^':
               f.push(str[i]);
               break;
            case ')':
               ans+=f.top();
               f.pop();
               break;
            default:
               ans+=str[i];
               break;
        }

        }
        cout<<ans<<endl;

    }

return 0;
}

A: #include <bits/stdc++.h>
using namespace std;

int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long int t;
cin>>t;
while(t--){
    string str;
    std::stack<char> f ;
    cin>>str;
    string ans="";
    for(int i=0;i<str.size();i++){
        switch(str[i]){
            case '(':
                break;
            case '+':
            case '*':
            case '/': // Change 1
            case '-':
            case '^':
               f.push(str[i]);
               break;
            case ')':
            if(f.size()>0){  // Change 2
               ans+=f.top();
               f.pop();
            }
               break;
            default:
               ans+=str[i];
               break;
        }
        }
        if(f.size()>0){
            while(f.size()>0){
                ans+=f.top();
                f.pop();
            }
        }
        cout<<ans<<endl;

    }

return 0;
}

There were two errors in your code

*

*You forgot to add '/' (this would give WA)

*If the stack was empty still your code was adding it to the string and popping empty stack

(I did some changes in your code)


text:
Q: Will singleton class be duplicated if is not directly referenced? Let's say I have the DLL assembly A, where I in the right way have implemented the singleton pattern. Let it be the class Manager with his Instance static property returning the only instance.
Let's say then that I have created the DLL assembly B where the class Controller is declared and this assembly references to the A and the Controller class uses the Manager, okay.
Finally, there is a console application C where I got the only reference to the assembly B and several instances of the class Controller.
Now, the question. Will those instance share the Manager class between them or not?

A:
Now, the question. Will those instance share the Manager class between them or not?

Yes, they will share the same instance because all those assemblies live in a single AppDomain. A different instance will be used if you create another application D (web, console, desktop, ...) where you reference the other assemblies and attempt to access the Manager.Instance.

A: Answer: yes, as the Manager is correctly implemented singleton.


text:
Q: fgets is getting skipped I have little program where I want to ask for an option and then for a filename.
  //Some code before
   printf("######################\n");
   printf("# 1. Register a file #\n");
   printf("# 2. Get global list #\n");
   printf("# 3. Download a file #\n");
   printf("# 4. Quit / Exit     #\n");
   printf("######################\n");
   printf("Enter decision: ");
      fflush(stdin);
   action = getchar();
   action -= '0';
   sprintf(input, "[%d]--", action);
   switch (action)
   {
    case 1:
     printf("Enter file name: ");
        fflush(stdin);
     fgets(input+strlen(input), LINE_LEN, stdin);
     input[strlen(input)] = (input[strlen(input)] == '\n') ? 0 : input[strlen(input)];
     if(write(sock, input, sizeof(input)) == -1) perror("Clienthandler Write 3");
    break;
//some code after

The problem is that my fgets is getting skipped, even in gdb, gdb shows after the fgets for inspect input the value "\n\000]--" when action = 1
This is the console output:
######################
# 1. Register a file #
# 2. Get global list #
# 3. Download a file #
# 4. Quit / Exit     #
######################
Enter decision: 1
Enter file name: ######################
# 1. Register a file #
# 2. Get global list #
# 3. Download a file #
# 4. Quit / Exit     #
######################
Enter decision: ^C

A: fget() is not getting skipped but reads the left over new-line from the previous input using getchar().
It is all about complete error checking and sane logging:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define LINE_LEN (1024)

int main(void)
{
  int action = 0;
  char input[LINE_LEN] = {0};
  size_t len = 0;

  printf("enter decision: ");
  {
    int c = fgetc(stdin); /* equivalent to getchar() */
    if (EOF == c)
    {
      putc('\n');

      if (ferror(stdin))
      {
        perror("fgetc(stdin) failed");
      }
      else
      {
        fprintf(stderr, "read EOF, aborting ...\n");
      }

      exit(EXIT_FAILURE);
    }

    action = c;
  }

  /* read left over from previous input: */
  {
    int c = fgetc(stdin);
    if (EOF == c)
    {
      putc('\n');

      if (ferror(stdin))
      {
        perror("fgetc(stdin) failed");
        exit(EXIT_FAILURE);
      }
    }
    else if ('\n' != c)
    {
      fprintf(stderr, "read unexpected input (%d), aborting ...\n", c);
      exit(EXIT_FAILURE);
    }
  }

  len = strlen(input);
  if (LINE_LEN <= len + 1)
  {
    fprintf(stderr, "input buffer full, aborting ...\n");
    exit(EXIT_FAILURE);
  }

  switch(action - '0')
  {
    case 1:
      printf("enter file name: ");
      if (NULL == fgets(input + len, LINE_LEN - len, stdin))
      {
        putc('\n');

        if (ferror(stdin))
        {
          perror("fgets() failed");
        }
        else
        {
          fprintf(stderr, "missing input, aborting ...\n");
        }

        exit(EXIT_FAILURE);
      }

      (input + len)[strcspn(input + len, "\n")] = '\0'; /* cut off new-line, if any. */

      printf("read file name '%s'\n", input + len);

      break;

    default:
      fprintf(stderr, "unknown action (%d), aborting ...\n", action);
      exit(EXIT_FAILURE);

      break;
  }
}


text:
Q: Is it possible to delete all rows in a subform by clicking a button in the form? I would like to delete rows in a table where the table is a sub-from. Is this possible? How can I do it?
Thanks

A: Use DAO. Very fast and automatic requery:
Private Sub DeleteButton_Click()

    Dim Records As DAO.Recordset

    Set Records = Me!NameOfYourSubformCONTROL.Form.RecordsetClone
    If Records.RecordCount > 0 Then
        Records.MoveFirst
        While Not Records.EOF
            Records.Delete
            Records.MoveNext
        Wend
    End If
    Records.Close

End Sub

A: Certainly - execute an appropriate SQL delete query to clear all records from the table constituting the Record Source for the subform as part of the On Click event handler for your button, e.g.:
Private Sub YourButton_Click()
    CurrentDb.Execute "delete from YourSubFormTable"
End Sub

After deleting the data, you'll need to requery the subform which you can do by invoking the 'requery' method of the form object:
Private Sub YourButton_Click()
    CurrentDb.Execute "delete from YourSubFormTable"
    YourSubForm.Requery
End Sub


text:
Q: Apache mod_speling PHP framework I have Apache's mod_speling module enabled and can't get lowercase URLs to work properly. This is running on Ubuntu.
Example: localhost/controller
The file name is Controller.php.
It works when I type in localhost/Controller.
Is there any way to set up Apache to use the lowercase version?
My configuration for mod_speling:
CheckSpelling On


text:
Q: No suitable method found for divide I checked the other "no suitable method found" threads, but none of them are for divide, so I'm not sure where to go from here.
I'm retrieving text the user entered (LoanAmount) and using it to display monthly payments.
I'm trying to display monthly payments for a mortgage with a 10-year term. I'm using the formula LoanAmount + (LoanAmount * InterestRate) / 120. I realize that interest calculations are more complicated than that, but for this example the interest doesn't compound.
I've tried casting LoanAmount.
BigDecimal purchasePrice = new BigDecimal(purchasePriceTextField.getText());
            BigDecimal downPayment = new BigDecimal(downPaymentTextField.getText());
            BigDecimal loanAmount = purchasePrice.subtract(downPayment);
            BigDecimal interestRate = new BigDecimal(interestRateTextField.getText());

            loanAmountTextField.setText(currency.format(loanAmount));
            BigDecimal temp = loanAmount + loanAmount.multiply(interestRate);
            tenYearTextField.setText(currency.format(temp.divide(120, 2, RoundingMode.HALF_UP)));

The exact error is
MortgageCalculatorController.java:69: no suitable method found for divide(int, int, RoundingMode)
tenYearTextField.setText(currency.format(temp.divide(120, 2, RoundingMode.HALF_UP)));

A: The Error indicates that there is no method divide with params int, int, RoundingMode in BigDecimal.
The Method you probably want to use is
public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode)
So you should probably change your line 69 to
tenYearTextField.setText(currency.format(temp.divide(BigDecimal.valueOf(120), 2, RoundingMode.HALF_UP)));
You may also get an error in Line 68, this will fix it:
BigDecimal temp = loanAmount.add(loanAmount.multiply(interestRate));


text:
Q: maximum volume?
I know I have to derive the formula for the volume $V=A_{base}*h$, with $h=600cm$, set it equal to zero and the result would be the maximum, but I don't know what parameters to take to get the area of the triangle.
I hope you can help me, thank you!

A: From your diagram, we can see that $(x/2)^2 + y^2 = 0.5^2$ by the Pythagorean theorem on the triangle face. From your diagram, we can see that the volume is equal to $\frac{xy}2$ for the face area times $6$ for the height, so we get $V=3xy$, which is the quantity we want to maximize. Use this equation $(x/2)^2 + y^2 = 0.5^2$ and solve for $y$. We get $ y = \sqrt{0.25-x^2/4}$. Substitute this into the volume equation to get $V=3x\sqrt{0.25-x^2/4}$. Find $V'$ and set it to $0$, and find the $x$ that makes $V' = 0$. Use $x$ to then find $y$. I hope this helps.


text:
Q: Sorting a hash in Perl when the keys are dynamic I have a hash as follows:

my %data = (
    'B2' => {
        'one' => {
            timestamp => '00:12:30'
        },
        'two' => {
            timestamp => '00:09:30'
        }
    },
    'C3' => {
        'three' => {
            timestamp => '00:13:45'
        },
        'adam' => {
            timestamp => '00:09:30'
        }
    }
);

(The structure is actually more complex than that; I'm simplifying it here.)
I wish to sort "globally" on timestamp and then the keys of the inner hashes (one, two, three adam).  But the keys of the inner hashes are dynamic; I don't know what they are going to be until the data is read from files.
I want the sorted output of the above hash to be:
00:09:30,C3,adam
00:09:30,B2,two
00:12:30,B2,one
00:13:45,C3,three

I've looked at many questions/answers regarding sorting hashes by keys and/or values, but I haven't been able to figure it out when the key names are not known ahead of time.  (Or maybe I'm just not understanding it.)
What I'm doing for now is two steps.
Flattening the hash into an array:
my @flattened;
for my $outer_key (keys %data) {
    for my $inner_key (keys %{$data{$outer_key}}) {
        push @flattened, [
            $data{$outer_key}{$inner_key}{timestamp}
            , $outer_key
            , $inner_key
        ];
    }
}

And then doing the sort:
for my $ary (sort { $a->[0] cmp $b->[0] || $a->[2] cmp $b->[2] } @flattened) {
    print join ',' => @$ary;
    print "\n";
}

I'm wondering if there is a more concise, elegant, efficient way of doing this?

A: This type question might be more suited to the Programmers Stack Exchange site or the Code Review one. Since it is asking about implementation, I think its fine to ask here. The sites tend to have some overlap.

As @DondiMichaelStroma pointed out, and as you already know, your code works great! However, there is more than one way to do it. For me, if this was in a small script, I would probably leave it as is and move on to the next part of the project. If this was in a more professional code base, I would make some changes.
For me, when writing for a professional code base, I try to keep a few things in mind.

*

*Readability

*Efficiency when it matters

*Not gold-plating it

*Unit Testing

So let's take a look at your code:
my %data = (
    'B2' => {
        'one' => {
            timestamp => '00:12:30'
        },
        'two' => {
            timestamp => '00:09:30'
        }
    },
    'C3' => {
        'three' => {
            timestamp => '00:13:45'
        },
        'adam' => {
            timestamp => '00:09:30'
        }
    }
);

The way data is defined is excellent and nicely formatted. This may not be how %data is built in your code, but maybe a unit test would have a hash like that.
my @flattened;
for my $outer_key (keys %data) {
    for my $inner_key (keys %{$data{$outer_key}}) {
        push @flattened, [
            $data{$outer_key}{$inner_key}{timestamp}
            , $outer_key
            , $inner_key
        ];
    }
}
for my $ary (sort { $a->[0] cmp $b->[0] || $a->[2] cmp $b->[2] } @flattened) {
    print join ',' => @$ary;
    print "\n";
}

The variable names could be more descriptive, and the @flattened array has some redundant data in it. Printing it with Data::Dumper, you can see we have C3 and B2 in multiple places.
$VAR1 = [
          '00:13:45',
          'C3',
          'three'
        ];
$VAR2 = [
          '00:09:30',
          'C3',
          'adam'
        ];
$VAR3 = [
          '00:12:30',
          'B2',
          'one'
        ];
$VAR4 = [
          '00:09:30',
          'B2',
          'two'
        ];

Maybe this isn't a big deal, or maybe you want to keep the functionality of getting all the data under the key B2.
Here's another way we could store that data:
my %flattened = (
    'B2' => [['one', '00:12:30'],
             ['two', '00:09:30']],
    'C3' => [['three','00:13:45'],
             ['adam', '00:09:30']]
);

It may make the sorting more complicated, but it makes the data structure simpler! Maybe this is getting closer to gold-plating, or maybe you'd benefit from this data structure in another part of the code. My preference is to keep data structures simple, and add extra code if needed when processing them. If you decide you need to dump %flattened to a log file, you might appreciate not seeing duplicate data.

Implementation
Design: I think we want to keep this as two distinct operations. This will help code clarity and we could test each function individually. The first function would convert between the data formats we want to use, and the second function would sort the data. These functions should be in a Perl module, and we can use Test::More to do the unit testing. I don't know where we are calling these functions from, so let's pretend we are calling them from main.pl, and we can put the functions in a module called Helper.pm. These names should be more descriptive, but again I'm not sure what the application is here! Great names lead to readable code.

main.pl
This is what main.pl could look like. Even though there are no comments, the descriptive names can make it self documenting. These names could be still be improved too!
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
use Utilities::Helper qw(sort_by_times_then_names convert_to_simple_format);

my %data = populate_data();

my @sorted_data = @{ sort_by_times_then_names( convert_to_simple_format( \%data ) ) };

print Dumper(@sorted_data);

Utilities/Helper.pm
Is this readable and elegant? I think it could use some improvements. More descriptive variable names would help in this module as well. However, it is easily testable, and keeps our main code clean and data structures simple.
package Utilities::Helper;
use strict;
use warnings;

use Exporter qw(import);
our @EXPORT_OK = qw(sort_by_times_then_names convert_to_simple_format);

# We could put a comment here explaning the expected input and output formats.
sub sort_by_times_then_names {

    my ( $data_ref ) = @_;

    # Here we can use the Schwartzian Transform to sort it
    # Normally, we would just be sorting an array. But here we
    # are converting the hash into an array and then sorting it.
    # Maybe that should be broken up into two steps to make to more clear!
    #my @sorted = map  { $_ } we don't actually need this map
    my @sorted = sort {
                        $a->[2] cmp $b->[2] # sort by timestamp
                                 ||
                        $a->[1] cmp $b->[1] # then sort by name
                      }
                 map  { my $outer_key=$_;       # convert $data_ref to an array of arrays
                        map {                    # first element is the outer_key
                             [$outer_key, @{$_}] # second element is the name
                            }                    # third element is the timestamp
                            @{$data_ref->{$_}}
                      }
                      keys %{$data_ref};
    # If you want the elements in a different order in the array,
    # you could modify the above code or change it when you print it.
    return \@sorted;
}

# We could put a comment here explaining the expected input and output formats.
sub convert_to_simple_format {
    my ( $data_ref ) = @_;

    my %reformatted_data;

    # $outer_key and $inner_key could be renamed to more accurately describe what the data they are representing.
    # Are they names? IDs? Places? License plate numbers?
    # Maybe we want to keep it generic so this function can handle different kinds of data.
    # I still like the idea of using nested for loops for this logic, because it is clear and intuitive.
    for my $outer_key ( keys %{$data_ref} ) {
        for my $inner_key ( keys %{$data_ref->{$outer_key}} ) {
            push @{$reformatted_data{$outer_key}},
                 [$inner_key, $data_ref->{$outer_key}{$inner_key}{timestamp}];
        }
    }

    return \%reformatted_data;
}

1;

run_unit_tests.pl
Finally, let's implement some unit testing. This is might be more than you were looking for with this question, but I think clean seams for testing is part of elegant code and I want to demonstrate that. Test::More is really great for this. I'll even throw in a test harness and formatter so we can get some elegant output. You can use TAP::Formatter::Console if you don't have TAP::Formatter::JUnit installed.
#!/usr/bin/env perl
use strict;
use warnings;
use TAP::Harness;

my $harness = TAP::Harness->new({
    formatter_class => 'TAP::Formatter::JUnit',
    merge           => 1,
    verbosity       => 1,
    normalize       => 1,
    color           => 1,
    timer           => 1,
});

$harness->runtests('t/helper.t');

t/helper.t
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use Utilities::Helper qw(sort_by_times_then_names convert_to_simple_format);

my %data = (
    'B2' => {
        'one' => {
            timestamp => '00:12:30'
        },
        'two' => {
            timestamp => '00:09:30'
        }
    },
    'C3' => {
        'three' => {
            timestamp => '00:13:45'
        },
        'adam' => {
            timestamp => '00:09:30'
        }
    }
);

my %formatted_data = %{ convert_to_simple_format( \%data ) };

my %expected_formatted_data = (
    'B2' => [['one', '00:12:30'],
             ['two', '00:09:30']],
    'C3' => [['three','00:13:45'],
             ['adam', '00:09:30']]
);

is_deeply(\%formatted_data, \%expected_formatted_data, "convert_to_simple_format test");

my @sorted_data = @{ sort_by_times_then_names( \%formatted_data ) };

my @expected_sorted_data = ( ['C3','adam', '00:09:30'],
                             ['B2','two',  '00:09:30'],
                             ['B2','one',  '00:12:30'],
                             ['C3','thee','00:13:45'] #intentionally typo to demonstrate output
                            );

is_deeply(\@sorted_data, \@expected_sorted_data, "sort_by_times_then_names test");

done_testing;

Test Output
The nice thing about testing this way is that it will tell you what is wrong when a test fails.
<testsuites>
  <testsuite failures="1"
             errors="1"
             time="0.0478239059448242"
             tests="2"
             name="helper_t">
    <testcase time="0.0452120304107666"
              name="1 - convert_to_simple_format test"></testcase>
    <testcase time="0.000266075134277344"
              name="2 - sort_by_times_then_names test">
      <failure type="TestFailed"
               message="not ok 2 - sort_by_times_then_names test"><![CDATA[not o
k 2 - sort_by_times_then_names test

#   Failed test 'sort_by_times_then_names test'
#   at t/helper.t line 45.
#     Structures begin differing at:
#          $got->[3][1] = 'three'
#     $expected->[3][1] = 'thee']]></failure>
    </testcase>
    <testcase time="0.00154280662536621" name="(teardown)" />
    <system-out><![CDATA[ok 1 - convert_to_simple_format test
not ok 2 - sort_by_times_then_names test

#   Failed test 'sort_by_times_then_names test'
#   at t/helper.t line 45.
#     Structures begin differing at:
#          $got->[3][1] = 'three'
#     $expected->[3][1] = 'thee'
1..2
]]></system-out>
    <system-err><![CDATA[Dubious, test returned 1 (wstat 256, 0x100)
]]></system-err>
    <error message="Dubious, test returned 1 (wstat 256, 0x100)" />
  </testsuite>
</testsuites>

In summary, I prefer readable and clear over concise. Sometimes you can make less efficient code that is easier to write and logically simpler. Putting ugly code inside functions is a great way to hide it! It isn't worth messing around with code to save 15ms when you run it. If your data set is large enough that performance becomes an issue, Perl might not be the right tool for the job.  If you are really looking for some concise code, post a challenge over at the Code Golf Stack Exchange.


text:
Q: Is it possible in Twig to set autoescape strategy in the layout file I have a layout file that has a {% block content %}{% endblock %} inside a Javascript array like this
<script type="text/javascript">
    cols:[
            {% block content %}{% endblock %}
        ];
</script>

And then is extended like this in the many templates that use the layout file like this (the real templates have many more lines of code and variables):
{% block content %}
    { view:"text", name:"visitDate", value:"{{ date }}", label:"Date/Time:", labelWidth:100, width:285, labelAlign:"right", readonly:true },
{% endblock %}

As the content block will always need to be escaped using the "js" strategy is there any way to specify this in the layout template I've tired:
<script type="text/javascript">
    cols:[
            {% autoescape 'js' %}
                {% block content %}{% endblock %}
            {% endautoescape %}
        ];
</script>

But that doesn't seem to work, and can't find any examples in the Twig documentation. I can get it to work if I add the autoescape block inside the content block in the templates, but this doesn't feel like the correct way to do this.
As an example, using the above code the following HTML/Javascript should be sent to the browser where {{ date }} = "17/12/2017 15:01:53":
<script type="text/javascript">
    cols:[
            { view:"text", name:"visitDate", value:"17\x2F12\x2F2017\x2015\x3A01\x3A53", label:"Date/Time:", labelWidth:100, width:285, labelAlign:"right", readonly:true },
        ];
</script>

Only the template variables in the child templates content block should be escaped not the actual Javascript code which is what you get if you use something along the lines of {{ block('content')|e('js') }}.

A: One solution I can think of is to create node visitor class, that will process every twig node and depending on the block's name it will apply corresponding escape strategy.

*

*First of all create custom twig extension

*Create node visitor object which will apply escape strategy to every node between opening and closing content blocks

*Register node vistor in the extension.

Here is an example visitor that will aplly js escape filter on every print node inside content block:
<?php

declare(strict_types=1);

namespace App\Twig;

class AppExtension extends \Twig_Extension
{
    /**
     * {@inheritdoc}
     */
    public function getNodeVisitors()
    {
        /**
         * Node visitor that applies `js` escaping strategy to every output node under `content` block
         *
         * @var \Twig_NodeVisitorInterface
         */
        $visitor = new class() implements \Twig_NodeVisitorInterface {
            /**
             * @var bool
             */
            private $escape = false;

            /**
             * {@inheritdoc}
             */
            public function enterNode(\Twig_Node $node, \Twig_Environment $env)
            {
                // Start of `content` block found, set `escape` to true to indicate that next nodes should be escaped
                if ($this->isContentBlockNode($node)) {
                    $this->escape = true;
                }

                return $node;
            }

            /**
             * {@inheritdoc}
             */
            public function leaveNode(\Twig_Node $node, \Twig_Environment $env)
            {
                if ($node instanceof \Twig_Node_Module) {
                    $this->escape = false;
                }

                if ($this->escape) {
                    if ($node instanceof \Twig_Node_Print) {
                        $expr = $node->getNode('expr');
                        // Skipping if escape strategy provided in the template for this node
                        if ($expr instanceof \Twig_Node_Expression_Filter) {
                            return $node;
                        }

                        $line = $expr->getTemplateLine();
                        $name = new \Twig_Node_Expression_Constant('escape', $line);
                        $args = new \Twig_Node(array(new \Twig_Node_Expression_Constant('js', $line), new \Twig_Node_Expression_Constant(null, $line), new \Twig_Node_Expression_Constant(true, $line)));

                        $filter = new \Twig_Node_Expression_Filter($expr, $name, $args, $line);

                        $class = get_class($node);

                        return new $class($filter, $node->getTemplateLine());
                    }
                }

                // End of `content` block, disable escape policy for further nodes
                if ($this->isContentBlockNode($node)) {
                    $this->escape = false;
                }

                return $node;
            }

            /**
             * {@inheritdoc}
             */
            public function getPriority()
            {
                return -10;
            }

            /**
             * Checks whether the node is `content` block
             *
             * @param \Twig_Node $node
             *
             * @return bool
             */
            private function isContentBlockNode(\Twig_Node $node): bool
            {
                return ($node instanceof \Twig_Node_Block && 'content' === $node->getAttribute('name'));
            }
        };

        return [$visitor];
    }
}